feat(invoice-check): 从erp查询PO订单数据来源
This commit is contained in:
1 parent
b15dd6808f
commit
1c34ab962f
40 files changed
+2682
-395
No files matched your search
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/__init__.py
|
||||
|
||||
用途:登记销售一期 Adapter(主体、目录扫描、PO/OA 占位、归档占位)。
|
||||
依赖:各 adapter 模块。
|
||||
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例。
|
||||
用途:登记销售一期 Adapter(主体、目录扫描、PO 取数、OA 占位、归档)。
|
||||
依赖:各 adapter 模块;PO 制式 PDF 在 voucher_check.po_order;ERP 取数在 erp_po_repository。
|
||||
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例,不调用 erp_po_print.fetch。
|
||||
"""
|
||||
|
||||
from app.services.voucher_check.adapters.base import (
|
||||
|
||||
@@ -80,7 +80,7 @@ class DirectoryScanAdapter(Protocol):
|
||||
|
||||
|
||||
class AcquireAdapter(Protocol):
|
||||
"""把外部单据打印后写入类型目录;PO / 销货放行单一期仅占位。"""
|
||||
"""把外部单据打印后写入类型目录;PO 制式 PDF 见 po_order,ERP 取数见 erp_po_repository。"""
|
||||
|
||||
source_type: str
|
||||
wired: bool
|
||||
@@ -88,7 +88,7 @@ class AcquireAdapter(Protocol):
|
||||
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
|
||||
"""
|
||||
获取并落入类型目录。
|
||||
【AI 触发时机】仅当独立抓取任务启用且 Adapter.wired=True 时调用;周任务不调用。
|
||||
【AI 触发时机】仅当 Adapter.wired=True 且独立抓取走本方法时调用;周任务不调用。PO 独立抓取请用 ErpPoPrintAdapter.fetch_documents,不要走 fetch。
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
@@ -1,32 +1,39 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/erp_po_print.py
|
||||
|
||||
用途:ERP 反查 PO 并打印 PDF 写入「PO订单」类型目录的占位 Adapter。
|
||||
依赖:adapters.base。
|
||||
逻辑:查询/打印方式待确认,周任务不调用;独立抓取任务启用前 wired=False。
|
||||
用途:ERP 反查 PO 后写入「PO订单」类型目录的 Adapter。
|
||||
依赖:adapters.base、erp_po_repository、voucher_check.po_order。
|
||||
逻辑:fetch_documents / publish_for_invoices 已接线(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
|
||||
@@ -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 预先算好。
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/dms_client.py
|
||||
|
||||
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、复制;不移动原件)。
|
||||
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。
|
||||
依赖:requests、Flask 配置;登录接口与合同库相同。
|
||||
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。归档复制策略为同名跳过。
|
||||
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
import threading
|
||||
import time
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
@@ -178,9 +179,44 @@ class SalesDmsClient:
|
||||
raise ServiceUnavailableError(
|
||||
data.get("Msg") or failure_message,
|
||||
code=failure_code,
|
||||
details={"dms_data": data.get("Data")} if data.get("Data") not in (None, "", {}) else {},
|
||||
)
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def _post_multipart(
|
||||
cls,
|
||||
path: str,
|
||||
*,
|
||||
files: dict[str, Any],
|
||||
data: dict[str, Any] | None = None,
|
||||
timeout: int = 60,
|
||||
failure_code: str = "VOUCHER_CHECK.DMS_UNAVAILABLE",
|
||||
failure_message: str = "文档库上传失败",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
POST multipart 到现网 DMS(用于附件 Upload)。
|
||||
核心逻辑:不手工设 Content-Type,交给 requests 带 boundary;401/403 刷新会话后重试。
|
||||
"""
|
||||
url = f"{cls.base_url()}{path}"
|
||||
try:
|
||||
session = cls._session()
|
||||
response = session.post(url, files=files, data=data or {}, timeout=timeout)
|
||||
if response.status_code in {401, 403}:
|
||||
session = cls._session(refresh=True)
|
||||
response = session.post(url, files=files, data=data or {}, timeout=timeout)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
except (requests.RequestException, ValueError) as exc:
|
||||
raise ServiceUnavailableError(failure_message, code=failure_code) from exc
|
||||
if int(payload.get("Code") or 0) != 0:
|
||||
raise ServiceUnavailableError(
|
||||
payload.get("Msg") or failure_message,
|
||||
code=failure_code,
|
||||
details={"dms_data": payload.get("Data")} if payload.get("Data") not in (None, "", {}) else {},
|
||||
)
|
||||
return payload
|
||||
|
||||
@classmethod
|
||||
def page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]:
|
||||
"""
|
||||
@@ -400,3 +436,144 @@ class SalesDmsClient:
|
||||
details={"leaf_name": wanted},
|
||||
)
|
||||
return dest_row, False
|
||||
|
||||
@classmethod
|
||||
def ensure_period_type_folder(cls, *, period_month: date, type_folder: str) -> str:
|
||||
"""
|
||||
确保销售开票附件/{yyyy}/{MM}/{类型目录} 存在并返回 FolderID。
|
||||
【AI 触发时机】要把新生成的 PO PDF 写入类型目录时调用;年/月/类型目录没有就建。
|
||||
|
||||
Args:
|
||||
period_month: 检核月份(用年、月两位目录名)。
|
||||
type_folder: 类型目录名,销售 PO 固定为「PO订单」。
|
||||
"""
|
||||
wanted = str(type_folder or "").strip()
|
||||
if not wanted:
|
||||
raise ValidationError("类型目录名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
cls.ensure_configured()
|
||||
root = cls.root_folder_id()
|
||||
year_id = cls.ensure_folder(parent_folder_id=root, leaf_name=f"{period_month.year:04d}")
|
||||
month_id = cls.ensure_folder(parent_folder_id=year_id, leaf_name=f"{period_month.month:02d}")
|
||||
return cls.ensure_folder(parent_folder_id=month_id, leaf_name=wanted)
|
||||
|
||||
@classmethod
|
||||
def upload_attachment(cls, *, filename: str, content: bytes) -> dict[str, Any]:
|
||||
"""
|
||||
把文件二进制上传为未入目录的附件,返回 Data(须含 ID)。
|
||||
核心逻辑:现网「新建文件」先 Upload 附件,再 CreateFiles 挂到文件夹。
|
||||
"""
|
||||
name = str(filename or "").strip()
|
||||
if not name:
|
||||
raise ValidationError("上传文件名不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID")
|
||||
if not content:
|
||||
raise ValidationError("上传文件内容不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID")
|
||||
payload = cls._post_multipart(
|
||||
"/Api/_api/DMS/Public/Attachment/Upload",
|
||||
files={"file": (name, content, "application/pdf")},
|
||||
timeout=120,
|
||||
failure_code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
|
||||
failure_message="文档库上传附件失败",
|
||||
)
|
||||
data = payload.get("Data")
|
||||
if not isinstance(data, dict) or not str(data.get("ID") or "").strip():
|
||||
raise ServiceUnavailableError(
|
||||
"文档库上传附件后未返回 AttachmentID",
|
||||
code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
|
||||
)
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def create_files(
|
||||
cls,
|
||||
*,
|
||||
parent_folder_id: str,
|
||||
files: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把已上传附件登记到指定文件夹(现网 functionCreationFile)。
|
||||
核心逻辑:POST Item/CreateFiles;Files[].AttachmentID 来自 Attachment/Upload。
|
||||
"""
|
||||
dest = str(parent_folder_id or "").strip()
|
||||
if not dest:
|
||||
raise ValidationError("上传目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
if not files:
|
||||
raise ValidationError("上传文件列表不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
return cls._post_json(
|
||||
"/Api/_api/APS/Public/Item/CreateFiles",
|
||||
{
|
||||
"LibraryID": cls.library_id(),
|
||||
"CategoryID": "",
|
||||
"ParentFolderID": dest,
|
||||
"Files": files,
|
||||
"TermID": [],
|
||||
"CheckedOutState": 0,
|
||||
"CheckedOutMemo": "",
|
||||
},
|
||||
timeout=60,
|
||||
failure_code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
|
||||
failure_message="文档库创建文件失败",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def upload_file_skip_same_name(
|
||||
cls,
|
||||
*,
|
||||
parent_folder_id: str,
|
||||
leaf_name: str,
|
||||
content: bytes,
|
||||
) -> tuple[dict[str, Any], bool]:
|
||||
"""
|
||||
上传文件到类型目录;目标已有同名则跳过、不覆盖。
|
||||
核心逻辑:先 Page 查 LeafName;没有则 Upload 附件再 CreateFiles。CreateFiles 报同名视为跳过。
|
||||
"""
|
||||
wanted = str(leaf_name or "").strip()
|
||||
dest = str(parent_folder_id or "").strip()
|
||||
if not dest:
|
||||
raise ValidationError("上传目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
if not wanted:
|
||||
raise ValidationError("上传文件名不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID")
|
||||
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
|
||||
attachment = cls.upload_attachment(filename=wanted, content=content)
|
||||
extension = str(attachment.get("Extension") or Path(wanted).suffix or ".pdf").strip()
|
||||
if extension and not extension.startswith("."):
|
||||
extension = f".{extension}"
|
||||
file_row = {
|
||||
"LeafName": wanted,
|
||||
"AttachmentID": str(attachment.get("ID") or "").strip(),
|
||||
"CheckedOutState": 0,
|
||||
"CheckedOutMemo": "",
|
||||
"Extension": extension,
|
||||
"FieldValues": [],
|
||||
}
|
||||
|
||||
try:
|
||||
cls.create_files(parent_folder_id=dest, files=[file_row])
|
||||
except ServiceUnavailableError as exc:
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
same_names = ((exc.details or {}).get("dms_data") or {}).get("SameLeafNames") or []
|
||||
if same_names or _is_name_conflict(exc.message):
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
raise
|
||||
|
||||
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if dest_row:
|
||||
return dest_row, False
|
||||
# 部分现网 CreateFiles 后 LeafName 不含扩展名,再按无后缀查一次。
|
||||
stem = Path(wanted).stem
|
||||
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=stem)
|
||||
if dest_row:
|
||||
return dest_row, False
|
||||
raise ServiceUnavailableError(
|
||||
"上传成功但类型目录未找到同名文件",
|
||||
code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
|
||||
details={"leaf_name": wanted},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/erp_po_repository.py
|
||||
|
||||
用途:按销售发票从 HXJM.oma99 对 TGHX.pmm99,取出制式采购单字段。
|
||||
依赖:erp_repository.open_erp_connection、po_order.models、voucher_check.config。
|
||||
逻辑:独立抓取任务调用;不进周二 runner。oma99 为空时用 oma16 走 oga99(12/13)或 oea99(11)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from typing import Any, Iterable, Mapping, Sequence
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.config import VoucherCheckEngineConfig
|
||||
from app.services.voucher_check.erp_repository import _erp_unavailable, is_sales_invoice_no, open_erp_connection
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine
|
||||
|
||||
INVOICE_SCHEMA = "HXJM"
|
||||
PO_SCHEMA = "TGHX"
|
||||
_BATCH_SIZE = 80
|
||||
|
||||
_TA_IMA02 = {"1": "无卤", "2": "不管控"}
|
||||
_TA_IMA03 = {"1": "RoHS", "0": "非环保", "9": "ERS"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InvoiceFlow:
|
||||
"""一张发票对应的多角流程序号。"""
|
||||
|
||||
invoice_no: str
|
||||
flow_no: str
|
||||
oma00: str = ""
|
||||
oma16: str = ""
|
||||
|
||||
|
||||
def _as_text(value: Any) -> str:
|
||||
"""TRIM 后收成字符串;None 当空串。"""
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _chunks(items: Sequence[str], size: int) -> Iterable[list[str]]:
|
||||
"""按绑定 IN 列表切批,避免超长 SQL。"""
|
||||
for index in range(0, len(items), size):
|
||||
yield list(items[index : index + size])
|
||||
|
||||
|
||||
def _in_clause(prefix: str, values: Sequence[str]) -> tuple[str, dict[str, str]]:
|
||||
"""
|
||||
生成 :prefix0,:prefix1 绑定与参数。
|
||||
核心逻辑:占位符名由本函数生成,禁止把业务值拼进 SQL。
|
||||
"""
|
||||
binds: dict[str, str] = {}
|
||||
names: list[str] = []
|
||||
for index, value in enumerate(values):
|
||||
key = f"{prefix}{index}"
|
||||
names.append(f":{key}")
|
||||
binds[key] = value
|
||||
return ", ".join(names), binds
|
||||
|
||||
|
||||
def _format_date(value: Any) -> str:
|
||||
"""展示用日期:2016/5/28,月日不补零。"""
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, datetime):
|
||||
value = value.date()
|
||||
if not isinstance(value, date):
|
||||
return _as_text(value)
|
||||
return f"{value.year}/{value.month}/{value.day}"
|
||||
|
||||
|
||||
def _format_decimal(value: Any, scale: int, *, thousands: bool = False) -> str:
|
||||
"""按 azi 小数位格式化;金额可带千分位。"""
|
||||
if value is None or value == "":
|
||||
return ""
|
||||
digits = max(0, int(scale or 0))
|
||||
quant = Decimal("1").scaleb(-digits)
|
||||
number = Decimal(str(value)).quantize(quant, rounding=ROUND_HALF_UP)
|
||||
if thousands:
|
||||
return f"{number:,.{digits}f}"
|
||||
if digits == 0:
|
||||
return str(int(number))
|
||||
return f"{number:.{digits}f}"
|
||||
|
||||
|
||||
def _format_qty(value: Any) -> str:
|
||||
"""采购量去掉无意义的尾随零。"""
|
||||
if value is None or value == "":
|
||||
return ""
|
||||
number = Decimal(str(value))
|
||||
if number == number.to_integral_value():
|
||||
return str(int(number))
|
||||
return format(number.normalize(), "f")
|
||||
|
||||
|
||||
def _join_address(*parts: Any) -> str:
|
||||
"""送货/账单地址:空段丢掉再拼接。"""
|
||||
chunks = [_as_text(part) for part in parts]
|
||||
return "".join(chunk for chunk in chunks if chunk)
|
||||
|
||||
|
||||
def _halogen_text(ta_ima02: Any, ta_ima03: Any) -> str:
|
||||
"""版面目前一列;优先环保等级(样张 RoHS),否则卤素管控。"""
|
||||
code3 = _as_text(ta_ima03)
|
||||
if code3 in _TA_IMA03:
|
||||
return _TA_IMA03[code3]
|
||||
code2 = _as_text(ta_ima02)
|
||||
return _TA_IMA02.get(code2, "")
|
||||
|
||||
|
||||
def _azi_scale(value: Any, default: int) -> int:
|
||||
"""币别小数位;空则用默认。"""
|
||||
text = _as_text(value)
|
||||
if not text:
|
||||
return default
|
||||
try:
|
||||
return max(0, int(Decimal(text)))
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
|
||||
def map_po_document(invoice_no: str, line_rows: Sequence[Mapping[str, Any]]) -> PoOrderDocument:
|
||||
"""
|
||||
把同一张 TGHX 采购单的明细行收成 PoOrderDocument。
|
||||
【AI 触发时机】ERP 已查出 pmm/pmn 行、生成 PDF 之前调用。
|
||||
|
||||
核心逻辑:头栏取首行;合计对 pmn88/pmn88t 求和;到货日用 pmn34;版本 pmnud02;
|
||||
原始编号优先 ta_ima11,否则 pmn24。不写 SQL。
|
||||
|
||||
Args:
|
||||
invoice_no: 销售发票号,只用于文件名。
|
||||
line_rows: 同一 pmm01 的有序明细(已是 dict,键为小写列名)。
|
||||
|
||||
Returns:
|
||||
可交给 save_po_order_pdf 的文档。
|
||||
|
||||
Raises:
|
||||
ValueError: 无明细或缺少 pmm01。
|
||||
"""
|
||||
if not line_rows:
|
||||
raise ValueError("采购单没有明细行")
|
||||
head = line_rows[0]
|
||||
po_no = _as_text(head.get("po_no") or head.get("pmm01"))
|
||||
if not po_no:
|
||||
raise ValueError("缺少采购单号")
|
||||
price_scale = _azi_scale(head.get("azi03"), 6)
|
||||
amount_scale = _azi_scale(head.get("azi04"), 2)
|
||||
total_scale = _azi_scale(head.get("azi05"), amount_scale)
|
||||
price_code = _as_text(head.get("price_term_code"))
|
||||
price_name = _as_text(head.get("price_term_name"))
|
||||
price_term = f"{price_code} {price_name}".strip()
|
||||
lines: list[PoOrderLine] = []
|
||||
untax_total = Decimal("0")
|
||||
tax_total = Decimal("0")
|
||||
for raw in line_rows:
|
||||
untax_amt = raw.get("pmn88")
|
||||
tax_amt = raw.get("pmn88t")
|
||||
if untax_amt not in (None, ""):
|
||||
untax_total += Decimal(str(untax_amt))
|
||||
if tax_amt not in (None, ""):
|
||||
tax_total += Decimal(str(tax_amt))
|
||||
origin_no = _as_text(raw.get("ta_ima11")) or _as_text(raw.get("pmn24"))
|
||||
lines.append(
|
||||
PoOrderLine(
|
||||
seq=_as_text(raw.get("pmn02") or (len(lines) + 1)),
|
||||
item_no=_as_text(raw.get("pmn04")),
|
||||
name=_as_text(raw.get("pmn041")),
|
||||
spec=_as_text(raw.get("ima021")),
|
||||
qty=_format_qty(raw.get("pmn20")),
|
||||
unit=_as_text(raw.get("pmn07")),
|
||||
arrive=_format_date(raw.get("pmn34")),
|
||||
origin_no=origin_no,
|
||||
version=_as_text(raw.get("pmnud02")),
|
||||
untax_price=_format_decimal(raw.get("pmn31"), price_scale),
|
||||
tax_price=_format_decimal(raw.get("pmn31t"), price_scale),
|
||||
untax_amt=_format_decimal(untax_amt, amount_scale, thousands=True),
|
||||
tax_amt=_format_decimal(tax_amt, amount_scale, thousands=True),
|
||||
halogen=_halogen_text(raw.get("ta_ima02"), raw.get("ta_ima03")),
|
||||
vendor_item=_as_text(raw.get("pmn06")),
|
||||
)
|
||||
)
|
||||
return PoOrderDocument(
|
||||
invoice_no=_as_text(invoice_no),
|
||||
po_no=po_no,
|
||||
po_date=_format_date(head.get("po_date") or head.get("pmm04")),
|
||||
po_type=_as_text(head.get("po_type") or head.get("smydesc")),
|
||||
pay_term=_as_text(head.get("pay_term") or head.get("pma02")),
|
||||
tax_type=_as_text(head.get("tax_type") or head.get("gec02")),
|
||||
price_term=price_term,
|
||||
currency=_as_text(head.get("currency") or head.get("pmm22")),
|
||||
ship_address=_join_address(
|
||||
head.get("ship031"),
|
||||
head.get("ship032"),
|
||||
head.get("ship033"),
|
||||
head.get("ship034"),
|
||||
head.get("ship035"),
|
||||
),
|
||||
bill_address=_join_address(
|
||||
head.get("bill031"),
|
||||
head.get("bill032"),
|
||||
head.get("bill033"),
|
||||
head.get("bill034"),
|
||||
head.get("bill035"),
|
||||
),
|
||||
vendor_code=_as_text(head.get("vendor_code") or head.get("pmm09")),
|
||||
vendor_name=_as_text(head.get("vendor_name") or head.get("pmc081")),
|
||||
vendor_tel=_as_text(head.get("vendor_tel") or head.get("pmc10")),
|
||||
vendor_fax=_as_text(head.get("vendor_fax") or head.get("pmc11")),
|
||||
vendor_addr=_as_text(head.get("vendor_addr") or head.get("pmc091")),
|
||||
company_name=_as_text(head.get("company_name") or head.get("zo02")),
|
||||
company_address=_as_text(head.get("company_address") or head.get("zo041")),
|
||||
company_phone=_as_text(head.get("company_phone") or head.get("zo05")),
|
||||
company_fax=_as_text(head.get("company_fax") or head.get("zo09")),
|
||||
maker="",
|
||||
untax_total=_format_decimal(untax_total, total_scale, thousands=True),
|
||||
tax_total=_format_decimal(tax_total, total_scale, thousands=True),
|
||||
lines=tuple(lines),
|
||||
)
|
||||
|
||||
|
||||
def _invoice_key_sql(placeholders: str) -> str:
|
||||
"""HXJM 应收头:发票号 → 类别、来源单、多角序号。"""
|
||||
return f"""
|
||||
SELECT DISTINCT
|
||||
TRIM(oma10) AS invoice_no,
|
||||
TRIM(oma00) AS oma00,
|
||||
TRIM(oma16) AS oma16,
|
||||
TRIM(oma99) AS oma99
|
||||
FROM {INVOICE_SCHEMA}.oma_file
|
||||
WHERE TRIM(oma10) IN ({placeholders})
|
||||
AND TRIM(omaconf) = 'Y'
|
||||
AND TRIM(omavoid) = 'N'
|
||||
AND TRIM(oma64) = '1'
|
||||
AND TRIM(oma00) IN ('11', '12', '13')
|
||||
"""
|
||||
|
||||
|
||||
def _fallback_sql(table: str, key_col: str, flow_col: str, placeholders: str) -> str:
|
||||
"""oma99 为空时,从出货单或订单借多角序号。"""
|
||||
return f"""
|
||||
SELECT TRIM({key_col}) AS doc_no,
|
||||
TRIM({flow_col}) AS flow_no
|
||||
FROM {INVOICE_SCHEMA}.{table}
|
||||
WHERE TRIM({key_col}) IN ({placeholders})
|
||||
"""
|
||||
|
||||
|
||||
def _po_detail_sql(placeholders: str) -> str:
|
||||
"""TGHX 采购单头身 + 码表,对照 apmr900;过滤作废/无效/BKR。"""
|
||||
s = PO_SCHEMA
|
||||
return f"""
|
||||
SELECT TRIM(pmm.pmm99) AS flow_no,
|
||||
TRIM(pmm.pmm01) AS po_no,
|
||||
pmm.pmm04 AS po_date,
|
||||
TRIM(smy.smydesc) AS po_type,
|
||||
TRIM(pma.pma02) AS pay_term,
|
||||
TRIM(gec.gec02) AS tax_type,
|
||||
TRIM(pmm.pmm41) AS price_term_code,
|
||||
TRIM(pnz.pnz02) AS price_term_name,
|
||||
TRIM(pmm.pmm22) AS currency,
|
||||
TRIM(pmm.pmm09) AS vendor_code,
|
||||
TRIM(pmc.pmc081) AS vendor_name,
|
||||
TRIM(pmc.pmc10) AS vendor_tel,
|
||||
TRIM(pmc.pmc11) AS vendor_fax,
|
||||
TRIM(pmc.pmc091) AS vendor_addr,
|
||||
TRIM(ship.pme031) AS ship031,
|
||||
TRIM(ship.pme032) AS ship032,
|
||||
TRIM(ship.pme033) AS ship033,
|
||||
TRIM(ship.pme034) AS ship034,
|
||||
TRIM(ship.pme035) AS ship035,
|
||||
TRIM(bill.pme031) AS bill031,
|
||||
TRIM(bill.pme032) AS bill032,
|
||||
TRIM(bill.pme033) AS bill033,
|
||||
TRIM(bill.pme034) AS bill034,
|
||||
TRIM(bill.pme035) AS bill035,
|
||||
TRIM(zo.zo02) AS company_name,
|
||||
TRIM(zo.zo041) AS company_address,
|
||||
TRIM(zo.zo05) AS company_phone,
|
||||
TRIM(zo.zo09) AS company_fax,
|
||||
pmn.pmn02 AS pmn02,
|
||||
TRIM(pmn.pmn04) AS pmn04,
|
||||
TRIM(pmn.pmn041) AS pmn041,
|
||||
TRIM(pmn.pmn06) AS pmn06,
|
||||
TRIM(pmn.pmn07) AS pmn07,
|
||||
pmn.pmn20 AS pmn20,
|
||||
TRIM(pmn.pmn24) AS pmn24,
|
||||
pmn.pmn31 AS pmn31,
|
||||
pmn.pmn31t AS pmn31t,
|
||||
pmn.pmn34 AS pmn34,
|
||||
pmn.pmn88 AS pmn88,
|
||||
pmn.pmn88t AS pmn88t,
|
||||
TRIM(pmn.pmnud02) AS pmnud02,
|
||||
TRIM(ima.ima021) AS ima021,
|
||||
TRIM(ima.ta_ima02) AS ta_ima02,
|
||||
TRIM(ima.ta_ima03) AS ta_ima03,
|
||||
TRIM(ima.ta_ima11) AS ta_ima11,
|
||||
azi.azi03 AS azi03,
|
||||
azi.azi04 AS azi04,
|
||||
azi.azi05 AS azi05
|
||||
FROM {s}.pmm_file pmm
|
||||
JOIN {s}.pmn_file pmn ON pmn.pmn01 = pmm.pmm01
|
||||
LEFT JOIN {s}.smy_file smy ON pmm.pmm01 LIKE TRIM(smy.smyslip) || '-%'
|
||||
LEFT JOIN {s}.pmc_file pmc ON TRIM(pmc.pmc01) = TRIM(pmm.pmm09)
|
||||
LEFT JOIN {s}.pma_file pma ON TRIM(pma.pma01) = TRIM(pmm.pmm20)
|
||||
LEFT JOIN {s}.gec_file gec ON TRIM(gec.gec01) = TRIM(pmm.pmm21) AND TRIM(gec.gec011) = '1'
|
||||
LEFT JOIN {s}.pnz_file pnz ON TRIM(pnz.pnz01) = TRIM(pmm.pmm41)
|
||||
LEFT JOIN {s}.azi_file azi ON TRIM(azi.azi01) = TRIM(pmm.pmm22)
|
||||
LEFT JOIN {s}.ima_file ima ON TRIM(ima.ima01) = TRIM(pmn.pmn04)
|
||||
LEFT JOIN {s}.pme_file ship ON TRIM(ship.pme01) = TRIM(pmm.pmm10)
|
||||
LEFT JOIN {s}.pme_file bill ON TRIM(bill.pme01) = TRIM(pmm.pmm11)
|
||||
LEFT JOIN {s}.zo_file zo ON zo.zo01 = '1'
|
||||
WHERE TRIM(pmm.pmm99) IN ({placeholders})
|
||||
AND TRIM(pmm.pmm18) != 'X'
|
||||
AND TRIM(pmm.pmmacti) = 'Y'
|
||||
AND NVL(TRIM(pmm.pmm02), ' ') != 'BKR'
|
||||
ORDER BY pmm.pmm01, pmn.pmn02
|
||||
"""
|
||||
|
||||
|
||||
def _rows_as_dicts(cursor: Any) -> list[dict[str, Any]]:
|
||||
"""把游标行收成小写键 dict。"""
|
||||
columns = [str(col[0]).lower() for col in (cursor.description or [])]
|
||||
return [dict(zip(columns, raw)) for raw in cursor]
|
||||
|
||||
|
||||
def _fetch_invoice_keys(cursor: Any, invoice_nos: Sequence[str]) -> list[dict[str, Any]]:
|
||||
"""分批查 HXJM 应收头。"""
|
||||
found: list[dict[str, Any]] = []
|
||||
for batch in _chunks(list(invoice_nos), _BATCH_SIZE):
|
||||
placeholders, binds = _in_clause("inv", batch)
|
||||
cursor.execute(_invoice_key_sql(placeholders), binds)
|
||||
found.extend(_rows_as_dicts(cursor))
|
||||
return found
|
||||
|
||||
|
||||
def _fetch_doc_flows(cursor: Any, table: str, key_col: str, flow_col: str, doc_nos: Sequence[str]) -> dict[str, str]:
|
||||
"""出货单/订单号 → 多角序号。"""
|
||||
mapping: dict[str, str] = {}
|
||||
unique = [item for item in dict.fromkeys(doc_nos) if item]
|
||||
for batch in _chunks(unique, _BATCH_SIZE):
|
||||
placeholders, binds = _in_clause("doc", batch)
|
||||
cursor.execute(_fallback_sql(table, key_col, flow_col, placeholders), binds)
|
||||
for row in _rows_as_dicts(cursor):
|
||||
doc_no = _as_text(row.get("doc_no"))
|
||||
flow_no = _as_text(row.get("flow_no"))
|
||||
if doc_no and flow_no:
|
||||
mapping[doc_no] = flow_no
|
||||
return mapping
|
||||
|
||||
|
||||
def resolve_invoice_flows(cursor: Any, invoice_nos: Sequence[str]) -> list[InvoiceFlow]:
|
||||
"""
|
||||
发票号 → 多角流程序号。
|
||||
核心逻辑:优先 TRIM(oma99);空则 12/13 查 oga99、11 查 oea99。同一发票多个序号会去重保留。
|
||||
"""
|
||||
wanted = [item for item in dict.fromkeys(_as_text(no) for no in invoice_nos) if is_sales_invoice_no(item)]
|
||||
if not wanted:
|
||||
return []
|
||||
keys = _fetch_invoice_keys(cursor, wanted)
|
||||
oga_docs = [_as_text(row.get("oma16")) for row in keys if _as_text(row.get("oma00")) in {"12", "13"} and not _as_text(row.get("oma99"))]
|
||||
oea_docs = [_as_text(row.get("oma16")) for row in keys if _as_text(row.get("oma00")) == "11" and not _as_text(row.get("oma99"))]
|
||||
oga_flows = _fetch_doc_flows(cursor, "oga_file", "oga01", "oga99", oga_docs) if oga_docs else {}
|
||||
oea_flows = _fetch_doc_flows(cursor, "oea_file", "oea01", "oea99", oea_docs) if oea_docs else {}
|
||||
|
||||
flows: list[InvoiceFlow] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for row in keys:
|
||||
invoice_no = _as_text(row.get("invoice_no"))
|
||||
oma00 = _as_text(row.get("oma00"))
|
||||
oma16 = _as_text(row.get("oma16"))
|
||||
flow_no = _as_text(row.get("oma99"))
|
||||
if not flow_no:
|
||||
if oma00 in {"12", "13"}:
|
||||
flow_no = oga_flows.get(oma16, "")
|
||||
elif oma00 == "11":
|
||||
flow_no = oea_flows.get(oma16, "")
|
||||
if not invoice_no or not flow_no:
|
||||
continue
|
||||
pair = (invoice_no, flow_no)
|
||||
if pair in seen:
|
||||
continue
|
||||
seen.add(pair)
|
||||
flows.append(InvoiceFlow(invoice_no=invoice_no, flow_no=flow_no, oma00=oma00, oma16=oma16))
|
||||
return flows
|
||||
|
||||
|
||||
def _fetch_po_lines(cursor: Any, flow_nos: Sequence[str]) -> list[dict[str, Any]]:
|
||||
"""按多角序号批量取 TGHX 采购明细。"""
|
||||
lines: list[dict[str, Any]] = []
|
||||
unique = [item for item in dict.fromkeys(flow_nos) if item]
|
||||
for batch in _chunks(unique, _BATCH_SIZE):
|
||||
placeholders, binds = _in_clause("flow", batch)
|
||||
cursor.execute(_po_detail_sql(placeholders), binds)
|
||||
lines.extend(_rows_as_dicts(cursor))
|
||||
return lines
|
||||
|
||||
|
||||
def fetch_po_documents_for_invoices(
|
||||
config: VoucherCheckEngineConfig,
|
||||
invoice_nos: Sequence[str],
|
||||
) -> list[PoOrderDocument]:
|
||||
"""
|
||||
按销售发票号从 ERP 组装制式采购单数据。
|
||||
【AI 触发时机】独立「抓取 PO」任务已有 invoice 清单、要生成 PDF 之前调用;不要在周二 runner 里调用。
|
||||
|
||||
核心逻辑:HXJM.oma99(空则 oga99/oea99)TRIM 后对 TGHX.pmm99;一票可多张 PO,每张一个文档。
|
||||
|
||||
Args:
|
||||
config: Oracle 只读连接。
|
||||
invoice_nos: 销售发票号;非 6 位以上字母数字的项会跳过。
|
||||
|
||||
Returns:
|
||||
PoOrderDocument 列表,按发票号、采购单号排序。找不到 PO 的发票不出现在结果里。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: Oracle 不可用。
|
||||
"""
|
||||
wanted = [item for item in dict.fromkeys(_as_text(no) for no in invoice_nos) if is_sales_invoice_no(item)]
|
||||
if not wanted:
|
||||
return []
|
||||
connection = None
|
||||
try:
|
||||
connection = open_erp_connection(config)
|
||||
cursor = connection.cursor()
|
||||
# [STEP 1] 发票 → 多角序号
|
||||
flows = resolve_invoice_flows(cursor, wanted)
|
||||
if not flows:
|
||||
return []
|
||||
# [STEP 2] 序号 → TGHX 采购单明细
|
||||
po_lines = _fetch_po_lines(cursor, [item.flow_no for item in flows])
|
||||
by_flow: dict[str, dict[str, list[dict[str, Any]]]] = defaultdict(lambda: defaultdict(list))
|
||||
for row in po_lines:
|
||||
flow_no = _as_text(row.get("flow_no"))
|
||||
po_no = _as_text(row.get("po_no"))
|
||||
if flow_no and po_no:
|
||||
by_flow[flow_no][po_no].append(row)
|
||||
# [STEP 3] 发票 × 采购单 交叉成文档
|
||||
documents: list[PoOrderDocument] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for flow in flows:
|
||||
for po_no, rows in by_flow.get(flow.flow_no, {}).items():
|
||||
key = (flow.invoice_no, po_no)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
documents.append(map_po_document(flow.invoice_no, rows))
|
||||
documents.sort(key=lambda item: (item.invoice_no, item.po_no))
|
||||
return documents
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise _erp_unavailable(config, exc) from exc
|
||||
finally:
|
||||
if connection is not None:
|
||||
try:
|
||||
connection.close()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1,13 +1,15 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/erp_repository.py
|
||||
|
||||
用途:从 Oracle HXJM 套账 apa_file 查询上一个自然月发票号集合。
|
||||
用途:从 Oracle HXJM 套账 oma_file 查询上一个自然月发票号集合;并提供共用只读连接。
|
||||
依赖:oracledb、Text2SQLService._init_oracle_client、voucher_check.config。
|
||||
逻辑:runner 阶段 A 调用;仅只读 SELECT;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。
|
||||
逻辑:runner 阶段 A 调用 fetch_month_invoices;采购单取数见 erp_po_repository,复用 open_erp_connection。
|
||||
只读 SELECT 已确认、未作废、状况码 1、帐款类别 11/12/13;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
@@ -16,16 +18,21 @@ from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.config import VoucherCheckEngineConfig
|
||||
|
||||
_TZ = ZoneInfo("Asia/Shanghai")
|
||||
_INVOICE_NO_RE = re.compile(r"^[A-Za-z0-9]{6,}$")
|
||||
|
||||
_INVOICE_SQL = """
|
||||
SELECT DISTINCT
|
||||
TRIM(apa08) AS invoice_no,
|
||||
TRUNC(apa09) AS invoice_date
|
||||
FROM apa_file
|
||||
WHERE apa09 >= :period_start
|
||||
AND apa09 < :next_period_start
|
||||
AND TRIM(apa08) IS NOT NULL
|
||||
ORDER BY TRUNC(apa09), TRIM(apa08)
|
||||
TRIM(oma10) AS invoice_no,
|
||||
TRUNC(oma02) AS invoice_date
|
||||
FROM oma_file
|
||||
WHERE oma02 >= :period_start
|
||||
AND oma02 < :next_period_start
|
||||
AND REGEXP_LIKE(TRIM(oma10), '^[A-Za-z0-9]{6,}$')
|
||||
AND TRIM(omaconf) = 'Y'
|
||||
AND TRIM(omavoid) = 'N'
|
||||
AND TRIM(oma64) = '1'
|
||||
AND TRIM(oma00) IN ('11', '12', '13')
|
||||
ORDER BY TRUNC(oma02), TRIM(oma10)
|
||||
"""
|
||||
|
||||
|
||||
@@ -37,6 +44,20 @@ class ErpInvoiceRow:
|
||||
invoice_date: date | None
|
||||
|
||||
|
||||
def is_sales_invoice_no(value: str | None) -> bool:
|
||||
"""
|
||||
判断 oma10 是否为可检核的销售发票号。
|
||||
核心逻辑:TRIM 后至少 6 位字母或数字(如 6975101806、EWZZ26090002)。现场 oma10 是手工录入,常被填成 0、空值或中文备注,那些不能当 invoice。
|
||||
|
||||
Args:
|
||||
value: oma10 原文。
|
||||
|
||||
Returns:
|
||||
True 表示可作为检核主体。
|
||||
"""
|
||||
return bool(_INVOICE_NO_RE.fullmatch(str(value or "").strip()))
|
||||
|
||||
|
||||
def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]:
|
||||
"""
|
||||
按 Asia/Shanghai 计算当前自然月起止。
|
||||
@@ -79,6 +100,64 @@ def previous_period_bounds(now: datetime | None = None) -> tuple[date, date, dat
|
||||
return period_month, current_month, period_start, next_start
|
||||
|
||||
|
||||
def open_erp_connection(config: VoucherCheckEngineConfig):
|
||||
"""
|
||||
打开立账凭证 Oracle 只读连接。
|
||||
核心逻辑:复用 Text2SQL 的 Instant Client 初始化;超时单位毫秒。调用方必须 close。
|
||||
|
||||
Args:
|
||||
config: 含 DSN/账号/超时的检核配置。
|
||||
|
||||
Returns:
|
||||
oracledb 连接。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 驱动缺失或连接失败。
|
||||
"""
|
||||
try:
|
||||
import oracledb
|
||||
except ImportError as exc:
|
||||
raise ServiceUnavailableError(
|
||||
"Oracle 驱动不可用",
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
) from exc
|
||||
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
try:
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
connection = oracledb.connect(
|
||||
user=config.erp_username,
|
||||
password=config.erp_password,
|
||||
dsn=config.erp_dsn,
|
||||
)
|
||||
connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000
|
||||
return connection
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise _erp_unavailable(config, exc) from exc
|
||||
|
||||
|
||||
def _erp_unavailable(config: VoucherCheckEngineConfig, exc: BaseException) -> ServiceUnavailableError:
|
||||
"""把 Oracle 异常收成统一错误码,日志只记类型不记密码。"""
|
||||
try:
|
||||
from flask import current_app
|
||||
|
||||
current_app.logger.error(
|
||||
"[voucher-check] ERP query failed dsn=%s error_type=%s",
|
||||
config.erp_dsn,
|
||||
type(exc).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return ServiceUnavailableError(
|
||||
"Oracle 查询失败",
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
details={"error_type": type(exc).__name__},
|
||||
)
|
||||
|
||||
|
||||
def fetch_month_invoices(
|
||||
config: VoucherCheckEngineConfig,
|
||||
*,
|
||||
@@ -86,6 +165,7 @@ def fetch_month_invoices(
|
||||
) -> tuple[date, list[ErpInvoiceRow]]:
|
||||
"""
|
||||
查询上一个自然月发票清单。
|
||||
核心逻辑:从 oma_file 按帐款日期 oma02 取上月;发票号 oma10 须为至少 6 位字母或数字(排除 0、空值、中文备注);仅确认(omaconf='Y')、未作废(omavoid='N')、状况码 oma64='1'、帐款类别 oma00 为 11/12/13。
|
||||
|
||||
Args:
|
||||
config: 含 Oracle DSN/账号的检核配置。
|
||||
@@ -98,26 +178,9 @@ def fetch_month_invoices(
|
||||
ServiceUnavailableError: Oracle 不可用。
|
||||
"""
|
||||
period_month, _current_month, period_start, next_start = previous_period_bounds(now)
|
||||
try:
|
||||
import oracledb
|
||||
except ImportError as exc:
|
||||
raise ServiceUnavailableError(
|
||||
"Oracle 驱动不可用",
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
) from exc
|
||||
|
||||
from flask import current_app
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
connection = None
|
||||
try:
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
connection = oracledb.connect(
|
||||
user=config.erp_username,
|
||||
password=config.erp_password,
|
||||
dsn=config.erp_dsn,
|
||||
)
|
||||
connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000
|
||||
connection = open_erp_connection(config)
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(
|
||||
_INVOICE_SQL,
|
||||
@@ -130,7 +193,7 @@ def fetch_month_invoices(
|
||||
seen: set[str] = set()
|
||||
for raw_no, raw_date in cursor:
|
||||
invoice_no = str(raw_no or "").strip()
|
||||
if not invoice_no or invoice_no in seen:
|
||||
if not is_sales_invoice_no(invoice_no) or invoice_no in seen:
|
||||
continue
|
||||
seen.add(invoice_no)
|
||||
invoice_date: date | None = None
|
||||
@@ -144,19 +207,7 @@ def fetch_month_invoices(
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
try:
|
||||
current_app.logger.error(
|
||||
"[voucher-check] ERP query failed dsn=%s error_type=%s",
|
||||
config.erp_dsn,
|
||||
type(exc).__name__,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
raise ServiceUnavailableError(
|
||||
"Oracle 查询失败",
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
details={"error_type": type(exc).__name__},
|
||||
) from exc
|
||||
raise _erp_unavailable(config, exc) from exc
|
||||
finally:
|
||||
if connection is not None:
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/__init__.py
|
||||
|
||||
用途:立账凭证「PO订单」制式采购单 PDF 的对外入口。
|
||||
依赖:models、filename、save、publish。
|
||||
逻辑:调用方先组装 PoOrderDocument(ERP 取数见 erp_po_repository),save_po_order_pdf 只写本地;
|
||||
publish_po_order_pdf 再上传。周检核 runner / erp_po_print.fetch 不要调用本包。
|
||||
"""
|
||||
|
||||
from app.services.voucher_check.po_order.filename import build_po_order_filename
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine, parse_po_order_document
|
||||
from app.services.voucher_check.po_order.publish import PoOrderPublishResult, publish_po_order_pdf
|
||||
from app.services.voucher_check.po_order.sample import sample_po_order_document
|
||||
from app.services.voucher_check.po_order.save import save_po_order_pdf
|
||||
|
||||
__all__ = [
|
||||
"PoOrderDocument",
|
||||
"PoOrderLine",
|
||||
"PoOrderPublishResult",
|
||||
"build_po_order_filename",
|
||||
"parse_po_order_document",
|
||||
"publish_po_order_pdf",
|
||||
"sample_po_order_document",
|
||||
"save_po_order_pdf",
|
||||
]
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/__main__.py
|
||||
|
||||
用途:用给定 JSON、对照样张或 ERP 发票号生成 `{invoice}-{订单号}.pdf`。
|
||||
依赖:save_po_order_pdf、sample_po_order_document;--invoice 另依赖 Flask 配置与 erp_po_repository。
|
||||
逻辑:python -m app.services.voucher_check.po_order --out-dir DIR [--json FILE|--sample|--invoice NO]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""
|
||||
命令行入口:JSON / 样张 / ERP 发票号 → 指定目录 PDF。
|
||||
【AI 触发时机】需要出 PO 订单 PDF、且不走周检核时运行本模块。
|
||||
"""
|
||||
parser = argparse.ArgumentParser(description="生成 PO 订单制式 PDF")
|
||||
parser.add_argument("--out-dir", required=True, help="PDF 输出目录")
|
||||
group = parser.add_mutually_exclusive_group(required=True)
|
||||
group.add_argument("--json", dest="json_path", help="采购单 JSON(含 invoice_no、po_no、lines)")
|
||||
group.add_argument("--sample", action="store_true", help="使用对照样张数据")
|
||||
group.add_argument("--invoice", help="从 ERP 按销售发票号取 TGHX 采购单(需应用配置)")
|
||||
args = parser.parse_args(argv)
|
||||
from app.services.voucher_check.po_order.save import save_po_order_pdf
|
||||
|
||||
if args.sample:
|
||||
from app.services.voucher_check.po_order.sample import sample_po_order_document
|
||||
|
||||
documents = [sample_po_order_document()]
|
||||
elif args.invoice:
|
||||
from app import create_app
|
||||
from app.services.voucher_check.config import load_engine_config
|
||||
from app.services.voucher_check.erp_po_repository import fetch_po_documents_for_invoices
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
documents = fetch_po_documents_for_invoices(load_engine_config(), [args.invoice])
|
||||
if not documents:
|
||||
print("no purchase order for invoice", args.invoice, file=sys.stderr)
|
||||
return 1
|
||||
else:
|
||||
payload = json.loads(Path(args.json_path).read_text(encoding="utf-8"))
|
||||
documents = [payload]
|
||||
for document in documents:
|
||||
print(save_po_order_pdf(document, args.out_dir))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 5.3 KiB |
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/filename.py
|
||||
|
||||
用途:按销售 Profile 规则生成 PO 订单 PDF 文件名。
|
||||
依赖:core.errors.ValidationError。
|
||||
逻辑:固定 `{invoice}-{order_no}.pdf`;禁止路径字符,供落盘与后续目录扫描共用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
_UNSAFE_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f]|(\.\.)')
|
||||
|
||||
|
||||
def build_po_order_filename(*, invoice_no: str, order_no: str) -> str:
|
||||
"""
|
||||
生成 `{invoice号}-{订单号}.pdf`。
|
||||
【AI 触发时机】保存或匹配 PO 订单 PDF 文件名时调用;不要自行拼接。
|
||||
|
||||
Args:
|
||||
invoice_no: 销售 invoice,禁止空串与路径字符。
|
||||
order_no: 采购单号(po_no),禁止空串与路径字符。
|
||||
|
||||
Returns:
|
||||
仅文件名,不含目录。
|
||||
|
||||
Raises:
|
||||
ValidationError: 缺号或含非法字符。
|
||||
"""
|
||||
invoice = str(invoice_no or "").strip()
|
||||
order = str(order_no or "").strip()
|
||||
if not invoice:
|
||||
raise ValidationError("缺少 invoice_no", code="VOUCHER_CHECK.PO_PDF_INVALID", details={"field": "invoice_no"})
|
||||
if not order:
|
||||
raise ValidationError("缺少 po_no", code="VOUCHER_CHECK.PO_PDF_INVALID", details={"field": "po_no"})
|
||||
if _UNSAFE_RE.search(invoice) or _UNSAFE_RE.search(order):
|
||||
raise ValidationError(
|
||||
"invoice 或订单号含非法路径字符",
|
||||
code="VOUCHER_CHECK.PO_PDF_INVALID",
|
||||
details=_unsafe_details(invoice, order),
|
||||
)
|
||||
return f"{invoice}-{order}.pdf"
|
||||
|
||||
|
||||
def _unsafe_details(invoice: str, order: str) -> dict[str, Any]:
|
||||
return {"invoice_no": invoice, "po_no": order}
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/fonts.py
|
||||
|
||||
用途:为制式采购单注册中文字体。
|
||||
依赖:reportlab;可选环境变量 VOUCHER_CHECK_PO_FONT_PATH。
|
||||
逻辑:优先系统宋体/Noto CJK(Docker 已装 fonts-noto-cjk),失败再回退 CID STSong-Light。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
|
||||
from reportlab.pdfbase.ttfonts import TTFont
|
||||
|
||||
_FONT_FAMILY = "VoucherPoCjk"
|
||||
_CID_FALLBACK = "STSong-Light"
|
||||
_REGISTERED: str | None = None
|
||||
|
||||
_CANDIDATES: tuple[tuple[str, int], ...] = (
|
||||
(r"C:\Windows\Fonts\simsun.ttc", 0),
|
||||
(r"C:\Windows\Fonts\simsun.ttf", 0),
|
||||
(r"C:\Windows\Fonts\msyh.ttc", 0),
|
||||
("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 2),
|
||||
("/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf", 0),
|
||||
("/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc", 2),
|
||||
("/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc", 2),
|
||||
("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", 0),
|
||||
("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 0),
|
||||
)
|
||||
|
||||
|
||||
def resolve_po_font() -> str:
|
||||
"""
|
||||
返回已注册的中文字体名,进程内只注册一次。
|
||||
核心逻辑:VOUCHER_CHECK_PO_FONT_PATH → 常见系统字体 → CID 内置宋体。
|
||||
"""
|
||||
global _REGISTERED
|
||||
if _REGISTERED:
|
||||
return _REGISTERED
|
||||
|
||||
env_path = str(os.getenv("VOUCHER_CHECK_PO_FONT_PATH") or "").strip()
|
||||
if env_path:
|
||||
registered = _try_ttf(Path(env_path), 0) or _try_ttf(Path(env_path), 2)
|
||||
if registered:
|
||||
_REGISTERED = registered
|
||||
return _REGISTERED
|
||||
|
||||
for raw, index in _CANDIDATES:
|
||||
registered = _try_ttf(Path(raw), index)
|
||||
if registered:
|
||||
_REGISTERED = registered
|
||||
return _REGISTERED
|
||||
|
||||
pdfmetrics.registerFont(UnicodeCIDFont(_CID_FALLBACK))
|
||||
_REGISTERED = _CID_FALLBACK
|
||||
return _REGISTERED
|
||||
|
||||
|
||||
def _try_ttf(path: Path, subfont_index: int) -> str | None:
|
||||
"""尝试把 TTF/TTC 注册为 VoucherPoCjk;文件不存在或 reportlab 拒收时返回 None。"""
|
||||
if not path.is_file():
|
||||
return None
|
||||
try:
|
||||
pdfmetrics.registerFont(TTFont(_FONT_FAMILY, str(path), subfontIndex=subfont_index))
|
||||
return _FONT_FAMILY
|
||||
except Exception:
|
||||
return None
|
||||
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/models.py
|
||||
|
||||
用途:制式采购单 PDF 的给定数据结构(与 ERP 查询解耦)。
|
||||
依赖:core.errors.ValidationError。
|
||||
逻辑:独立抓取任务拿到 invoice + PO 明细后填入本模型;renderer 只消费这些字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Mapping
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
def _as_text(value: Any) -> str:
|
||||
"""把给定值收成版面用字符串,None 当空串。"""
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _po_invalid(message: str, *, details: dict[str, Any] | None = None) -> ValidationError:
|
||||
return ValidationError(message, code="VOUCHER_CHECK.PO_PDF_INVALID", details=details or {})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PoOrderLine:
|
||||
"""采购单明细行;金额/数量已格式化成展示字符串,渲染层不再重算。"""
|
||||
|
||||
seq: str
|
||||
item_no: str
|
||||
name: str = ""
|
||||
spec: str = ""
|
||||
extra_spec: str = ""
|
||||
qty: str = ""
|
||||
unit: str = ""
|
||||
arrive: str = ""
|
||||
origin_no: str = ""
|
||||
version: str = ""
|
||||
untax_price: str = ""
|
||||
tax_price: str = ""
|
||||
untax_amt: str = ""
|
||||
tax_amt: str = ""
|
||||
halogen: str = ""
|
||||
vendor_item: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PoOrderDocument:
|
||||
"""
|
||||
一张采购单的给定数据。
|
||||
invoice_no 只用于文件名 `{invoice}-{po_no}.pdf`,不印在 Crystal 风格版面上。
|
||||
"""
|
||||
|
||||
invoice_no: str
|
||||
po_no: str
|
||||
po_date: str = ""
|
||||
po_type: str = ""
|
||||
pay_term: str = ""
|
||||
tax_type: str = ""
|
||||
price_term: str = ""
|
||||
currency: str = ""
|
||||
ship_address: str = ""
|
||||
bill_address: str = ""
|
||||
vendor_code: str = ""
|
||||
vendor_name: str = ""
|
||||
vendor_tel: str = ""
|
||||
vendor_fax: str = ""
|
||||
vendor_addr: str = ""
|
||||
company_name: str = ""
|
||||
company_address: str = ""
|
||||
company_phone: str = ""
|
||||
company_fax: str = ""
|
||||
maker: str = ""
|
||||
untax_total: str = ""
|
||||
tax_total: str = ""
|
||||
lines: tuple[PoOrderLine, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def parse_po_order_document(payload: Mapping[str, Any]) -> PoOrderDocument:
|
||||
"""
|
||||
把给定 dict/JSON 收成 PoOrderDocument。
|
||||
【AI 触发时机】调用方已从 ERP 或手工 JSON 拿到采购单字段、要生成 PDF 之前调用。
|
||||
|
||||
核心逻辑:只做必填校验与类型收口,不查库、不补默认公司名。
|
||||
|
||||
Args:
|
||||
payload: 须含 invoice_no、po_no;lines 为明细列表。其余键与样张字段同名。
|
||||
|
||||
Returns:
|
||||
可交给 save_po_order_pdf 的冻结文档。
|
||||
|
||||
Raises:
|
||||
ValidationError: invoice / 订单号缺失。
|
||||
"""
|
||||
if not isinstance(payload, Mapping):
|
||||
raise _po_invalid("采购单数据必须是对象")
|
||||
invoice_no = _as_text(payload.get("invoice_no") or payload.get("invoice"))
|
||||
po_no = _as_text(payload.get("po_no") or payload.get("order_no"))
|
||||
if not invoice_no:
|
||||
raise _po_invalid("缺少 invoice_no", details={"field": "invoice_no"})
|
||||
if not po_no:
|
||||
raise _po_invalid("缺少 po_no", details={"field": "po_no"})
|
||||
|
||||
raw_lines = payload.get("lines") or []
|
||||
if raw_lines and not isinstance(raw_lines, list):
|
||||
raise _po_invalid("lines 必须是数组", details={"field": "lines"})
|
||||
|
||||
lines: list[PoOrderLine] = []
|
||||
for index, raw in enumerate(raw_lines):
|
||||
if not isinstance(raw, Mapping):
|
||||
raise _po_invalid("明细行必须是对象", details={"field": "lines", "index": index})
|
||||
seq = _as_text(raw.get("seq") or raw.get("item_seq") or (index + 1))
|
||||
item_no = _as_text(raw.get("item_no") or raw.get("part_no"))
|
||||
lines.append(
|
||||
PoOrderLine(
|
||||
seq=seq,
|
||||
item_no=item_no,
|
||||
name=_as_text(raw.get("name")),
|
||||
spec=_as_text(raw.get("spec")),
|
||||
extra_spec=_as_text(raw.get("extra_spec")),
|
||||
qty=_as_text(raw.get("qty")),
|
||||
unit=_as_text(raw.get("unit")),
|
||||
arrive=_as_text(raw.get("arrive") or raw.get("arrive_date")),
|
||||
origin_no=_as_text(raw.get("origin_no")),
|
||||
version=_as_text(raw.get("version")),
|
||||
untax_price=_as_text(raw.get("untax_price")),
|
||||
tax_price=_as_text(raw.get("tax_price")),
|
||||
untax_amt=_as_text(raw.get("untax_amt")),
|
||||
tax_amt=_as_text(raw.get("tax_amt")),
|
||||
halogen=_as_text(raw.get("halogen")),
|
||||
vendor_item=_as_text(raw.get("vendor_item")),
|
||||
)
|
||||
)
|
||||
|
||||
return PoOrderDocument(
|
||||
invoice_no=invoice_no,
|
||||
po_no=po_no,
|
||||
po_date=_as_text(payload.get("po_date")),
|
||||
po_type=_as_text(payload.get("po_type")),
|
||||
pay_term=_as_text(payload.get("pay_term")),
|
||||
tax_type=_as_text(payload.get("tax_type")),
|
||||
price_term=_as_text(payload.get("price_term")),
|
||||
currency=_as_text(payload.get("currency")),
|
||||
ship_address=_as_text(payload.get("ship_address")),
|
||||
bill_address=_as_text(payload.get("bill_address")),
|
||||
vendor_code=_as_text(payload.get("vendor_code")),
|
||||
vendor_name=_as_text(payload.get("vendor_name")),
|
||||
vendor_tel=_as_text(payload.get("vendor_tel")),
|
||||
vendor_fax=_as_text(payload.get("vendor_fax")),
|
||||
vendor_addr=_as_text(payload.get("vendor_addr")),
|
||||
company_name=_as_text(payload.get("company_name")),
|
||||
company_address=_as_text(payload.get("company_address")),
|
||||
company_phone=_as_text(payload.get("company_phone")),
|
||||
company_fax=_as_text(payload.get("company_fax")),
|
||||
maker=_as_text(payload.get("maker")),
|
||||
untax_total=_as_text(payload.get("untax_total")),
|
||||
tax_total=_as_text(payload.get("tax_total")),
|
||||
lines=tuple(lines),
|
||||
)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/publish.py
|
||||
|
||||
用途:生成制式采购单 PDF 并上传到文档库当月「PO订单」目录。
|
||||
依赖:save_po_order_pdf、SalesDmsClient、filename。
|
||||
逻辑:先本地渲染,再 Attachment/Upload + CreateFiles;同名跳过。不进周检核 runner。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
from app.services.voucher_check.adapters.base import ScannedFile
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
from app.services.voucher_check.filename_match import match_filename
|
||||
from app.services.voucher_check.po_order.filename import build_po_order_filename
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document
|
||||
from app.services.voucher_check.po_order.save import save_po_order_pdf
|
||||
|
||||
PO_TYPE_FOLDER = "PO订单"
|
||||
PO_FILENAME_TEMPLATE = "{invoice}-{order_no}.pdf"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PoOrderPublishResult:
|
||||
"""一次制式采购单落库结果。"""
|
||||
|
||||
file: ScannedFile
|
||||
skipped_same_name: bool
|
||||
|
||||
|
||||
def publish_po_order_pdf(
|
||||
document: PoOrderDocument | Mapping[str, Any],
|
||||
*,
|
||||
period_month: date,
|
||||
type_folder: str = PO_TYPE_FOLDER,
|
||||
) -> PoOrderPublishResult:
|
||||
"""
|
||||
生成 `{invoice}-{订单号}.pdf` 并上传到销售开票附件/{年}/{月}/PO订单/。
|
||||
【AI 触发时机】已拿到给定采购单数据、需要写入文档库类型目录时调用。
|
||||
不要在周检核 runner 里调用。ERP 取数由 fetch_po_documents_for_invoices 或调用方完成。
|
||||
|
||||
核心逻辑:渲染到临时文件 → 确保年/月/PO订单目录 → 同名跳过否则 Upload+CreateFiles。
|
||||
|
||||
Args:
|
||||
document: PoOrderDocument 或同结构 dict。
|
||||
period_month: 类型目录所属自然月(用其年、月两位文件夹名)。
|
||||
type_folder: 默认「PO订单」,须与销售 Profile 一致。
|
||||
|
||||
Returns:
|
||||
文档库中的文件元数据;skipped_same_name 表示沿用已有同名文件。
|
||||
"""
|
||||
payload = document if isinstance(document, PoOrderDocument) else parse_po_order_document(document)
|
||||
filename = build_po_order_filename(invoice_no=payload.invoice_no, order_no=payload.po_no)
|
||||
if match_filename(filename, template=PO_FILENAME_TEMPLATE, invoice_no=payload.invoice_no) is None:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError("生成的文件名不符合 {invoice}-{订单号}.pdf", code="VOUCHER_CHECK.PO_PDF_INVALID")
|
||||
|
||||
SalesDmsClient.ensure_configured()
|
||||
yyyy = f"{period_month.year:04d}"
|
||||
mm = f"{period_month.month:02d}"
|
||||
folder_path = f"销售开票附件/{yyyy}/{mm}/{type_folder}"
|
||||
folder_id = SalesDmsClient.ensure_period_type_folder(period_month=period_month, type_folder=type_folder)
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="hxops-po-") as tmp:
|
||||
local_path = save_po_order_pdf(payload, tmp, overwrite=True)
|
||||
content = Path(local_path).read_bytes()
|
||||
|
||||
row, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id=folder_id,
|
||||
leaf_name=filename,
|
||||
content=content,
|
||||
)
|
||||
item_id = str(row.get("ID") or "").strip() or None
|
||||
return PoOrderPublishResult(
|
||||
file=ScannedFile(
|
||||
filename=str(row.get("LeafName") or filename).strip() or filename,
|
||||
item_id=item_id,
|
||||
folder_id=folder_id,
|
||||
path=str(row.get("Path") or f"{folder_path}/{filename}"),
|
||||
extra={
|
||||
"skipped_same_name": skipped,
|
||||
"version_id": row.get("VersionID"),
|
||||
"type_folder": type_folder,
|
||||
},
|
||||
),
|
||||
skipped_same_name=skipped,
|
||||
)
|
||||
@@ -0,0 +1,343 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/renderer.py
|
||||
|
||||
用途:按已确认的 Crystal / apmr900 对照样张画出制式采购单 PDF。
|
||||
依赖:reportlab、fonts、models、页眉 Logo。
|
||||
逻辑:无满格单元格;项次最左;表头三行折行;不查询 ERP。多页时续页只重复页眉与表头。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from reportlab.lib.colors import HexColor
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
from app.services.voucher_check.po_order.fonts import resolve_po_font
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine
|
||||
|
||||
INK = HexColor("#111111")
|
||||
LINE = HexColor("#333333")
|
||||
DEFAULT_LOGO = Path(__file__).resolve().parent / "assets" / "welltrust-logo.png"
|
||||
ROW_H = 13 * mm
|
||||
HEADER_H = 11 * mm
|
||||
FOOT_Y = 18 * mm
|
||||
TOTALS_H = 16 * mm
|
||||
|
||||
|
||||
def render_po_order_pdf(document: PoOrderDocument, out_path: Path, *, logo_path: Path | None = None) -> None:
|
||||
"""
|
||||
把给定采购单画到 out_path(调用方已定文件名)。
|
||||
核心逻辑:先分页再逐页绘制,避免明细把合计和签核挤出页外。
|
||||
"""
|
||||
font = resolve_po_font()
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
page_w, page_h = A4
|
||||
left = 16 * mm
|
||||
right = page_w - 16 * mm
|
||||
pages = _paginate(document.lines, page_h)
|
||||
page_count = len(pages)
|
||||
c = canvas.Canvas(str(out_path), pagesize=A4)
|
||||
c.setTitle(f"采购单 {document.po_no}")
|
||||
c.setAuthor("HXOPS")
|
||||
logo = logo_path if logo_path is not None else DEFAULT_LOGO
|
||||
for index, page_lines in enumerate(pages):
|
||||
page_no = f"{index + 1}/{page_count}"
|
||||
is_last = index == page_count - 1
|
||||
_draw_page(
|
||||
c,
|
||||
document=document,
|
||||
lines=page_lines,
|
||||
font=font,
|
||||
left=left,
|
||||
right=right,
|
||||
page_h=page_h,
|
||||
page_no=page_no,
|
||||
show_po_fields=(index == 0),
|
||||
show_totals=is_last,
|
||||
logo_path=logo,
|
||||
)
|
||||
c.showPage()
|
||||
c.save()
|
||||
|
||||
|
||||
def _paginate(lines: tuple[PoOrderLine, ...], page_h: float) -> list[list[PoOrderLine]]:
|
||||
"""按版心高度切页;末页预留合计高度。"""
|
||||
remaining = list(lines)
|
||||
pages: list[list[PoOrderLine]] = []
|
||||
first = True
|
||||
if not remaining:
|
||||
return [[]]
|
||||
while remaining:
|
||||
last_max = _max_rows(page_h, first_page=first, last_page=True)
|
||||
if len(remaining) <= last_max:
|
||||
pages.append(remaining)
|
||||
break
|
||||
# 留至少一行给末页,避免把合计画进已排满的页。
|
||||
max_rows = _max_rows(page_h, first_page=first, last_page=False)
|
||||
take = min(max(1, max_rows), len(remaining) - 1)
|
||||
pages.append(remaining[:take])
|
||||
remaining = remaining[take:]
|
||||
first = False
|
||||
return pages or [[]]
|
||||
|
||||
|
||||
def _max_rows(page_h: float, *, first_page: bool, last_page: bool) -> int:
|
||||
"""估算一页能放下的明细行数。"""
|
||||
header_block = 86 * mm if first_page else 42 * mm
|
||||
reserved = FOOT_Y + 8 * mm + HEADER_H
|
||||
if last_page:
|
||||
reserved += TOTALS_H
|
||||
usable = page_h - header_block - reserved
|
||||
return max(1, int(usable // ROW_H))
|
||||
|
||||
|
||||
def _draw_page(
|
||||
c: canvas.Canvas,
|
||||
*,
|
||||
document: PoOrderDocument,
|
||||
lines: list[PoOrderLine],
|
||||
font: str,
|
||||
left: float,
|
||||
right: float,
|
||||
page_h: float,
|
||||
page_no: str,
|
||||
show_po_fields: bool,
|
||||
show_totals: bool,
|
||||
logo_path: Path,
|
||||
) -> None:
|
||||
y = page_h - 10 * mm
|
||||
y = _draw_letterhead(c, document, font, left, right, y, page_no, logo_path)
|
||||
if show_po_fields:
|
||||
y = _draw_po_fields(c, document, font, left, right, y)
|
||||
else:
|
||||
y -= 4 * mm
|
||||
_hline(c, left, right, y, 0.8)
|
||||
y -= 1 * mm
|
||||
y = _draw_table_header(c, font, left, right, y)
|
||||
y = _draw_table_rows(c, lines, font, left, y)
|
||||
if show_totals:
|
||||
_draw_totals(c, document, font, left, y)
|
||||
_draw_footer(c, font, left, right)
|
||||
|
||||
|
||||
def _draw_letterhead(
|
||||
c: canvas.Canvas,
|
||||
document: PoOrderDocument,
|
||||
font: str,
|
||||
left: float,
|
||||
right: float,
|
||||
y: float,
|
||||
page_no: str,
|
||||
logo_path: Path,
|
||||
) -> float:
|
||||
"""Logo 在左;右侧公司名、「采购单」、地址、电话;制表者/页次下一行靠右。"""
|
||||
logo_w = 52 * mm
|
||||
logo_h = 14 * mm
|
||||
logo_bottom = y - logo_h
|
||||
if logo_path.is_file():
|
||||
c.drawImage(
|
||||
str(logo_path),
|
||||
left,
|
||||
logo_bottom,
|
||||
width=logo_w,
|
||||
height=logo_h,
|
||||
mask="auto",
|
||||
preserveAspectRatio=True,
|
||||
anchor="sw",
|
||||
)
|
||||
text_x = left + 56 * mm
|
||||
block_mid = (text_x + right) / 2
|
||||
_text(c, font, block_mid, y - 3.5 * mm, document.company_name, 11, centre=True)
|
||||
_text(c, font, block_mid, y - 8.2 * mm, "采购单", 10, centre=True)
|
||||
fax = document.company_fax or ""
|
||||
_text(c, font, text_x, y - 13 * mm, f"地址:{document.company_address}", 8)
|
||||
_text(c, font, text_x, y - 17.5 * mm, f"公司电话:{document.company_phone} 公司传真:{fax}", 8)
|
||||
_text(c, font, right - 52 * mm, y - 22.5 * mm, f"制表者: {document.maker}", 8)
|
||||
_text(c, font, right, y - 22.5 * mm, f"页次: {page_no}", 8, right_align=True)
|
||||
y = min(logo_bottom, y - 24 * mm) - 2 * mm
|
||||
_hline(c, left, right, y, 0.8)
|
||||
return y - 6 * mm
|
||||
|
||||
|
||||
def _draw_po_fields(
|
||||
c: canvas.Canvas,
|
||||
document: PoOrderDocument,
|
||||
font: str,
|
||||
left: float,
|
||||
right: float,
|
||||
y: float,
|
||||
) -> float:
|
||||
"""左栏采购单号、右栏采购日期,与对照样张一致。"""
|
||||
col2 = left + 98 * mm
|
||||
val1 = left + 22 * mm
|
||||
val2 = col2 + 20 * mm
|
||||
po_label = f"{document.po_no} {document.po_type}".rstrip()
|
||||
_text(c, font, left, y, "采购单号:")
|
||||
_text(c, font, val1, y, po_label)
|
||||
_text(c, font, col2, y, "采购日期:")
|
||||
_text(c, font, val2, y, document.po_date)
|
||||
y -= 5.2 * mm
|
||||
_text(c, font, left, y, "付款条件:")
|
||||
_text(c, font, val1, y, document.pay_term)
|
||||
_text(c, font, col2, y, "税 种:")
|
||||
_text(c, font, val2, y, document.tax_type)
|
||||
y -= 5.2 * mm
|
||||
_text(c, font, left, y, "价格条件:")
|
||||
_text(c, font, val1, y, document.price_term)
|
||||
_text(c, font, col2, y, "币 种:")
|
||||
_text(c, font, val2, y, document.currency)
|
||||
y -= 5.2 * mm
|
||||
_text(c, font, left, y, "送货地址:")
|
||||
_text(c, font, val1, y, document.ship_address or " ")
|
||||
y -= 5.2 * mm
|
||||
_text(c, font, left, y, "帐单地址:")
|
||||
_text(c, font, val1, y, document.bill_address or " ")
|
||||
y -= 6 * mm
|
||||
_text(c, font, left, y, "供应厂商:")
|
||||
_text(c, font, val1, y, f"{document.vendor_code} {document.vendor_name}".strip())
|
||||
_text(c, font, left + 118 * mm, y, f"Tel: {document.vendor_tel}")
|
||||
y -= 5 * mm
|
||||
_text(c, font, val1, y, document.vendor_addr, 8)
|
||||
_text(c, font, left + 118 * mm, y, f"Fax: {document.vendor_fax}")
|
||||
y -= 4 * mm
|
||||
_hline(c, left, right, y, 0.8)
|
||||
return y - 1 * mm
|
||||
|
||||
|
||||
def _table_columns(left: float) -> dict[str, float]:
|
||||
return {
|
||||
"seq": left,
|
||||
"item": left + 8 * mm,
|
||||
"origin": left + 50 * mm,
|
||||
"arrive": left + 80 * mm,
|
||||
"qty": left + 108 * mm,
|
||||
"unit": left + 116 * mm,
|
||||
"price": left + 142 * mm,
|
||||
"amt": left + 164 * mm,
|
||||
"halo": left + 168 * mm,
|
||||
}
|
||||
|
||||
|
||||
def _draw_table_header(c: canvas.Canvas, font: str, left: float, right: float, y: float) -> float:
|
||||
"""Crystal 风格:无竖格,表头三行折行,项次最左。"""
|
||||
cols = _table_columns(left)
|
||||
table_top = y
|
||||
_hline(c, left, right, table_top, 0.7)
|
||||
h1 = table_top - 3.6 * mm
|
||||
h2 = table_top - 7.0 * mm
|
||||
h3 = table_top - 10.2 * mm
|
||||
_text(c, font, cols["seq"], h1, "项次", 7)
|
||||
_text(c, font, cols["item"], h1, "料件编号", 7)
|
||||
_text(c, font, cols["item"], h2, "品名/规格", 7)
|
||||
_text(c, font, cols["item"], h3, "厂商料号额外品名规格说明", 6.5)
|
||||
_text(c, font, cols["origin"], h1, "原始编号", 7)
|
||||
_text(c, font, cols["origin"], h2, "版本", 7)
|
||||
_text(c, font, cols["origin"], h3, "行序", 6.5)
|
||||
_text(c, font, cols["arrive"], h1, "到货日", 7)
|
||||
_text(c, font, cols["qty"] - 8 * mm, h1, "数 量", 7)
|
||||
_text(c, font, cols["unit"], h1, "单 位", 7)
|
||||
_text(c, font, cols["price"], h1, "税前单价", 7, right_align=True)
|
||||
_text(c, font, cols["price"], h2, "含税单价", 7, right_align=True)
|
||||
_text(c, font, cols["amt"], h1, "税前金额", 7, right_align=True)
|
||||
_text(c, font, cols["amt"], h2, "含税金额", 7, right_align=True)
|
||||
_text(c, font, cols["halo"], h1, "卤素", 7)
|
||||
_text(c, font, cols["halo"], h2, "管控", 7)
|
||||
_text(c, font, cols["halo"] + 10 * mm, h1, "环保", 7)
|
||||
_text(c, font, cols["halo"] + 10 * mm, h2, "等级", 7)
|
||||
c.setStrokeColor(LINE)
|
||||
c.setLineWidth(0.4)
|
||||
c.line(cols["price"] - 22 * mm, h2 - 1.2 * mm, cols["price"], h2 - 1.2 * mm)
|
||||
c.line(cols["amt"] - 22 * mm, h2 - 1.2 * mm, cols["amt"], h2 - 1.2 * mm)
|
||||
y = table_top - HEADER_H
|
||||
_hline(c, left, right, y, 0.5)
|
||||
return y
|
||||
|
||||
|
||||
def _draw_table_rows(c: canvas.Canvas, lines: list[PoOrderLine], font: str, left: float, y: float) -> float:
|
||||
"""每笔三行:料号/品名/规格,无斑马底、无竖线格。"""
|
||||
cols = _table_columns(left)
|
||||
for line in lines:
|
||||
r1 = y - 3.8 * mm
|
||||
r2 = y - 7.6 * mm
|
||||
r3 = y - 11.2 * mm
|
||||
_text(c, font, cols["seq"], r1, line.seq, 8)
|
||||
_text(c, font, cols["item"], r1, line.item_no, 8)
|
||||
_text(c, font, cols["item"], r2, line.name, 8)
|
||||
_text(c, font, cols["item"], r3, line.spec or line.extra_spec, 8)
|
||||
_text(c, font, cols["origin"], r1, line.vendor_item, 8)
|
||||
origin_second = line.origin_no or line.version
|
||||
_text(c, font, cols["origin"], r2, origin_second, 8)
|
||||
_text(c, font, cols["arrive"], r1, line.arrive, 8)
|
||||
_text(c, font, cols["qty"], r1, line.qty, 8, right_align=True)
|
||||
_text(c, font, cols["unit"], r1, line.unit, 8)
|
||||
_text(c, font, cols["price"], r1, line.untax_price, 8, right_align=True)
|
||||
_text(c, font, cols["price"], r2, line.tax_price, 8, right_align=True)
|
||||
_text(c, font, cols["amt"], r1, line.untax_amt, 8, right_align=True)
|
||||
_text(c, font, cols["amt"], r2, line.tax_amt, 8, right_align=True)
|
||||
_text(c, font, cols["halo"], r1, line.halogen, 8)
|
||||
y -= ROW_H
|
||||
return y
|
||||
|
||||
|
||||
def _draw_totals(c: canvas.Canvas, document: PoOrderDocument, font: str, left: float, y: float) -> None:
|
||||
"""合计靠右,金额带细框。"""
|
||||
cols = _table_columns(left)
|
||||
y -= 6 * mm
|
||||
box_w = 22 * mm
|
||||
box_h = 4.6 * mm
|
||||
_text(c, font, cols["price"] - 28 * mm, y, "税前金额总和:", 8)
|
||||
_rect(c, cols["amt"] - box_w, y - 1.2 * mm, box_w, box_h)
|
||||
_text(c, font, cols["amt"] - 1.2 * mm, y, document.untax_total, 8, right_align=True)
|
||||
y -= 6 * mm
|
||||
_text(c, font, cols["price"] - 28 * mm, y, "含税金额总和:", 8)
|
||||
_rect(c, cols["amt"] - box_w, y - 1.2 * mm, box_w, box_h)
|
||||
_text(c, font, cols["amt"] - 1.2 * mm, y, document.tax_total, 8, right_align=True)
|
||||
|
||||
|
||||
def _draw_footer(c: canvas.Canvas, font: str, left: float, right: float) -> None:
|
||||
"""核准/审核/经办横排;线左 (apmr900)、线右 (结束)。"""
|
||||
span = right - left
|
||||
_text(c, font, left + 10 * mm, FOOT_Y + 5 * mm, "核准", 10)
|
||||
_text(c, font, left + span / 2, FOOT_Y + 5 * mm, "审核", 10, centre=True)
|
||||
_text(c, font, right - 10 * mm, FOOT_Y + 5 * mm, "经办", 10, right_align=True)
|
||||
_hline(c, left, right, FOOT_Y, 0.7)
|
||||
_text(c, font, left, FOOT_Y - 1.1 * mm, "(apmr900)", 8)
|
||||
_text(c, font, right, FOOT_Y - 1.1 * mm, "(结束)", 8, right_align=True)
|
||||
|
||||
|
||||
def _text(
|
||||
c: canvas.Canvas,
|
||||
font: str,
|
||||
x: float,
|
||||
y: float,
|
||||
text: str,
|
||||
size: float = 9,
|
||||
*,
|
||||
colour=INK,
|
||||
right_align: bool = False,
|
||||
centre: bool = False,
|
||||
) -> None:
|
||||
c.setFillColor(colour)
|
||||
c.setFont(font, size)
|
||||
value = text or ""
|
||||
if centre:
|
||||
c.drawCentredString(x, y, value)
|
||||
elif right_align:
|
||||
c.drawRightString(x, y, value)
|
||||
else:
|
||||
c.drawString(x, y, value)
|
||||
|
||||
|
||||
def _hline(c: canvas.Canvas, x1: float, x2: float, y: float, width: float = 0.4) -> None:
|
||||
c.setStrokeColor(LINE)
|
||||
c.setLineWidth(width)
|
||||
c.line(x1, y, x2, y)
|
||||
|
||||
|
||||
def _rect(c: canvas.Canvas, x: float, y: float, w: float, h: float) -> None:
|
||||
c.setStrokeColor(LINE)
|
||||
c.setLineWidth(0.5)
|
||||
c.rect(x, y, w, h, stroke=1, fill=0)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/sample.py
|
||||
|
||||
用途:对照 apmr900 原件的样张数据,供单测与本地出样,不是正式业务数据。
|
||||
依赖:models.parse_po_order_document。
|
||||
逻辑:字段来自 e:\\Work\\Agent\\立账凭证\\采购单.pdf;invoice_no 仅用于文件名演示。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document
|
||||
|
||||
SAMPLE_PO_ORDER_PAYLOAD: dict[str, Any] = {
|
||||
"invoice_no": "INV-SAMPLE",
|
||||
"company_phone": "0512-63136988",
|
||||
"company_fax": "",
|
||||
"company_address": "江苏省苏州市吴江区经济开发区山湖西路789号",
|
||||
"company_name": "苏州和信精密科技有限公司",
|
||||
"maker": "AI",
|
||||
"po_date": "2016/5/28",
|
||||
"po_no": "5201-1605280003",
|
||||
"po_type": "原料采购单",
|
||||
"price_term": "A01 取核价单价",
|
||||
"ship_address": "",
|
||||
"pay_term": "月结一个月",
|
||||
"tax_type": "进项(17%含税)",
|
||||
"currency": "RMB",
|
||||
"bill_address": "",
|
||||
"vendor_name": "北川科技(苏州)有限公司",
|
||||
"vendor_code": "VCCD00013",
|
||||
"vendor_tel": "0512-62810369",
|
||||
"vendor_fax": "0512-62810368",
|
||||
"vendor_addr": "苏州市工业园区胜浦分区银胜路61号",
|
||||
"untax_total": "4,455.50",
|
||||
"tax_total": "5,212.94",
|
||||
"lines": [
|
||||
{
|
||||
"item_no": "3450541801",
|
||||
"seq": "1",
|
||||
"qty": "730",
|
||||
"unit": "PCS",
|
||||
"arrive": "2016/6/16",
|
||||
"untax_price": "3.350000",
|
||||
"untax_amt": "2,445.50",
|
||||
"halogen": "RoHS",
|
||||
"name": "FRAME CUBE CORNER",
|
||||
"spec": "H20*W36.5*L36.7",
|
||||
"tax_price": "3.919500",
|
||||
"tax_amt": "2,861.24",
|
||||
"origin_no": "3301-1605260004",
|
||||
"version": "-0001",
|
||||
"vendor_item": "3450541801",
|
||||
},
|
||||
{
|
||||
"item_no": "3450541801",
|
||||
"seq": "2",
|
||||
"qty": "600",
|
||||
"unit": "PCS",
|
||||
"arrive": "2016/6/16",
|
||||
"untax_price": "3.350000",
|
||||
"untax_amt": "2,010.00",
|
||||
"halogen": "RoHS",
|
||||
"name": "FRAME CUBE CORNER",
|
||||
"spec": "H20*W36.5*L36.7",
|
||||
"tax_price": "3.919500",
|
||||
"tax_amt": "2,351.70",
|
||||
"origin_no": "3301-1605100007",
|
||||
"version": "-0001",
|
||||
"vendor_item": "3450541801",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def sample_po_order_document() -> PoOrderDocument:
|
||||
"""返回对照样张用的采购单数据;正式任务必须改用真实给定数据。"""
|
||||
return parse_po_order_document(SAMPLE_PO_ORDER_PAYLOAD)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/po_order/save.py
|
||||
|
||||
用途:根据给定采购单数据生成 PDF,并按 `{invoice}-{订单号}.pdf` 保存到本地。
|
||||
依赖:filename、models、renderer。
|
||||
逻辑:不查 ERP。上传文档库请用 publish_po_order_pdf。周检核 runner 不要调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
|
||||
from app.services.voucher_check.po_order.filename import build_po_order_filename
|
||||
from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document
|
||||
from app.services.voucher_check.po_order.renderer import render_po_order_pdf
|
||||
|
||||
|
||||
def save_po_order_pdf(
|
||||
document: PoOrderDocument | Mapping[str, Any],
|
||||
output_dir: str | Path,
|
||||
*,
|
||||
overwrite: bool = True,
|
||||
) -> Path:
|
||||
"""
|
||||
生成制式采购单 PDF 并保存。
|
||||
【AI 触发时机】已拿到销售 invoice 与一张 PO 的给定字段、需要落盘 PDF 时调用。
|
||||
不要在周检核 runner 里调用。ERP 取数见 erp_po_repository.fetch_po_documents_for_invoices。
|
||||
|
||||
核心逻辑:解析/校验文档 → `{invoice}-{po_no}.pdf` → Crystal 风格渲染到 output_dir。
|
||||
|
||||
Args:
|
||||
document: PoOrderDocument 或同结构 dict(须含 invoice_no、po_no)。
|
||||
output_dir: 本地目录;不存在则创建。上传文档库请改用 publish_po_order_pdf。
|
||||
overwrite: 为 False 且目标已存在时直接返回现有路径,不覆盖。
|
||||
|
||||
Returns:
|
||||
生成(或已存在)的 PDF 绝对路径。
|
||||
"""
|
||||
payload = document if isinstance(document, PoOrderDocument) else parse_po_order_document(document)
|
||||
filename = build_po_order_filename(invoice_no=payload.invoice_no, order_no=payload.po_no)
|
||||
target = Path(output_dir).expanduser().resolve() / filename
|
||||
if target.exists() and not overwrite:
|
||||
return target
|
||||
render_po_order_pdf(payload, target)
|
||||
return target
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/tests/voucher_check/test_engine_profile_and_scan.py
|
||||
|
||||
用途:销售一期引擎的期间、命名匹配、缺件双口径、Adapter 占位与目录扫描单测。
|
||||
依赖:pytest;不连 Oracle / 文档库。
|
||||
逻辑:覆盖上月边界、六类文件名、同一 invoice 多缺件、PO/OA 未接线。
|
||||
逻辑:覆盖上月边界、oma_file 发票 SQL、六类文件名、同一 invoice 多缺件、PO fetch()/OA 仍未接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,11 +18,39 @@ from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryS
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
|
||||
from app.services.voucher_check.aggregator import aggregate_file_results
|
||||
from app.services.voucher_check.erp_repository import previous_period_bounds
|
||||
from app.services.voucher_check.erp_repository import _INVOICE_SQL, is_sales_invoice_no, previous_period_bounds
|
||||
from app.services.voucher_check.filename_match import first_match, match_filename
|
||||
from app.services.voucher_check.profiles.sales import SALES_PROFILE, required_file_rules
|
||||
|
||||
|
||||
def test_invoice_sql_reads_confirmed_oma_file():
|
||||
"""销售 invoice 清单来自 oma_file:已确认、未作废、状况码 1、帐款类别 11/12/13;oma10 至少 6 位字母或数字。"""
|
||||
sql = " ".join(_INVOICE_SQL.split())
|
||||
assert "FROM oma_file" in sql
|
||||
assert "TRIM(oma10)" in sql
|
||||
assert "TRUNC(oma02)" in sql
|
||||
assert "REGEXP_LIKE(TRIM(oma10), '^[A-Za-z0-9]{6,}$')" in sql
|
||||
assert "TRIM(omaconf) = 'Y'" in sql
|
||||
assert "TRIM(omavoid) = 'N'" in sql
|
||||
assert "TRIM(oma64) = '1'" in sql
|
||||
assert "TRIM(oma00) IN ('11', '12', '13')" in sql
|
||||
assert "apa_file" not in sql
|
||||
assert "apa08" not in sql
|
||||
|
||||
|
||||
def test_sales_invoice_no_rejects_placeholder_and_chinese():
|
||||
"""正规发票号为至少 6 位字母或数字;0、空值、中文备注不能进主体清单。"""
|
||||
assert is_sales_invoice_no("6975101806") is True
|
||||
assert is_sales_invoice_no("394522129") is True
|
||||
assert is_sales_invoice_no("EWZZ26090002") is True
|
||||
assert is_sales_invoice_no("ewzz26090006") is True
|
||||
assert is_sales_invoice_no("0") is False
|
||||
assert is_sales_invoice_no("泰国HUB仓出货") is False
|
||||
assert is_sales_invoice_no("") is False
|
||||
assert is_sales_invoice_no(" ") is False
|
||||
assert is_sales_invoice_no(None) is False
|
||||
|
||||
|
||||
def test_previous_period_bounds_from_early_september():
|
||||
"""周二跑批时检核上个月;2026-09-01 应得到 2026-08。"""
|
||||
now = datetime(2026, 9, 1, 6, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_erp_po_repository.py
|
||||
|
||||
用途:HXJM.oma99 → TGHX.pmm99 采购单取数与字段映射。
|
||||
依赖:pytest;不连 Oracle。
|
||||
逻辑:断言 TRIM 关联、oma99 空走 oga/oea、到货日 pmn34、周检核 fetch 仍未接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.erp_po_repository import (
|
||||
INVOICE_SCHEMA,
|
||||
PO_SCHEMA,
|
||||
_po_detail_sql,
|
||||
fetch_po_documents_for_invoices,
|
||||
map_po_document,
|
||||
resolve_invoice_flows,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
class _NamedCursor:
|
||||
"""按 SQL 关键字返回带列名的预制行。"""
|
||||
|
||||
def __init__(self, scripts: dict[str, tuple[list[str], list[tuple]]]):
|
||||
self.scripts = scripts
|
||||
self.executed: list[tuple[str, dict | None]] = []
|
||||
self.description: list[tuple[str]] = []
|
||||
self._rows: list[tuple] = []
|
||||
|
||||
def execute(self, sql: str, params=None):
|
||||
self.executed.append((sql, params))
|
||||
compact = " ".join(sql.split()).upper()
|
||||
for needle, (columns, rows) in self.scripts.items():
|
||||
if needle.upper() in compact:
|
||||
self.description = [(name,) for name in columns]
|
||||
self._rows = list(rows)
|
||||
return
|
||||
raise AssertionError(f"unexpected sql: {sql}")
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._rows)
|
||||
|
||||
|
||||
def _config():
|
||||
return SimpleNamespace(erp_dsn="host/db", erp_username="ro", erp_password="x", erp_timeout_seconds=5)
|
||||
|
||||
|
||||
_OMA_COLS = ["invoice_no", "oma00", "oma16", "oma99"]
|
||||
_FLOW_COLS = ["doc_no", "flow_no"]
|
||||
|
||||
|
||||
def test_po_sql_targets_tghx_and_trims_flow_no():
|
||||
"""采购单必须查 TGHX,并用 TRIM(pmm99) 对多角序号。"""
|
||||
sql = " ".join(_po_detail_sql(":flow0").split())
|
||||
assert f"FROM {PO_SCHEMA}.pmm_file" in sql
|
||||
assert f"{PO_SCHEMA}.pmn_file" in sql
|
||||
assert "TRIM(pmm.pmm99) IN" in sql
|
||||
assert "TRIM(pmm.pmm18) != 'X'" in sql
|
||||
assert "TRIM(pmm.pmmacti) = 'Y'" in sql
|
||||
assert "BKR" in sql
|
||||
assert "pmn34" in sql
|
||||
assert INVOICE_SCHEMA not in sql
|
||||
|
||||
|
||||
def test_map_po_document_uses_pmn34_and_sample_like_fields():
|
||||
"""到货日用 pmn34;环保等级 RoHS;原始编号优先 ta_ima11。"""
|
||||
document = map_po_document(
|
||||
"EWZZ26090002",
|
||||
[
|
||||
{
|
||||
"po_no": "5220-2609010001",
|
||||
"po_date": date(2026, 9, 1),
|
||||
"po_type": "原料采购单",
|
||||
"pay_term": "月结一个月",
|
||||
"tax_type": "进项(17%含税)",
|
||||
"price_term_code": "A01",
|
||||
"price_term_name": "取核价单价",
|
||||
"currency": "RMB",
|
||||
"vendor_code": "V001",
|
||||
"vendor_name": "测试厂",
|
||||
"vendor_tel": "0512-1",
|
||||
"vendor_fax": "0512-2",
|
||||
"vendor_addr": "苏州",
|
||||
"ship031": "送货路",
|
||||
"ship032": "1号",
|
||||
"bill031": "账单路",
|
||||
"company_name": "TGHX公司",
|
||||
"company_address": "地址",
|
||||
"company_phone": "123",
|
||||
"company_fax": "",
|
||||
"pmn02": 1,
|
||||
"pmn04": "3450541801",
|
||||
"pmn041": "FRAME",
|
||||
"ima021": "H20",
|
||||
"pmn20": 730,
|
||||
"pmn07": "PCS",
|
||||
"pmn34": date(2026, 9, 16),
|
||||
"pmn33": date(2026, 9, 10),
|
||||
"pmn24": "3301-1",
|
||||
"ta_ima11": "RAW-11",
|
||||
"pmnud02": "-0001",
|
||||
"pmn31": "3.35",
|
||||
"pmn31t": "3.9195",
|
||||
"pmn88": "2445.5",
|
||||
"pmn88t": "2861.24",
|
||||
"ta_ima02": "1",
|
||||
"ta_ima03": "1",
|
||||
"pmn06": "VEN-1",
|
||||
"azi03": 6,
|
||||
"azi04": 2,
|
||||
"azi05": 2,
|
||||
}
|
||||
],
|
||||
)
|
||||
assert document.invoice_no == "EWZZ26090002"
|
||||
assert document.po_no == "5220-2609010001"
|
||||
assert document.po_date == "2026/9/1"
|
||||
assert document.price_term == "A01 取核价单价"
|
||||
assert document.ship_address == "送货路1号"
|
||||
assert document.lines[0].arrive == "2026/9/16"
|
||||
assert document.lines[0].halogen == "RoHS"
|
||||
assert document.lines[0].origin_no == "RAW-11"
|
||||
assert document.lines[0].version == "-0001"
|
||||
assert document.untax_total == "2,445.50"
|
||||
assert document.maker == ""
|
||||
|
||||
|
||||
def test_map_po_document_falls_back_origin_and_halogen():
|
||||
"""原始编号空 ta_ima11 时用 pmn24;无环保码时用卤素管控。"""
|
||||
document = map_po_document(
|
||||
"INV0001",
|
||||
[
|
||||
{
|
||||
"po_no": "PO1",
|
||||
"pmn02": 1,
|
||||
"pmn24": "3301-9",
|
||||
"ta_ima11": " ",
|
||||
"ta_ima02": "1",
|
||||
"ta_ima03": "",
|
||||
"pmn88": 0,
|
||||
"pmn88t": 0,
|
||||
}
|
||||
],
|
||||
)
|
||||
assert document.lines[0].origin_no == "3301-9"
|
||||
assert document.lines[0].halogen == "无卤"
|
||||
|
||||
|
||||
def test_resolve_invoice_flows_prefers_oma99():
|
||||
cursor = _NamedCursor(
|
||||
{
|
||||
"OMA_FILE": (
|
||||
_OMA_COLS,
|
||||
[("EWZZ26090002", "12", "8520-2609010002", "S004 -26090001")],
|
||||
)
|
||||
}
|
||||
)
|
||||
flows = resolve_invoice_flows(cursor, ["EWZZ26090002"])
|
||||
assert len(flows) == 1
|
||||
assert flows[0].flow_no == "S004 -26090001"
|
||||
assert not any("OGA_FILE" in sql.upper() or "OEA_FILE" in sql.upper() for sql, _ in cursor.executed)
|
||||
|
||||
|
||||
def test_resolve_invoice_flows_uses_oga99_when_oma99_empty():
|
||||
cursor = _NamedCursor(
|
||||
{
|
||||
"OMA_FILE": (_OMA_COLS, [("EWZZ1A", "12", "8520-1", "")]),
|
||||
"OGA_FILE": (_FLOW_COLS, [("8520-1", "S004-FALLBACK")]),
|
||||
}
|
||||
)
|
||||
flows = resolve_invoice_flows(cursor, ["EWZZ1A"])
|
||||
assert flows[0].flow_no == "S004-FALLBACK"
|
||||
assert any("OGA_FILE" in sql.upper() for sql, _ in cursor.executed)
|
||||
|
||||
|
||||
def test_resolve_invoice_flows_uses_oea99_for_deposit():
|
||||
cursor = _NamedCursor(
|
||||
{
|
||||
"OMA_FILE": (_OMA_COLS, [("EWZZ1B", "11", "1101-1", None)]),
|
||||
"OEA_FILE": (_FLOW_COLS, [("1101-1", "S004-SO")]),
|
||||
}
|
||||
)
|
||||
flows = resolve_invoice_flows(cursor, ["EWZZ1B"])
|
||||
assert flows[0].oma00 == "11"
|
||||
assert flows[0].flow_no == "S004-SO"
|
||||
assert any("OEA_FILE" in sql.upper() for sql, _ in cursor.executed)
|
||||
|
||||
|
||||
def test_fetch_po_documents_crosses_invoice_and_po(monkeypatch):
|
||||
"""同一流程序号下的采购单挂到对应发票;绑定值已 TRIM。"""
|
||||
|
||||
class _Cursor(_NamedCursor):
|
||||
def execute(self, sql, params=None):
|
||||
super().execute(sql, params)
|
||||
compact = " ".join(sql.split()).upper()
|
||||
if "PMM_FILE" in compact:
|
||||
assert params is not None
|
||||
assert "S004-26090001" in params.values()
|
||||
|
||||
class _Conn:
|
||||
def cursor(self):
|
||||
return _Cursor(
|
||||
{
|
||||
"OMA_FILE": (_OMA_COLS, [("EWZZ26090002", "12", "8520-1", "S004-26090001")]),
|
||||
"PMM_FILE": (
|
||||
["flow_no", "po_no", "po_date", "pmn02", "pmn04", "pmn20", "pmn34", "pmn88", "pmn88t"],
|
||||
[
|
||||
("S004-26090001", "5220-2609010001", date(2026, 9, 1), 1, "P1", 10, date(2026, 9, 16), 100, 117),
|
||||
],
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.erp_po_repository.open_erp_connection",
|
||||
lambda config: _Conn(),
|
||||
)
|
||||
docs = fetch_po_documents_for_invoices(_config(), ["EWZZ26090002"])
|
||||
assert len(docs) == 1
|
||||
assert docs[0].invoice_no == "EWZZ26090002"
|
||||
assert docs[0].po_no == "5220-2609010001"
|
||||
assert docs[0].lines[0].arrive == "2026/9/16"
|
||||
|
||||
|
||||
def test_fetch_po_documents_one_invoice_many_pos(monkeypatch):
|
||||
"""一票可对应多张 TGHX 采购单。"""
|
||||
|
||||
class _Conn:
|
||||
def cursor(self):
|
||||
return _NamedCursor(
|
||||
{
|
||||
"OMA_FILE": (_OMA_COLS, [("EWZZ26090002", "12", "8520-1", "S004-26090001")]),
|
||||
"PMM_FILE": (
|
||||
["flow_no", "po_no", "pmn02", "pmn88", "pmn88t"],
|
||||
[
|
||||
("S004-26090001", "5220-2609010001", 1, 10, 11),
|
||||
("S004-26090001", "5220-2609010002", 1, 20, 22),
|
||||
],
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.erp_po_repository.open_erp_connection",
|
||||
lambda config: _Conn(),
|
||||
)
|
||||
docs = fetch_po_documents_for_invoices(_config(), ["EWZZ26090002"])
|
||||
assert [item.po_no for item in docs] == ["5220-2609010001", "5220-2609010002"]
|
||||
|
||||
|
||||
def test_fetch_po_documents_skips_blank_invoice_list(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.erp_po_repository.open_erp_connection",
|
||||
lambda config: (_ for _ in ()).throw(AssertionError("should not connect")),
|
||||
)
|
||||
assert fetch_po_documents_for_invoices(_config(), ["0", " "]) == []
|
||||
|
||||
|
||||
def test_adapter_fetch_stays_unwired_while_documents_work(monkeypatch):
|
||||
adapter = ErpPoPrintAdapter()
|
||||
assert adapter.wired is False
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
adapter.fetch(period_month=date(2026, 8, 1), subjects=[])
|
||||
assert exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.erp_po_repository.fetch_po_documents_for_invoices",
|
||||
lambda config, invoices: [map_po_document("INV0001", [{"po_no": "PO1", "pmn02": 1}])],
|
||||
)
|
||||
docs = adapter.fetch_documents(["INV0001"], config=_config())
|
||||
assert docs[0].po_no == "PO1"
|
||||
|
||||
|
||||
def test_adapter_publish_for_invoices_uploads_each(monkeypatch):
|
||||
adapter = ErpPoPrintAdapter()
|
||||
uploaded: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
adapter,
|
||||
"fetch_documents",
|
||||
lambda invoices, config=None: [
|
||||
map_po_document("EWZZ26090002", [{"po_no": "PO-A", "pmn02": 1}]),
|
||||
map_po_document("EWZZ26090002", [{"po_no": "PO-B", "pmn02": 1}]),
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
adapter,
|
||||
"upload_given",
|
||||
lambda document, period_month: uploaded.append(document.po_no) or document.po_no,
|
||||
)
|
||||
results = adapter.publish_for_invoices(["EWZZ26090002"], period_month=date(2026, 8, 1), config=_config())
|
||||
assert uploaded == ["PO-A", "PO-B"]
|
||||
assert results == ["PO-A", "PO-B"]
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_po_order_pdf.py
|
||||
|
||||
用途:制式采购单 PDF 命名与给定数据落盘。
|
||||
依赖:pytest、pypdf、voucher_check.po_order。
|
||||
逻辑:不连 ERP / 文档库;断言文件名 `{invoice}-{订单号}.pdf` 且正文含采购单号。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from pypdf import PdfReader
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.po_order import (
|
||||
build_po_order_filename,
|
||||
parse_po_order_document,
|
||||
sample_po_order_document,
|
||||
save_po_order_pdf,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_build_po_order_filename():
|
||||
"""文件名固定 invoice-订单号.pdf。"""
|
||||
assert build_po_order_filename(invoice_no="INV001", order_no="5201-1605280003") == "INV001-5201-1605280003.pdf"
|
||||
|
||||
|
||||
def test_build_po_order_filename_rejects_path_chars():
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
build_po_order_filename(invoice_no="INV/001", order_no="PO1")
|
||||
assert exc.value.code == "VOUCHER_CHECK.PO_PDF_INVALID"
|
||||
|
||||
|
||||
def test_parse_requires_invoice_and_po():
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
parse_po_order_document({"po_no": "PO1"})
|
||||
assert exc.value.code == "VOUCHER_CHECK.PO_PDF_INVALID"
|
||||
|
||||
|
||||
def test_save_po_order_pdf_uses_invoice_order_filename(tmp_path: Path):
|
||||
"""给定样张数据后保存为 {invoice}-{订单号}.pdf,且可抽出采购单号。"""
|
||||
document = sample_po_order_document()
|
||||
path = save_po_order_pdf(document, tmp_path)
|
||||
assert path.name == "INV-SAMPLE-5201-1605280003.pdf"
|
||||
assert path.is_file()
|
||||
assert path.stat().st_size > 1000
|
||||
text = "".join((page.extract_text() or "") for page in PdfReader(str(path)).pages)
|
||||
assert "5201-1605280003" in text
|
||||
assert "北川科技" in text
|
||||
assert "FRAME CUBE CORNER" in text
|
||||
|
||||
|
||||
def test_save_po_order_pdf_from_dict(tmp_path: Path):
|
||||
path = save_po_order_pdf(
|
||||
{"invoice_no": "INV001", "po_no": "PO-9", "company_name": "测试公司", "lines": [{"seq": "1", "item_no": "A1", "qty": "2"}]},
|
||||
tmp_path,
|
||||
)
|
||||
assert path.name == "INV001-PO-9.pdf"
|
||||
|
||||
|
||||
def test_overwrite_false_keeps_existing(tmp_path: Path):
|
||||
first = save_po_order_pdf({"invoice_no": "INV001", "po_no": "PO-9"}, tmp_path)
|
||||
stamp = first.stat().st_mtime_ns
|
||||
again = save_po_order_pdf({"invoice_no": "INV001", "po_no": "PO-9", "maker": "B"}, tmp_path, overwrite=False)
|
||||
assert again == first
|
||||
assert first.stat().st_mtime_ns == stamp
|
||||
|
||||
|
||||
def test_adapter_render_given_does_not_wire_fetch(tmp_path: Path):
|
||||
"""fetch 仍未接线;render_given 只根据给定数据出 PDF。"""
|
||||
adapter = ErpPoPrintAdapter()
|
||||
assert adapter.wired is False
|
||||
path = adapter.render_given(sample_po_order_document(), tmp_path)
|
||||
assert path.name == "INV-SAMPLE-5201-1605280003.pdf"
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_po_order_upload.py
|
||||
|
||||
用途:制式采购单 PDF 上传到文档库「PO订单」目录。
|
||||
依赖:pytest;mock SalesDmsClient,不连文档库。
|
||||
逻辑:同名跳过、年/月/类型目录确保存在、CreateFiles 载荷含 AttachmentID。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
from app.services.voucher_check.po_order import publish_po_order_pdf, sample_po_order_document
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_ensure_period_type_folder_creates_year_month_type(monkeypatch):
|
||||
"""销售开票附件下按 年/月/PO订单 逐级建目录。"""
|
||||
created: list[tuple[str, str]] = []
|
||||
|
||||
def ensure_folder(*, parent_folder_id: str, leaf_name: str) -> str:
|
||||
created.append((parent_folder_id, leaf_name))
|
||||
return f"{parent_folder_id}/{leaf_name}"
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_configured", lambda: None)
|
||||
monkeypatch.setattr(SalesDmsClient, "root_folder_id", lambda: "sales-root")
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_folder", ensure_folder)
|
||||
folder_id = SalesDmsClient.ensure_period_type_folder(period_month=date(2026, 8, 1), type_folder="PO订单")
|
||||
assert created == [("sales-root", "2026"), ("sales-root/2026", "08"), ("sales-root/2026/08", "PO订单")]
|
||||
assert folder_id.endswith("PO订单")
|
||||
|
||||
|
||||
def test_upload_file_skips_when_same_name_exists(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"find_child_file",
|
||||
lambda **_kwargs: {"ID": "exist-1", "LeafName": "INV001-PO-9.pdf"},
|
||||
)
|
||||
uploads: list[object] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **kwargs: uploads.append(kwargs) or {})
|
||||
row, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id="po-folder",
|
||||
leaf_name="INV001-PO-9.pdf",
|
||||
content=b"%PDF-fake",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "exist-1"
|
||||
assert uploads == []
|
||||
|
||||
|
||||
def test_upload_file_creates_when_missing(monkeypatch):
|
||||
listing = {"n": 0}
|
||||
|
||||
def find_child_file(**_kwargs):
|
||||
listing["n"] += 1
|
||||
if listing["n"] == 1:
|
||||
return None
|
||||
return {"ID": "new-1", "LeafName": "INV001-PO-9.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"upload_attachment",
|
||||
lambda **_kwargs: {"ID": "att-1", "Extension": ".pdf", "LeafName": "INV001-PO-9"},
|
||||
)
|
||||
created: list[dict] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "create_files", lambda **kwargs: created.append(kwargs) or {"Code": 0})
|
||||
row, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id="po-folder",
|
||||
leaf_name="INV001-PO-9.pdf",
|
||||
content=b"%PDF-fake",
|
||||
)
|
||||
assert skipped is False
|
||||
assert row["ID"] == "new-1"
|
||||
assert created[0]["parent_folder_id"] == "po-folder"
|
||||
assert created[0]["files"][0]["AttachmentID"] == "att-1"
|
||||
assert created[0]["files"][0]["LeafName"] == "INV001-PO-9.pdf"
|
||||
|
||||
|
||||
def test_upload_treats_create_same_name_as_skip(monkeypatch):
|
||||
listing = {"n": 0}
|
||||
|
||||
def find_child_file(**_kwargs):
|
||||
listing["n"] += 1
|
||||
if listing["n"] == 1:
|
||||
return None
|
||||
return {"ID": "exist-2", "LeafName": "INV001-PO-9.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **_kwargs: {"ID": "att-2", "Extension": ".pdf"})
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"create_files",
|
||||
lambda **_kwargs: (_ for _ in ()).throw(
|
||||
ServiceUnavailableError(
|
||||
"存在同名文件",
|
||||
code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
|
||||
details={"dms_data": {"SameLeafNames": ["INV001-PO-9.pdf"]}},
|
||||
)
|
||||
),
|
||||
)
|
||||
row, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id="po-folder",
|
||||
leaf_name="INV001-PO-9.pdf",
|
||||
content=b"%PDF-fake",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "exist-2"
|
||||
|
||||
|
||||
def test_upload_finds_leaf_name_without_extension(monkeypatch):
|
||||
"""部分现网 CreateFiles 后 LeafName 不含 .pdf,按无后缀再查一次。"""
|
||||
listing = {"n": 0}
|
||||
|
||||
def find_child_file(*, parent_folder_id: str, leaf_name: str):
|
||||
listing["n"] += 1
|
||||
if listing["n"] == 1:
|
||||
return None
|
||||
if str(leaf_name).endswith(".pdf"):
|
||||
return None
|
||||
return {"ID": "new-stem", "LeafName": leaf_name}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **_kwargs: {"ID": "att-3", "Extension": ".pdf"})
|
||||
monkeypatch.setattr(SalesDmsClient, "create_files", lambda **_kwargs: {"Code": 0})
|
||||
row, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id="po-folder",
|
||||
leaf_name="INV001-PO-9.pdf",
|
||||
content=b"%PDF-fake",
|
||||
)
|
||||
assert skipped is False
|
||||
assert row["ID"] == "new-stem"
|
||||
assert row["LeafName"] == "INV001-PO-9"
|
||||
|
||||
|
||||
def test_publish_po_order_pdf_uploads_to_type_folder(monkeypatch):
|
||||
"""给定数据生成后上传到 销售开票附件/{年}/{月}/PO订单/。"""
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_configured", lambda: None)
|
||||
monkeypatch.setattr(SalesDmsClient, "ensure_period_type_folder", lambda **_kwargs: "po-folder")
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def upload_file_skip_same_name(*, parent_folder_id: str, leaf_name: str, content: bytes):
|
||||
captured["parent_folder_id"] = parent_folder_id
|
||||
captured["leaf_name"] = leaf_name
|
||||
captured["size"] = len(content)
|
||||
return {"ID": "item-1", "LeafName": leaf_name, "Path": f"销售开票附件/2026/08/PO订单/{leaf_name}"}, False
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "upload_file_skip_same_name", upload_file_skip_same_name)
|
||||
result = publish_po_order_pdf(sample_po_order_document(), period_month=date(2026, 8, 1))
|
||||
assert result.skipped_same_name is False
|
||||
assert result.file.filename == "INV-SAMPLE-5201-1605280003.pdf"
|
||||
assert result.file.folder_id == "po-folder"
|
||||
assert result.file.path == "销售开票附件/2026/08/PO订单/INV-SAMPLE-5201-1605280003.pdf"
|
||||
assert captured["parent_folder_id"] == "po-folder"
|
||||
assert captured["leaf_name"] == "INV-SAMPLE-5201-1605280003.pdf"
|
||||
assert int(captured["size"] or 0) > 1000
|
||||
|
||||
|
||||
def test_adapter_upload_given_does_not_wire_fetch(monkeypatch):
|
||||
"""fetch 仍未接线;upload_given 只根据给定数据上传。"""
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake_publish(document, period_month):
|
||||
captured["period_month"] = period_month
|
||||
captured["invoice_no"] = getattr(document, "invoice_no", None)
|
||||
return type("R", (), {"file": None, "skipped_same_name": False})()
|
||||
|
||||
monkeypatch.setattr("app.services.voucher_check.po_order.publish_po_order_pdf", fake_publish)
|
||||
adapter = ErpPoPrintAdapter()
|
||||
assert adapter.wired is False
|
||||
adapter.upload_given(sample_po_order_document(), period_month=date(2026, 8, 1))
|
||||
assert captured["period_month"] == date(2026, 8, 1)
|
||||
assert captured["invoice_no"] == "INV-SAMPLE"
|
||||
Reference in new issue
Block a user