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
@@ -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