diff --git a/backend/app/services/voucher_check/adapters/__init__.py b/backend/app/services/voucher_check/adapters/__init__.py index 9314e478..183ca61a 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 模块。 -逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例。 +用途:登记销售一期 Adapter(主体、目录扫描、PO 取数、OA 占位、归档)。 +依赖:各 adapter 模块;PO 制式 PDF 在 voucher_check.po_order;ERP 取数在 erp_po_repository。 +逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例,不调用 erp_po_print.fetch。 """ from app.services.voucher_check.adapters.base import ( diff --git a/backend/app/services/voucher_check/adapters/base.py b/backend/app/services/voucher_check/adapters/base.py index a728e03a..0f9c70ff 100644 --- a/backend/app/services/voucher_check/adapters/base.py +++ b/backend/app/services/voucher_check/adapters/base.py @@ -80,7 +80,7 @@ class DirectoryScanAdapter(Protocol): class AcquireAdapter(Protocol): - """把外部单据打印后写入类型目录;PO / 销货放行单一期仅占位。""" + """把外部单据打印后写入类型目录;PO 制式 PDF 见 po_order,ERP 取数见 erp_po_repository。""" source_type: str wired: bool @@ -88,7 +88,7 @@ class AcquireAdapter(Protocol): def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]: """ 获取并落入类型目录。 - 【AI 触发时机】仅当独立抓取任务启用且 Adapter.wired=True 时调用;周任务不调用。 + 【AI 触发时机】仅当 Adapter.wired=True 且独立抓取走本方法时调用;周任务不调用。PO 独立抓取请用 ErpPoPrintAdapter.fetch_documents,不要走 fetch。 """ ... diff --git a/backend/app/services/voucher_check/adapters/erp_po_print.py b/backend/app/services/voucher_check/adapters/erp_po_print.py index 32a4e968..da098c14 100644 --- a/backend/app/services/voucher_check/adapters/erp_po_print.py +++ b/backend/app/services/voucher_check/adapters/erp_po_print.py @@ -1,32 +1,39 @@ """ backend/app/services/voucher_check/adapters/erp_po_print.py -用途:ERP 反查 PO 并打印 PDF 写入「PO订单」类型目录的占位 Adapter。 -依赖:adapters.base。 -逻辑:查询/打印方式待确认,周任务不调用;独立抓取任务启用前 wired=False。 +用途:ERP 反查 PO 后写入「PO订单」类型目录的 Adapter。 +依赖:adapters.base、erp_po_repository、voucher_check.po_order。 +逻辑:fetch_documents / publish_for_invoices 已接线(HXJM.oma99 → TGHX.pmm99)。 + fetch() 仍占位,周任务不调用。render_given 只出本地 PDF。 """ from __future__ import annotations from datetime import date +from pathlib import Path +from typing import TYPE_CHECKING, Any, Mapping, Sequence from app.core.errors import ServiceUnavailableError from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow +if TYPE_CHECKING: + from app.services.voucher_check.config import VoucherCheckEngineConfig + from app.services.voucher_check.po_order import PoOrderDocument, PoOrderPublishResult + class ErpPoPrintAdapter: - """PO 打印占位;未接线时禁止生成假 PDF。""" + """PO 获取:ERP 取数与上传已就绪;周检核 fetch 仍不启用。""" source_type = "erp_po_print" wired = False def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]: """ - 预留:按 invoice 反查 PO 并打印到类型目录。 - 【AI 触发时机】仅当独立「抓取 PO」任务上线后调用,不要在周检核 runner 中调用。 + 周检核入口仍关闭。 + 【AI 触发时机】不要在周二 runner 中调用。独立抓取请用 fetch_documents / publish_for_invoices。 """ raise ServiceUnavailableError( - "ERP PO 打印尚未接线", + "ERP PO 打印尚未接入周检核", code="VOUCHER_CHECK.ADAPTER_NOT_WIRED", details={ "adapter": self.source_type, @@ -34,3 +41,65 @@ class ErpPoPrintAdapter: "subject_count": len(subjects), }, ) + + def fetch_documents( + self, + invoice_nos: Sequence[str], + *, + config: VoucherCheckEngineConfig | None = None, + ) -> list[PoOrderDocument]: + """ + 按发票号从 ERP 组装制式采购单数据。 + 【AI 触发时机】独立抓取 PO、已有 invoice 清单时调用;不要在周二 runner 里调用。 + """ + from app.services.voucher_check.config import load_engine_config + from app.services.voucher_check.erp_po_repository import fetch_po_documents_for_invoices + + engine = config if config is not None else load_engine_config() + return fetch_po_documents_for_invoices(engine, invoice_nos) + + def render_given( + self, + document: PoOrderDocument | Mapping[str, Any], + output_dir: str | Path, + *, + overwrite: bool = True, + ) -> Path: + """ + 根据给定采购单数据生成 `{invoice}-{订单号}.pdf` 到本地目录。 + 【AI 触发时机】只需核对版式、不上传文档库时调用。 + """ + from app.services.voucher_check.po_order import save_po_order_pdf + + return save_po_order_pdf(document, output_dir, overwrite=overwrite) + + def upload_given( + self, + document: PoOrderDocument | Mapping[str, Any], + *, + period_month: date, + ) -> PoOrderPublishResult: + """ + 生成制式 PDF 并上传到销售开票附件/{年}/{月}/PO订单/。 + 【AI 触发时机】已拿到 invoice 与 PO 字段、需要写入文档库类型目录时调用。 + 同名跳过;不要在周检核 runner 中调用。 + """ + from app.services.voucher_check.po_order import publish_po_order_pdf + + return publish_po_order_pdf(document, period_month=period_month) + + def publish_for_invoices( + self, + invoice_nos: Sequence[str], + *, + period_month: date, + config: VoucherCheckEngineConfig | None = None, + ) -> list[PoOrderPublishResult]: + """ + 按发票号查 ERP、生成 PDF 并上传到当月「PO订单」目录。 + 【AI 触发时机】独立抓取任务要写入文档库时调用;不要在周二 runner 里调用。 + """ + results: list[PoOrderPublishResult] = [] + for document in self.fetch_documents(invoice_nos, config=config): + results.append(self.upload_given(document, period_month=period_month)) + return results diff --git a/backend/app/services/voucher_check/adapters/hxjm_apa_subject.py b/backend/app/services/voucher_check/adapters/hxjm_apa_subject.py index 23e8e265..96a1f693 100644 --- a/backend/app/services/voucher_check/adapters/hxjm_apa_subject.py +++ b/backend/app/services/voucher_check/adapters/hxjm_apa_subject.py @@ -1,9 +1,9 @@ """ backend/app/services/voucher_check/adapters/hxjm_apa_subject.py -用途:从 HXJM apa_file 拉取上一个月销售 invoice 清单。 +用途:从 HXJM oma_file 拉取上一个月销售 invoice 清单。 依赖:erp_repository.fetch_month_invoices、fingerprint。 -逻辑:周任务 subject_adapter=hxjm_apa;期间由 erp_repository 按上月计算。 +逻辑:周任务 subject_adapter=hxjm_apa(历史注册名,实际查 oma_file);期间由 erp_repository 按上月计算。 """ from __future__ import annotations @@ -17,14 +17,14 @@ from app.services.voucher_check.fingerprint import build_material_fingerprint class HxjmApaSubjectAdapter: - """HXJM apa08/apa09 主体 Adapter。""" + """HXJM oma_file 主体 Adapter(注册名 hxjm_apa,查询 oma10/oma02 及确认/作废/状况/类别过滤)。""" source_type = "hxjm_apa" def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]: """ - 查询上月发票号集合并生成主体指纹。 - 核心逻辑:委托 fetch_month_invoices;返回期间必须与传入 period_month 一致。 + 查询上月已确认且未作废的发票号集合并生成主体指纹。 + 核心逻辑:委托 fetch_month_invoices(oma_file.oma10/oma02,确认/未作废/状况码 1/类别 11-13);返回期间必须与传入 period_month 一致。 Args: period_month: 检核月首日,由 runner 预先算好。 diff --git a/backend/app/services/voucher_check/dms_client.py b/backend/app/services/voucher_check/dms_client.py index b78dd52f..bab57b3f 100644 --- a/backend/app/services/voucher_check/dms_client.py +++ b/backend/app/services/voucher_check/dms_client.py @@ -1,9 +1,9 @@ """ backend/app/services/voucher_check/dms_client.py -用途:销售开票附件文档库客户端(登录、列目录、建文件夹、复制;不移动原件)。 +用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。 依赖:requests、Flask 配置;登录接口与合同库相同。 -逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。归档复制策略为同名跳过。 +逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。 """ from __future__ import annotations @@ -11,6 +11,7 @@ from __future__ import annotations import threading import time from datetime import date +from pathlib import Path from typing import Any import requests @@ -178,9 +179,44 @@ class SalesDmsClient: raise ServiceUnavailableError( data.get("Msg") or failure_message, code=failure_code, + details={"dms_data": data.get("Data")} if data.get("Data") not in (None, "", {}) else {}, ) return data + @classmethod + def _post_multipart( + cls, + path: str, + *, + files: dict[str, Any], + data: dict[str, Any] | None = None, + timeout: int = 60, + failure_code: str = "VOUCHER_CHECK.DMS_UNAVAILABLE", + failure_message: str = "文档库上传失败", + ) -> dict[str, Any]: + """ + POST multipart 到现网 DMS(用于附件 Upload)。 + 核心逻辑:不手工设 Content-Type,交给 requests 带 boundary;401/403 刷新会话后重试。 + """ + url = f"{cls.base_url()}{path}" + try: + session = cls._session() + response = session.post(url, files=files, data=data or {}, timeout=timeout) + if response.status_code in {401, 403}: + session = cls._session(refresh=True) + response = session.post(url, files=files, data=data or {}, timeout=timeout) + response.raise_for_status() + payload = response.json() + except (requests.RequestException, ValueError) as exc: + raise ServiceUnavailableError(failure_message, code=failure_code) from exc + if int(payload.get("Code") or 0) != 0: + raise ServiceUnavailableError( + payload.get("Msg") or failure_message, + code=failure_code, + details={"dms_data": payload.get("Data")} if payload.get("Data") not in (None, "", {}) else {}, + ) + return payload + @classmethod def page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]: """ @@ -400,3 +436,144 @@ class SalesDmsClient: details={"leaf_name": wanted}, ) return dest_row, False + + @classmethod + def ensure_period_type_folder(cls, *, period_month: date, type_folder: str) -> str: + """ + 确保销售开票附件/{yyyy}/{MM}/{类型目录} 存在并返回 FolderID。 + 【AI 触发时机】要把新生成的 PO PDF 写入类型目录时调用;年/月/类型目录没有就建。 + + Args: + period_month: 检核月份(用年、月两位目录名)。 + type_folder: 类型目录名,销售 PO 固定为「PO订单」。 + """ + wanted = str(type_folder or "").strip() + if not wanted: + raise ValidationError("类型目录名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + cls.ensure_configured() + root = cls.root_folder_id() + year_id = cls.ensure_folder(parent_folder_id=root, leaf_name=f"{period_month.year:04d}") + month_id = cls.ensure_folder(parent_folder_id=year_id, leaf_name=f"{period_month.month:02d}") + return cls.ensure_folder(parent_folder_id=month_id, leaf_name=wanted) + + @classmethod + def upload_attachment(cls, *, filename: str, content: bytes) -> dict[str, Any]: + """ + 把文件二进制上传为未入目录的附件,返回 Data(须含 ID)。 + 核心逻辑:现网「新建文件」先 Upload 附件,再 CreateFiles 挂到文件夹。 + """ + name = str(filename or "").strip() + if not name: + raise ValidationError("上传文件名不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID") + if not content: + raise ValidationError("上传文件内容不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID") + payload = cls._post_multipart( + "/Api/_api/DMS/Public/Attachment/Upload", + files={"file": (name, content, "application/pdf")}, + timeout=120, + failure_code="VOUCHER_CHECK.PO_UPLOAD_FAILED", + failure_message="文档库上传附件失败", + ) + data = payload.get("Data") + if not isinstance(data, dict) or not str(data.get("ID") or "").strip(): + raise ServiceUnavailableError( + "文档库上传附件后未返回 AttachmentID", + code="VOUCHER_CHECK.PO_UPLOAD_FAILED", + ) + return data + + @classmethod + def create_files( + cls, + *, + parent_folder_id: str, + files: list[dict[str, Any]], + ) -> dict[str, Any]: + """ + 把已上传附件登记到指定文件夹(现网 functionCreationFile)。 + 核心逻辑:POST Item/CreateFiles;Files[].AttachmentID 来自 Attachment/Upload。 + """ + dest = str(parent_folder_id or "").strip() + if not dest: + raise ValidationError("上传目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + if not files: + raise ValidationError("上传文件列表不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + return cls._post_json( + "/Api/_api/APS/Public/Item/CreateFiles", + { + "LibraryID": cls.library_id(), + "CategoryID": "", + "ParentFolderID": dest, + "Files": files, + "TermID": [], + "CheckedOutState": 0, + "CheckedOutMemo": "", + }, + timeout=60, + failure_code="VOUCHER_CHECK.PO_UPLOAD_FAILED", + failure_message="文档库创建文件失败", + ) + + @classmethod + def upload_file_skip_same_name( + cls, + *, + parent_folder_id: str, + leaf_name: str, + content: bytes, + ) -> tuple[dict[str, Any], bool]: + """ + 上传文件到类型目录;目标已有同名则跳过、不覆盖。 + 核心逻辑:先 Page 查 LeafName;没有则 Upload 附件再 CreateFiles。CreateFiles 报同名视为跳过。 + """ + wanted = str(leaf_name or "").strip() + dest = str(parent_folder_id or "").strip() + if not dest: + raise ValidationError("上传目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID") + if not wanted: + raise ValidationError("上传文件名不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID") + + existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) + if existing: + return existing, True + + attachment = cls.upload_attachment(filename=wanted, content=content) + extension = str(attachment.get("Extension") or Path(wanted).suffix or ".pdf").strip() + if extension and not extension.startswith("."): + extension = f".{extension}" + file_row = { + "LeafName": wanted, + "AttachmentID": str(attachment.get("ID") or "").strip(), + "CheckedOutState": 0, + "CheckedOutMemo": "", + "Extension": extension, + "FieldValues": [], + } + + try: + cls.create_files(parent_folder_id=dest, files=[file_row]) + except ServiceUnavailableError as exc: + existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) + if existing: + return existing, True + same_names = ((exc.details or {}).get("dms_data") or {}).get("SameLeafNames") or [] + if same_names or _is_name_conflict(exc.message): + existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) + if existing: + return existing, True + raise + + dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted) + if dest_row: + return dest_row, False + # 部分现网 CreateFiles 后 LeafName 不含扩展名,再按无后缀查一次。 + stem = Path(wanted).stem + dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=stem) + if dest_row: + return dest_row, False + raise ServiceUnavailableError( + "上传成功但类型目录未找到同名文件", + code="VOUCHER_CHECK.PO_UPLOAD_FAILED", + details={"leaf_name": wanted}, + ) + diff --git a/backend/app/services/voucher_check/erp_po_repository.py b/backend/app/services/voucher_check/erp_po_repository.py new file mode 100644 index 00000000..3eae3714 --- /dev/null +++ b/backend/app/services/voucher_check/erp_po_repository.py @@ -0,0 +1,464 @@ +""" +backend/app/services/voucher_check/erp_po_repository.py + +用途:按销售发票从 HXJM.oma99 对 TGHX.pmm99,取出制式采购单字段。 +依赖:erp_repository.open_erp_connection、po_order.models、voucher_check.config。 +逻辑:独立抓取任务调用;不进周二 runner。oma99 为空时用 oma16 走 oga99(12/13)或 oea99(11)。 +""" + +from __future__ import annotations + +from collections import defaultdict +from dataclasses import dataclass +from datetime import date, datetime +from decimal import ROUND_HALF_UP, Decimal +from typing import Any, Iterable, Mapping, Sequence + +from app.core.errors import ServiceUnavailableError +from app.services.voucher_check.config import VoucherCheckEngineConfig +from app.services.voucher_check.erp_repository import _erp_unavailable, is_sales_invoice_no, open_erp_connection +from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine + +INVOICE_SCHEMA = "HXJM" +PO_SCHEMA = "TGHX" +_BATCH_SIZE = 80 + +_TA_IMA02 = {"1": "无卤", "2": "不管控"} +_TA_IMA03 = {"1": "RoHS", "0": "非环保", "9": "ERS"} + + +@dataclass(frozen=True) +class InvoiceFlow: + """一张发票对应的多角流程序号。""" + + invoice_no: str + flow_no: str + oma00: str = "" + oma16: str = "" + + +def _as_text(value: Any) -> str: + """TRIM 后收成字符串;None 当空串。""" + if value is None: + return "" + return str(value).strip() + + +def _chunks(items: Sequence[str], size: int) -> Iterable[list[str]]: + """按绑定 IN 列表切批,避免超长 SQL。""" + for index in range(0, len(items), size): + yield list(items[index : index + size]) + + +def _in_clause(prefix: str, values: Sequence[str]) -> tuple[str, dict[str, str]]: + """ + 生成 :prefix0,:prefix1 绑定与参数。 + 核心逻辑:占位符名由本函数生成,禁止把业务值拼进 SQL。 + """ + binds: dict[str, str] = {} + names: list[str] = [] + for index, value in enumerate(values): + key = f"{prefix}{index}" + names.append(f":{key}") + binds[key] = value + return ", ".join(names), binds + + +def _format_date(value: Any) -> str: + """展示用日期:2016/5/28,月日不补零。""" + if value is None: + return "" + if isinstance(value, datetime): + value = value.date() + if not isinstance(value, date): + return _as_text(value) + return f"{value.year}/{value.month}/{value.day}" + + +def _format_decimal(value: Any, scale: int, *, thousands: bool = False) -> str: + """按 azi 小数位格式化;金额可带千分位。""" + if value is None or value == "": + return "" + digits = max(0, int(scale or 0)) + quant = Decimal("1").scaleb(-digits) + number = Decimal(str(value)).quantize(quant, rounding=ROUND_HALF_UP) + if thousands: + return f"{number:,.{digits}f}" + if digits == 0: + return str(int(number)) + return f"{number:.{digits}f}" + + +def _format_qty(value: Any) -> str: + """采购量去掉无意义的尾随零。""" + if value is None or value == "": + return "" + number = Decimal(str(value)) + if number == number.to_integral_value(): + return str(int(number)) + return format(number.normalize(), "f") + + +def _join_address(*parts: Any) -> str: + """送货/账单地址:空段丢掉再拼接。""" + chunks = [_as_text(part) for part in parts] + return "".join(chunk for chunk in chunks if chunk) + + +def _halogen_text(ta_ima02: Any, ta_ima03: Any) -> str: + """版面目前一列;优先环保等级(样张 RoHS),否则卤素管控。""" + code3 = _as_text(ta_ima03) + if code3 in _TA_IMA03: + return _TA_IMA03[code3] + code2 = _as_text(ta_ima02) + return _TA_IMA02.get(code2, "") + + +def _azi_scale(value: Any, default: int) -> int: + """币别小数位;空则用默认。""" + text = _as_text(value) + if not text: + return default + try: + return max(0, int(Decimal(text))) + except Exception: + return default + + +def map_po_document(invoice_no: str, line_rows: Sequence[Mapping[str, Any]]) -> PoOrderDocument: + """ + 把同一张 TGHX 采购单的明细行收成 PoOrderDocument。 + 【AI 触发时机】ERP 已查出 pmm/pmn 行、生成 PDF 之前调用。 + + 核心逻辑:头栏取首行;合计对 pmn88/pmn88t 求和;到货日用 pmn34;版本 pmnud02; + 原始编号优先 ta_ima11,否则 pmn24。不写 SQL。 + + Args: + invoice_no: 销售发票号,只用于文件名。 + line_rows: 同一 pmm01 的有序明细(已是 dict,键为小写列名)。 + + Returns: + 可交给 save_po_order_pdf 的文档。 + + Raises: + ValueError: 无明细或缺少 pmm01。 + """ + if not line_rows: + raise ValueError("采购单没有明细行") + head = line_rows[0] + po_no = _as_text(head.get("po_no") or head.get("pmm01")) + if not po_no: + raise ValueError("缺少采购单号") + price_scale = _azi_scale(head.get("azi03"), 6) + amount_scale = _azi_scale(head.get("azi04"), 2) + total_scale = _azi_scale(head.get("azi05"), amount_scale) + price_code = _as_text(head.get("price_term_code")) + price_name = _as_text(head.get("price_term_name")) + price_term = f"{price_code} {price_name}".strip() + lines: list[PoOrderLine] = [] + untax_total = Decimal("0") + tax_total = Decimal("0") + for raw in line_rows: + untax_amt = raw.get("pmn88") + tax_amt = raw.get("pmn88t") + if untax_amt not in (None, ""): + untax_total += Decimal(str(untax_amt)) + if tax_amt not in (None, ""): + tax_total += Decimal(str(tax_amt)) + origin_no = _as_text(raw.get("ta_ima11")) or _as_text(raw.get("pmn24")) + lines.append( + PoOrderLine( + seq=_as_text(raw.get("pmn02") or (len(lines) + 1)), + item_no=_as_text(raw.get("pmn04")), + name=_as_text(raw.get("pmn041")), + spec=_as_text(raw.get("ima021")), + qty=_format_qty(raw.get("pmn20")), + unit=_as_text(raw.get("pmn07")), + arrive=_format_date(raw.get("pmn34")), + origin_no=origin_no, + version=_as_text(raw.get("pmnud02")), + untax_price=_format_decimal(raw.get("pmn31"), price_scale), + tax_price=_format_decimal(raw.get("pmn31t"), price_scale), + untax_amt=_format_decimal(untax_amt, amount_scale, thousands=True), + tax_amt=_format_decimal(tax_amt, amount_scale, thousands=True), + halogen=_halogen_text(raw.get("ta_ima02"), raw.get("ta_ima03")), + vendor_item=_as_text(raw.get("pmn06")), + ) + ) + return PoOrderDocument( + invoice_no=_as_text(invoice_no), + po_no=po_no, + po_date=_format_date(head.get("po_date") or head.get("pmm04")), + po_type=_as_text(head.get("po_type") or head.get("smydesc")), + pay_term=_as_text(head.get("pay_term") or head.get("pma02")), + tax_type=_as_text(head.get("tax_type") or head.get("gec02")), + price_term=price_term, + currency=_as_text(head.get("currency") or head.get("pmm22")), + ship_address=_join_address( + head.get("ship031"), + head.get("ship032"), + head.get("ship033"), + head.get("ship034"), + head.get("ship035"), + ), + bill_address=_join_address( + head.get("bill031"), + head.get("bill032"), + head.get("bill033"), + head.get("bill034"), + head.get("bill035"), + ), + vendor_code=_as_text(head.get("vendor_code") or head.get("pmm09")), + vendor_name=_as_text(head.get("vendor_name") or head.get("pmc081")), + vendor_tel=_as_text(head.get("vendor_tel") or head.get("pmc10")), + vendor_fax=_as_text(head.get("vendor_fax") or head.get("pmc11")), + vendor_addr=_as_text(head.get("vendor_addr") or head.get("pmc091")), + company_name=_as_text(head.get("company_name") or head.get("zo02")), + company_address=_as_text(head.get("company_address") or head.get("zo041")), + company_phone=_as_text(head.get("company_phone") or head.get("zo05")), + company_fax=_as_text(head.get("company_fax") or head.get("zo09")), + maker="", + untax_total=_format_decimal(untax_total, total_scale, thousands=True), + tax_total=_format_decimal(tax_total, total_scale, thousands=True), + lines=tuple(lines), + ) + + +def _invoice_key_sql(placeholders: str) -> str: + """HXJM 应收头:发票号 → 类别、来源单、多角序号。""" + return f""" +SELECT DISTINCT + TRIM(oma10) AS invoice_no, + TRIM(oma00) AS oma00, + TRIM(oma16) AS oma16, + TRIM(oma99) AS oma99 + FROM {INVOICE_SCHEMA}.oma_file + WHERE TRIM(oma10) IN ({placeholders}) + AND TRIM(omaconf) = 'Y' + AND TRIM(omavoid) = 'N' + AND TRIM(oma64) = '1' + AND TRIM(oma00) IN ('11', '12', '13') +""" + + +def _fallback_sql(table: str, key_col: str, flow_col: str, placeholders: str) -> str: + """oma99 为空时,从出货单或订单借多角序号。""" + return f""" +SELECT TRIM({key_col}) AS doc_no, + TRIM({flow_col}) AS flow_no + FROM {INVOICE_SCHEMA}.{table} + WHERE TRIM({key_col}) IN ({placeholders}) +""" + + +def _po_detail_sql(placeholders: str) -> str: + """TGHX 采购单头身 + 码表,对照 apmr900;过滤作废/无效/BKR。""" + s = PO_SCHEMA + return f""" +SELECT TRIM(pmm.pmm99) AS flow_no, + TRIM(pmm.pmm01) AS po_no, + pmm.pmm04 AS po_date, + TRIM(smy.smydesc) AS po_type, + TRIM(pma.pma02) AS pay_term, + TRIM(gec.gec02) AS tax_type, + TRIM(pmm.pmm41) AS price_term_code, + TRIM(pnz.pnz02) AS price_term_name, + TRIM(pmm.pmm22) AS currency, + TRIM(pmm.pmm09) AS vendor_code, + TRIM(pmc.pmc081) AS vendor_name, + TRIM(pmc.pmc10) AS vendor_tel, + TRIM(pmc.pmc11) AS vendor_fax, + TRIM(pmc.pmc091) AS vendor_addr, + TRIM(ship.pme031) AS ship031, + TRIM(ship.pme032) AS ship032, + TRIM(ship.pme033) AS ship033, + TRIM(ship.pme034) AS ship034, + TRIM(ship.pme035) AS ship035, + TRIM(bill.pme031) AS bill031, + TRIM(bill.pme032) AS bill032, + TRIM(bill.pme033) AS bill033, + TRIM(bill.pme034) AS bill034, + TRIM(bill.pme035) AS bill035, + TRIM(zo.zo02) AS company_name, + TRIM(zo.zo041) AS company_address, + TRIM(zo.zo05) AS company_phone, + TRIM(zo.zo09) AS company_fax, + pmn.pmn02 AS pmn02, + TRIM(pmn.pmn04) AS pmn04, + TRIM(pmn.pmn041) AS pmn041, + TRIM(pmn.pmn06) AS pmn06, + TRIM(pmn.pmn07) AS pmn07, + pmn.pmn20 AS pmn20, + TRIM(pmn.pmn24) AS pmn24, + pmn.pmn31 AS pmn31, + pmn.pmn31t AS pmn31t, + pmn.pmn34 AS pmn34, + pmn.pmn88 AS pmn88, + pmn.pmn88t AS pmn88t, + TRIM(pmn.pmnud02) AS pmnud02, + TRIM(ima.ima021) AS ima021, + TRIM(ima.ta_ima02) AS ta_ima02, + TRIM(ima.ta_ima03) AS ta_ima03, + TRIM(ima.ta_ima11) AS ta_ima11, + azi.azi03 AS azi03, + azi.azi04 AS azi04, + azi.azi05 AS azi05 + FROM {s}.pmm_file pmm + JOIN {s}.pmn_file pmn ON pmn.pmn01 = pmm.pmm01 + LEFT JOIN {s}.smy_file smy ON pmm.pmm01 LIKE TRIM(smy.smyslip) || '-%' + LEFT JOIN {s}.pmc_file pmc ON TRIM(pmc.pmc01) = TRIM(pmm.pmm09) + LEFT JOIN {s}.pma_file pma ON TRIM(pma.pma01) = TRIM(pmm.pmm20) + LEFT JOIN {s}.gec_file gec ON TRIM(gec.gec01) = TRIM(pmm.pmm21) AND TRIM(gec.gec011) = '1' + LEFT JOIN {s}.pnz_file pnz ON TRIM(pnz.pnz01) = TRIM(pmm.pmm41) + LEFT JOIN {s}.azi_file azi ON TRIM(azi.azi01) = TRIM(pmm.pmm22) + LEFT JOIN {s}.ima_file ima ON TRIM(ima.ima01) = TRIM(pmn.pmn04) + LEFT JOIN {s}.pme_file ship ON TRIM(ship.pme01) = TRIM(pmm.pmm10) + LEFT JOIN {s}.pme_file bill ON TRIM(bill.pme01) = TRIM(pmm.pmm11) + LEFT JOIN {s}.zo_file zo ON zo.zo01 = '1' + WHERE TRIM(pmm.pmm99) IN ({placeholders}) + AND TRIM(pmm.pmm18) != 'X' + AND TRIM(pmm.pmmacti) = 'Y' + AND NVL(TRIM(pmm.pmm02), ' ') != 'BKR' + ORDER BY pmm.pmm01, pmn.pmn02 +""" + + +def _rows_as_dicts(cursor: Any) -> list[dict[str, Any]]: + """把游标行收成小写键 dict。""" + columns = [str(col[0]).lower() for col in (cursor.description or [])] + return [dict(zip(columns, raw)) for raw in cursor] + + +def _fetch_invoice_keys(cursor: Any, invoice_nos: Sequence[str]) -> list[dict[str, Any]]: + """分批查 HXJM 应收头。""" + found: list[dict[str, Any]] = [] + for batch in _chunks(list(invoice_nos), _BATCH_SIZE): + placeholders, binds = _in_clause("inv", batch) + cursor.execute(_invoice_key_sql(placeholders), binds) + found.extend(_rows_as_dicts(cursor)) + return found + + +def _fetch_doc_flows(cursor: Any, table: str, key_col: str, flow_col: str, doc_nos: Sequence[str]) -> dict[str, str]: + """出货单/订单号 → 多角序号。""" + mapping: dict[str, str] = {} + unique = [item for item in dict.fromkeys(doc_nos) if item] + for batch in _chunks(unique, _BATCH_SIZE): + placeholders, binds = _in_clause("doc", batch) + cursor.execute(_fallback_sql(table, key_col, flow_col, placeholders), binds) + for row in _rows_as_dicts(cursor): + doc_no = _as_text(row.get("doc_no")) + flow_no = _as_text(row.get("flow_no")) + if doc_no and flow_no: + mapping[doc_no] = flow_no + return mapping + + +def resolve_invoice_flows(cursor: Any, invoice_nos: Sequence[str]) -> list[InvoiceFlow]: + """ + 发票号 → 多角流程序号。 + 核心逻辑:优先 TRIM(oma99);空则 12/13 查 oga99、11 查 oea99。同一发票多个序号会去重保留。 + """ + wanted = [item for item in dict.fromkeys(_as_text(no) for no in invoice_nos) if is_sales_invoice_no(item)] + if not wanted: + return [] + keys = _fetch_invoice_keys(cursor, wanted) + oga_docs = [_as_text(row.get("oma16")) for row in keys if _as_text(row.get("oma00")) in {"12", "13"} and not _as_text(row.get("oma99"))] + oea_docs = [_as_text(row.get("oma16")) for row in keys if _as_text(row.get("oma00")) == "11" and not _as_text(row.get("oma99"))] + oga_flows = _fetch_doc_flows(cursor, "oga_file", "oga01", "oga99", oga_docs) if oga_docs else {} + oea_flows = _fetch_doc_flows(cursor, "oea_file", "oea01", "oea99", oea_docs) if oea_docs else {} + + flows: list[InvoiceFlow] = [] + seen: set[tuple[str, str]] = set() + for row in keys: + invoice_no = _as_text(row.get("invoice_no")) + oma00 = _as_text(row.get("oma00")) + oma16 = _as_text(row.get("oma16")) + flow_no = _as_text(row.get("oma99")) + if not flow_no: + if oma00 in {"12", "13"}: + flow_no = oga_flows.get(oma16, "") + elif oma00 == "11": + flow_no = oea_flows.get(oma16, "") + if not invoice_no or not flow_no: + continue + pair = (invoice_no, flow_no) + if pair in seen: + continue + seen.add(pair) + flows.append(InvoiceFlow(invoice_no=invoice_no, flow_no=flow_no, oma00=oma00, oma16=oma16)) + return flows + + +def _fetch_po_lines(cursor: Any, flow_nos: Sequence[str]) -> list[dict[str, Any]]: + """按多角序号批量取 TGHX 采购明细。""" + lines: list[dict[str, Any]] = [] + unique = [item for item in dict.fromkeys(flow_nos) if item] + for batch in _chunks(unique, _BATCH_SIZE): + placeholders, binds = _in_clause("flow", batch) + cursor.execute(_po_detail_sql(placeholders), binds) + lines.extend(_rows_as_dicts(cursor)) + return lines + + +def fetch_po_documents_for_invoices( + config: VoucherCheckEngineConfig, + invoice_nos: Sequence[str], +) -> list[PoOrderDocument]: + """ + 按销售发票号从 ERP 组装制式采购单数据。 + 【AI 触发时机】独立「抓取 PO」任务已有 invoice 清单、要生成 PDF 之前调用;不要在周二 runner 里调用。 + + 核心逻辑:HXJM.oma99(空则 oga99/oea99)TRIM 后对 TGHX.pmm99;一票可多张 PO,每张一个文档。 + + Args: + config: Oracle 只读连接。 + invoice_nos: 销售发票号;非 6 位以上字母数字的项会跳过。 + + Returns: + PoOrderDocument 列表,按发票号、采购单号排序。找不到 PO 的发票不出现在结果里。 + + Raises: + ServiceUnavailableError: Oracle 不可用。 + """ + wanted = [item for item in dict.fromkeys(_as_text(no) for no in invoice_nos) if is_sales_invoice_no(item)] + if not wanted: + return [] + connection = None + try: + connection = open_erp_connection(config) + cursor = connection.cursor() + # [STEP 1] 发票 → 多角序号 + flows = resolve_invoice_flows(cursor, wanted) + if not flows: + return [] + # [STEP 2] 序号 → TGHX 采购单明细 + po_lines = _fetch_po_lines(cursor, [item.flow_no for item in flows]) + by_flow: dict[str, dict[str, list[dict[str, Any]]]] = defaultdict(lambda: defaultdict(list)) + for row in po_lines: + flow_no = _as_text(row.get("flow_no")) + po_no = _as_text(row.get("po_no")) + if flow_no and po_no: + by_flow[flow_no][po_no].append(row) + # [STEP 3] 发票 × 采购单 交叉成文档 + documents: list[PoOrderDocument] = [] + seen: set[tuple[str, str]] = set() + for flow in flows: + for po_no, rows in by_flow.get(flow.flow_no, {}).items(): + key = (flow.invoice_no, po_no) + if key in seen: + continue + seen.add(key) + documents.append(map_po_document(flow.invoice_no, rows)) + documents.sort(key=lambda item: (item.invoice_no, item.po_no)) + return documents + except ServiceUnavailableError: + raise + except Exception as exc: + raise _erp_unavailable(config, exc) from exc + finally: + if connection is not None: + try: + connection.close() + except Exception: + pass diff --git a/backend/app/services/voucher_check/erp_repository.py b/backend/app/services/voucher_check/erp_repository.py index 2155075d..b3b38756 100644 --- a/backend/app/services/voucher_check/erp_repository.py +++ b/backend/app/services/voucher_check/erp_repository.py @@ -1,13 +1,15 @@ """ backend/app/services/voucher_check/erp_repository.py -用途:从 Oracle HXJM 套账 apa_file 查询上一个自然月发票号集合。 +用途:从 Oracle HXJM 套账 oma_file 查询上一个自然月发票号集合;并提供共用只读连接。 依赖:oracledb、Text2SQLService._init_oracle_client、voucher_check.config。 -逻辑:runner 阶段 A 调用;仅只读 SELECT;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。 +逻辑:runner 阶段 A 调用 fetch_month_invoices;采购单取数见 erp_po_repository,复用 open_erp_connection。 + 只读 SELECT 已确认、未作废、状况码 1、帐款类别 11/12/13;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。 """ from __future__ import annotations +import re from dataclasses import dataclass from datetime import date, datetime from zoneinfo import ZoneInfo @@ -16,16 +18,21 @@ from app.core.errors import ServiceUnavailableError from app.services.voucher_check.config import VoucherCheckEngineConfig _TZ = ZoneInfo("Asia/Shanghai") +_INVOICE_NO_RE = re.compile(r"^[A-Za-z0-9]{6,}$") _INVOICE_SQL = """ SELECT DISTINCT - TRIM(apa08) AS invoice_no, - TRUNC(apa09) AS invoice_date - FROM apa_file - WHERE apa09 >= :period_start - AND apa09 < :next_period_start - AND TRIM(apa08) IS NOT NULL - ORDER BY TRUNC(apa09), TRIM(apa08) + TRIM(oma10) AS invoice_no, + TRUNC(oma02) AS invoice_date + FROM oma_file + WHERE oma02 >= :period_start + AND oma02 < :next_period_start + AND REGEXP_LIKE(TRIM(oma10), '^[A-Za-z0-9]{6,}$') + AND TRIM(omaconf) = 'Y' + AND TRIM(omavoid) = 'N' + AND TRIM(oma64) = '1' + AND TRIM(oma00) IN ('11', '12', '13') + ORDER BY TRUNC(oma02), TRIM(oma10) """ @@ -37,6 +44,20 @@ class ErpInvoiceRow: invoice_date: date | None +def is_sales_invoice_no(value: str | None) -> bool: + """ + 判断 oma10 是否为可检核的销售发票号。 + 核心逻辑:TRIM 后至少 6 位字母或数字(如 6975101806、EWZZ26090002)。现场 oma10 是手工录入,常被填成 0、空值或中文备注,那些不能当 invoice。 + + Args: + value: oma10 原文。 + + Returns: + True 表示可作为检核主体。 + """ + return bool(_INVOICE_NO_RE.fullmatch(str(value or "").strip())) + + def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]: """ 按 Asia/Shanghai 计算当前自然月起止。 @@ -79,6 +100,64 @@ def previous_period_bounds(now: datetime | None = None) -> tuple[date, date, dat return period_month, current_month, period_start, next_start +def open_erp_connection(config: VoucherCheckEngineConfig): + """ + 打开立账凭证 Oracle 只读连接。 + 核心逻辑:复用 Text2SQL 的 Instant Client 初始化;超时单位毫秒。调用方必须 close。 + + Args: + config: 含 DSN/账号/超时的检核配置。 + + Returns: + oracledb 连接。 + + Raises: + ServiceUnavailableError: 驱动缺失或连接失败。 + """ + try: + import oracledb + except ImportError as exc: + raise ServiceUnavailableError( + "Oracle 驱动不可用", + code="VOUCHER_CHECK.ERP_UNAVAILABLE", + ) from exc + + from app.services.text2sql import Text2SQLService + + try: + Text2SQLService._init_oracle_client(oracledb) + connection = oracledb.connect( + user=config.erp_username, + password=config.erp_password, + dsn=config.erp_dsn, + ) + connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000 + return connection + except ServiceUnavailableError: + raise + except Exception as exc: + raise _erp_unavailable(config, exc) from exc + + +def _erp_unavailable(config: VoucherCheckEngineConfig, exc: BaseException) -> ServiceUnavailableError: + """把 Oracle 异常收成统一错误码,日志只记类型不记密码。""" + try: + from flask import current_app + + current_app.logger.error( + "[voucher-check] ERP query failed dsn=%s error_type=%s", + config.erp_dsn, + type(exc).__name__, + ) + except Exception: + pass + return ServiceUnavailableError( + "Oracle 查询失败", + code="VOUCHER_CHECK.ERP_UNAVAILABLE", + details={"error_type": type(exc).__name__}, + ) + + def fetch_month_invoices( config: VoucherCheckEngineConfig, *, @@ -86,6 +165,7 @@ def fetch_month_invoices( ) -> tuple[date, list[ErpInvoiceRow]]: """ 查询上一个自然月发票清单。 + 核心逻辑:从 oma_file 按帐款日期 oma02 取上月;发票号 oma10 须为至少 6 位字母或数字(排除 0、空值、中文备注);仅确认(omaconf='Y')、未作废(omavoid='N')、状况码 oma64='1'、帐款类别 oma00 为 11/12/13。 Args: config: 含 Oracle DSN/账号的检核配置。 @@ -98,26 +178,9 @@ def fetch_month_invoices( ServiceUnavailableError: Oracle 不可用。 """ period_month, _current_month, period_start, next_start = previous_period_bounds(now) - try: - import oracledb - except ImportError as exc: - raise ServiceUnavailableError( - "Oracle 驱动不可用", - code="VOUCHER_CHECK.ERP_UNAVAILABLE", - ) from exc - - from flask import current_app - from app.services.text2sql import Text2SQLService - connection = None try: - Text2SQLService._init_oracle_client(oracledb) - connection = oracledb.connect( - user=config.erp_username, - password=config.erp_password, - dsn=config.erp_dsn, - ) - connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000 + connection = open_erp_connection(config) cursor = connection.cursor() cursor.execute( _INVOICE_SQL, @@ -130,7 +193,7 @@ def fetch_month_invoices( seen: set[str] = set() for raw_no, raw_date in cursor: invoice_no = str(raw_no or "").strip() - if not invoice_no or invoice_no in seen: + if not is_sales_invoice_no(invoice_no) or invoice_no in seen: continue seen.add(invoice_no) invoice_date: date | None = None @@ -144,19 +207,7 @@ def fetch_month_invoices( except ServiceUnavailableError: raise except Exception as exc: - try: - current_app.logger.error( - "[voucher-check] ERP query failed dsn=%s error_type=%s", - config.erp_dsn, - type(exc).__name__, - ) - except Exception: - pass - raise ServiceUnavailableError( - "Oracle 查询失败", - code="VOUCHER_CHECK.ERP_UNAVAILABLE", - details={"error_type": type(exc).__name__}, - ) from exc + raise _erp_unavailable(config, exc) from exc finally: if connection is not None: try: diff --git a/backend/app/services/voucher_check/po_order/__init__.py b/backend/app/services/voucher_check/po_order/__init__.py new file mode 100644 index 00000000..79ea259f --- /dev/null +++ b/backend/app/services/voucher_check/po_order/__init__.py @@ -0,0 +1,25 @@ +""" +backend/app/services/voucher_check/po_order/__init__.py + +用途:立账凭证「PO订单」制式采购单 PDF 的对外入口。 +依赖:models、filename、save、publish。 +逻辑:调用方先组装 PoOrderDocument(ERP 取数见 erp_po_repository),save_po_order_pdf 只写本地; + publish_po_order_pdf 再上传。周检核 runner / erp_po_print.fetch 不要调用本包。 +""" + +from app.services.voucher_check.po_order.filename import build_po_order_filename +from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine, parse_po_order_document +from app.services.voucher_check.po_order.publish import PoOrderPublishResult, publish_po_order_pdf +from app.services.voucher_check.po_order.sample import sample_po_order_document +from app.services.voucher_check.po_order.save import save_po_order_pdf + +__all__ = [ + "PoOrderDocument", + "PoOrderLine", + "PoOrderPublishResult", + "build_po_order_filename", + "parse_po_order_document", + "publish_po_order_pdf", + "sample_po_order_document", + "save_po_order_pdf", +] diff --git a/backend/app/services/voucher_check/po_order/__main__.py b/backend/app/services/voucher_check/po_order/__main__.py new file mode 100644 index 00000000..1d6a40b4 --- /dev/null +++ b/backend/app/services/voucher_check/po_order/__main__.py @@ -0,0 +1,55 @@ +""" +backend/app/services/voucher_check/po_order/__main__.py + +用途:用给定 JSON、对照样张或 ERP 发票号生成 `{invoice}-{订单号}.pdf`。 +依赖:save_po_order_pdf、sample_po_order_document;--invoice 另依赖 Flask 配置与 erp_po_repository。 +逻辑:python -m app.services.voucher_check.po_order --out-dir DIR [--json FILE|--sample|--invoice NO] +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + + +def main(argv: list[str] | None = None) -> int: + """ + 命令行入口:JSON / 样张 / ERP 发票号 → 指定目录 PDF。 + 【AI 触发时机】需要出 PO 订单 PDF、且不走周检核时运行本模块。 + """ + parser = argparse.ArgumentParser(description="生成 PO 订单制式 PDF") + parser.add_argument("--out-dir", required=True, help="PDF 输出目录") + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--json", dest="json_path", help="采购单 JSON(含 invoice_no、po_no、lines)") + group.add_argument("--sample", action="store_true", help="使用对照样张数据") + group.add_argument("--invoice", help="从 ERP 按销售发票号取 TGHX 采购单(需应用配置)") + args = parser.parse_args(argv) + from app.services.voucher_check.po_order.save import save_po_order_pdf + + if args.sample: + from app.services.voucher_check.po_order.sample import sample_po_order_document + + documents = [sample_po_order_document()] + elif args.invoice: + from app import create_app + from app.services.voucher_check.config import load_engine_config + from app.services.voucher_check.erp_po_repository import fetch_po_documents_for_invoices + + app = create_app() + with app.app_context(): + documents = fetch_po_documents_for_invoices(load_engine_config(), [args.invoice]) + if not documents: + print("no purchase order for invoice", args.invoice, file=sys.stderr) + return 1 + else: + payload = json.loads(Path(args.json_path).read_text(encoding="utf-8")) + documents = [payload] + for document in documents: + print(save_po_order_pdf(document, args.out_dir)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/backend/app/services/voucher_check/po_order/assets/welltrust-logo.png b/backend/app/services/voucher_check/po_order/assets/welltrust-logo.png new file mode 100644 index 00000000..511754e0 Binary files /dev/null and b/backend/app/services/voucher_check/po_order/assets/welltrust-logo.png differ diff --git a/backend/app/services/voucher_check/po_order/filename.py b/backend/app/services/voucher_check/po_order/filename.py new file mode 100644 index 00000000..d12b222a --- /dev/null +++ b/backend/app/services/voucher_check/po_order/filename.py @@ -0,0 +1,50 @@ +""" +backend/app/services/voucher_check/po_order/filename.py + +用途:按销售 Profile 规则生成 PO 订单 PDF 文件名。 +依赖:core.errors.ValidationError。 +逻辑:固定 `{invoice}-{order_no}.pdf`;禁止路径字符,供落盘与后续目录扫描共用。 +""" + +from __future__ import annotations + +import re +from typing import Any + +from app.core.errors import ValidationError + +_UNSAFE_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f]|(\.\.)') + + +def build_po_order_filename(*, invoice_no: str, order_no: str) -> str: + """ + 生成 `{invoice号}-{订单号}.pdf`。 + 【AI 触发时机】保存或匹配 PO 订单 PDF 文件名时调用;不要自行拼接。 + + Args: + invoice_no: 销售 invoice,禁止空串与路径字符。 + order_no: 采购单号(po_no),禁止空串与路径字符。 + + Returns: + 仅文件名,不含目录。 + + Raises: + ValidationError: 缺号或含非法字符。 + """ + invoice = str(invoice_no or "").strip() + order = str(order_no or "").strip() + if not invoice: + raise ValidationError("缺少 invoice_no", code="VOUCHER_CHECK.PO_PDF_INVALID", details={"field": "invoice_no"}) + if not order: + raise ValidationError("缺少 po_no", code="VOUCHER_CHECK.PO_PDF_INVALID", details={"field": "po_no"}) + if _UNSAFE_RE.search(invoice) or _UNSAFE_RE.search(order): + raise ValidationError( + "invoice 或订单号含非法路径字符", + code="VOUCHER_CHECK.PO_PDF_INVALID", + details=_unsafe_details(invoice, order), + ) + return f"{invoice}-{order}.pdf" + + +def _unsafe_details(invoice: str, order: str) -> dict[str, Any]: + return {"invoice_no": invoice, "po_no": order} diff --git a/backend/app/services/voucher_check/po_order/fonts.py b/backend/app/services/voucher_check/po_order/fonts.py new file mode 100644 index 00000000..afe1c095 --- /dev/null +++ b/backend/app/services/voucher_check/po_order/fonts.py @@ -0,0 +1,70 @@ +""" +backend/app/services/voucher_check/po_order/fonts.py + +用途:为制式采购单注册中文字体。 +依赖:reportlab;可选环境变量 VOUCHER_CHECK_PO_FONT_PATH。 +逻辑:优先系统宋体/Noto CJK(Docker 已装 fonts-noto-cjk),失败再回退 CID STSong-Light。 +""" + +from __future__ import annotations + +import os +from pathlib import Path + +from reportlab.pdfbase import pdfmetrics +from reportlab.pdfbase.cidfonts import UnicodeCIDFont +from reportlab.pdfbase.ttfonts import TTFont + +_FONT_FAMILY = "VoucherPoCjk" +_CID_FALLBACK = "STSong-Light" +_REGISTERED: str | None = None + +_CANDIDATES: tuple[tuple[str, int], ...] = ( + (r"C:\Windows\Fonts\simsun.ttc", 0), + (r"C:\Windows\Fonts\simsun.ttf", 0), + (r"C:\Windows\Fonts\msyh.ttc", 0), + ("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 2), + ("/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf", 0), + ("/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc", 2), + ("/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc", 2), + ("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", 0), + ("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 0), +) + + +def resolve_po_font() -> str: + """ + 返回已注册的中文字体名,进程内只注册一次。 + 核心逻辑:VOUCHER_CHECK_PO_FONT_PATH → 常见系统字体 → CID 内置宋体。 + """ + global _REGISTERED + if _REGISTERED: + return _REGISTERED + + env_path = str(os.getenv("VOUCHER_CHECK_PO_FONT_PATH") or "").strip() + if env_path: + registered = _try_ttf(Path(env_path), 0) or _try_ttf(Path(env_path), 2) + if registered: + _REGISTERED = registered + return _REGISTERED + + for raw, index in _CANDIDATES: + registered = _try_ttf(Path(raw), index) + if registered: + _REGISTERED = registered + return _REGISTERED + + pdfmetrics.registerFont(UnicodeCIDFont(_CID_FALLBACK)) + _REGISTERED = _CID_FALLBACK + return _REGISTERED + + +def _try_ttf(path: Path, subfont_index: int) -> str | None: + """尝试把 TTF/TTC 注册为 VoucherPoCjk;文件不存在或 reportlab 拒收时返回 None。""" + if not path.is_file(): + return None + try: + pdfmetrics.registerFont(TTFont(_FONT_FAMILY, str(path), subfontIndex=subfont_index)) + return _FONT_FAMILY + except Exception: + return None diff --git a/backend/app/services/voucher_check/po_order/models.py b/backend/app/services/voucher_check/po_order/models.py new file mode 100644 index 00000000..8b35c0be --- /dev/null +++ b/backend/app/services/voucher_check/po_order/models.py @@ -0,0 +1,162 @@ +""" +backend/app/services/voucher_check/po_order/models.py + +用途:制式采购单 PDF 的给定数据结构(与 ERP 查询解耦)。 +依赖:core.errors.ValidationError。 +逻辑:独立抓取任务拿到 invoice + PO 明细后填入本模型;renderer 只消费这些字段。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Mapping + +from app.core.errors import ValidationError + + +def _as_text(value: Any) -> str: + """把给定值收成版面用字符串,None 当空串。""" + if value is None: + return "" + return str(value).strip() + + +def _po_invalid(message: str, *, details: dict[str, Any] | None = None) -> ValidationError: + return ValidationError(message, code="VOUCHER_CHECK.PO_PDF_INVALID", details=details or {}) + + +@dataclass(frozen=True) +class PoOrderLine: + """采购单明细行;金额/数量已格式化成展示字符串,渲染层不再重算。""" + + seq: str + item_no: str + name: str = "" + spec: str = "" + extra_spec: str = "" + qty: str = "" + unit: str = "" + arrive: str = "" + origin_no: str = "" + version: str = "" + untax_price: str = "" + tax_price: str = "" + untax_amt: str = "" + tax_amt: str = "" + halogen: str = "" + vendor_item: str = "" + + +@dataclass(frozen=True) +class PoOrderDocument: + """ + 一张采购单的给定数据。 + invoice_no 只用于文件名 `{invoice}-{po_no}.pdf`,不印在 Crystal 风格版面上。 + """ + + invoice_no: str + po_no: str + po_date: str = "" + po_type: str = "" + pay_term: str = "" + tax_type: str = "" + price_term: str = "" + currency: str = "" + ship_address: str = "" + bill_address: str = "" + vendor_code: str = "" + vendor_name: str = "" + vendor_tel: str = "" + vendor_fax: str = "" + vendor_addr: str = "" + company_name: str = "" + company_address: str = "" + company_phone: str = "" + company_fax: str = "" + maker: str = "" + untax_total: str = "" + tax_total: str = "" + lines: tuple[PoOrderLine, ...] = field(default_factory=tuple) + + +def parse_po_order_document(payload: Mapping[str, Any]) -> PoOrderDocument: + """ + 把给定 dict/JSON 收成 PoOrderDocument。 + 【AI 触发时机】调用方已从 ERP 或手工 JSON 拿到采购单字段、要生成 PDF 之前调用。 + + 核心逻辑:只做必填校验与类型收口,不查库、不补默认公司名。 + + Args: + payload: 须含 invoice_no、po_no;lines 为明细列表。其余键与样张字段同名。 + + Returns: + 可交给 save_po_order_pdf 的冻结文档。 + + Raises: + ValidationError: invoice / 订单号缺失。 + """ + if not isinstance(payload, Mapping): + raise _po_invalid("采购单数据必须是对象") + invoice_no = _as_text(payload.get("invoice_no") or payload.get("invoice")) + po_no = _as_text(payload.get("po_no") or payload.get("order_no")) + if not invoice_no: + raise _po_invalid("缺少 invoice_no", details={"field": "invoice_no"}) + if not po_no: + raise _po_invalid("缺少 po_no", details={"field": "po_no"}) + + raw_lines = payload.get("lines") or [] + if raw_lines and not isinstance(raw_lines, list): + raise _po_invalid("lines 必须是数组", details={"field": "lines"}) + + lines: list[PoOrderLine] = [] + for index, raw in enumerate(raw_lines): + if not isinstance(raw, Mapping): + raise _po_invalid("明细行必须是对象", details={"field": "lines", "index": index}) + seq = _as_text(raw.get("seq") or raw.get("item_seq") or (index + 1)) + item_no = _as_text(raw.get("item_no") or raw.get("part_no")) + lines.append( + PoOrderLine( + seq=seq, + item_no=item_no, + name=_as_text(raw.get("name")), + spec=_as_text(raw.get("spec")), + extra_spec=_as_text(raw.get("extra_spec")), + qty=_as_text(raw.get("qty")), + unit=_as_text(raw.get("unit")), + arrive=_as_text(raw.get("arrive") or raw.get("arrive_date")), + origin_no=_as_text(raw.get("origin_no")), + version=_as_text(raw.get("version")), + untax_price=_as_text(raw.get("untax_price")), + tax_price=_as_text(raw.get("tax_price")), + untax_amt=_as_text(raw.get("untax_amt")), + tax_amt=_as_text(raw.get("tax_amt")), + halogen=_as_text(raw.get("halogen")), + vendor_item=_as_text(raw.get("vendor_item")), + ) + ) + + return PoOrderDocument( + invoice_no=invoice_no, + po_no=po_no, + po_date=_as_text(payload.get("po_date")), + po_type=_as_text(payload.get("po_type")), + pay_term=_as_text(payload.get("pay_term")), + tax_type=_as_text(payload.get("tax_type")), + price_term=_as_text(payload.get("price_term")), + currency=_as_text(payload.get("currency")), + ship_address=_as_text(payload.get("ship_address")), + bill_address=_as_text(payload.get("bill_address")), + vendor_code=_as_text(payload.get("vendor_code")), + vendor_name=_as_text(payload.get("vendor_name")), + vendor_tel=_as_text(payload.get("vendor_tel")), + vendor_fax=_as_text(payload.get("vendor_fax")), + vendor_addr=_as_text(payload.get("vendor_addr")), + company_name=_as_text(payload.get("company_name")), + company_address=_as_text(payload.get("company_address")), + company_phone=_as_text(payload.get("company_phone")), + company_fax=_as_text(payload.get("company_fax")), + maker=_as_text(payload.get("maker")), + untax_total=_as_text(payload.get("untax_total")), + tax_total=_as_text(payload.get("tax_total")), + lines=tuple(lines), + ) diff --git a/backend/app/services/voucher_check/po_order/publish.py b/backend/app/services/voucher_check/po_order/publish.py new file mode 100644 index 00000000..b50e448b --- /dev/null +++ b/backend/app/services/voucher_check/po_order/publish.py @@ -0,0 +1,93 @@ +""" +backend/app/services/voucher_check/po_order/publish.py + +用途:生成制式采购单 PDF 并上传到文档库当月「PO订单」目录。 +依赖:save_po_order_pdf、SalesDmsClient、filename。 +逻辑:先本地渲染,再 Attachment/Upload + CreateFiles;同名跳过。不进周检核 runner。 +""" + +from __future__ import annotations + +import tempfile +from dataclasses import dataclass +from datetime import date +from pathlib import Path +from typing import Any, Mapping + +from app.services.voucher_check.adapters.base import ScannedFile +from app.services.voucher_check.dms_client import SalesDmsClient +from app.services.voucher_check.filename_match import match_filename +from app.services.voucher_check.po_order.filename import build_po_order_filename +from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document +from app.services.voucher_check.po_order.save import save_po_order_pdf + +PO_TYPE_FOLDER = "PO订单" +PO_FILENAME_TEMPLATE = "{invoice}-{order_no}.pdf" + + +@dataclass(frozen=True) +class PoOrderPublishResult: + """一次制式采购单落库结果。""" + + file: ScannedFile + skipped_same_name: bool + + +def publish_po_order_pdf( + document: PoOrderDocument | Mapping[str, Any], + *, + period_month: date, + type_folder: str = PO_TYPE_FOLDER, +) -> PoOrderPublishResult: + """ + 生成 `{invoice}-{订单号}.pdf` 并上传到销售开票附件/{年}/{月}/PO订单/。 + 【AI 触发时机】已拿到给定采购单数据、需要写入文档库类型目录时调用。 + 不要在周检核 runner 里调用。ERP 取数由 fetch_po_documents_for_invoices 或调用方完成。 + + 核心逻辑:渲染到临时文件 → 确保年/月/PO订单目录 → 同名跳过否则 Upload+CreateFiles。 + + Args: + document: PoOrderDocument 或同结构 dict。 + period_month: 类型目录所属自然月(用其年、月两位文件夹名)。 + type_folder: 默认「PO订单」,须与销售 Profile 一致。 + + Returns: + 文档库中的文件元数据;skipped_same_name 表示沿用已有同名文件。 + """ + payload = document if isinstance(document, PoOrderDocument) else parse_po_order_document(document) + filename = build_po_order_filename(invoice_no=payload.invoice_no, order_no=payload.po_no) + if match_filename(filename, template=PO_FILENAME_TEMPLATE, invoice_no=payload.invoice_no) is None: + from app.core.errors import ValidationError + + raise ValidationError("生成的文件名不符合 {invoice}-{订单号}.pdf", code="VOUCHER_CHECK.PO_PDF_INVALID") + + SalesDmsClient.ensure_configured() + yyyy = f"{period_month.year:04d}" + mm = f"{period_month.month:02d}" + folder_path = f"销售开票附件/{yyyy}/{mm}/{type_folder}" + folder_id = SalesDmsClient.ensure_period_type_folder(period_month=period_month, type_folder=type_folder) + + with tempfile.TemporaryDirectory(prefix="hxops-po-") as tmp: + local_path = save_po_order_pdf(payload, tmp, overwrite=True) + content = Path(local_path).read_bytes() + + row, skipped = SalesDmsClient.upload_file_skip_same_name( + parent_folder_id=folder_id, + leaf_name=filename, + content=content, + ) + item_id = str(row.get("ID") or "").strip() or None + return PoOrderPublishResult( + file=ScannedFile( + filename=str(row.get("LeafName") or filename).strip() or filename, + item_id=item_id, + folder_id=folder_id, + path=str(row.get("Path") or f"{folder_path}/{filename}"), + extra={ + "skipped_same_name": skipped, + "version_id": row.get("VersionID"), + "type_folder": type_folder, + }, + ), + skipped_same_name=skipped, + ) diff --git a/backend/app/services/voucher_check/po_order/renderer.py b/backend/app/services/voucher_check/po_order/renderer.py new file mode 100644 index 00000000..39e216ee --- /dev/null +++ b/backend/app/services/voucher_check/po_order/renderer.py @@ -0,0 +1,343 @@ +""" +backend/app/services/voucher_check/po_order/renderer.py + +用途:按已确认的 Crystal / apmr900 对照样张画出制式采购单 PDF。 +依赖:reportlab、fonts、models、页眉 Logo。 +逻辑:无满格单元格;项次最左;表头三行折行;不查询 ERP。多页时续页只重复页眉与表头。 +""" + +from __future__ import annotations + +from pathlib import Path + +from reportlab.lib.colors import HexColor +from reportlab.lib.pagesizes import A4 +from reportlab.lib.units import mm +from reportlab.pdfgen import canvas + +from app.services.voucher_check.po_order.fonts import resolve_po_font +from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine + +INK = HexColor("#111111") +LINE = HexColor("#333333") +DEFAULT_LOGO = Path(__file__).resolve().parent / "assets" / "welltrust-logo.png" +ROW_H = 13 * mm +HEADER_H = 11 * mm +FOOT_Y = 18 * mm +TOTALS_H = 16 * mm + + +def render_po_order_pdf(document: PoOrderDocument, out_path: Path, *, logo_path: Path | None = None) -> None: + """ + 把给定采购单画到 out_path(调用方已定文件名)。 + 核心逻辑:先分页再逐页绘制,避免明细把合计和签核挤出页外。 + """ + font = resolve_po_font() + out_path.parent.mkdir(parents=True, exist_ok=True) + page_w, page_h = A4 + left = 16 * mm + right = page_w - 16 * mm + pages = _paginate(document.lines, page_h) + page_count = len(pages) + c = canvas.Canvas(str(out_path), pagesize=A4) + c.setTitle(f"采购单 {document.po_no}") + c.setAuthor("HXOPS") + logo = logo_path if logo_path is not None else DEFAULT_LOGO + for index, page_lines in enumerate(pages): + page_no = f"{index + 1}/{page_count}" + is_last = index == page_count - 1 + _draw_page( + c, + document=document, + lines=page_lines, + font=font, + left=left, + right=right, + page_h=page_h, + page_no=page_no, + show_po_fields=(index == 0), + show_totals=is_last, + logo_path=logo, + ) + c.showPage() + c.save() + + +def _paginate(lines: tuple[PoOrderLine, ...], page_h: float) -> list[list[PoOrderLine]]: + """按版心高度切页;末页预留合计高度。""" + remaining = list(lines) + pages: list[list[PoOrderLine]] = [] + first = True + if not remaining: + return [[]] + while remaining: + last_max = _max_rows(page_h, first_page=first, last_page=True) + if len(remaining) <= last_max: + pages.append(remaining) + break + # 留至少一行给末页,避免把合计画进已排满的页。 + max_rows = _max_rows(page_h, first_page=first, last_page=False) + take = min(max(1, max_rows), len(remaining) - 1) + pages.append(remaining[:take]) + remaining = remaining[take:] + first = False + return pages or [[]] + + +def _max_rows(page_h: float, *, first_page: bool, last_page: bool) -> int: + """估算一页能放下的明细行数。""" + header_block = 86 * mm if first_page else 42 * mm + reserved = FOOT_Y + 8 * mm + HEADER_H + if last_page: + reserved += TOTALS_H + usable = page_h - header_block - reserved + return max(1, int(usable // ROW_H)) + + +def _draw_page( + c: canvas.Canvas, + *, + document: PoOrderDocument, + lines: list[PoOrderLine], + font: str, + left: float, + right: float, + page_h: float, + page_no: str, + show_po_fields: bool, + show_totals: bool, + logo_path: Path, +) -> None: + y = page_h - 10 * mm + y = _draw_letterhead(c, document, font, left, right, y, page_no, logo_path) + if show_po_fields: + y = _draw_po_fields(c, document, font, left, right, y) + else: + y -= 4 * mm + _hline(c, left, right, y, 0.8) + y -= 1 * mm + y = _draw_table_header(c, font, left, right, y) + y = _draw_table_rows(c, lines, font, left, y) + if show_totals: + _draw_totals(c, document, font, left, y) + _draw_footer(c, font, left, right) + + +def _draw_letterhead( + c: canvas.Canvas, + document: PoOrderDocument, + font: str, + left: float, + right: float, + y: float, + page_no: str, + logo_path: Path, +) -> float: + """Logo 在左;右侧公司名、「采购单」、地址、电话;制表者/页次下一行靠右。""" + logo_w = 52 * mm + logo_h = 14 * mm + logo_bottom = y - logo_h + if logo_path.is_file(): + c.drawImage( + str(logo_path), + left, + logo_bottom, + width=logo_w, + height=logo_h, + mask="auto", + preserveAspectRatio=True, + anchor="sw", + ) + text_x = left + 56 * mm + block_mid = (text_x + right) / 2 + _text(c, font, block_mid, y - 3.5 * mm, document.company_name, 11, centre=True) + _text(c, font, block_mid, y - 8.2 * mm, "采购单", 10, centre=True) + fax = document.company_fax or "" + _text(c, font, text_x, y - 13 * mm, f"地址:{document.company_address}", 8) + _text(c, font, text_x, y - 17.5 * mm, f"公司电话:{document.company_phone} 公司传真:{fax}", 8) + _text(c, font, right - 52 * mm, y - 22.5 * mm, f"制表者: {document.maker}", 8) + _text(c, font, right, y - 22.5 * mm, f"页次: {page_no}", 8, right_align=True) + y = min(logo_bottom, y - 24 * mm) - 2 * mm + _hline(c, left, right, y, 0.8) + return y - 6 * mm + + +def _draw_po_fields( + c: canvas.Canvas, + document: PoOrderDocument, + font: str, + left: float, + right: float, + y: float, +) -> float: + """左栏采购单号、右栏采购日期,与对照样张一致。""" + col2 = left + 98 * mm + val1 = left + 22 * mm + val2 = col2 + 20 * mm + po_label = f"{document.po_no} {document.po_type}".rstrip() + _text(c, font, left, y, "采购单号:") + _text(c, font, val1, y, po_label) + _text(c, font, col2, y, "采购日期:") + _text(c, font, val2, y, document.po_date) + y -= 5.2 * mm + _text(c, font, left, y, "付款条件:") + _text(c, font, val1, y, document.pay_term) + _text(c, font, col2, y, "税 种:") + _text(c, font, val2, y, document.tax_type) + y -= 5.2 * mm + _text(c, font, left, y, "价格条件:") + _text(c, font, val1, y, document.price_term) + _text(c, font, col2, y, "币 种:") + _text(c, font, val2, y, document.currency) + y -= 5.2 * mm + _text(c, font, left, y, "送货地址:") + _text(c, font, val1, y, document.ship_address or " ") + y -= 5.2 * mm + _text(c, font, left, y, "帐单地址:") + _text(c, font, val1, y, document.bill_address or " ") + y -= 6 * mm + _text(c, font, left, y, "供应厂商:") + _text(c, font, val1, y, f"{document.vendor_code} {document.vendor_name}".strip()) + _text(c, font, left + 118 * mm, y, f"Tel: {document.vendor_tel}") + y -= 5 * mm + _text(c, font, val1, y, document.vendor_addr, 8) + _text(c, font, left + 118 * mm, y, f"Fax: {document.vendor_fax}") + y -= 4 * mm + _hline(c, left, right, y, 0.8) + return y - 1 * mm + + +def _table_columns(left: float) -> dict[str, float]: + return { + "seq": left, + "item": left + 8 * mm, + "origin": left + 50 * mm, + "arrive": left + 80 * mm, + "qty": left + 108 * mm, + "unit": left + 116 * mm, + "price": left + 142 * mm, + "amt": left + 164 * mm, + "halo": left + 168 * mm, + } + + +def _draw_table_header(c: canvas.Canvas, font: str, left: float, right: float, y: float) -> float: + """Crystal 风格:无竖格,表头三行折行,项次最左。""" + cols = _table_columns(left) + table_top = y + _hline(c, left, right, table_top, 0.7) + h1 = table_top - 3.6 * mm + h2 = table_top - 7.0 * mm + h3 = table_top - 10.2 * mm + _text(c, font, cols["seq"], h1, "项次", 7) + _text(c, font, cols["item"], h1, "料件编号", 7) + _text(c, font, cols["item"], h2, "品名/规格", 7) + _text(c, font, cols["item"], h3, "厂商料号额外品名规格说明", 6.5) + _text(c, font, cols["origin"], h1, "原始编号", 7) + _text(c, font, cols["origin"], h2, "版本", 7) + _text(c, font, cols["origin"], h3, "行序", 6.5) + _text(c, font, cols["arrive"], h1, "到货日", 7) + _text(c, font, cols["qty"] - 8 * mm, h1, "数 量", 7) + _text(c, font, cols["unit"], h1, "单 位", 7) + _text(c, font, cols["price"], h1, "税前单价", 7, right_align=True) + _text(c, font, cols["price"], h2, "含税单价", 7, right_align=True) + _text(c, font, cols["amt"], h1, "税前金额", 7, right_align=True) + _text(c, font, cols["amt"], h2, "含税金额", 7, right_align=True) + _text(c, font, cols["halo"], h1, "卤素", 7) + _text(c, font, cols["halo"], h2, "管控", 7) + _text(c, font, cols["halo"] + 10 * mm, h1, "环保", 7) + _text(c, font, cols["halo"] + 10 * mm, h2, "等级", 7) + c.setStrokeColor(LINE) + c.setLineWidth(0.4) + c.line(cols["price"] - 22 * mm, h2 - 1.2 * mm, cols["price"], h2 - 1.2 * mm) + c.line(cols["amt"] - 22 * mm, h2 - 1.2 * mm, cols["amt"], h2 - 1.2 * mm) + y = table_top - HEADER_H + _hline(c, left, right, y, 0.5) + return y + + +def _draw_table_rows(c: canvas.Canvas, lines: list[PoOrderLine], font: str, left: float, y: float) -> float: + """每笔三行:料号/品名/规格,无斑马底、无竖线格。""" + cols = _table_columns(left) + for line in lines: + r1 = y - 3.8 * mm + r2 = y - 7.6 * mm + r3 = y - 11.2 * mm + _text(c, font, cols["seq"], r1, line.seq, 8) + _text(c, font, cols["item"], r1, line.item_no, 8) + _text(c, font, cols["item"], r2, line.name, 8) + _text(c, font, cols["item"], r3, line.spec or line.extra_spec, 8) + _text(c, font, cols["origin"], r1, line.vendor_item, 8) + origin_second = line.origin_no or line.version + _text(c, font, cols["origin"], r2, origin_second, 8) + _text(c, font, cols["arrive"], r1, line.arrive, 8) + _text(c, font, cols["qty"], r1, line.qty, 8, right_align=True) + _text(c, font, cols["unit"], r1, line.unit, 8) + _text(c, font, cols["price"], r1, line.untax_price, 8, right_align=True) + _text(c, font, cols["price"], r2, line.tax_price, 8, right_align=True) + _text(c, font, cols["amt"], r1, line.untax_amt, 8, right_align=True) + _text(c, font, cols["amt"], r2, line.tax_amt, 8, right_align=True) + _text(c, font, cols["halo"], r1, line.halogen, 8) + y -= ROW_H + return y + + +def _draw_totals(c: canvas.Canvas, document: PoOrderDocument, font: str, left: float, y: float) -> None: + """合计靠右,金额带细框。""" + cols = _table_columns(left) + y -= 6 * mm + box_w = 22 * mm + box_h = 4.6 * mm + _text(c, font, cols["price"] - 28 * mm, y, "税前金额总和:", 8) + _rect(c, cols["amt"] - box_w, y - 1.2 * mm, box_w, box_h) + _text(c, font, cols["amt"] - 1.2 * mm, y, document.untax_total, 8, right_align=True) + y -= 6 * mm + _text(c, font, cols["price"] - 28 * mm, y, "含税金额总和:", 8) + _rect(c, cols["amt"] - box_w, y - 1.2 * mm, box_w, box_h) + _text(c, font, cols["amt"] - 1.2 * mm, y, document.tax_total, 8, right_align=True) + + +def _draw_footer(c: canvas.Canvas, font: str, left: float, right: float) -> None: + """核准/审核/经办横排;线左 (apmr900)、线右 (结束)。""" + span = right - left + _text(c, font, left + 10 * mm, FOOT_Y + 5 * mm, "核准", 10) + _text(c, font, left + span / 2, FOOT_Y + 5 * mm, "审核", 10, centre=True) + _text(c, font, right - 10 * mm, FOOT_Y + 5 * mm, "经办", 10, right_align=True) + _hline(c, left, right, FOOT_Y, 0.7) + _text(c, font, left, FOOT_Y - 1.1 * mm, "(apmr900)", 8) + _text(c, font, right, FOOT_Y - 1.1 * mm, "(结束)", 8, right_align=True) + + +def _text( + c: canvas.Canvas, + font: str, + x: float, + y: float, + text: str, + size: float = 9, + *, + colour=INK, + right_align: bool = False, + centre: bool = False, +) -> None: + c.setFillColor(colour) + c.setFont(font, size) + value = text or "" + if centre: + c.drawCentredString(x, y, value) + elif right_align: + c.drawRightString(x, y, value) + else: + c.drawString(x, y, value) + + +def _hline(c: canvas.Canvas, x1: float, x2: float, y: float, width: float = 0.4) -> None: + c.setStrokeColor(LINE) + c.setLineWidth(width) + c.line(x1, y, x2, y) + + +def _rect(c: canvas.Canvas, x: float, y: float, w: float, h: float) -> None: + c.setStrokeColor(LINE) + c.setLineWidth(0.5) + c.rect(x, y, w, h, stroke=1, fill=0) diff --git a/backend/app/services/voucher_check/po_order/sample.py b/backend/app/services/voucher_check/po_order/sample.py new file mode 100644 index 00000000..4427fb6c --- /dev/null +++ b/backend/app/services/voucher_check/po_order/sample.py @@ -0,0 +1,79 @@ +""" +backend/app/services/voucher_check/po_order/sample.py + +用途:对照 apmr900 原件的样张数据,供单测与本地出样,不是正式业务数据。 +依赖:models.parse_po_order_document。 +逻辑:字段来自 e:\\Work\\Agent\\立账凭证\\采购单.pdf;invoice_no 仅用于文件名演示。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document + +SAMPLE_PO_ORDER_PAYLOAD: dict[str, Any] = { + "invoice_no": "INV-SAMPLE", + "company_phone": "0512-63136988", + "company_fax": "", + "company_address": "江苏省苏州市吴江区经济开发区山湖西路789号", + "company_name": "苏州和信精密科技有限公司", + "maker": "AI", + "po_date": "2016/5/28", + "po_no": "5201-1605280003", + "po_type": "原料采购单", + "price_term": "A01 取核价单价", + "ship_address": "", + "pay_term": "月结一个月", + "tax_type": "进项(17%含税)", + "currency": "RMB", + "bill_address": "", + "vendor_name": "北川科技(苏州)有限公司", + "vendor_code": "VCCD00013", + "vendor_tel": "0512-62810369", + "vendor_fax": "0512-62810368", + "vendor_addr": "苏州市工业园区胜浦分区银胜路61号", + "untax_total": "4,455.50", + "tax_total": "5,212.94", + "lines": [ + { + "item_no": "3450541801", + "seq": "1", + "qty": "730", + "unit": "PCS", + "arrive": "2016/6/16", + "untax_price": "3.350000", + "untax_amt": "2,445.50", + "halogen": "RoHS", + "name": "FRAME CUBE CORNER", + "spec": "H20*W36.5*L36.7", + "tax_price": "3.919500", + "tax_amt": "2,861.24", + "origin_no": "3301-1605260004", + "version": "-0001", + "vendor_item": "3450541801", + }, + { + "item_no": "3450541801", + "seq": "2", + "qty": "600", + "unit": "PCS", + "arrive": "2016/6/16", + "untax_price": "3.350000", + "untax_amt": "2,010.00", + "halogen": "RoHS", + "name": "FRAME CUBE CORNER", + "spec": "H20*W36.5*L36.7", + "tax_price": "3.919500", + "tax_amt": "2,351.70", + "origin_no": "3301-1605100007", + "version": "-0001", + "vendor_item": "3450541801", + }, + ], +} + + +def sample_po_order_document() -> PoOrderDocument: + """返回对照样张用的采购单数据;正式任务必须改用真实给定数据。""" + return parse_po_order_document(SAMPLE_PO_ORDER_PAYLOAD) diff --git a/backend/app/services/voucher_check/po_order/save.py b/backend/app/services/voucher_check/po_order/save.py new file mode 100644 index 00000000..fc05b07b --- /dev/null +++ b/backend/app/services/voucher_check/po_order/save.py @@ -0,0 +1,46 @@ +""" +backend/app/services/voucher_check/po_order/save.py + +用途:根据给定采购单数据生成 PDF,并按 `{invoice}-{订单号}.pdf` 保存到本地。 +依赖:filename、models、renderer。 +逻辑:不查 ERP。上传文档库请用 publish_po_order_pdf。周检核 runner 不要调用。 +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Mapping + +from app.services.voucher_check.po_order.filename import build_po_order_filename +from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document +from app.services.voucher_check.po_order.renderer import render_po_order_pdf + + +def save_po_order_pdf( + document: PoOrderDocument | Mapping[str, Any], + output_dir: str | Path, + *, + overwrite: bool = True, +) -> Path: + """ + 生成制式采购单 PDF 并保存。 + 【AI 触发时机】已拿到销售 invoice 与一张 PO 的给定字段、需要落盘 PDF 时调用。 + 不要在周检核 runner 里调用。ERP 取数见 erp_po_repository.fetch_po_documents_for_invoices。 + + 核心逻辑:解析/校验文档 → `{invoice}-{po_no}.pdf` → Crystal 风格渲染到 output_dir。 + + Args: + document: PoOrderDocument 或同结构 dict(须含 invoice_no、po_no)。 + output_dir: 本地目录;不存在则创建。上传文档库请改用 publish_po_order_pdf。 + overwrite: 为 False 且目标已存在时直接返回现有路径,不覆盖。 + + Returns: + 生成(或已存在)的 PDF 绝对路径。 + """ + payload = document if isinstance(document, PoOrderDocument) else parse_po_order_document(document) + filename = build_po_order_filename(invoice_no=payload.invoice_no, order_no=payload.po_no) + target = Path(output_dir).expanduser().resolve() / filename + if target.exists() and not overwrite: + return target + render_po_order_pdf(payload, target) + return target diff --git a/backend/app/services/voucher_check/profiles/sales.py b/backend/app/services/voucher_check/profiles/sales.py index 0c24e95c..08ad91ec 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;erp_po_print / oa_sales_release 仅登记,不在周二 runner 调用。 +逻辑:周任务扫描 source_type=directory_scan;subject_adapter=hxjm_apa 实际查 oma_file;erp_po_print.fetch / oa_sales_release 仅登记,不在周二 runner 调用。PO 独立抓取走 fetch_documents。 """ from __future__ import annotations diff --git a/backend/app/services/voucher_check/runner.py b/backend/app/services/voucher_check/runner.py index 9d99991d..6fa9b68c 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 / oa_sales_release;命中文件复制到所有归档,同名跳过仍记 archived。 +逻辑:不调用 erp_po_print.fetch / oa_sales_release.fetch;命中文件复制到所有归档,同名跳过仍记 archived。 """ from __future__ import annotations diff --git a/backend/requirements.txt b/backend/requirements.txt index fc797896..e62f110a 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -29,6 +29,8 @@ pillow==11.3.0 numpy==2.3.3 pypdf==6.1.0 pypdfium2==5.0.0 +# 立账凭证制式采购单 PDF(Crystal/apmr900 对照版式);不替代 pypdf 的读/合并能力。 +reportlab==4.4.3 python-pptx==1.0.2 beautifulsoup4==4.14.2 lxml==6.0.2 diff --git a/backend/tests/voucher_check/test_engine_profile_and_scan.py b/backend/tests/voucher_check/test_engine_profile_and_scan.py index 1a40fcf8..e3a43401 100644 --- a/backend/tests/voucher_check/test_engine_profile_and_scan.py +++ b/backend/tests/voucher_check/test_engine_profile_and_scan.py @@ -3,7 +3,7 @@ backend/tests/voucher_check/test_engine_profile_and_scan.py 用途:销售一期引擎的期间、命名匹配、缺件双口径、Adapter 占位与目录扫描单测。 依赖:pytest;不连 Oracle / 文档库。 -逻辑:覆盖上月边界、六类文件名、同一 invoice 多缺件、PO/OA 未接线。 +逻辑:覆盖上月边界、oma_file 发票 SQL、六类文件名、同一 invoice 多缺件、PO fetch()/OA 仍未接线。 """ from __future__ import annotations @@ -18,11 +18,39 @@ from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryS from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter from app.services.voucher_check.aggregator import aggregate_file_results -from app.services.voucher_check.erp_repository import previous_period_bounds +from app.services.voucher_check.erp_repository import _INVOICE_SQL, is_sales_invoice_no, previous_period_bounds from app.services.voucher_check.filename_match import first_match, match_filename from app.services.voucher_check.profiles.sales import SALES_PROFILE, required_file_rules +def test_invoice_sql_reads_confirmed_oma_file(): + """销售 invoice 清单来自 oma_file:已确认、未作废、状况码 1、帐款类别 11/12/13;oma10 至少 6 位字母或数字。""" + sql = " ".join(_INVOICE_SQL.split()) + assert "FROM oma_file" in sql + assert "TRIM(oma10)" in sql + assert "TRUNC(oma02)" in sql + assert "REGEXP_LIKE(TRIM(oma10), '^[A-Za-z0-9]{6,}$')" in sql + assert "TRIM(omaconf) = 'Y'" in sql + assert "TRIM(omavoid) = 'N'" in sql + assert "TRIM(oma64) = '1'" in sql + assert "TRIM(oma00) IN ('11', '12', '13')" in sql + assert "apa_file" not in sql + assert "apa08" not in sql + + +def test_sales_invoice_no_rejects_placeholder_and_chinese(): + """正规发票号为至少 6 位字母或数字;0、空值、中文备注不能进主体清单。""" + assert is_sales_invoice_no("6975101806") is True + assert is_sales_invoice_no("394522129") is True + assert is_sales_invoice_no("EWZZ26090002") is True + assert is_sales_invoice_no("ewzz26090006") is True + assert is_sales_invoice_no("0") is False + assert is_sales_invoice_no("泰国HUB仓出货") is False + assert is_sales_invoice_no("") is False + assert is_sales_invoice_no(" ") is False + assert is_sales_invoice_no(None) is False + + def test_previous_period_bounds_from_early_september(): """周二跑批时检核上个月;2026-09-01 应得到 2026-08。""" now = datetime(2026, 9, 1, 6, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai")) diff --git a/backend/tests/voucher_check/test_erp_po_repository.py b/backend/tests/voucher_check/test_erp_po_repository.py new file mode 100644 index 00000000..af732eac --- /dev/null +++ b/backend/tests/voucher_check/test_erp_po_repository.py @@ -0,0 +1,307 @@ +""" +backend/tests/voucher_check/test_erp_po_repository.py + +用途:HXJM.oma99 → TGHX.pmm99 采购单取数与字段映射。 +依赖:pytest;不连 Oracle。 +逻辑:断言 TRIM 关联、oma99 空走 oga/oea、到货日 pmn34、周检核 fetch 仍未接线。 +""" + +from __future__ import annotations + +from datetime import date +from types import SimpleNamespace + +import pytest + +from app.core.errors import ServiceUnavailableError +from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter +from app.services.voucher_check.erp_po_repository import ( + INVOICE_SCHEMA, + PO_SCHEMA, + _po_detail_sql, + fetch_po_documents_for_invoices, + map_po_document, + resolve_invoice_flows, +) + +pytestmark = pytest.mark.pure_unit + + +class _NamedCursor: + """按 SQL 关键字返回带列名的预制行。""" + + def __init__(self, scripts: dict[str, tuple[list[str], list[tuple]]]): + self.scripts = scripts + self.executed: list[tuple[str, dict | None]] = [] + self.description: list[tuple[str]] = [] + self._rows: list[tuple] = [] + + def execute(self, sql: str, params=None): + self.executed.append((sql, params)) + compact = " ".join(sql.split()).upper() + for needle, (columns, rows) in self.scripts.items(): + if needle.upper() in compact: + self.description = [(name,) for name in columns] + self._rows = list(rows) + return + raise AssertionError(f"unexpected sql: {sql}") + + def __iter__(self): + return iter(self._rows) + + +def _config(): + return SimpleNamespace(erp_dsn="host/db", erp_username="ro", erp_password="x", erp_timeout_seconds=5) + + +_OMA_COLS = ["invoice_no", "oma00", "oma16", "oma99"] +_FLOW_COLS = ["doc_no", "flow_no"] + + +def test_po_sql_targets_tghx_and_trims_flow_no(): + """采购单必须查 TGHX,并用 TRIM(pmm99) 对多角序号。""" + sql = " ".join(_po_detail_sql(":flow0").split()) + assert f"FROM {PO_SCHEMA}.pmm_file" in sql + assert f"{PO_SCHEMA}.pmn_file" in sql + assert "TRIM(pmm.pmm99) IN" in sql + assert "TRIM(pmm.pmm18) != 'X'" in sql + assert "TRIM(pmm.pmmacti) = 'Y'" in sql + assert "BKR" in sql + assert "pmn34" in sql + assert INVOICE_SCHEMA not in sql + + +def test_map_po_document_uses_pmn34_and_sample_like_fields(): + """到货日用 pmn34;环保等级 RoHS;原始编号优先 ta_ima11。""" + document = map_po_document( + "EWZZ26090002", + [ + { + "po_no": "5220-2609010001", + "po_date": date(2026, 9, 1), + "po_type": "原料采购单", + "pay_term": "月结一个月", + "tax_type": "进项(17%含税)", + "price_term_code": "A01", + "price_term_name": "取核价单价", + "currency": "RMB", + "vendor_code": "V001", + "vendor_name": "测试厂", + "vendor_tel": "0512-1", + "vendor_fax": "0512-2", + "vendor_addr": "苏州", + "ship031": "送货路", + "ship032": "1号", + "bill031": "账单路", + "company_name": "TGHX公司", + "company_address": "地址", + "company_phone": "123", + "company_fax": "", + "pmn02": 1, + "pmn04": "3450541801", + "pmn041": "FRAME", + "ima021": "H20", + "pmn20": 730, + "pmn07": "PCS", + "pmn34": date(2026, 9, 16), + "pmn33": date(2026, 9, 10), + "pmn24": "3301-1", + "ta_ima11": "RAW-11", + "pmnud02": "-0001", + "pmn31": "3.35", + "pmn31t": "3.9195", + "pmn88": "2445.5", + "pmn88t": "2861.24", + "ta_ima02": "1", + "ta_ima03": "1", + "pmn06": "VEN-1", + "azi03": 6, + "azi04": 2, + "azi05": 2, + } + ], + ) + assert document.invoice_no == "EWZZ26090002" + assert document.po_no == "5220-2609010001" + assert document.po_date == "2026/9/1" + assert document.price_term == "A01 取核价单价" + assert document.ship_address == "送货路1号" + assert document.lines[0].arrive == "2026/9/16" + assert document.lines[0].halogen == "RoHS" + assert document.lines[0].origin_no == "RAW-11" + assert document.lines[0].version == "-0001" + assert document.untax_total == "2,445.50" + assert document.maker == "" + + +def test_map_po_document_falls_back_origin_and_halogen(): + """原始编号空 ta_ima11 时用 pmn24;无环保码时用卤素管控。""" + document = map_po_document( + "INV0001", + [ + { + "po_no": "PO1", + "pmn02": 1, + "pmn24": "3301-9", + "ta_ima11": " ", + "ta_ima02": "1", + "ta_ima03": "", + "pmn88": 0, + "pmn88t": 0, + } + ], + ) + assert document.lines[0].origin_no == "3301-9" + assert document.lines[0].halogen == "无卤" + + +def test_resolve_invoice_flows_prefers_oma99(): + cursor = _NamedCursor( + { + "OMA_FILE": ( + _OMA_COLS, + [("EWZZ26090002", "12", "8520-2609010002", "S004 -26090001")], + ) + } + ) + flows = resolve_invoice_flows(cursor, ["EWZZ26090002"]) + assert len(flows) == 1 + assert flows[0].flow_no == "S004 -26090001" + assert not any("OGA_FILE" in sql.upper() or "OEA_FILE" in sql.upper() for sql, _ in cursor.executed) + + +def test_resolve_invoice_flows_uses_oga99_when_oma99_empty(): + cursor = _NamedCursor( + { + "OMA_FILE": (_OMA_COLS, [("EWZZ1A", "12", "8520-1", "")]), + "OGA_FILE": (_FLOW_COLS, [("8520-1", "S004-FALLBACK")]), + } + ) + flows = resolve_invoice_flows(cursor, ["EWZZ1A"]) + assert flows[0].flow_no == "S004-FALLBACK" + assert any("OGA_FILE" in sql.upper() for sql, _ in cursor.executed) + + +def test_resolve_invoice_flows_uses_oea99_for_deposit(): + cursor = _NamedCursor( + { + "OMA_FILE": (_OMA_COLS, [("EWZZ1B", "11", "1101-1", None)]), + "OEA_FILE": (_FLOW_COLS, [("1101-1", "S004-SO")]), + } + ) + flows = resolve_invoice_flows(cursor, ["EWZZ1B"]) + assert flows[0].oma00 == "11" + assert flows[0].flow_no == "S004-SO" + assert any("OEA_FILE" in sql.upper() for sql, _ in cursor.executed) + + +def test_fetch_po_documents_crosses_invoice_and_po(monkeypatch): + """同一流程序号下的采购单挂到对应发票;绑定值已 TRIM。""" + + class _Cursor(_NamedCursor): + def execute(self, sql, params=None): + super().execute(sql, params) + compact = " ".join(sql.split()).upper() + if "PMM_FILE" in compact: + assert params is not None + assert "S004-26090001" in params.values() + + class _Conn: + def cursor(self): + return _Cursor( + { + "OMA_FILE": (_OMA_COLS, [("EWZZ26090002", "12", "8520-1", "S004-26090001")]), + "PMM_FILE": ( + ["flow_no", "po_no", "po_date", "pmn02", "pmn04", "pmn20", "pmn34", "pmn88", "pmn88t"], + [ + ("S004-26090001", "5220-2609010001", date(2026, 9, 1), 1, "P1", 10, date(2026, 9, 16), 100, 117), + ], + ), + } + ) + + def close(self): + return None + + monkeypatch.setattr( + "app.services.voucher_check.erp_po_repository.open_erp_connection", + lambda config: _Conn(), + ) + docs = fetch_po_documents_for_invoices(_config(), ["EWZZ26090002"]) + assert len(docs) == 1 + assert docs[0].invoice_no == "EWZZ26090002" + assert docs[0].po_no == "5220-2609010001" + assert docs[0].lines[0].arrive == "2026/9/16" + + +def test_fetch_po_documents_one_invoice_many_pos(monkeypatch): + """一票可对应多张 TGHX 采购单。""" + + class _Conn: + def cursor(self): + return _NamedCursor( + { + "OMA_FILE": (_OMA_COLS, [("EWZZ26090002", "12", "8520-1", "S004-26090001")]), + "PMM_FILE": ( + ["flow_no", "po_no", "pmn02", "pmn88", "pmn88t"], + [ + ("S004-26090001", "5220-2609010001", 1, 10, 11), + ("S004-26090001", "5220-2609010002", 1, 20, 22), + ], + ), + } + ) + + def close(self): + return None + + monkeypatch.setattr( + "app.services.voucher_check.erp_po_repository.open_erp_connection", + lambda config: _Conn(), + ) + docs = fetch_po_documents_for_invoices(_config(), ["EWZZ26090002"]) + assert [item.po_no for item in docs] == ["5220-2609010001", "5220-2609010002"] + + +def test_fetch_po_documents_skips_blank_invoice_list(monkeypatch): + monkeypatch.setattr( + "app.services.voucher_check.erp_po_repository.open_erp_connection", + lambda config: (_ for _ in ()).throw(AssertionError("should not connect")), + ) + assert fetch_po_documents_for_invoices(_config(), ["0", " "]) == [] + + +def test_adapter_fetch_stays_unwired_while_documents_work(monkeypatch): + adapter = ErpPoPrintAdapter() + assert adapter.wired is False + with pytest.raises(ServiceUnavailableError) as exc: + adapter.fetch(period_month=date(2026, 8, 1), subjects=[]) + assert exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED" + + monkeypatch.setattr( + "app.services.voucher_check.erp_po_repository.fetch_po_documents_for_invoices", + lambda config, invoices: [map_po_document("INV0001", [{"po_no": "PO1", "pmn02": 1}])], + ) + docs = adapter.fetch_documents(["INV0001"], config=_config()) + assert docs[0].po_no == "PO1" + + +def test_adapter_publish_for_invoices_uploads_each(monkeypatch): + adapter = ErpPoPrintAdapter() + uploaded: list[str] = [] + monkeypatch.setattr( + adapter, + "fetch_documents", + lambda invoices, config=None: [ + map_po_document("EWZZ26090002", [{"po_no": "PO-A", "pmn02": 1}]), + map_po_document("EWZZ26090002", [{"po_no": "PO-B", "pmn02": 1}]), + ], + ) + monkeypatch.setattr( + adapter, + "upload_given", + lambda document, period_month: uploaded.append(document.po_no) or document.po_no, + ) + results = adapter.publish_for_invoices(["EWZZ26090002"], period_month=date(2026, 8, 1), config=_config()) + assert uploaded == ["PO-A", "PO-B"] + assert results == ["PO-A", "PO-B"] diff --git a/backend/tests/voucher_check/test_po_order_pdf.py b/backend/tests/voucher_check/test_po_order_pdf.py new file mode 100644 index 00000000..87a4a359 --- /dev/null +++ b/backend/tests/voucher_check/test_po_order_pdf.py @@ -0,0 +1,79 @@ +""" +backend/tests/voucher_check/test_po_order_pdf.py + +用途:制式采购单 PDF 命名与给定数据落盘。 +依赖:pytest、pypdf、voucher_check.po_order。 +逻辑:不连 ERP / 文档库;断言文件名 `{invoice}-{订单号}.pdf` 且正文含采购单号。 +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from pypdf import PdfReader + +from app.core.errors import ValidationError +from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter +from app.services.voucher_check.po_order import ( + build_po_order_filename, + parse_po_order_document, + sample_po_order_document, + save_po_order_pdf, +) + +pytestmark = pytest.mark.pure_unit + + +def test_build_po_order_filename(): + """文件名固定 invoice-订单号.pdf。""" + assert build_po_order_filename(invoice_no="INV001", order_no="5201-1605280003") == "INV001-5201-1605280003.pdf" + + +def test_build_po_order_filename_rejects_path_chars(): + with pytest.raises(ValidationError) as exc: + build_po_order_filename(invoice_no="INV/001", order_no="PO1") + assert exc.value.code == "VOUCHER_CHECK.PO_PDF_INVALID" + + +def test_parse_requires_invoice_and_po(): + with pytest.raises(ValidationError) as exc: + parse_po_order_document({"po_no": "PO1"}) + assert exc.value.code == "VOUCHER_CHECK.PO_PDF_INVALID" + + +def test_save_po_order_pdf_uses_invoice_order_filename(tmp_path: Path): + """给定样张数据后保存为 {invoice}-{订单号}.pdf,且可抽出采购单号。""" + document = sample_po_order_document() + path = save_po_order_pdf(document, tmp_path) + assert path.name == "INV-SAMPLE-5201-1605280003.pdf" + assert path.is_file() + assert path.stat().st_size > 1000 + text = "".join((page.extract_text() or "") for page in PdfReader(str(path)).pages) + assert "5201-1605280003" in text + assert "北川科技" in text + assert "FRAME CUBE CORNER" in text + + +def test_save_po_order_pdf_from_dict(tmp_path: Path): + path = save_po_order_pdf( + {"invoice_no": "INV001", "po_no": "PO-9", "company_name": "测试公司", "lines": [{"seq": "1", "item_no": "A1", "qty": "2"}]}, + tmp_path, + ) + assert path.name == "INV001-PO-9.pdf" + + +def test_overwrite_false_keeps_existing(tmp_path: Path): + first = save_po_order_pdf({"invoice_no": "INV001", "po_no": "PO-9"}, tmp_path) + stamp = first.stat().st_mtime_ns + again = save_po_order_pdf({"invoice_no": "INV001", "po_no": "PO-9", "maker": "B"}, tmp_path, overwrite=False) + assert again == first + assert first.stat().st_mtime_ns == stamp + + +def test_adapter_render_given_does_not_wire_fetch(tmp_path: Path): + """fetch 仍未接线;render_given 只根据给定数据出 PDF。""" + adapter = ErpPoPrintAdapter() + assert adapter.wired is False + path = adapter.render_given(sample_po_order_document(), tmp_path) + assert path.name == "INV-SAMPLE-5201-1605280003.pdf" diff --git a/backend/tests/voucher_check/test_po_order_upload.py b/backend/tests/voucher_check/test_po_order_upload.py new file mode 100644 index 00000000..52250ead --- /dev/null +++ b/backend/tests/voucher_check/test_po_order_upload.py @@ -0,0 +1,179 @@ +""" +backend/tests/voucher_check/test_po_order_upload.py + +用途:制式采购单 PDF 上传到文档库「PO订单」目录。 +依赖:pytest;mock SalesDmsClient,不连文档库。 +逻辑:同名跳过、年/月/类型目录确保存在、CreateFiles 载荷含 AttachmentID。 +""" + +from __future__ import annotations + +from datetime import date + +import pytest + +from app.core.errors import ServiceUnavailableError +from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter +from app.services.voucher_check.dms_client import SalesDmsClient +from app.services.voucher_check.po_order import publish_po_order_pdf, sample_po_order_document + +pytestmark = pytest.mark.pure_unit + + +def test_ensure_period_type_folder_creates_year_month_type(monkeypatch): + """销售开票附件下按 年/月/PO订单 逐级建目录。""" + created: list[tuple[str, str]] = [] + + def ensure_folder(*, parent_folder_id: str, leaf_name: str) -> str: + created.append((parent_folder_id, leaf_name)) + return f"{parent_folder_id}/{leaf_name}" + + monkeypatch.setattr(SalesDmsClient, "ensure_configured", lambda: None) + monkeypatch.setattr(SalesDmsClient, "root_folder_id", lambda: "sales-root") + monkeypatch.setattr(SalesDmsClient, "ensure_folder", ensure_folder) + folder_id = SalesDmsClient.ensure_period_type_folder(period_month=date(2026, 8, 1), type_folder="PO订单") + assert created == [("sales-root", "2026"), ("sales-root/2026", "08"), ("sales-root/2026/08", "PO订单")] + assert folder_id.endswith("PO订单") + + +def test_upload_file_skips_when_same_name_exists(monkeypatch): + monkeypatch.setattr( + SalesDmsClient, + "find_child_file", + lambda **_kwargs: {"ID": "exist-1", "LeafName": "INV001-PO-9.pdf"}, + ) + uploads: list[object] = [] + monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **kwargs: uploads.append(kwargs) or {}) + row, skipped = SalesDmsClient.upload_file_skip_same_name( + parent_folder_id="po-folder", + leaf_name="INV001-PO-9.pdf", + content=b"%PDF-fake", + ) + assert skipped is True + assert row["ID"] == "exist-1" + assert uploads == [] + + +def test_upload_file_creates_when_missing(monkeypatch): + listing = {"n": 0} + + def find_child_file(**_kwargs): + listing["n"] += 1 + if listing["n"] == 1: + return None + return {"ID": "new-1", "LeafName": "INV001-PO-9.pdf"} + + monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file) + monkeypatch.setattr( + SalesDmsClient, + "upload_attachment", + lambda **_kwargs: {"ID": "att-1", "Extension": ".pdf", "LeafName": "INV001-PO-9"}, + ) + created: list[dict] = [] + monkeypatch.setattr(SalesDmsClient, "create_files", lambda **kwargs: created.append(kwargs) or {"Code": 0}) + row, skipped = SalesDmsClient.upload_file_skip_same_name( + parent_folder_id="po-folder", + leaf_name="INV001-PO-9.pdf", + content=b"%PDF-fake", + ) + assert skipped is False + assert row["ID"] == "new-1" + assert created[0]["parent_folder_id"] == "po-folder" + assert created[0]["files"][0]["AttachmentID"] == "att-1" + assert created[0]["files"][0]["LeafName"] == "INV001-PO-9.pdf" + + +def test_upload_treats_create_same_name_as_skip(monkeypatch): + listing = {"n": 0} + + def find_child_file(**_kwargs): + listing["n"] += 1 + if listing["n"] == 1: + return None + return {"ID": "exist-2", "LeafName": "INV001-PO-9.pdf"} + + monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file) + monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **_kwargs: {"ID": "att-2", "Extension": ".pdf"}) + monkeypatch.setattr( + SalesDmsClient, + "create_files", + lambda **_kwargs: (_ for _ in ()).throw( + ServiceUnavailableError( + "存在同名文件", + code="VOUCHER_CHECK.PO_UPLOAD_FAILED", + details={"dms_data": {"SameLeafNames": ["INV001-PO-9.pdf"]}}, + ) + ), + ) + row, skipped = SalesDmsClient.upload_file_skip_same_name( + parent_folder_id="po-folder", + leaf_name="INV001-PO-9.pdf", + content=b"%PDF-fake", + ) + assert skipped is True + assert row["ID"] == "exist-2" + + +def test_upload_finds_leaf_name_without_extension(monkeypatch): + """部分现网 CreateFiles 后 LeafName 不含 .pdf,按无后缀再查一次。""" + listing = {"n": 0} + + def find_child_file(*, parent_folder_id: str, leaf_name: str): + listing["n"] += 1 + if listing["n"] == 1: + return None + if str(leaf_name).endswith(".pdf"): + return None + return {"ID": "new-stem", "LeafName": leaf_name} + + monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file) + monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **_kwargs: {"ID": "att-3", "Extension": ".pdf"}) + monkeypatch.setattr(SalesDmsClient, "create_files", lambda **_kwargs: {"Code": 0}) + row, skipped = SalesDmsClient.upload_file_skip_same_name( + parent_folder_id="po-folder", + leaf_name="INV001-PO-9.pdf", + content=b"%PDF-fake", + ) + assert skipped is False + assert row["ID"] == "new-stem" + assert row["LeafName"] == "INV001-PO-9" + + +def test_publish_po_order_pdf_uploads_to_type_folder(monkeypatch): + """给定数据生成后上传到 销售开票附件/{年}/{月}/PO订单/。""" + monkeypatch.setattr(SalesDmsClient, "ensure_configured", lambda: None) + monkeypatch.setattr(SalesDmsClient, "ensure_period_type_folder", lambda **_kwargs: "po-folder") + captured: dict[str, object] = {} + + def upload_file_skip_same_name(*, parent_folder_id: str, leaf_name: str, content: bytes): + captured["parent_folder_id"] = parent_folder_id + captured["leaf_name"] = leaf_name + captured["size"] = len(content) + return {"ID": "item-1", "LeafName": leaf_name, "Path": f"销售开票附件/2026/08/PO订单/{leaf_name}"}, False + + monkeypatch.setattr(SalesDmsClient, "upload_file_skip_same_name", upload_file_skip_same_name) + result = publish_po_order_pdf(sample_po_order_document(), period_month=date(2026, 8, 1)) + assert result.skipped_same_name is False + assert result.file.filename == "INV-SAMPLE-5201-1605280003.pdf" + assert result.file.folder_id == "po-folder" + assert result.file.path == "销售开票附件/2026/08/PO订单/INV-SAMPLE-5201-1605280003.pdf" + assert captured["parent_folder_id"] == "po-folder" + assert captured["leaf_name"] == "INV-SAMPLE-5201-1605280003.pdf" + assert int(captured["size"] or 0) > 1000 + + +def test_adapter_upload_given_does_not_wire_fetch(monkeypatch): + """fetch 仍未接线;upload_given 只根据给定数据上传。""" + captured: dict[str, object] = {} + + def fake_publish(document, period_month): + captured["period_month"] = period_month + captured["invoice_no"] = getattr(document, "invoice_no", None) + return type("R", (), {"file": None, "skipped_same_name": False})() + + monkeypatch.setattr("app.services.voucher_check.po_order.publish_po_order_pdf", fake_publish) + adapter = ErpPoPrintAdapter() + assert adapter.wired is False + adapter.upload_given(sample_po_order_document(), period_month=date(2026, 8, 1)) + assert captured["period_month"] == date(2026, 8, 1) + assert captured["invoice_no"] == "INV-SAMPLE" diff --git a/docs/demand.md b/docs/demand.md index 414f7e5b..755aa67b 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -210,13 +210,13 @@ ### 3.x 立账凭证检核补充需求 - AI 工作台中的“立账凭证”入口及页面仅对 `role=admin` 用户开放;普通用户不展示入口,直接访问地址时返回工作台应用页。 -- **核心目标**:按业务方 Profile **每周二**增量检核**上一个自然月**;销售 invoice 清单沿用旧口径(HXJM `apa_file.apa08/apa09`);从 ERP/OA/文档库获取必检资料,按 `invoice` 归入「所有归档」,输出缺件汇总 Excel。 +- **核心目标**:按业务方 Profile **每周二**增量检核**上一个自然月**;销售 invoice 清单来自 HXJM `oma_file`(`oma10`/`oma02`,已确认、未作废、状况码 1、帐款类别 11/12/13);从 ERP/OA/文档库获取必检资料,按 `invoice` 归入「所有归档」,输出缺件汇总 Excel。 - **销售一期资料**:PO 订单、报关资料、销货放行申请单、发票、报关单、提单。获取后先写入文档库 `销售开票附件/{年}/{月}/{类型目录}/`,再归档到同月 `所有归档/{invoice号}/`。 - **OA**:一期仅模拟页面打销货放行单;后期对接新 OA 接口,规则不变。 - **文档库**:复用现有文档管理系统(全公司一个库,LibraryID 与合同相同);销售开票附件是该库下独立文件夹,只单独配根 FolderID,不得复用合同根目录。 - **通知**:每个检核批次一条企业微信汇总;接收人在界面从系统用户多选,未配置则不发。 - **判定边界**:只做文件获取、命名/关联校验和归档结果;不读取文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。 -- **实现状态**:周任务已按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总落地;PO/OA 打印仍待接线。不做 Chatflow;查询走工作台 API。 +- **实现状态**:周任务已按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总落地;PO 制式 PDF 可生成上传,ERP 取数见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)(发票 HXJM、采购单 TGHX,`TRIM(oma99)=TRIM(pmm99)` 已接线,仅独立抓取,周二 runner 不调用);OA 打印仍待接线。不做 Chatflow;查询走工作台 API。 - 权威需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md)。 ### 3.x 货代发货通知库存源补充需求 diff --git a/docs/features/accounting-voucher-check/README.md b/docs/features/accounting-voucher-check/README.md index c4da665b..89147e4e 100644 --- a/docs/features/accounting-voucher-check/README.md +++ b/docs/features/accounting-voucher-check/README.md @@ -7,10 +7,12 @@ | **技术规格** | 研发、测试 | [technical.md](technical.md) | | **原型** | 产品、业务、测试 | [accounting-voucher-check-prototype.html](accounting-voucher-check-prototype.html) · [说明](accounting-voucher-check-prototype.md) · [最近一次检核卡片](accounting-voucher-check-latest-run-prototype.html) | | **部署验收清单** | 运维、研发 | [ops-checklist.md](ops-checklist.md) | +| **PO 制式 PDF 样张 JSON** | 研发 | [po-order-sample.json](po-order-sample.json) · 入口 `python -m app.services.voucher_check.po_order --out-dir DIR --json FILE` | +| **ERP 采购单取数表字段** | 研发 | [technical-design.md §3.4](technical-design.md)(发票 HXJM、采购单 TGHX;`TRIM(oma99)=TRIM(pmm99)`;独立抓取已接线) | **定位**:以业务方 Profile 驱动的批量资料检核;**每周二**增量处理上一个自然月。销售开票附件先落入文档库类型目录,再按 `invoice` 归入「所有归档」。 **要解决的问题**:不同业务方从 ERP、OA、固定目录等来源获取不同必检资料,统一检核、归档、汇总缺件并通知。 **检核内容**:只做必检文件的获取、存在性和归档结果;不做文件内容解析或金额、供应商等字段一致性核对。 **结果输出**:每批生成 Excel,区分缺件文件总数和缺件 `invoice` 数;企业微信每批一条汇总通知,完整明细以 Excel 与执行记录为准。 -**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。ERP PO / OA 销货放行打印仍待接线。 +**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。PO 制式 PDF 生成并上传到「PO订单」已实现;ERP 取数(HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`)已接线,仅独立抓取,周二 runner 不调用;OA 销货放行打印仍待接线。 diff --git a/docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html b/docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html index 1f3ade5b..3233554f 100644 --- a/docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html +++ b/docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html @@ -307,7 +307,7 @@ const forceSteps = [ { percent: 8, status: "排队中", step: "已入队强制重检上月", hint: "等待 schedule worker 领取", metrics: [0, 0, 0, 0] }, - { percent: 22, status: "执行中", step: "拉取上月销售 invoice", hint: "HXJM apa_file · 期间 2026-08", metrics: [128, 0, 0, 0] }, + { percent: 22, status: "执行中", step: "拉取上月销售 invoice", hint: "HXJM oma_file · 期间 2026-08", metrics: [128, 0, 0, 0] }, { percent: 58, status: "执行中", step: "扫描销售开票附件类型目录", hint: "已处理 74 / 128 张 invoice", metrics: [128, 410, 5, 3] }, { percent: 82, status: "执行中", step: "按 invoice 归档(同名跳过)", hint: "正在写入所有归档", metrics: [128, 690, 9, 5] }, { percent: 100, status: "缺件", step: "本批已完成,缺件结果已写入 Excel。", hint: "", metrics: [128, 742, 11, 6], done: true }, 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 f3cbbbe2..145bc3a1 100644 --- a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md +++ b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md @@ -15,7 +15,7 @@ ## 业务口径 -- 销售一期:**每周二**增量检核上一个自然月;invoice 来自 HXJM `apa_file`;获取后写入类型目录再归入 `所有归档/{invoice号}/`。 +- 销售一期:**每周二**增量检核上一个自然月;invoice 来自 HXJM `oma_file`;获取后写入类型目录再归入 `所有归档/{invoice号}/`。 - 销货放行申请单:一期模拟 OA 页面;后期换新接口。关联字段不完整时直接跳过。 - 采购二期:展示六类拟定文件规则;路径、主体来源和 Adapter 参数待确认,原型不执行采购检核。 - 批量缺件同时统计“缺件文件总数”和“缺件 `invoice` 数”;同一 `invoice` 缺多个文件时前者累计多个、后者只计一次。 diff --git a/docs/features/accounting-voucher-check/demand.md b/docs/features/accounting-voucher-check/demand.md index 7edf1292..83cdf673 100644 --- a/docs/features/accounting-voucher-check/demand.md +++ b/docs/features/accounting-voucher-check/demand.md @@ -1,8 +1,8 @@ # 立账凭证资料检核需求说明 -> 文档版本:v1.11 -> 更新时间:2026-09-09 -> 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置 +> 文档版本:v1.13 +> 更新时间:2026-09-14 +> 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置。PO 制式 PDF 已可生成上传;ERP 取数(HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`)已接线,仅独立抓取,周二周任务不调用。 > > 本文是本期需求权威。部署与冒烟见 [ops-checklist.md](ops-checklist.md)。旧共享盘存在性扫描、Chatflow Tool 与一票一状态表已移除,不得再按该口径扩展。 @@ -44,7 +44,7 @@ 新增业务方时优先新增或调整 Profile;只有新增外部系统或获取协议时才开发新的来源 Adapter。 -销售一期主体清单**沿用旧方案 ERP 口径**:HXJM 套账只读查询 `apa_file`,`apa08` 为发票号、`apa09` 为发票日期,发票号非空。检核期间仍按上表取**上一个自然月**(例如周二跑批则检核上个月),不沿用旧实现的「当前月」。 +销售一期主体清单来自 HXJM 套账只读查询 `oma_file`:`oma10` 为发票号码,须为至少 6 位字母或数字(如 `6975101806`、`EWZZ26090002`;排除 NULL、空串、`0`、中文备注),`oma02` 为帐款日期(DATE),且 `omaconf='Y'`(已确认)、`omavoid='N'`(未作废)、`oma64='1'`(状况码)、`oma00` 为 `11`/`12`/`13` 之一(帐款类别)。检核期间仍按上表取**上一个自然月**(例如周二跑批则检核上个月),不沿用旧实现的「当前月」。 ### 3.3 结果状态 @@ -100,7 +100,7 @@ | 文件类型 | 命名方式 | 获取方式 | 存放路径 | `invoice` 关联 | 扫描/查询条件 | | -------------- | ------------------------------ | -------------------------- | --------------------------------------------- | --------------------------- | ---------------------- | -| PO 订单 | `{invoice号}-{订单号}.pdf` | ERP 查询对应 PO 后打印 PDF | `文档库/销售开票附件/{yyyy}/{MM}/PO订单/` | 以销售 `invoice` 反查 PO | **待确认**:查询字段、关联与打印方式 | +| PO 订单 | `{invoice号}-{订单号}.pdf` | 按发票从 TGHX 取数生成制式采购单 PDF,并上传到当月「PO订单」目录(独立抓取;周任务只扫描目录) | `文档库/销售开票附件/{yyyy}/{MM}/PO订单/` | `TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)` → `pmm01` | **已确认**:发票 HXJM、采购单 TGHX;多角序号关联(样本 `EWZZ26090002` → `5220-2609010001`)。拿到 `pmm01` 后按 [technical-design.md §3.4](technical-design.md) 对照 apmr900 取数;命名 `{invoice}-{订单号}.pdf`;上传走 Attachment/Upload + CreateFiles,同名跳过 | | 报关资料 | `{invoice号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/报关资料/` | 文件名含 `invoice` | 扫描上月对应类型目录 | | 销货放行申请单 | `{invoice号}-{销货单号}.pdf` | OA 自定义报表逐条打印 PDF | `文档库/销售开票附件/{yyyy}/{MM}/销货单/` | OA 列表读取发票号、销货单号 | 见 5.1 | | 发票 | `{invoice号}-{发票号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/发票/` | 文件名含 `invoice` | 扫描上月对应类型目录 | @@ -145,12 +145,29 @@ flowchart TD | 步骤 | 操作与规则 | | ---- | -------------------------------------------------------- | -| 1 | 以上月销售 `invoice` 清单为入口 | -| 2 | 在 ERP 查询并反查对应 PO 订单 | -| 3 | 每个 PO 订单打印并保存一个 PDF | -| 4 | 按 `invoice + 订单号` 命名,写入当月「PO订单」存放目录 | -| 5 | 再复制到「所有归档/{invoice号}/」 | -| 6 | **待确认**:ERP 查询字段、invoice 与 PO 关联、打印入口与 PDF 落盘方式 | +| 1 | 以上月销售 `invoice` 清单为入口(HXJM `oma_file.oma10`) | +| 2 | 在 **TGHX** 套账按 `TRIM(oma99)=TRIM(pmm99)` 反查采购单号 `pmm01`(多角贸易;见技术设计 §3.4.1) | +| 3 | 按 [technical-design.md §3.4](technical-design.md) 从 **TGHX** 的 `pmm_file`(头)、`pmn_file`(身)及码表取出制式 PDF 字段;不跑 TIPTOP 客户端打印 | +| 4 | 每个 PO 用 HXOPS 制式采购单生成一个 PDF(对照 apmr900) | +| 5 | 按 `{invoice号}-{订单号}.pdf` 命名,写入当月「PO订单」存放目录 | +| 6 | 再复制到「所有归档/{invoice号}/」 | +| 7 | 周检核只扫描类型目录,不在周二 runner 里生成 PDF | + +制式 PDF:`save_po_order_pdf` 只写本地;写入文档库用 `publish_po_order_pdf`(`ErpPoPrintAdapter.upload_given`)。调用方传入已组装好的采购单字段(含 `invoice_no`、`po_no`、明细行)以及类型目录所属月 `period_month`;`invoice_no` 只出现在文件名,不印在采购单版面。年/月/「PO订单」目录没有就建。目标已有同名文件则跳过、不覆盖。独立抓取任务上线前不要把生成或上传塞进周检核。 + +拿到 `pmm01` 之后的主表(业务可读摘要;完整对照见技术设计 §3.4): + +| 业务栏 | 表.字段 | +| --- | --- | +| 采购单号 / 日期 / 单别 | `pmm01` / `pmm04` / `smydesc` | +| 付款条件 / 税种 / 价格条件 / 币种 | `pma02` / `gec02` / `pmm41`+`pnz02` / `pmm22` | +| 送货 / 账单地址 | `pme_file`(码为 `pmm10` / `pmm11`) | +| 供应商 | `pmm09`,名称地址电话传真来自 `pmc_file` | +| 公司抬头 | `zo_file`(`zo02`/`zo041`/`zo05`/`zo09`) | +| 明细:项次、料号、品名、规格、数量单位、单价金额 | `pmn02`/`pmn04`/`pmn041`/`ima021`/`pmn20`/`pmn07`/`pmn31`/`pmn31t`/`pmn88`/`pmn88t` | +| 到货日 | `pmn34`(原始到厂日期;不用 `pmn33`) | +| 请购单号 / 厂商料号 | `pmn24` / `pmn06` | +| 卤素 / 环保 | `ima_file.ta_ima02` / `ta_ima03`(码值转文案) | ### 5.3 通用存放与归档流程 @@ -187,11 +204,13 @@ flowchart TD | 登录接口 | `POST {基址}/Login/_api/Login`,body:`LoginName` / `Pwd` | | 目录/文件查询 | `POST {基址}/Api/_api/APS/Public/Item/Page`(`LibraryID`、`ParentFolderID`、分页) | | 建文件夹 | `POST {基址}/Api/_api/APS/Public/Item/SaveFolder`(`LibraryID`、`ParentFolderID`、`LeafName`、`FieldValues`) | +| 上传附件 | `POST {基址}/Api/_api/DMS/Public/Attachment/Upload`(multipart 字段名 `file`),返回 `Data.ID` 作为 AttachmentID | +| 登记到目录 | `POST {基址}/Api/_api/APS/Public/Item/CreateFiles`(`ParentFolderID` 为当月「PO订单」FolderID;`Files[].LeafName` 带 `.pdf`;`Files[].AttachmentID` 来自 Upload) | | 复制文件 | `POST {基址}/Api/_api/APS/Public/Item/Copy`(`ItemID` 数组、目标 `ParentFolderID`)。归档**禁止**使用 Move | | 账号 | 复用现有 DMS 账号;用户名与密码只放环境变量/密钥注入,禁止写入代码、Profile JSON、Excel 或日志 | | 库与目录 | 全公司只有一个文档库:`LibraryID` 与现网 `CONTRACT_DMS_LIBRARY_ID` 相同(`LibraryName` 为「文档库」)。「设备合同书」「销售开票附件」都是该库下的文件夹,**不要另配 LibraryID**。销售根目录单独配置 FolderID,**不得**复用合同根目录。现网销售根 FolderID 为 `727c3683-dcdb-4d62-a5b1-b164224162bc`(接口无 `FolderID` 字段,用条目 `ID` / `IDPath`) | -下载、建文件夹、复制到「所有归档」须走同一套已登录会话。归档只复制、不移动;目标已有同名文件则跳过。仍不把凭据写入需求正文。 +下载、建文件夹、上传到类型目录、复制到「所有归档」须走同一套已登录会话。归档只复制、不移动;类型目录上传与归档复制均为同名跳过。仍不把凭据写入需求正文。 ## 6. 批量缺件汇总与企业微信通知 @@ -238,18 +257,18 @@ flowchart TD 3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。 4. 企业微信每批仅发送一条缺件汇总通知,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。 5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。 -6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、企微选人界面已确认;ERP PO 反查与打印、OA 模拟页细节仍通过配置承接,不能把凭据写死在通用逻辑中。 +6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、企微选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 模拟页细节仍通过配置承接,不能把凭据写死在通用逻辑中。 7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。 ## 9. 待补充事项 | 待确认项 | 当前结论 | 仍缺什么 | | --- | --- | --- | -| 销售 invoice 清单 | **已确认**:HXJM `apa_file.apa08/apa09`,期间为上一个月 | 无 | -| ERP 反查 PO 并打印 | **待确认** | 查询字段、关联、打印入口、PDF 保存 | +| 销售 invoice 清单 | **已确认**:HXJM `oma_file.oma10/oma02`,`oma10` 至少 6 位字母或数字,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00 IN (11,12,13)`,期间为上一个月 | 无 | +| ERP 反查 PO 并打印 | **打印、上传与取数已接线(独立抓取,周二 runner 不调用)**。采购单在 **TGHX**。关联 **已确认**:`TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)`(样本 `EWZZ26090002` → `5220-2609010001`,`pmm02=TRI`)。`oma99` 为空时才走 `oma16` 备用。到货日 `pmn34`。详见 [technical-design.md §3.4](technical-design.md) | 制表者;卤素/环保是否拆列。原始编号优先 `ta_ima11` 否则 `pmn24`(业务仍略含糊)。`oma99` 为空的备用路径尚未用空值票验证 | | OA 销货放行单 | **已确认方向**:一期只做模拟页面;后期对接新 OA 接口 | 模拟登录、分页、打印落盘细节 | -| 文档管理系统 | **已确认**:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、复制 `Item/Copy` | 无 | +| 文档管理系统 | **已确认**:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、上传 `Attachment/Upload` + `Item/CreateFiles`、复制 `Item/Copy`;同名跳过 | 无 | | 企微接收人 | **已确认产品**:界面从系统用户多选;人可以后配 | 业务最终勾选哪些人 | | 周任务 | **已确认**:每周二(默认 06:00 上海时区) | 无 | | 销售类型目录名 | **已确认固定**:`PO订单`、`报关资料`、`销货单`、`发票`、`报关单`、`提单` | 无 | -| 重复文件策略 | **已确认**:同名跳过 | 目标 `所有归档/{invoice}/` 已有相同文件名则不覆盖,记已归档 | +| 重复文件策略 | **已确认**:同名跳过 | 目标 `所有归档/{invoice}/` 或类型目录「PO订单」已有相同文件名则不覆盖 | diff --git a/docs/features/accounting-voucher-check/hxops-po-sample.py b/docs/features/accounting-voucher-check/hxops-po-sample.py index ded51324..2070e86b 100644 --- a/docs/features/accounting-voucher-check/hxops-po-sample.py +++ b/docs/features/accounting-voucher-check/hxops-po-sample.py @@ -1,305 +1,46 @@ """ docs/features/accounting-voucher-check/hxops-po-sample.py -用途:用 ERP 打印件同款模拟数据生成「HXOPS 制式采购单」样张,供与 apmr900 对照。 -依赖:reportlab、Windows 宋体、welltrust-logo.png(从原件抽出的页眉 Logo)。 -逻辑:独立脚本,不接入周检核;数据写死自 采购单.pdf;不贴「无」图。 +用途:用对照样张数据调用生产渲染器,生成「HXOPS 制式采购单」供与 apmr900 并排看。 +依赖:backend app.services.voucher_check.po_order(需在 backend 目录或 PYTHONPATH 含 backend)。 +逻辑:不再维护第二套画表代码;正式落盘请用 save_po_order_pdf,文件名为 {invoice}-{订单号}.pdf。 """ from __future__ import annotations +import sys from pathlib import Path -from reportlab.lib.colors import HexColor -from reportlab.lib.pagesizes import A4 -from reportlab.lib.units import mm -from reportlab.pdfbase import pdfmetrics -from reportlab.pdfbase.ttfonts import TTFont -from reportlab.pdfgen import canvas +ROOT = Path(__file__).resolve().parents[3] +BACKEND = ROOT / "backend" +if str(BACKEND) not in sys.path: + sys.path.insert(0, str(BACKEND)) -FONT = "SimSun" -FONT_PATH = Path(r"C:\Windows\Fonts\simsun.ttc") -LOGO_PATH = Path(__file__).resolve().parent / "welltrust-logo.png" -INK = HexColor("#111111") -LINE = HexColor("#333333") -SOFT = HexColor("#666666") - -# 数据来自 e:\Work\Agent\立账凭证\采购单.pdf(apmr900 / Crystal Reports) -SAMPLE = { - "company_phone": "0512-63136988", - "company_fax": "", - "company_address": "江苏省苏州市吴江区经济开发区山湖西路789号", - "company_name": "苏州和信精密科技有限公司", - "maker": "梁春艳", - "page": "1/1", - "po_date": "2016/5/28", - "po_no": "5201-1605280003", - "po_type": "原料采购单", - "price_term": "A01 取核价单价", - "ship_address": "", - "pay_term": "月结一个月", - "tax_type": "进项(17%含税)", - "currency": "RMB", - "bill_address": "", - "vendor_name": "北川科技(苏州)有限公司", - "vendor_code": "VCCD00013", - "vendor_tel": "0512-62810369", - "vendor_fax": "0512-62810368", - "vendor_addr": "苏州市工业园区胜浦分区银胜路61号", - "untax_total": "4,455.50", - "tax_total": "5,212.94", - "lines": [ - { - "item_no": "3450541801", - "seq": "1", - "qty": "730", - "unit": "PCS", - "arrive": "2016/6/16", - "untax_price": "3.350000", - "untax_amt": "2,445.50", - "halogen": "RoHS", - "name": "FRAME CUBE CORNER", - "spec": "H20*W36.5*L36.7", - "tax_price": "3.919500", - "tax_amt": "2,861.24", - "origin_no": "3301-1605260004", - "version": "-0001", - "vendor_item": "3450541801", - }, - { - "item_no": "3450541801", - "seq": "2", - "qty": "600", - "unit": "PCS", - "arrive": "2016/6/16", - "untax_price": "3.350000", - "untax_amt": "2,010.00", - "halogen": "RoHS", - "name": "FRAME CUBE CORNER", - "spec": "H20*W36.5*L36.7", - "tax_price": "3.919500", - "tax_amt": "2,351.70", - "origin_no": "3301-1605100007", - "version": "-0001", - "vendor_item": "3450541801", - }, - ], -} +from app.services.voucher_check.po_order import save_po_order_pdf, sample_po_order_document # noqa: E402 -def _register_font() -> None: - """注册宋体,接近鼎捷报表常用中文字形。""" - pdfmetrics.registerFont(TTFont(FONT, str(FONT_PATH), subfontIndex=0)) - - -def _text(c: canvas.Canvas, x: float, y: float, text: str, size: float = 9, color=INK) -> None: - c.setFillColor(color) - c.setFont(FONT, size) - c.drawString(x, y, text) - - -def _right(c: canvas.Canvas, x: float, y: float, text: str, size: float = 8, color=INK) -> None: - """右对齐文字,用于数量和金额。""" - c.setFillColor(color) - c.setFont(FONT, size) - c.drawRightString(x, y, text) - - -def _hline(c: canvas.Canvas, x1: float, x2: float, y: float, width: float = 0.4) -> None: - c.setStrokeColor(LINE) - c.setLineWidth(width) - c.line(x1, y, x2, y) - - -def _rect(c: canvas.Canvas, x: float, y: float, w: float, h: float, fill=None) -> None: - c.setStrokeColor(LINE) - c.setLineWidth(0.5) - if fill is not None: - c.setFillColor(fill) - c.rect(x, y, w, h, stroke=1, fill=1) - else: - c.rect(x, y, w, h, stroke=1, fill=0) - - -def build_pdf(out_path: Path) -> None: +def main() -> None: """ - 按 A4 竖版画出采购单样张。 - 核心逻辑:版心对齐原件 Crystal 报表的信息分区,不复制 Crystal 精确坐标。 + 生成样张 PDF。 + 核心逻辑:生产命名为 INV-SAMPLE-5201-1605280003.pdf,并复制一份对照文件名便于并排打开。 """ - _register_font() - out_path.parent.mkdir(parents=True, exist_ok=True) - page_w, page_h = A4 - c = canvas.Canvas(str(out_path), pagesize=A4) - c.setTitle("HXOPS 制式采购单样张") - c.setAuthor("HXOPS") - left = 16 * mm - right = page_w - 16 * mm - y = page_h - 10 * mm - - # [STEP 1] Logo 在左;右侧公司名、「采购单」、地址、电话;制表者/页次单独下一行靠右。 - logo_w = 52 * mm - logo_h = 14 * mm - logo_bottom = y - logo_h - if LOGO_PATH.exists(): - c.drawImage( - str(LOGO_PATH), - left, - logo_bottom, - width=logo_w, - height=logo_h, - mask="auto", - preserveAspectRatio=True, - anchor="sw", - ) - text_x = left + 56 * mm - block_mid = (text_x + right) / 2 - c.setFont(FONT, 11) - c.setFillColor(INK) - c.drawCentredString(block_mid, y - 3.5 * mm, SAMPLE["company_name"]) - c.setFont(FONT, 10) - c.drawCentredString(block_mid, y - 8.2 * mm, "采购单") - _text(c, text_x, y - 13 * mm, f"地址:{SAMPLE['company_address']}", 8) - _text(c, text_x, y - 17.5 * mm, f"公司电话:{SAMPLE['company_phone']} 公司传真:", 8) - _text(c, right - 52 * mm, y - 22.5 * mm, f"制表者: {SAMPLE['maker']}", 8) - c.setFont(FONT, 8) - c.drawRightString(right, y - 22.5 * mm, f"页次: {SAMPLE['page']}") - y = min(logo_bottom, y - 24 * mm) - 2 * mm - _hline(c, left, right, y, 0.8) - y -= 6 * mm - - # [STEP 2] 原件左栏采购单号、右栏采购日期(与上一版左右对调) - col2 = left + 98 * mm - val1 = left + 22 * mm - val2 = col2 + 20 * mm - _text(c, left, y, "采购单号:") - _text(c, val1, y, f"{SAMPLE['po_no']} {SAMPLE['po_type']}") - _text(c, col2, y, "采购日期:") - _text(c, val2, y, SAMPLE["po_date"]) - y -= 5.2 * mm - _text(c, left, y, "付款条件:") - _text(c, val1, y, SAMPLE["pay_term"]) - _text(c, col2, y, "税 种:") - _text(c, val2, y, SAMPLE["tax_type"]) - y -= 5.2 * mm - _text(c, left, y, "价格条件:") - _text(c, val1, y, SAMPLE["price_term"]) - _text(c, col2, y, "币 种:") - _text(c, val2, y, SAMPLE["currency"]) - y -= 5.2 * mm - _text(c, left, y, "送货地址:") - _text(c, val1, y, SAMPLE["ship_address"] or " ") - y -= 5.2 * mm - _text(c, left, y, "帐单地址:") - _text(c, val1, y, SAMPLE["bill_address"] or " ") - y -= 6 * mm - _text(c, left, y, "供应厂商:") - _text(c, val1, y, f"{SAMPLE['vendor_code']} {SAMPLE['vendor_name']}") - _text(c, left + 118 * mm, y, f"Tel: {SAMPLE['vendor_tel']}") - y -= 5 * mm - _text(c, val1, y, SAMPLE["vendor_addr"], 8) - _text(c, left + 118 * mm, y, f"Fax: {SAMPLE['vendor_fax']}") - y -= 4 * mm - _hline(c, left, right, y, 0.8) - y -= 1 * mm - - # [STEP 4] 按 Crystal 原件:无满格单元格;表头三行折行;项次在最左。 - x_seq = left - x_item = left + 8 * mm - x_origin = left + 50 * mm - x_arrive = left + 80 * mm - x_qty = left + 108 * mm - x_unit = left + 116 * mm - x_price = left + 142 * mm - x_amt = left + 164 * mm - x_halo = left + 168 * mm - header_h = 11 * mm - table_top = y - _hline(c, left, right, table_top, 0.7) - h1 = table_top - 3.6 * mm - h2 = table_top - 7.0 * mm - h3 = table_top - 10.2 * mm - _text(c, x_seq, h1, "项次", 7) - _text(c, x_item, h1, "料件编号", 7) - _text(c, x_item, h2, "品名/规格", 7) - _text(c, x_item, h3, "厂商料号额外品名规格说明", 6.5) - _text(c, x_origin, h1, "原始编号", 7) - _text(c, x_origin, h2, "版本", 7) - _text(c, x_origin, h3, "行序", 6.5) - _text(c, x_arrive, h1, "到货日", 7) - _text(c, x_qty - 8 * mm, h1, "数 量", 7) - _text(c, x_unit, h1, "单 位", 7) - _right(c, x_price, h1, "税前单价", 7) - _right(c, x_price, h2, "含税单价", 7) - _right(c, x_amt, h1, "税前金额", 7) - _right(c, x_amt, h2, "含税金额", 7) - _text(c, x_halo, h1, "卤素", 7) - _text(c, x_halo, h2, "管控", 7) - _text(c, x_halo + 10 * mm, h1, "环保", 7) - _text(c, x_halo + 10 * mm, h2, "等级", 7) - c.setStrokeColor(LINE) - c.setLineWidth(0.4) - c.line(x_price - 22 * mm, h2 - 1.2 * mm, x_price, h2 - 1.2 * mm) - c.line(x_amt - 22 * mm, h2 - 1.2 * mm, x_amt, h2 - 1.2 * mm) - y = table_top - header_h - _hline(c, left, right, y, 0.5) - - # [STEP 5] 每笔三行:料号/品名/规格,无斑马底、无竖线格 - row_h = 13 * mm - for line in SAMPLE["lines"]: - r1 = y - 3.8 * mm - r2 = y - 7.6 * mm - r3 = y - 11.2 * mm - _text(c, x_seq, r1, line["seq"], 8) - _text(c, x_item, r1, line["item_no"], 8) - _text(c, x_item, r2, line["name"], 8) - _text(c, x_item, r3, line["spec"], 8) - _text(c, x_origin, r1, line["vendor_item"], 8) - _text(c, x_origin, r2, line["origin_no"], 8) - _text(c, x_arrive, r1, line["arrive"], 8) - _right(c, x_qty, r1, line["qty"], 8) - _text(c, x_unit, r1, line["unit"], 8) - _right(c, x_price, r1, line["untax_price"], 8) - _right(c, x_price, r2, line["tax_price"], 8) - _right(c, x_amt, r1, line["untax_amt"], 8) - _right(c, x_amt, r2, line["tax_amt"], 8) - _text(c, x_halo, r1, line["halogen"], 8) - y -= row_h - - # [STEP 6] 合计靠右,金额带原件那种细框 - y -= 6 * mm - box_w = 22 * mm - box_h = 4.6 * mm - _text(c, x_price - 28 * mm, y, "税前金额总和:", 8) - _rect(c, x_amt - box_w, y - 1.2 * mm, box_w, box_h) - _right(c, x_amt - 1.2 * mm, y, SAMPLE["untax_total"], 8) - y -= 6 * mm - _text(c, x_price - 28 * mm, y, "含税金额总和:", 8) - _rect(c, x_amt - box_w, y - 1.2 * mm, box_w, box_h) - _right(c, x_amt - 1.2 * mm, y, SAMPLE["tax_total"], 8) - - # 底部按 ERP 截图:三字在线上方均分;横线穿过 (apmr900) / (结束) - foot_y = 18 * mm - span = right - left - _text(c, left + 10 * mm, foot_y + 5 * mm, "核准", 10) - c.setFont(FONT, 10) - c.drawCentredString(left + span / 2, foot_y + 5 * mm, "审核") - c.drawRightString(right - 10 * mm, foot_y + 5 * mm, "经办") - _hline(c, left, right, foot_y, 0.7) - _text(c, left, foot_y - 1.1 * mm, "(apmr900)", 8) - c.setFont(FONT, 8) - c.drawRightString(right, foot_y - 1.1 * mm, "(结束)") - c.showPage() - c.save() + document = sample_po_order_document() + targets = [ + ROOT / "docs" / "features" / "accounting-voucher-check", + Path(r"e:\Work\Agent\立账凭证"), + ] + for folder in targets: + try: + path = save_po_order_pdf(document, folder) + alias = folder / "采购单-hxops-sample.pdf" + alias.write_bytes(path.read_bytes()) + print(path) + print(alias) + except PermissionError: + print(f"skip locked: {folder}") + except OSError as exc: + print(f"skip {folder}: {exc}") if __name__ == "__main__": - targets = [ - Path(r"e:\Code\hxops\docs\features\accounting-voucher-check\采购单-hxops-sample.pdf"), - Path(r"e:\Work\Agent\立账凭证\采购单-hxops-sample.pdf"), - ] - for path in targets: - try: - build_pdf(path) - print(path) - except PermissionError: - print(f"skip locked: {path}") + main() diff --git a/docs/features/accounting-voucher-check/ops-checklist.md b/docs/features/accounting-voucher-check/ops-checklist.md index 3c167ee4..63982a9d 100644 --- a/docs/features/accounting-voucher-check/ops-checklist.md +++ b/docs/features/accounting-voucher-check/ops-checklist.md @@ -1,6 +1,6 @@ # 立账凭证检核 — 部署验收清单 -> 覆盖当前引擎:每周二检核**上一个自然月**、HXJM `apa_file` 发票清单、文档库类型目录扫描与按票归档(Copy,同名跳过)、单文件结果与企微批次汇总。 +> 覆盖当前引擎:每周二检核**上一个自然月**、HXJM `oma_file` 发票清单、文档库类型目录扫描与按票归档(Copy,同名跳过)、单文件结果与企微批次汇总。PO 取数仅独立抓取(TGHX 只读授权见 §2),不进周任务。 > > 产品需求见 [demand.md](demand.md),设计见 [technical-design.md](technical-design.md)。 > @@ -67,6 +67,9 @@ VOUCHER_CHECK_DMS_ROOT_FOLDER_ID= # VOUCHER_CHECK_DMS_LIBRARY_ID= # VOUCHER_CHECK_DMS_USERNAME= # VOUCHER_CHECK_DMS_PASSWORD= + +# 可选:制式采购单中文字体(默认 Windows 宋体或镜像 fonts-noto-cjk) +# VOUCHER_CHECK_PO_FONT_PATH= ``` 检查: @@ -74,6 +77,26 @@ VOUCHER_CHECK_DMS_ROOT_FOLDER_ID= - [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_ERP_*` / `VOUCHER_CHECK_DMS_*` - [ ] 密码未出现在 `job_params`、日志样例、Excel 字段中 - [ ] 不再配置 `VOUCHER_CHECK_LOCAL_ROOT` / `VOUCHER_CHECK_SHARE_*`(旧共享盘方案已移除) +- [ ] 只读账号除 HXJM `oma_file` 外,还须能读 **TGHX** 采购单及码表、以及 HXJM 备用出货/订单表(周任务仍不查这些表;独立抓取 PO 需要)。DBA 对只读用户执行(把 `` 换成实际账号,勿把密码写进工单附件以外的仓库): + +```sql +-- HXJM:发票头;oma99 为空时备用 +GRANT SELECT ON HXJM.oma_file TO ; +GRANT SELECT ON HXJM.oga_file TO ; +GRANT SELECT ON HXJM.oea_file TO ; +-- TGHX:采购单头身 + apmr900 码表 +GRANT SELECT ON TGHX.pmm_file TO ; +GRANT SELECT ON TGHX.pmn_file TO ; +GRANT SELECT ON TGHX.smy_file TO ; +GRANT SELECT ON TGHX.pmc_file TO ; +GRANT SELECT ON TGHX.pma_file TO ; +GRANT SELECT ON TGHX.gec_file TO ; +GRANT SELECT ON TGHX.pnz_file TO ; +GRANT SELECT ON TGHX.azi_file TO ; +GRANT SELECT ON TGHX.ima_file TO ; +GRANT SELECT ON TGHX.pme_file TO ; +GRANT SELECT ON TGHX.zo_file TO ; +``` --- @@ -116,6 +139,18 @@ VOUCHER_CHECK_DMS_ROOT_FOLDER_ID= - [ ] DMS 或 ERP 不可用时批次 `failed`,不得把空结果批量判为缺件 - [ ] 企微失败告警到达(若开启) +### 4.5 独立抓取 PO(不走周二任务) + +- [ ] 只读账号已 GRANT TGHX(见 §2);周任务日志中**没有** `fetch_po_documents_for_invoices` / `publish_for_invoices` +- [ ] 在 `backend/` 用样本发票出本地 PDF(需应用配置与 Oracle): + +```bash +python -m app.services.voucher_check.po_order --out-dir ./tmp-po --invoice EWZZ26090002 +``` + +- [ ] 文件名为 `{发票号}-{pmm01}.pdf`(样本应为 `EWZZ26090002-5220-2609010001.pdf`) +- [ ] 上传走 `ErpPoPrintAdapter.publish_for_invoices`,同名跳过;不要把该方法接到周二 runner + --- ## 5. 在 jobs 表识别立账凭证检核 diff --git a/docs/features/accounting-voucher-check/po-order-sample.json b/docs/features/accounting-voucher-check/po-order-sample.json new file mode 100644 index 00000000..c813386f --- /dev/null +++ b/docs/features/accounting-voucher-check/po-order-sample.json @@ -0,0 +1,43 @@ +{ + "invoice_no": "INV-SAMPLE", + "po_no": "5201-1605280003", + "po_date": "2016/5/28", + "po_type": "原料采购单", + "pay_term": "月结一个月", + "tax_type": "进项(17%含税)", + "price_term": "A01 取核价单价", + "currency": "RMB", + "ship_address": "", + "bill_address": "", + "vendor_code": "VCCD00013", + "vendor_name": "北川科技(苏州)有限公司", + "vendor_tel": "0512-62810369", + "vendor_fax": "0512-62810368", + "vendor_addr": "苏州市工业园区胜浦分区银胜路61号", + "company_name": "苏州和信精密科技有限公司", + "company_address": "江苏省苏州市吴江区经济开发区山湖西路789号", + "company_phone": "0512-63136988", + "company_fax": "", + "maker": "AI", + "untax_total": "4,455.50", + "tax_total": "5,212.94", + "lines": [ + { + "seq": "1", + "item_no": "3450541801", + "name": "FRAME CUBE CORNER", + "spec": "H20*W36.5*L36.7", + "qty": "730", + "unit": "PCS", + "arrive": "2016/6/16", + "origin_no": "3301-1605260004", + "version": "-0001", + "untax_price": "3.350000", + "tax_price": "3.919500", + "untax_amt": "2,445.50", + "tax_amt": "2,861.24", + "halogen": "RoHS", + "vendor_item": "3450541801" + } + ] +} diff --git a/docs/features/accounting-voucher-check/technical-design.md b/docs/features/accounting-voucher-check/technical-design.md index e34bcc1b..ea158a4c 100644 --- a/docs/features/accounting-voucher-check/technical-design.md +++ b/docs/features/accounting-voucher-check/technical-design.md @@ -1,8 +1,8 @@ # 立账凭证资料检核技术设计 -> 文档版本:v2.5 -> 更新时间:2026-09-09 -> 状态:销售一期引擎已落地;ERP PO / OA 打印仍待接线 +> 文档版本:v2.10 +> 更新时间:2026-09-14 +> 状态:销售一期引擎已落地;发票清单改查 oma_file;PO 制式 PDF 生成并上传到「PO订单」目录已实现;ERP 取数(HXJM.oma99 → TGHX.pmm99)已接线,仅独立抓取任务调用,周二 runner 不调用;OA 打印仍待接线 > 需求基线:[demand.md](demand.md) > > 本文替代旧实现「当月 + 单一共享盘 + 固定文件名存在性」。旧表、共享盘扫描与 Chatflow Tool 已删除,不得按旧口径扩展。 @@ -58,7 +58,7 @@ business_profiles/ | 配置项 | 说明 | | -------------------------------------- | ------------------------------------------------------------------------------------------------- | | `profile_code` / `profile_version` | 业务方及发布版本,例如 `sales:v1` | -| `subject_adapter` | 获取本期 `invoice` 主体清单。销售一期:HXJM `apa_file`(`apa08`/`apa09`),期间为上一个月 | +| `subject_adapter` | 获取本期 `invoice` 主体清单。销售一期:HXJM `oma_file`(`oma10` 至少 6 位字母或数字、`oma02` 帐款日期,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00` 为 11/12/13),期间为上一个月 | | `file_rules` | 必检标识、命名模板、关联字段、来源 Adapter、查询/扫描条件、临时/归档模板 | | `notification` | 企业微信接收人、启用开关、模板、去重策略 | | `incremental_policy` | 指纹字段、可跳过状态、强制重检规则 | @@ -75,6 +75,165 @@ business_profiles/ Adapter 不负责归档、Excel 或通知;引擎不理解 ERP/OA 的具体页面、SQL、目录规则。 +### 3.3 PO 订单制式 PDF + +不调用 TIPTOP 客户端打印。给定一张 PO 的字段后,由 HXOPS 按 Crystal `apmr900` 对照样张生成 PDF。 + +| 项 | 约定 | +| --- | --- | +| 本地落盘 | `save_po_order_pdf`;Adapter `ErpPoPrintAdapter.render_given` | +| 上传文档库 | `publish_po_order_pdf`;Adapter `ErpPoPrintAdapter.upload_given`。目标 `销售开票附件/{yyyy}/{MM}/PO订单/`;年/月/类型目录没有就 `SaveFolder` | +| 上传接口 | 现网「新建文件」:`Attachment/Upload`(multipart `file` → `Data.ID`)再 `Item/CreateFiles`(`ParentFolderID` + `Files[].AttachmentID` / `LeafName` 带 `.pdf`) | +| 同名 | 类型目录已有相同 `LeafName` 则跳过、不覆盖(与归档 Copy 一致) | +| 命令行 | 在 `backend/` 执行 `python -m app.services.voucher_check.po_order --out-dir DIR [--json FILE.json|--sample|--invoice 发票号]`(只出本地 PDF,不上传) | +| 文件名 | `{invoice_no}-{po_no}.pdf`;`invoice_no` 只用于命名,不印在采购单版面 | +| 数据 | 给定 `PoOrderDocument` / JSON,或 `fetch_po_documents_for_invoices` / `--invoice` 从 Oracle 组装;`po_order` 模块不要写 SQL | +| 周任务 | 仍只扫描「PO订单」目录;`erp_po_print.fetch` 保持 `wired=False`,不要调用 `fetch_documents` / `upload_given` | +| 字体 | 默认 Windows 宋体或镜像内 `fonts-noto-cjk`;可选 `VOUCHER_CHECK_PO_FONT_PATH` | + +对照样张数据在 `po_order/sample.py`,仅供版式核对。 + +### 3.4 ERP 采购单取数(对照 apmr900;独立抓取已接线) + +对照现场 TIPTOP 打印作业 `apmr900.4gl`(採購單)。销售发票在 **HXJM**;对应采购单在 **TGHX**(多角贸易抛转后的采购厂,不是 HXJM 自己的 `pmm_file`,也不是 HOX)。拿到 `TGHX.pmm01` 之后按本节填 `PoOrderDocument`;**不要**调 TIPTOP 客户端打印。码表(`pmc`/`pme`/`smy`/`zo` 等)随采购单走 **TGHX**。 + +实现:`erp_po_repository.fetch_po_documents_for_invoices`;Adapter `fetch_documents` / `publish_for_invoices`。只给独立抓取任务用,**不要**从周二 runner 调用,也**不要**把 `wired` 改成 `True`。只读账号需 GRANT 见 [ops-checklist.md](ops-checklist.md)。 + +#### 3.4.1 入口与关联 + +销售发票号 `oma10` **不会**写在采购单上。两边靠同一条多角流程序号: + +```text +HXJM.oma_file.oma10 发票号码(检核主体) + │ + ▼ +HXJM.oma_file.oma99 多角序号 + │ TRIM 后等值(已用样本验证) + ▼ +TGHX.pmm_file.pmm99 多角贸易流程序号 + │ + ▼ +TGHX.pmm_file.pmm01 采购单号 → 文件名 {invoice}-{pmm01}.pdf +``` + +**已验证样本**(2026-09-14):发票 `EWZZ26090002`(`oma00=12` 出货应收,帐款单 `R012-2609010003`,出货单 `oma16=8520-2609010002`)→ `oma99` / `pmm99` 均为 `S004-26090001` 一类值(中间可能有空格,JOIN 必须 `TRIM`)→ TGHX 采购单 `5220-2609010001`,`pmm02=TRI`,`pmm901=Y`,`pmm904=S004`。本样本一对一。该票 `oma66=HXJM`,**不能**用 `oma66` 判断采购单套账。 + +| 步骤 | 来源 | 字段 | 状态 | +| --- | --- | --- | --- | +| 本期发票清单 | `HXJM.oma_file` | `oma10` / `oma02`;过滤与主体 Adapter 相同 | 已确认 | +| 采购单套账 | `TGHX.pmm_file` / `TGHX.pmn_file` | 销售开票附件要印的 PO 在 TGHX | **已确认** | +| 发票 → 采购单号 | `TRIM(HXJM.oma99) = TRIM(TGHX.pmm99)` | 得到 `pmm01`。JOIN 前两边都 TRIM(流程序号可能含空格) | **已确认** | +| `oma99` 为空 | `oma16` 备用 | 类别 12/13:`HXJM.oga_file.oga99`;类别 11:`HXJM.oea_file.oea99`;再对 `TGHX.pmm99`。本样本 `oma99` 有值,备用路径尚未跑过 | 仅当 `oma99` 空时使用 | +| 多角辅助栏 | `pmm901` / `pmm02` / `pmm904` | 样本为 `pmm901='Y'`、`pmm02='TRI'`、流程 `S004`。不要用 `oma66` 当套账 | 核对用,不是单号 | +| 一票几张 PO | 本样本 1 张 | 实现仍按一票可多张:每个 `pmm01` 一个 PDF `{invoice}-{pmm01}.pdf` | 本样本 1:1;多单时按 1:N 出文件 | +| 文件名中的订单号 | `TGHX.pmm01` | → `PoOrderDocument.po_no` | 已确认 | + +取数示例(与样本同一口径): + +```sql +SELECT oma01, oma00, oma10, oma16, oma66, oma99 + FROM HXJM.oma_file + WHERE TRIM(oma10) = :invoice + AND omaconf = 'Y' AND omavoid = 'N' AND oma64 = '1'; + +SELECT pmm01, pmm02, pmm09, pmm18, pmm25, pmm99, pmm901, pmm904 + FROM TGHX.pmm_file + WHERE TRIM(pmm99) = TRIM(:oma99) + AND pmm18 != 'X' + AND pmmacti = 'Y' + AND pmm02 != 'BKR'; +``` + +#### 3.4.2 主查询(与 apmr900 主 SQL 一致) + +头 `pmm_file` 内连身 `pmn_file`(`pmm01 = pmn01`),再左连码表。建议排序 `pmm01, pmn02`。 + +apmr900 固定过滤(**已确认沿用**,含未审核单;`pmm18` 确认码为 Y/N/X,只排除作废 X): + +- `pmm18 != 'X'`(未作废;Y 已确认、N 未确认都出) +- `pmmacti = 'Y'`(有效) +- `pmm02 != 'BKR'`(排除备用金采购) +- `gec011 = '1'`(进项税别;与 `gec_file` 连上后该条件实际接近内连) + +不额外要求 `pmm25` 已核准/已发出。 + +| 表 | 关联 | 取出字段 | 用途 | +| --- | --- | --- | --- | +| `pmm_file` | 主表 | `pmm01` 采购单号、`pmm04` 采购日期、`pmm09` 厂商编号、`pmm10` 送货地址码、`pmm11` 账单地址码、`pmm20` 付款条件码、`pmm21` 税别码、`pmm22` 币别、`pmm41` 价格条件码、`pmm43` 税率 | 头栏 | +| `pmn_file` | `pmn01 = pmm01` | `pmn02` 项次、`pmn04` 料号、`pmn041` 品名规格、`pmn06` 厂商料号、`pmn07` 单位、`pmn20` 数量、`pmn24` 请购单号、`pmn25` 请购项次、`pmn31`/`pmn31t` 未税/含税单价、`pmn33` 交货日、`pmn34` 到厂日、`pmn88`/`pmn88t` 未税/含税金额、`pmnud02` 版本 | 明细 | +| `smy_file` | `pmm01 LIKE smyslip \|\| '-%'` | `smydesc` 单别说明 | `po_type`(如「原料采购单」) | +| `pmc_file` | `pmc01 = pmm09` | `pmc081` 供应商全名、`pmc091` 地址、`pmc10` 电话、`pmc11` 传真 | 供应厂商 | +| `pma_file` | `pma01 = pmm20` | `pma02` | `pay_term` | +| `gec_file` | `gec01 = pmm21` 且 `gec011 = '1'` | `gec02` | `tax_type`(说明里通常已含税率,如「进项(17%含税)」;不必再拼 `pmm43`) | +| `pnz_file` | `pnz01 = pmm41` | `pnz02` | 价格条件说明;`price_term` 建议 `pmm41` + 空格 + `pnz02`(样张「A01 取核价单价」) | +| `azi_file` | `azi01 = pmm22` | `azi03`/`azi04`/`azi05` | 单价/金额/合计小数位,格式化用,不印字段名 | +| `ima_file` | `ima01 = pmn04` | `ima021` 规格、`ta_ima02` 卤素管控、`ta_ima03` 环保等级、`ta_ima11` 原始编号(现场备忘列名) | 明细规格、环保列、原始编号候选 | + +`ta_ima02` / `ta_ima03` 在 apmr900 里已转成文案后再进 Crystal: + +| 字段 | 码值 | 打印文案 | +| --- | --- | --- | +| `ta_ima02` | `1` / `2` | 无卤 / 不管控 | +| `ta_ima03` | `1` / `0` / `9` | RoHS / 非环保 / ERS | + +#### 3.4.3 循环内补查(每行或每单一次) + +| 表 | 条件 | 取出字段 | 用途 | +| --- | --- | --- | --- | +| `pme_file` | `pme01 = pmm10` | `pme031`~`pme035` | `ship_address`;空段丢掉再拼接 | +| `pme_file` | `pme01 = pmm11` | `pme031`~`pme035` | `bill_address`;同上 | +| `zo_file` | `zo01 = '1'`(简体),**TGHX** 套账 | `zo02` 公司名、`zo041` 地址、`zo05` 电话、`zo09` 传真 | `company_*`。抬头是采购单所属厂(TGHX),不一定是苏州 HXJM | +| `gfe_file` | `gfe01 = pmn07` 或 `pmn86` | `gfe03` | 数量小数位 | + +合计:同一 `pmm01` 对 `pmn88`、`pmn88t` 求和,格式化后写入 `untax_total` / `tax_total`(apmr900 在 4gl 里先算好再进 Crystal)。 + +#### 3.4.4 `PoOrderDocument` 对照(一期 PDF 实际用到的) + +`invoice_no` 只用于文件名,不从采购单表取,沿用主体清单的 `oma10`。 + +| `PoOrderDocument` / `PoOrderLine` | ERP | 说明 | +| --- | --- | --- | +| `po_no` | `pmm01` | | +| `po_date` | `pmm04` | 展示格式待与样张对齐(样张 `2016/5/28`) | +| `po_type` | `smydesc` | | +| `pay_term` | `pma02` | | +| `tax_type` | `gec02` | | +| `price_term` | `pmm41` + `pnz02` | | +| `currency` | `pmm22` | | +| `ship_address` / `bill_address` | `pme031`~`pme035` | 分别按 `pmm10` / `pmm11` | +| `vendor_code` / `vendor_name` / `vendor_tel` / `vendor_fax` / `vendor_addr` | `pmm09` / `pmc081` / `pmc10` / `pmc11` / `pmc091` | | +| `company_name` / `company_address` / `company_phone` / `company_fax` | `zo02` / `zo041` / `zo05` / `zo09` | `zo12` 是否覆盖电话待确认 | +| `maker` | **待确认** | 现场打印通常是当前用户;批处理没有登录人。候选:`pmm12` 采购员姓名(需再连员工表)或固定文案 | +| `untax_total` / `tax_total` | `SUM(pmn88)` / `SUM(pmn88t)` | | +| `seq` | `pmn02` | | +| `item_no` | `pmn04` | | +| `name` | `pmn041` | | +| `spec` | `ima021` | | +| `qty` / `unit` | `pmn20` / `pmn07` | 一期按采购数量/单位。计价 `pmn87`/`pmn86`、双单位 `pmn80`~`pmn85` 待确认是否要印 | +| `arrive` | `pmn34` | **已确认**:版面「到货日」用原始到厂日期。不要用 `pmn33`(发货日)或 `pmn35`~`pmn37` | +| `origin_no` | `ta_ima11` 或 `pmn24` | **待确认**。现场备忘把「原始编号」写成 `ima.ta_ima11`;`pmn24` 是请购单号,样张 `3301-…` 也像请购单 | +| `vendor_item` | `pmn06` | 厂商料号 | +| `untax_price` / `tax_price` / `untax_amt` / `tax_amt` | `pmn31` / `pmn31t` / `pmn88` / `pmn88t` | 按 `azi03`/`azi04` 格式化 | +| `halogen` | `ta_ima02` 和/或 `ta_ima03` | 版面有「卤素管控」「环保等级」两列,模型目前一个字段;样张 `RoHS` 对应 `ta_ima03`。是否拆字段待确认 | +| `version` | `pmnud02` | 现场备忘「自订栏位-文字 = 版本」;apmr900 主查询已取 `pmnud02` | +| `extra_spec` | **待确认** | 表头「厂商料号额外品名规格说明」在 apmr900 里来自 `pmq_file`(开关 `tm.d`) | + +**到货日**:HXOPS 印 `pmn34`(原始到厂日期)。apmr900 的 4gl 虽把 `pmn33` 也塞进 Crystal,本取数不采用。`pmn35`~`pmn37` 不要取。 + +#### 3.4.5 一期默认不取(apmr900 有、当前 PDF 没有) + +未确认前不要查、不要扩模型: + +| 表 | apmr900 用途 | +| --- | --- | +| `pmo_file` | 单据前/后、项次前/后特别说明 | +| `pmq_file` | 厂商料号额外品名规格(`tm.d = 'Y'`) | +| 历史 `pmm_file`+`pmn_file` | 同料号最近采购记录(`tm.c` 笔数) | +| `pmk_file` + `gem_file` | 请购部门(`pmn24` → `pmk13` → `gem02`) | +| `pmmud01`、`pmn100`、`ta_pmm03`/`ta_pmm04`/`ta_pmm05` | 现场加过进 CR,当前版面未用 | + +打印次数 `pmmprno + 1` 是 TIPTOP 客户端副作用;HXOPS 只读,**不要**回写。 + ## 4. 周度上月增量流程 ```mermaid @@ -206,9 +365,9 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 1. **已做**:Profile、文件规则、批次/单文件结果表、上月期间、周二 cron、销售 DMS 只读、directory_scan、缺件聚合、批次企微、工作台任务列表、最近一次检核卡片与企微发送记录。 2. **已做**:`dms_archive` 建文件夹(`SaveFolder`)+ 复制(`Item/Copy`),重复策略同名跳过;命中文件记 `archived`。 -3. **已预留**:`erp_po_print`、`oa_sales_release` Adapter,周任务不调用。 -4. 接入 ERP PO 打印与 OA 模拟页,作为独立抓取任务写入类型目录。 -5. 采购通过新增 Profile 和 Adapter 参数接入。 +3. **已做**:制式采购单 PDF(`save_po_order_pdf`)及上传到当月「PO订单」目录(`publish_po_order_pdf` / `upload_given`),命名 `{invoice}-{order_no}.pdf`,同名跳过;`erp_po_print.fetch` 与 OA 仍占位,周任务不调用生成或上传。 +4. **已做**:ERP PO 取数(独立抓取:`fetch_po_documents_for_invoices` / `publish_for_invoices`,表字段见 §3.4)。**不要**把生成或上传 PDF 塞进周二 runner。关联:`TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)`。 +5. 接入 OA 模拟页;采购通过新增 Profile 和 Adapter 参数接入。 ## 10. 验收重点 @@ -231,14 +390,14 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 | 旧实现 | 当前实现 | | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | | 每日 `0 6 * * *`,检核**当前自然月** | **每周二** `0 6 * * 2`,检核**上一个自然月** | -| HXJM `apa_file.apa08/apa09` 拉发票清单 | **沿用该口径**,仅把期间改为上一个月 | -| 共享盘 `vouche/{YYYY}/{MM}/{invoice_no}/` 只做文件名存在性 | 从文档库类型目录扫描(ERP/OA 打印一期未接线),先落入 `销售开票附件/{年}/{月}/{类型}/`,再归档到同月 `所有归档/{invoice}/` | +| HXJM `apa_file.apa08/apa09` 拉发票清单 | 改为 `oma_file`:`oma10` 发票号码、`oma02` 帐款日期;仅 `omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00` 为 11/12/13;期间为上一个月 | +| 共享盘 `vouche/{YYYY}/{MM}/{invoice_no}/` 只做文件名存在性 | 从文档库类型目录扫描(PO 取数仅独立抓取;OA 打印一期未接线),先落入 `销售开票附件/{年}/{月}/{类型}/`,再归档到同月 `所有归档/{invoice}/` | | 必检「核价单.pdf」「采购单.pdf」 | 销售一期:PO、报关资料、销货放行申请单、发票、报关单、提单 | | 一票一状态;缺资料按票发企微 textcard、同票同日节流 | 单文件结果;每批一条汇总通知 + invoice 行 Excel | | Chatflow Tool `/api/accounting-voucher-check/tools/*` | 已删除;查询走工作台 `/api/workspace/accounting-voucher-check/*` | 约束: -- 不得按旧「核价单/采购单」文件名或**当前月**期间扩展;销售主体仍用 `apa_file` 上月清单。 +- 不得按旧「核价单/采购单」文件名或**当前月**期间扩展;销售主体用 `oma_file` 上月清单(已确认、未作废、状况码 1、帐款类别 11/12/13)。 - 不得再写入 `voucher_check_invoice_states` / `voucher_check_run_items`。 - 部署与冒烟见 [ops-checklist.md](ops-checklist.md)。 diff --git a/docs/features/accounting-voucher-check/technical.md b/docs/features/accounting-voucher-check/technical.md index 9fdaefa2..3d331e04 100644 --- a/docs/features/accounting-voucher-check/technical.md +++ b/docs/features/accounting-voucher-check/technical.md @@ -202,7 +202,7 @@ error_message 失败原因 | Adapter | 用途 | 销售/采购示例 | | ------------------------- | ---------------------------------- | -------------------------------- | | `directory_scan` | 固定目录按规则扫描文件 | 销售发票、提单;采购对账单、发票 | -| `erp_query_print` | ERP 查询业务单据并打印 PDF | 销售 PO、采购 PO | +| `erp_query_print` / `erp_po_print` | 销售 PO:独立抓取按发票从 TGHX 取数(`fetch_documents` / `publish_for_invoices`),生成制式 PDF 并上传到「PO订单」;`fetch()` 仍占位,周任务不调用。表字段见 [technical-design.md §3.4](technical-design.md) | 销售 PO、采购 PO | | `oa_report_print` | OA 报表过滤后逐条打印 | 销售销货放行单 | | `oa_relation_print` | 根据出货单号等关联字段查 OA 并打印 | 采购核价单 | | `upload_directory_scan` | 网盘或上传目录扫描 | 采购送货单 | @@ -529,10 +529,10 @@ backend/app/domains/document_check/ | -------------------------------- | ------------------------------------------------ | | 销售开票附件文档库路径 | 已确认固定:`销售开票附件/{年}/{月}/{类型目录}`,类型目录为 `PO订单`/`报关资料`/`销货单`/`发票`/`报关单`/`提单`,归档 `所有归档/{invoice}` | | 采购各固定目录路径 | 待确认 | -| 销售 invoice 主体来源与 ERP 字段 | 已确认:HXJM `apa_file` `apa08`/`apa09`,期间上一个月 | +| 销售 invoice 主体来源与 ERP 字段 | 已确认:HXJM `oma_file` `oma10`/`oma02`,`oma10` 至少 6 位字母或数字,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00 IN (11,12,13)`,期间上一个月 | | 采购 invoice 主体来源 | 待确认 | -| ERP PO 查询字段与打印方式 | **待确认** | +| ERP PO 查询字段与打印方式 | **打印与取数已接线(独立抓取)**。发票 HXJM、采购单 **TGHX**。关联 `TRIM(oma99)=TRIM(pmm99)`。对照 apmr900,见 [technical-design.md §3.4](technical-design.md)。到货日 `pmn34`。周二 runner 不调用 | | OA 登录、报表分页和打印接口 | 一期模拟页面;后期对接新 OA 接口 | -| 文档管理系统 | 已确认:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、复制 `Item/Copy`;同名跳过 | +| 文档管理系统 | 已确认:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、上传 `Attachment/Upload` + `Item/CreateFiles`、复制 `Item/Copy`;同名跳过 | | 企业微信通知接收人、模板和频率 | 界面从系统用户多选;每周二;具体人选可后配 | | Profile 管理方式 | 首期可使用版本化 YAML/JSON,后续评估管理后台配置 | diff --git a/docs/funclist.md b/docs/funclist.md index 1ed22a6b..f84934ab 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -216,8 +216,9 @@ | 功能项 | 状态 | 说明 | | --- | --- | --- | -| 销售一期需求、规格与技术设计 | 已文档化 | [需求](features/accounting-voucher-check/demand.md) · [规格](features/accounting-voucher-check/technical.md) · [设计](features/accounting-voucher-check/technical-design.md);每周增量检核上一个月,按 Profile 从 ERP、OA、目录获取并归档 | -| 通用 Profile + Adapter 架构 | 实施中 | 销售 Profile 与 Adapter 协议已落地;周任务扫描文档库类型目录;ERP PO / OA 销货放行单打印仅占位 | +| 销售一期需求、规格与技术设计 | 已文档化 | [需求](features/accounting-voucher-check/demand.md) · [规格](features/accounting-voucher-check/technical.md) · [设计](features/accounting-voucher-check/technical-design.md);每周增量检核上一个月;销售 invoice 来自 HXJM `oma_file`(已确认、未作废、状况码 1、帐款类别 11/12/13) | +| 通用 Profile + Adapter 架构 | 实施中 | 销售 Profile 与 Adapter 协议已落地;周任务扫描文档库类型目录;OA 销货放行单打印仅占位 | +| PO 订单制式 PDF | 已实现(取数仅独立抓取) | `save_po_order_pdf` 按给定数据生成 Crystal/apmr900 对照版式;`fetch_po_documents_for_invoices` / `publish_for_invoices` 按发票从 TGHX 取数并上传到 `销售开票附件/{年}/{月}/PO订单/`;`erp_po_print.fetch` 不进周二 runner;关联 `TRIM(oma99)=TRIM(pmm99)`,见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md) | | 单一共享盘旧检核 | 已移除 | 已删除共享盘扫描、Chatflow Tool、`voucher_check_invoice_states` / `voucher_check_run_items` | | 增量、归档与缺件通知 | 实施中 | 每周二上月;单文件结果;归档复制同名跳过;企微每批一条汇总 | | 工作台查询 | 已实现 | 工作台含检核任务与企微发送记录两 Tab;期间为年+月(默认上月,月份可「全部」看该年);Tab 下「最近一次检核」卡片不跟筛选;「强制重检上月」在卡片上(admin);`GET /runs/latest`、`/runs`、`/notifications` | diff --git a/docs/tec.md b/docs/tec.md index 19a844d6..060c353d 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -215,12 +215,12 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 ### 2.x 立账凭证检核(accounting-voucher-check) - 前端路由 `/workspace/accounting-voucher-check` 标记 `requiresAdmin`,工作台侧栏按当前用户角色隐藏入口;全局路由守卫负责阻止非管理员直接访问。 -- **目标架构**:通用检核引擎 + 业务方 Profile + 来源 Adapter。**每周二**处理上一个自然月;invoice 主体来自 HXJM `apa_file`(`apa08`/`apa09`);引擎负责增量、归档、缺件双口径、Excel 与企微批次汇总。 -- **销售一期来源**:ERP 打印 PO(查询与打印方式待确认)、OA 销货放行单一期模拟页面(后期换新接口)、文档库扫描报关资料/发票/报关单/提单。获取后写入 `销售开票附件/{yyyy}/{MM}/{类型目录}/`,再归档到同月 `所有归档/{invoice}/`。 -- **文档库**:复用现有 DMS(`CONTRACT_DMS_BASE_URL`、`/Login/_api/Login`、`/Api/_api/APS/Public/Item/Page`、`SaveFolder`、`Item/Copy`、现有账号);LibraryID 与合同相同,销售开票附件只单独配置根 FolderID。归档复制策略为同名跳过。 +- **目标架构**:通用检核引擎 + 业务方 Profile + 来源 Adapter。**每周二**处理上一个自然月;invoice 主体来自 HXJM `oma_file`(`oma10`/`oma02`,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00` 为 11/12/13);引擎负责增量、归档、缺件双口径、Excel 与企微批次汇总。 +- **销售一期来源**:PO 订单由 HXOPS 按制式采购单生成 PDF 并上传到当月「PO订单」目录。发票在 HXJM,采购单在 **TGHX**(多角);关联已确认 `TRIM(oma99)=TRIM(pmm99)`,见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)。OA 销货放行单一期模拟页面、文档库扫描报关资料/发票/报关单/提单。获取后写入 `销售开票附件/{yyyy}/{MM}/{类型目录}/`,再归档到同月 `所有归档/{invoice}/`。 +- **文档库**:复用现有 DMS(`CONTRACT_DMS_BASE_URL`、`/Login/_api/Login`、`/Api/_api/APS/Public/Item/Page`、`SaveFolder`、`Attachment/Upload`、`Item/CreateFiles`、`Item/Copy`、现有账号);LibraryID 与合同相同,销售开票附件只单独配置根 FolderID。类型目录上传与归档复制均为同名跳过。 - **通知**:排程/任务界面从系统用户多选企微接收人;未配置不发送。 - **判定边界**:不读取文件内容、不调用 LLM 判断合格、不回写 ERP。批次级依赖不可用时整批失败,不得把空结果批量判为缺件。 -- **当前代码**:周任务已切到上月清单 + 文档库类型目录扫描 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微;ERP PO / OA 打印仍为占位 Adapter。旧共享盘扫描、Chatflow Tool 与 `voucher_check_invoice_states` / `voucher_check_run_items` 已删除。 +- **当前代码**:周任务已切到上月 `oma_file` 清单 + 文档库类型目录扫描 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微;PO 制式 PDF 生成与上传到「PO订单」已实现。ERP PO 取数(`HXJM.oma99` → `TGHX.pmm99`)已接线,仅独立抓取;`erp_po_print.fetch` / OA 仍为占位,周任务不调用。旧共享盘扫描、Chatflow Tool 与 `voucher_check_invoice_states` / `voucher_check_run_items` 已删除。 - 详细业务需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md),研发落地设计见 [docs/features/accounting-voucher-check/technical-design.md](features/accounting-voucher-check/technical-design.md)。 ### 2.x 货代发货通知批次库存能力 diff --git a/frontend/src/locales/en/errors.json b/frontend/src/locales/en/errors.json index caea9a78..520d72cc 100644 --- a/frontend/src/locales/en/errors.json +++ b/frontend/src/locales/en/errors.json @@ -524,6 +524,8 @@ "VOUCHER_CHECK_RUN_IN_PROGRESS": "An accounting voucher check is already queued or running. Try again later.", "VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "The accounting voucher check schedule was not found.", "VOUCHER_CHECK_PERSIST_FAILED": "Failed to persist voucher check results.", + "VOUCHER_CHECK_PO_PDF_INVALID": "Purchase-order PDF data is invalid. Provide a valid invoice number and order number.", + "VOUCHER_CHECK_PO_UPLOAD_FAILED": "Failed to upload the purchase-order PDF to the DMS PO-order folder.", "TRANSFER_PERMISSION_DENIED": "No in-transit transfer permission.", "TRANSFER_RECEIPT_NOT_MATURED": "Same-day receipt is not matured yet.", "TRANSFER_FILE_NOT_READY": "Receipt file is not ready.", diff --git a/frontend/src/locales/th/errors.json b/frontend/src/locales/th/errors.json index a4016691..7e5e9d87 100644 --- a/frontend/src/locales/th/errors.json +++ b/frontend/src/locales/th/errors.json @@ -524,6 +524,8 @@ "VOUCHER_CHECK_RUN_IN_PROGRESS": "งานตรวจเอกสารบัญชียังอยู่ในคิวหรือกำลังทำงาน โปรดลองใหม่ภายหลัง", "VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "ไม่พบตารางงานตรวจเอกสารบัญชี", "VOUCHER_CHECK_PERSIST_FAILED": "บันทึกผลการตรวจไม่สำเร็จ", + "VOUCHER_CHECK_PO_PDF_INVALID": "ข้อมูล PDF ใบสั่งซื้อไม่ถูกต้อง กรุณาระบุเลขที่ใบแจ้งหนี้และเลขที่ใบสั่งที่ถูกต้อง", + "VOUCHER_CHECK_PO_UPLOAD_FAILED": "อัปโหลดไฟล์ PDF ใบสั่งซื้อไปยังโฟลเดอร์ PO订单 ในคลังเอกสารไม่สำเร็จ", "TRANSFER_PERMISSION_DENIED": "ไม่มีสิทธิ์โอนระหว่างคลัง", "TRANSFER_RECEIPT_NOT_MATURED": "การรับของวันนี้ยังไม่พร้อมดำเนินการ", "TRANSFER_FILE_NOT_READY": "ไฟล์รับของยังไม่พร้อม", diff --git a/frontend/src/locales/zh-CN/errors.json b/frontend/src/locales/zh-CN/errors.json index 8286b10c..6f04828d 100644 --- a/frontend/src/locales/zh-CN/errors.json +++ b/frontend/src/locales/zh-CN/errors.json @@ -524,6 +524,8 @@ "VOUCHER_CHECK_RUN_IN_PROGRESS": "立账凭证检核正在执行或排队中,请稍后再试。", "VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "未找到立账凭证检核排程任务。", "VOUCHER_CHECK_PERSIST_FAILED": "检核结果落库失败。", + "VOUCHER_CHECK_PO_PDF_INVALID": "采购单 PDF 数据无效:请提供合法的发票号和订单号。", + "VOUCHER_CHECK_PO_UPLOAD_FAILED": "采购单 PDF 上传到文档库「PO订单」目录失败。", "TRANSFER_PERMISSION_DENIED": "无在途调拨权限。", "TRANSFER_RECEIPT_NOT_MATURED": "当天收料尚未成熟,不可查询或调拨。", "TRANSFER_FILE_NOT_READY": "收料文件尚未就绪。", diff --git a/frontend/src/locales/zh-TW/errors.json b/frontend/src/locales/zh-TW/errors.json index c1a79a33..8a1815b8 100644 --- a/frontend/src/locales/zh-TW/errors.json +++ b/frontend/src/locales/zh-TW/errors.json @@ -524,6 +524,8 @@ "VOUCHER_CHECK_RUN_IN_PROGRESS": "立帳憑證檢核正在執行或排隊中,請稍後再試。", "VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "找不到立帳憑證檢核排程任務。", "VOUCHER_CHECK_PERSIST_FAILED": "檢核結果寫入失敗。", + "VOUCHER_CHECK_PO_PDF_INVALID": "採購單 PDF 資料無效:請提供合法的發票號和訂單號。", + "VOUCHER_CHECK_PO_UPLOAD_FAILED": "採購單 PDF 上傳到文件庫「PO訂單」目錄失敗。", "TRANSFER_PERMISSION_DENIED": "無在途調撥權限。", "TRANSFER_RECEIPT_NOT_MATURED": "當天收料尚未成熟,不可查詢或調撥。", "TRANSFER_FILE_NOT_READY": "收料檔案尚未就緒。",