1
This commit is contained in:
1 parent
78576f5745
commit
63b997a7e4
68 files changed
+3680
-1413
No files matched your search
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/__init__.py
|
||||
|
||||
用途:登记销售一期 Adapter(主体、目录扫描、PO/OA 占位、归档占位)。
|
||||
依赖:各 adapter 模块。
|
||||
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例。
|
||||
"""
|
||||
|
||||
from app.services.voucher_check.adapters.base import (
|
||||
AcquireAdapter,
|
||||
ArchiveAdapter,
|
||||
DirectoryScanAdapter,
|
||||
ScanOutcome,
|
||||
ScannedFile,
|
||||
SubjectAdapter,
|
||||
SubjectRow,
|
||||
)
|
||||
from app.services.voucher_check.adapters.dms_archive import DmsArchiveAdapter
|
||||
from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryScanAdapter
|
||||
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
|
||||
from app.services.voucher_check.adapters.hxjm_apa_subject import HxjmApaSubjectAdapter
|
||||
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
|
||||
from app.services.voucher_check.adapters.registry import get_adapter, register_adapter, registered_adapter_names
|
||||
|
||||
register_adapter("hxjm_apa", HxjmApaSubjectAdapter)
|
||||
register_adapter("directory_scan", DmsDirectoryScanAdapter)
|
||||
register_adapter("erp_po_print", ErpPoPrintAdapter)
|
||||
register_adapter("oa_sales_release", OaSalesReleaseAdapter)
|
||||
register_adapter("dms_archive", DmsArchiveAdapter)
|
||||
|
||||
__all__ = [
|
||||
"AcquireAdapter",
|
||||
"ArchiveAdapter",
|
||||
"DirectoryScanAdapter",
|
||||
"DmsArchiveAdapter",
|
||||
"DmsDirectoryScanAdapter",
|
||||
"ErpPoPrintAdapter",
|
||||
"HxjmApaSubjectAdapter",
|
||||
"OaSalesReleaseAdapter",
|
||||
"ScanOutcome",
|
||||
"ScannedFile",
|
||||
"SubjectAdapter",
|
||||
"SubjectRow",
|
||||
"get_adapter",
|
||||
"register_adapter",
|
||||
"registered_adapter_names",
|
||||
]
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/base.py
|
||||
|
||||
用途:立账凭证来源 Adapter 统一数据结构与协议。
|
||||
依赖:无。
|
||||
逻辑:引擎只消费这些类型;ERP/OA/DMS 细节留在各 Adapter 内。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from typing import Any, Protocol
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SubjectRow:
|
||||
"""应检 invoice 主体。"""
|
||||
|
||||
invoice_no: str
|
||||
invoice_date: date | None
|
||||
source_fingerprint: str
|
||||
attributes: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScannedFile:
|
||||
"""类型目录中命中的一个文件。"""
|
||||
|
||||
filename: str
|
||||
item_id: str | None = None
|
||||
folder_id: str | None = None
|
||||
path: str | None = None
|
||||
fingerprint: str | None = None
|
||||
extra: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScanOutcome:
|
||||
"""一条文件规则对一张 invoice 的扫描结果。"""
|
||||
|
||||
status: str # matched / missing / technical_error
|
||||
file: ScannedFile | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
folder_id: str | None = None
|
||||
folder_path: str | None = None
|
||||
|
||||
|
||||
class SubjectAdapter(Protocol):
|
||||
"""获取期间内应检主体。"""
|
||||
|
||||
source_type: str
|
||||
|
||||
def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]:
|
||||
"""
|
||||
拉取一个自然月的 invoice 清单。
|
||||
【AI 触发时机】周任务或强制重检需要本期主体时调用。
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class DirectoryScanAdapter(Protocol):
|
||||
"""扫描文档库类型目录。"""
|
||||
|
||||
source_type: str
|
||||
|
||||
def scan(
|
||||
self,
|
||||
*,
|
||||
period_month: date,
|
||||
invoice_no: str,
|
||||
rule: dict[str, Any],
|
||||
) -> ScanOutcome:
|
||||
"""
|
||||
在对应类型目录中按命名模板匹配文件。
|
||||
【AI 触发时机】周任务对每张 invoice 的每条 directory_scan 规则调用。
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class AcquireAdapter(Protocol):
|
||||
"""把外部单据打印后写入类型目录;PO / 销货放行单一期仅占位。"""
|
||||
|
||||
source_type: str
|
||||
wired: bool
|
||||
|
||||
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
|
||||
"""
|
||||
获取并落入类型目录。
|
||||
【AI 触发时机】仅当独立抓取任务启用且 Adapter.wired=True 时调用;周任务不调用。
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class ArchiveAdapter(Protocol):
|
||||
"""把已匹配文件复制到所有归档/{invoice}/。"""
|
||||
|
||||
wired: bool
|
||||
|
||||
def archive(
|
||||
self,
|
||||
*,
|
||||
period_month: date,
|
||||
invoice_no: str,
|
||||
file: ScannedFile,
|
||||
rule: dict[str, Any],
|
||||
) -> ScannedFile:
|
||||
"""
|
||||
复制到归档子目录;目标已有同名文件则跳过覆盖。
|
||||
【AI 触发时机】扫描命中且命名校验通过后调用。
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/dms_archive.py
|
||||
|
||||
用途:把类型目录中的命中文件复制到「所有归档/{invoice}/」。
|
||||
依赖:dms_client(SaveFolder + Copy);不调用 Move。
|
||||
逻辑:wired=True;目标目录已有同名文件则跳过并记 archived,复制失败记技术失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScannedFile
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
|
||||
|
||||
class DmsArchiveAdapter:
|
||||
"""按票归档:建「所有归档/{invoice}/」并复制,同名跳过。"""
|
||||
|
||||
source_type = "dms_archive"
|
||||
wired = True
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._archive_root_ids: dict[str, str] = {}
|
||||
|
||||
def _archive_root_id(self, period_month: date) -> str:
|
||||
key = period_month.strftime("%Y-%m")
|
||||
if key not in self._archive_root_ids:
|
||||
self._archive_root_ids[key] = SalesDmsClient.ensure_month_archive_root(
|
||||
period_month=period_month
|
||||
)
|
||||
return self._archive_root_ids[key]
|
||||
|
||||
def archive(
|
||||
self,
|
||||
*,
|
||||
period_month: date,
|
||||
invoice_no: str,
|
||||
file: ScannedFile,
|
||||
rule: dict[str, Any],
|
||||
) -> ScannedFile:
|
||||
"""
|
||||
确保所有归档/{invoice}/ 存在,并把命中文件复制进去(不移动类型目录原件)。
|
||||
【AI 触发时机】扫描命中且 invoice 关联校验通过后调用。
|
||||
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有同 LeafName 则跳过覆盖。
|
||||
"""
|
||||
yyyy = f"{period_month.year:04d}"
|
||||
mm = f"{period_month.month:02d}"
|
||||
archive_path = f"销售开票附件/{yyyy}/{mm}/所有归档/{invoice_no}/{file.filename}"
|
||||
source_item_id = str(file.item_id or "").strip()
|
||||
if not source_item_id:
|
||||
raise ServiceUnavailableError(
|
||||
"命中文件缺少文档库条目 ID,无法复制",
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
details={"adapter": self.source_type, "rule": rule.get("code")},
|
||||
)
|
||||
archive_root_id = self._archive_root_id(period_month)
|
||||
dest_folder_id = SalesDmsClient.ensure_folder(
|
||||
parent_folder_id=archive_root_id,
|
||||
leaf_name=str(invoice_no).strip(),
|
||||
)
|
||||
dest_row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id=source_item_id,
|
||||
dest_folder_id=dest_folder_id,
|
||||
leaf_name=file.filename,
|
||||
)
|
||||
return ScannedFile(
|
||||
filename=file.filename,
|
||||
item_id=str(dest_row.get("ID") or "").strip() or None,
|
||||
folder_id=dest_folder_id,
|
||||
path=archive_path,
|
||||
fingerprint=file.fingerprint,
|
||||
extra={
|
||||
"skipped_same_name": skipped,
|
||||
"source_item_id": source_item_id,
|
||||
"dest_version_id": dest_row.get("VersionID"),
|
||||
"rule": rule.get("code"),
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/dms_directory_scan.py
|
||||
|
||||
用途:扫描销售开票附件/{年}/{月}/{类型目录} 并按命名模板匹配 invoice。
|
||||
依赖:dms_client、filename_match、fingerprint。
|
||||
逻辑:目录不存在视为该规则缺件;登录/Page 失败视为技术失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScanOutcome, ScannedFile
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
from app.services.voucher_check.filename_match import first_match
|
||||
from app.services.voucher_check.fingerprint import build_material_fingerprint
|
||||
|
||||
|
||||
class DmsDirectoryScanAdapter:
|
||||
"""文档库类型目录扫描 Adapter。"""
|
||||
|
||||
source_type = "directory_scan"
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._month_folder_ids: dict[str, str | None] = {}
|
||||
self._type_folder_ids: dict[str, str | None] = {}
|
||||
self._type_files: dict[str, list[dict[str, Any]]] = {}
|
||||
|
||||
def _period_key(self, period_month: date) -> str:
|
||||
return period_month.strftime("%Y-%m")
|
||||
|
||||
def _month_folder_id(self, period_month: date) -> str | None:
|
||||
key = self._period_key(period_month)
|
||||
if key not in self._month_folder_ids:
|
||||
_year_id, month_id = SalesDmsClient.resolve_period_folder(period_month=period_month)
|
||||
self._month_folder_ids[key] = month_id
|
||||
return self._month_folder_ids[key]
|
||||
|
||||
def _type_folder_id(self, period_month: date, type_folder: str) -> str | None:
|
||||
cache_key = f"{self._period_key(period_month)}/{type_folder}"
|
||||
if cache_key not in self._type_folder_ids:
|
||||
month_id = self._month_folder_id(period_month)
|
||||
if not month_id:
|
||||
self._type_folder_ids[cache_key] = None
|
||||
else:
|
||||
self._type_folder_ids[cache_key] = SalesDmsClient.find_child_folder(
|
||||
parent_folder_id=month_id,
|
||||
leaf_name=type_folder,
|
||||
)
|
||||
return self._type_folder_ids[cache_key]
|
||||
|
||||
def scan(
|
||||
self,
|
||||
*,
|
||||
period_month: date,
|
||||
invoice_no: str,
|
||||
rule: dict[str, Any],
|
||||
) -> ScanOutcome:
|
||||
"""
|
||||
在类型目录中匹配当前 invoice 的文件。
|
||||
核心逻辑:缓存月目录与类型目录列表,避免每票重复 Page。
|
||||
"""
|
||||
type_folder = str(rule.get("type_folder") or "").strip()
|
||||
template = str(rule.get("filename_template") or "").strip()
|
||||
yyyy = f"{period_month.year:04d}"
|
||||
mm = f"{period_month.month:02d}"
|
||||
folder_path = f"销售开票附件/{yyyy}/{mm}/{type_folder}"
|
||||
try:
|
||||
folder_id = self._type_folder_id(period_month, type_folder)
|
||||
if not folder_id:
|
||||
return ScanOutcome(
|
||||
status="missing",
|
||||
folder_path=folder_path,
|
||||
)
|
||||
cache_key = folder_id
|
||||
if cache_key not in self._type_files:
|
||||
self._type_files[cache_key] = SalesDmsClient.list_files(folder_id=folder_id)
|
||||
rows = self._type_files[cache_key]
|
||||
names = [str(row.get("LeafName") or "").strip() for row in rows]
|
||||
hit = first_match(names, template=template, invoice_no=invoice_no)
|
||||
if hit is None:
|
||||
return ScanOutcome(status="missing", folder_id=folder_id, folder_path=folder_path)
|
||||
row = next((item for item in rows if str(item.get("LeafName") or "").strip() == hit.filename), {})
|
||||
item_id = str((row or {}).get("ID") or "") or None
|
||||
version_id = str((row or {}).get("VersionID") or "")
|
||||
fingerprint = build_material_fingerprint(
|
||||
[(f"{hit.filename}|{item_id or ''}|{version_id}", 0, 0)]
|
||||
)
|
||||
return ScanOutcome(
|
||||
status="matched",
|
||||
folder_id=folder_id,
|
||||
folder_path=folder_path,
|
||||
file=ScannedFile(
|
||||
filename=hit.filename,
|
||||
item_id=item_id,
|
||||
folder_id=folder_id,
|
||||
path=str((row or {}).get("Path") or folder_path),
|
||||
fingerprint=fingerprint,
|
||||
extra={"version_id": (row or {}).get("VersionID")},
|
||||
),
|
||||
)
|
||||
except ServiceUnavailableError as exc:
|
||||
return ScanOutcome(
|
||||
status="technical_error",
|
||||
folder_path=folder_path,
|
||||
error_code=exc.code,
|
||||
error_message=exc.message,
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/erp_po_print.py
|
||||
|
||||
用途:ERP 反查 PO 并打印 PDF 写入「PO订单」类型目录的占位 Adapter。
|
||||
依赖:adapters.base。
|
||||
逻辑:查询/打印方式待确认,周任务不调用;独立抓取任务启用前 wired=False。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow
|
||||
|
||||
|
||||
class ErpPoPrintAdapter:
|
||||
"""PO 打印占位;未接线时禁止生成假 PDF。"""
|
||||
|
||||
source_type = "erp_po_print"
|
||||
wired = False
|
||||
|
||||
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
|
||||
"""
|
||||
预留:按 invoice 反查 PO 并打印到类型目录。
|
||||
【AI 触发时机】仅当独立「抓取 PO」任务上线后调用,不要在周检核 runner 中调用。
|
||||
"""
|
||||
raise ServiceUnavailableError(
|
||||
"ERP PO 打印尚未接线",
|
||||
code="VOUCHER_CHECK.ADAPTER_NOT_WIRED",
|
||||
details={
|
||||
"adapter": self.source_type,
|
||||
"period": period_month.isoformat(),
|
||||
"subject_count": len(subjects),
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/hxjm_apa_subject.py
|
||||
|
||||
用途:从 HXJM apa_file 拉取上一个月销售 invoice 清单。
|
||||
依赖:erp_repository.fetch_month_invoices、fingerprint。
|
||||
逻辑:周任务 subject_adapter=hxjm_apa;期间由 erp_repository 按上月计算。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
|
||||
from app.services.voucher_check.adapters.base import SubjectRow
|
||||
from app.services.voucher_check.erp_repository import fetch_month_invoices
|
||||
from app.services.voucher_check.fingerprint import build_material_fingerprint
|
||||
|
||||
|
||||
class HxjmApaSubjectAdapter:
|
||||
"""HXJM apa08/apa09 主体 Adapter。"""
|
||||
|
||||
source_type = "hxjm_apa"
|
||||
|
||||
def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]:
|
||||
"""
|
||||
查询上月发票号集合并生成主体指纹。
|
||||
核心逻辑:委托 fetch_month_invoices;返回期间必须与传入 period_month 一致。
|
||||
|
||||
Args:
|
||||
period_month: 检核月首日,由 runner 预先算好。
|
||||
config: 含 ERP 连接的运行配置。
|
||||
|
||||
Returns:
|
||||
SubjectRow 列表。
|
||||
"""
|
||||
actual_period, rows = fetch_month_invoices(config)
|
||||
if actual_period != period_month:
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
|
||||
raise ServiceUnavailableError(
|
||||
"ERP 期间与批次期间不一致",
|
||||
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
|
||||
details={
|
||||
"expected": period_month.isoformat(),
|
||||
"actual": actual_period.isoformat(),
|
||||
},
|
||||
)
|
||||
subjects: list[SubjectRow] = []
|
||||
for row in rows:
|
||||
fingerprint = build_material_fingerprint(
|
||||
[(row.invoice_no, 0, int((row.invoice_date or period_month).toordinal()))]
|
||||
)
|
||||
subjects.append(
|
||||
SubjectRow(
|
||||
invoice_no=row.invoice_no,
|
||||
invoice_date=row.invoice_date,
|
||||
source_fingerprint=fingerprint,
|
||||
attributes={"scope_code": getattr(config, "scope_code", "HXJM")},
|
||||
)
|
||||
)
|
||||
return subjects
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/oa_sales_release.py
|
||||
|
||||
用途:OA 销货放行单模拟页面打印的占位 Adapter。
|
||||
依赖:adapters.base。
|
||||
逻辑:一期规则已定但页面自动化未实现;周任务不调用,只扫描「销货单」目录。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow
|
||||
|
||||
|
||||
class OaSalesReleaseAdapter:
|
||||
"""销货放行单打印占位;未接线时禁止生成假 PDF。"""
|
||||
|
||||
source_type = "oa_sales_release"
|
||||
wired = False
|
||||
|
||||
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
|
||||
"""
|
||||
预留:按上月/归档/HXJM/发票号非空过滤后逐条打印。
|
||||
【AI 触发时机】仅当独立「抓取销货放行单」任务上线后调用。
|
||||
"""
|
||||
raise ServiceUnavailableError(
|
||||
"OA 销货放行单打印尚未接线",
|
||||
code="VOUCHER_CHECK.ADAPTER_NOT_WIRED",
|
||||
details={
|
||||
"adapter": self.source_type,
|
||||
"period": period_month.isoformat(),
|
||||
"subject_count": len(subjects),
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/registry.py
|
||||
|
||||
用途:按 source_type / adapter 名解析已注册 Adapter。
|
||||
依赖:adapters.base。
|
||||
逻辑:模块 import 时 register;引擎禁止使用未登记的 source_type。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
_REGISTRY: dict[str, Callable[[], Any]] = {}
|
||||
|
||||
|
||||
def register_adapter(name: str, factory: Callable[[], Any]) -> None:
|
||||
"""登记 Adapter 工厂。同名后注册覆盖,便于测试注入。"""
|
||||
key = str(name or "").strip()
|
||||
if not key:
|
||||
raise ValidationError("Adapter 名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
_REGISTRY[key] = factory
|
||||
|
||||
|
||||
def get_adapter(name: str) -> Any:
|
||||
"""
|
||||
按名称构造 Adapter。
|
||||
核心逻辑:未注册则配置失败,避免引擎落到未知来源。
|
||||
"""
|
||||
key = str(name or "").strip()
|
||||
factory = _REGISTRY.get(key)
|
||||
if factory is None:
|
||||
raise ValidationError(
|
||||
f"未注册的 Adapter: {key}",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"adapter": key},
|
||||
)
|
||||
return factory()
|
||||
|
||||
|
||||
def registered_adapter_names() -> tuple[str, ...]:
|
||||
"""返回已登记名称,供测试断言。"""
|
||||
return tuple(sorted(_REGISTRY))
|
||||
Reference in new issue
Block a user