fix(contract-plan): 采购合同请款支持根据公司查不同账套
This commit is contained in:
1 parent
6867aeb90c
commit
89c8da2990
20 files changed
+381
-116
No files matched your search
@@ -6,7 +6,7 @@ backend/app/api/contract_payment.py
|
||||
逻辑:页面查询合同、节点、本周待发送摘要、四张汇总卡和周汇总批次;失败批次返回可展示原因。同步和预警操作入队,避免请求线程执行外部系统和企微调用;发送后可按 Job 查询是否真正完成。
|
||||
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
||||
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
"""
|
||||
@@ -38,6 +38,7 @@ from app.services.contract_payment.ledger_focus import (
|
||||
apply_ledger_focus,
|
||||
ledger_focus_counts,
|
||||
)
|
||||
from app.services.contract_payment.erp_payment_service import erp_schema_for_company
|
||||
from app.services.contract_payment.parse_service import unique_parse_issues
|
||||
from app.services.contract_payment.review_service import apply_manual_review
|
||||
from app.services.contract_payment.sync_service import (
|
||||
@@ -159,6 +160,8 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
|
||||
"contract_no": row.contract_no,
|
||||
"workflow_no": row.workflow_no,
|
||||
"purchase_order_no": row.purchase_order_no,
|
||||
"company_name": row.company_name,
|
||||
"erp_schema": erp_schema_for_company(row.company_name),
|
||||
"supplier_name": row.supplier_name,
|
||||
"total_amount": str(row.total_amount) if row.total_amount is not None else None,
|
||||
"currency": row.currency,
|
||||
|
||||
@@ -33,6 +33,8 @@ class ContractPaymentContract(Base):
|
||||
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
supplier_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
# OA 合同申请单「公司」。付款事实按该公司映射到 ERP 账套,空值按 HXJM 处理。
|
||||
company_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
applicant_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
total_amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 2), nullable=True)
|
||||
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
|
||||
@@ -34,7 +34,7 @@ from app.services.integrations.wecom.notify import (
|
||||
send_wecom_file_message,
|
||||
upload_wecom_temp_media,
|
||||
)
|
||||
from app.services.contract_payment.erp_payment_service import fetch_paid_records, resolve_paid_node_dates
|
||||
from app.services.contract_payment.erp_payment_service import erp_schema_for_company, fetch_paid_records, resolve_paid_node_dates
|
||||
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
@@ -77,21 +77,22 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
.filter(ContractPaymentNode.status == "active", ContractPaymentContract.status == "active")
|
||||
.all()
|
||||
)
|
||||
paid_records = fetch_paid_records(
|
||||
contract.purchase_order_no
|
||||
for _node, contract in rows
|
||||
if _node.node_type in {"prepayment", "shipment"}
|
||||
)
|
||||
payable_orders = [
|
||||
(str(contract.purchase_order_no or "").strip(), contract.company_name)
|
||||
for node, contract in rows
|
||||
if node.node_type in {"prepayment", "shipment"} and str(contract.purchase_order_no or "").strip()
|
||||
]
|
||||
paid_records = fetch_paid_records(payable_orders)
|
||||
paid_node_dates: dict[int, str | None] = {}
|
||||
nodes_by_purchase_order: dict[str, list[ContractPaymentNode]] = defaultdict(list)
|
||||
nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list)
|
||||
for node, contract in rows:
|
||||
purchase_order_no = str(contract.purchase_order_no or "").strip()
|
||||
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
|
||||
nodes_by_purchase_order[purchase_order_no].append(node)
|
||||
for purchase_order_no, payment_nodes in nodes_by_purchase_order.items():
|
||||
nodes_by_ledger[(erp_schema_for_company(contract.company_name), purchase_order_no)].append(node)
|
||||
for ledger_key, payment_nodes in nodes_by_ledger.items():
|
||||
paid_node_dates.update(resolve_paid_node_dates(
|
||||
[(node.id, node.node_type, node.amount) for node in payment_nodes],
|
||||
paid_records.get(purchase_order_no, []),
|
||||
paid_records.get(ledger_key, []),
|
||||
))
|
||||
for node, contract in rows:
|
||||
anchor = _anchor_date(contract=contract, node=node)
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/contract_payment/erp_payment_service.py
|
||||
|
||||
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款和出货款的付款完成事实来源。
|
||||
依赖:oracledb、Text2SQLService 的 Oracle 客户端初始化能力及 Flask 配置。
|
||||
逻辑:仅执行只读查询;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
|
||||
逻辑:按 OA「公司」选择账套后只读查询 `{账套}.apa_file`;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +17,51 @@ from flask import current_app
|
||||
|
||||
|
||||
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2}
|
||||
# OA 合同申请单「公司」到 ERP 账套。未列出的公司默认 HXJM。标识符只允许来自这个白名单。
|
||||
_SCHEMA_BY_COMPANY = {
|
||||
"无锡和宏智散热科技有限公司": "WZHHZ",
|
||||
"和泰科技(吴江)有限公司": "HTT",
|
||||
"苏州和信精密科技有限公司": "HXJM",
|
||||
}
|
||||
_DEFAULT_ERP_SCHEMA = "HXJM"
|
||||
_ALLOWED_ERP_SCHEMAS = frozenset({"HXJM", "WZHHZ", "HTT"})
|
||||
|
||||
|
||||
def normalize_company_name(company_name: str | None) -> str:
|
||||
"""压缩空白并把全角括号改成半角,便于和账套映射表精确比对。"""
|
||||
text = "".join(str(company_name or "").split())
|
||||
return text.replace("(", "(").replace(")", ")")
|
||||
|
||||
|
||||
def erp_schema_for_company(company_name: str | None) -> str:
|
||||
"""
|
||||
按 OA 合同申请单上的公司确定 ERP 账套。
|
||||
|
||||
核心逻辑:无锡和宏智散热科技有限公司用 WZHHZ,和泰科技(吴江)有限公司用 HTT,
|
||||
苏州和信精密科技有限公司以及其余公司用 HXJM。公司为空时也用 HXJM,保持存量合同行为。
|
||||
Args:
|
||||
company_name: OA「公司」字段原文。
|
||||
Returns:
|
||||
白名单内的账套代码。
|
||||
"""
|
||||
schema = _SCHEMA_BY_COMPANY.get(normalize_company_name(company_name), _DEFAULT_ERP_SCHEMA)
|
||||
return schema if schema in _ALLOWED_ERP_SCHEMAS else _DEFAULT_ERP_SCHEMA
|
||||
|
||||
|
||||
def _paid_records_sql(schema: str, placeholders: str) -> str:
|
||||
"""拼出指定账套的只读付款 SQL。schema 必须已在白名单内,禁止把公司名称拼进 SQL。"""
|
||||
if schema not in _ALLOWED_ERP_SCHEMAS:
|
||||
raise ValueError(f"unsupported erp schema: {schema}")
|
||||
return f"""
|
||||
SELECT TRIM(apaud03) AS purchase_order_no,
|
||||
NVL(apa34f, 0) AS paid_amount,
|
||||
TRUNC(apa02) AS paid_date
|
||||
FROM {schema}.apa_file
|
||||
WHERE TRIM(apaud03) IN ({placeholders})
|
||||
AND TRIM(TO_CHAR(apa00)) = '15'
|
||||
AND UPPER(TRIM(apa41)) = 'Y'
|
||||
AND TRIM(TO_CHAR(apa63)) = '1'
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -28,20 +73,27 @@ class ErpPaidRow:
|
||||
paid_date: str | None
|
||||
|
||||
|
||||
def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpPaidRow]]:
|
||||
def fetch_paid_records(orders: Iterable[tuple[str, str | None]]) -> dict[tuple[str, str], list[ErpPaidRow]]:
|
||||
"""
|
||||
查询采购单已完成付款记录(含付款日期)。
|
||||
按公司对应的 ERP 账套查询采购单已完成付款记录(含付款日期)。
|
||||
|
||||
AI 触发时机:合同付款预警每日扫描前,需要判断预付款/出货款是否已经完成付款。
|
||||
核心逻辑:查询 `apa_file`,先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f`(金额)与 `apa02`(付款日期)。
|
||||
核心逻辑:公司映射到 HXJM / WZHHZ / HTT 后,分别查询该账套的 `apa_file`;
|
||||
先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f` 与 `apa02`。
|
||||
某一账套查询失败只影响该账套,其它账套继续。
|
||||
Args:
|
||||
purchase_order_nos: 待查询的采购单号集合;空集合不会连接 ERP。
|
||||
orders: `(采购单号, OA公司)`;公司为空时按 HXJM。空集合不会连接 ERP。
|
||||
Returns:
|
||||
采购单号到合格付款记录列表的映射。ERP 未配置、驱动不可用或查询失败时返回空映射,
|
||||
`(账套, 采购单号)` 到合格付款记录列表的映射。ERP 未配置或驱动不可用时返回空映射,
|
||||
由调用方按未付款处理,避免错误停止预警。
|
||||
"""
|
||||
normalized = sorted({str(value or "").strip() for value in purchase_order_nos if str(value or "").strip()})
|
||||
if not normalized:
|
||||
grouped: dict[str, set[str]] = {}
|
||||
for purchase_order_no, company_name in orders:
|
||||
po = str(purchase_order_no or "").strip()
|
||||
if not po:
|
||||
continue
|
||||
grouped.setdefault(erp_schema_for_company(company_name), set()).add(po)
|
||||
if not grouped:
|
||||
return {}
|
||||
dsn = str(current_app.config.get("CONTRACT_PAYMENT_ERP_DSN") or "").strip()
|
||||
username = str(current_app.config.get("CONTRACT_PAYMENT_ERP_USERNAME") or "").strip()
|
||||
@@ -71,33 +123,33 @@ def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpP
|
||||
timeout = max(int(current_app.config.get("CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS") or 30), 5)
|
||||
connection.call_timeout = timeout * 1000
|
||||
cursor = connection.cursor()
|
||||
placeholders = ", ".join(f":po_{index}" for index in range(len(normalized)))
|
||||
# [STEP 1] 只取「厂商预付款作业」类型的付款记录:apa00='15' 为厂商预付款作业标志,
|
||||
# 过滤掉其它作业类型(如对账/其它付款),避免把非预付款的付款误匹配到预付款/出货款节点;
|
||||
# 后再叠加 apa41='Y'(有效)与 apa63=1(已完成付款)两层过滤,仅统计真正完成的预付款。
|
||||
# apaud03 varchar2 40 采购单号
|
||||
sql = f"""
|
||||
SELECT TRIM(apaud03) AS purchase_order_no,
|
||||
NVL(apa34f, 0) AS paid_amount,
|
||||
TRUNC(apa02) AS paid_date
|
||||
FROM apa_file
|
||||
WHERE TRIM(apaud03) IN ({placeholders})
|
||||
AND TRIM(TO_CHAR(apa00)) = '15'
|
||||
AND UPPER(TRIM(apa41)) = 'Y'
|
||||
AND TRIM(TO_CHAR(apa63)) = '1'
|
||||
"""
|
||||
cursor.execute(sql, {f"po_{index}": value for index, value in enumerate(normalized)})
|
||||
result: dict[str, list[ErpPaidRow]] = {}
|
||||
for raw_po, raw_amount, raw_paid_date in cursor:
|
||||
po = str(raw_po or "").strip()
|
||||
if not po:
|
||||
continue
|
||||
result: dict[tuple[str, str], list[ErpPaidRow]] = {}
|
||||
# [STEP 1] 同一连接按账套分别查 `{账套}.apa_file`。登录用户是 hxjm,未加前缀时只会读到 HXJM。
|
||||
# apa00='15' 限定厂商预付款作业,再叠加 apa41='Y' 与 apa63=1,避免把其它付款记到预付款/出货款。
|
||||
for schema, purchase_orders in grouped.items():
|
||||
normalized = sorted(purchase_orders)
|
||||
placeholders = ", ".join(f":po_{index}" for index in range(len(normalized)))
|
||||
try:
|
||||
amount = Decimal(str(raw_amount or "0"))
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
continue
|
||||
paid_date = getattr(raw_paid_date, "isoformat", lambda: None)().split("T")[0] if raw_paid_date else None
|
||||
result.setdefault(po, []).append(ErpPaidRow(amount=amount, paid_date=paid_date))
|
||||
cursor.execute(
|
||||
_paid_records_sql(schema, placeholders),
|
||||
{f"po_{index}": value for index, value in enumerate(normalized)},
|
||||
)
|
||||
for raw_po, raw_amount, raw_paid_date in cursor:
|
||||
po = str(raw_po or "").strip()
|
||||
if not po:
|
||||
continue
|
||||
try:
|
||||
amount = Decimal(str(raw_amount or "0"))
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
continue
|
||||
paid_date = getattr(raw_paid_date, "isoformat", lambda: None)().split("T")[0] if raw_paid_date else None
|
||||
result.setdefault((schema, po), []).append(ErpPaidRow(amount=amount, paid_date=paid_date))
|
||||
except Exception as exc:
|
||||
code = getattr(exc, "code", None) or getattr(exc, "full_code", None)
|
||||
current_app.logger.warning(
|
||||
"合同付款预警:账套 %s 付款查询失败,该账套按未付款处理,error_type=%s code=%s message=%s",
|
||||
schema, type(exc).__name__, code, str(exc) or getattr(exc, "message", ""),
|
||||
)
|
||||
return result
|
||||
except Exception as exc:
|
||||
# 记录具体 Oracle 错误码(如 ORA-01017/00942/12514)与消息,便于定位账号权限/服务名问题;不输出密码。
|
||||
@@ -117,10 +169,10 @@ def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpP
|
||||
pass
|
||||
|
||||
|
||||
def fetch_paid_amounts(purchase_order_nos: Iterable[str]) -> dict[str, list[Decimal]]:
|
||||
"""查询采购单已完成付款金额列表(兼容旧调用方)。"""
|
||||
records = fetch_paid_records(purchase_order_nos)
|
||||
return {po: [row.amount for row in rows] for po, rows in records.items()}
|
||||
def fetch_paid_amounts(orders: Iterable[tuple[str, str | None]]) -> dict[tuple[str, str], list[Decimal]]:
|
||||
"""查询各账套采购单已完成付款金额列表。"""
|
||||
records = fetch_paid_records(orders)
|
||||
return {key: [row.amount for row in rows] for key, rows in records.items()}
|
||||
|
||||
|
||||
def _select_match(
|
||||
|
||||
@@ -676,7 +676,8 @@ class ContractOaClient:
|
||||
"""
|
||||
解析合同申请单表格与附件区域。
|
||||
|
||||
截图确认的字段名为“流程编号、采购单号、合同单位、合同金额、合同书币别、合同生效日期、约定到货日期”;
|
||||
截图确认的字段名为“流程编号、公司、采购单号、合同单位、合同金额、合同书币别、合同生效日期、约定到货日期”;
|
||||
「公司」决定 ERP 账套,「合同单位」是供应商,两者不能混用。
|
||||
解析保留原始 labels,便于首次联调快速发现同义字段变化。
|
||||
"""
|
||||
tree = _html_tree(page)
|
||||
@@ -708,6 +709,7 @@ class ContractOaClient:
|
||||
"contract_no": contract_no,
|
||||
"workflow_no": workflow_no,
|
||||
"purchase_order_no": _field_value(labels, "采购单号") or _purchase_order_no_from_title(_field_value(labels, "标题")),
|
||||
"company_name": _field_value(labels, "公司"),
|
||||
"supplier_name": _field_value(labels, "合同单位", "供应商"),
|
||||
"applicant_name": _field_value(labels, "申请人", "申请人员", "申请人姓名"),
|
||||
"total_amount": total_amount,
|
||||
@@ -807,6 +809,7 @@ class ContractOaClient:
|
||||
"contract_no": detail.get("contract_no") or None,
|
||||
"workflow_no": detail.get("workflow_no") or process_id,
|
||||
"purchase_order_no": detail.get("purchase_order_no"),
|
||||
"company_name": detail.get("company_name"),
|
||||
"supplier_name": detail.get("supplier_name"),
|
||||
"applicant_name": detail.get("applicant_name"),
|
||||
"total_amount": detail.get("total_amount"),
|
||||
@@ -907,12 +910,43 @@ def _pick(row: dict[str, Any], *keys: str) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _cell_text(cell: Any) -> str:
|
||||
"""
|
||||
读取表单单元格的展示值。
|
||||
|
||||
核心逻辑:下拉框的 HTML 会带上全部选项。只取 `option selected`;没有 selected 时,
|
||||
用同格隐藏 input 的 value 对上 option 的 value。普通文本格仍拼接可见文字。
|
||||
有下拉框但无法确定选中项时返回空,避免把候选项拼成公司名。
|
||||
"""
|
||||
selects = cell.xpath(".//select")
|
||||
if not selects:
|
||||
return _clean_text(" ".join(cell.xpath(".//text()")))
|
||||
select = selects[0]
|
||||
for option in select.xpath("./option[@selected]"):
|
||||
text = _clean_text("".join(option.xpath(".//text()")))
|
||||
if text:
|
||||
return text
|
||||
current = ""
|
||||
for node in cell.xpath(".//input[@value]"):
|
||||
current = str(node.get("value") or "").strip()
|
||||
if current:
|
||||
break
|
||||
if current:
|
||||
for option in select.xpath("./option"):
|
||||
if str(option.get("value") or "").strip() != current:
|
||||
continue
|
||||
text = _clean_text("".join(option.xpath(".//text()")))
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
def _table_fields(tree: Any) -> dict[str, str]:
|
||||
"""解析表格中“标签单元格 + 值单元格”对;同一行可包含多组字段。"""
|
||||
"""解析表格中“标签单元格 + 值单元格”对;同一行可包含多组字段。下拉框只取选中项。"""
|
||||
fields: dict[str, str] = {}
|
||||
for row in tree.xpath("//tr"):
|
||||
cells = row.xpath("./th|./td")
|
||||
texts = [_clean_text(" ".join(cell.xpath(".//text()"))) for cell in cells]
|
||||
texts = [_cell_text(cell) for cell in cells]
|
||||
for index in range(0, len(texts) - 1, 2):
|
||||
label, value = texts[index], texts[index + 1]
|
||||
if label and value and len(label) <= 32:
|
||||
|
||||
@@ -178,6 +178,7 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
|
||||
contract = ContractPaymentContract(
|
||||
contract_no=contract_no,
|
||||
purchase_order_no=str(item.get("purchase_order_no") or "").strip() or None,
|
||||
company_name=str(item.get("company_name") or "").strip() or None,
|
||||
supplier_name=str(item.get("supplier_name") or "").strip() or None,
|
||||
applicant_name=str(item.get("applicant_name") or "").strip() or None,
|
||||
total_amount=positive_amount(item.get("total_amount")),
|
||||
@@ -198,6 +199,11 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
|
||||
if force:
|
||||
overwritten += _overwrite_oa_fields(contract, item, operator_id=operator_id)
|
||||
contract.purchase_order_no = contract.purchase_order_no or str(item.get("purchase_order_no") or "").strip() or None
|
||||
incoming_company = str(item.get("company_name") or "").strip()
|
||||
stored_company = str(contract.company_name or "").strip()
|
||||
# 早期解析把下拉框全部选项拼进了公司。选中项是其中一段时,用选中项替换整段。
|
||||
if incoming_company and (not stored_company or (incoming_company != stored_company and incoming_company in stored_company)):
|
||||
contract.company_name = incoming_company
|
||||
contract.applicant_name = contract.applicant_name or str(item.get("applicant_name") or "").strip() or None
|
||||
# [STEP 0] 普通同步只回填“仍为空”的 OA 标量字段,不用本次值覆盖已有值。
|
||||
# 合同金额的 0 与空相同,不能挡住正文正数,也不能用 OA 的 0 覆盖已有正数。
|
||||
@@ -475,6 +481,7 @@ def _overwrite_oa_fields(contract: ContractPaymentContract, item: dict[str, Any]
|
||||
"""
|
||||
field_parsers = {
|
||||
"purchase_order_no": lambda value: str(value).strip() or None,
|
||||
"company_name": lambda value: str(value).strip() or None,
|
||||
"supplier_name": lambda value: str(value).strip() or None,
|
||||
"applicant_name": lambda value: str(value).strip() or None,
|
||||
"total_amount": lambda value: positive_amount(value),
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""add contract payment company name
|
||||
|
||||
Revision ID: cp2f3a4b5c6d
|
||||
Revises: 43a8179cdd88
|
||||
|
||||
用途:合同台账保存 OA 合同申请单「公司」,供预付款/出货款按账套查询 ERP。
|
||||
依赖:当前迁移头 43a8179cdd88。
|
||||
逻辑:新增可空 company_name;存量合同保持空值,扫描时按 HXJM 账套处理,直到下次 OA 同步补上公司。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "cp2f3a4b5c6d"
|
||||
down_revision = "43a8179cdd88"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为合同台账增加 OA 公司字段。"""
|
||||
op.add_column(
|
||||
"contract_payment_contracts",
|
||||
sa.Column("company_name", sa.String(length=255), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除合同台账 OA 公司字段。"""
|
||||
op.drop_column("contract_payment_contracts", "company_name")
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_parse.py
|
||||
|
||||
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。
|
||||
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载;OA「公司」决定 ERP 账套,同一采购单号不能跨账套记成已付。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
@@ -881,3 +881,108 @@ def test_erp_combined_payment_marks_prepayment_and_shipment_paid():
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
|
||||
# 一笔请款同时预付款+出货款:金额等于两者之和,一次性标记两者为已付。
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
|
||||
|
||||
|
||||
def test_oa_company_dropdown_uses_selected_option(app):
|
||||
"""关键断言:公司下拉框只取 selected 项,不把全部候选项拼进公司名。"""
|
||||
page = """
|
||||
<table><tr>
|
||||
<td>公司</td>
|
||||
<td>
|
||||
<select name="disfield8496">
|
||||
<option value=""></option>
|
||||
<option value="0">和泰电子(吴江)有限公司</option>
|
||||
<option value="1">和泰科技(吴江)有限公司</option>
|
||||
<option value="2" selected="selected">苏州和信精密科技有限公司</option>
|
||||
<option value="4">无锡和宏智散热科技有限公司</option>
|
||||
</select>
|
||||
<input name="field8496" value="2" />
|
||||
</td>
|
||||
<td>合同单位</td><td>如兮环境科技(苏州)有限公司</td>
|
||||
</tr></table>
|
||||
"""
|
||||
with app.app_context():
|
||||
result = ContractOaClient()._parse_detail_html(page, base_url="http://oa.example/workflow/detail")
|
||||
assert result["company_name"] == "苏州和信精密科技有限公司"
|
||||
assert result["supplier_name"] == "如兮环境科技(苏州)有限公司"
|
||||
|
||||
|
||||
def test_oa_contract_detail_reads_company_not_supplier(app):
|
||||
"""关键断言:账套使用「公司」,合同单位仍是供应商。"""
|
||||
page = """
|
||||
<table>
|
||||
<tr><td>公司</td><td>无锡和宏智散热科技有限公司</td><td>合同单位</td><td>无锡君鑫机械制造有限公司</td></tr>
|
||||
<tr><td>采购单号</td><td>5202-2608270001</td></tr>
|
||||
</table>
|
||||
"""
|
||||
with app.app_context():
|
||||
result = ContractOaClient()._parse_detail_html(page, base_url="http://oa.example/workflow/detail")
|
||||
assert result["company_name"] == "无锡和宏智散热科技有限公司"
|
||||
assert result["supplier_name"] == "无锡君鑫机械制造有限公司"
|
||||
assert result["purchase_order_no"] == "5202-2608270001"
|
||||
|
||||
|
||||
def test_company_name_selects_erp_schema():
|
||||
"""关键断言:指定公司走对应账套,全角括号与其余公司(含空公司)走 HXJM。"""
|
||||
from app.services.contract_payment.erp_payment_service import erp_schema_for_company, _paid_records_sql
|
||||
|
||||
assert erp_schema_for_company("无锡和宏智散热科技有限公司") == "WZHHZ"
|
||||
assert erp_schema_for_company("和泰科技(吴江)有限公司") == "HTT"
|
||||
assert erp_schema_for_company("苏州和信精密科技有限公司") == "HXJM"
|
||||
assert erp_schema_for_company("其它公司") == "HXJM"
|
||||
assert erp_schema_for_company(None) == "HXJM"
|
||||
assert "WZHHZ.apa_file" in _paid_records_sql("WZHHZ", ":po_0")
|
||||
try:
|
||||
_paid_records_sql("无锡和宏智散热科技有限公司", ":po_0")
|
||||
except ValueError:
|
||||
rejected = True
|
||||
else:
|
||||
rejected = False
|
||||
assert rejected
|
||||
|
||||
|
||||
def test_paid_fact_stays_inside_the_company_schema(app, monkeypatch):
|
||||
"""关键断言:同一采购单号在 WZHHZ 已付,不能把 HXJM 合同标成已付。"""
|
||||
from app.services.contract_payment.erp_payment_service import ErpPaidRow
|
||||
|
||||
seen: dict[str, list] = {}
|
||||
|
||||
def fake_fetch(orders):
|
||||
seen["orders"] = list(orders)
|
||||
return {("WZHHZ", "5202-2608270001"): [ErpPaidRow(amount=Decimal("18000"), paid_date="2026-09-02")]}
|
||||
|
||||
monkeypatch.setattr("app.services.contract_payment.alert_service.fetch_paid_records", fake_fetch)
|
||||
with app.app_context():
|
||||
wuxi = ContractPaymentContract(
|
||||
purchase_order_no="5202-2608270001",
|
||||
company_name="无锡和宏智散热科技有限公司",
|
||||
oa_archive_at=datetime(2026, 9, 1, 9, 0),
|
||||
status="active",
|
||||
)
|
||||
suzhou = ContractPaymentContract(
|
||||
purchase_order_no="5202-2608270001",
|
||||
company_name="苏州和信精密科技有限公司",
|
||||
oa_archive_at=datetime(2026, 9, 1, 9, 0),
|
||||
status="active",
|
||||
)
|
||||
db.session.add_all([wuxi, suzhou])
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ContractPaymentNode(
|
||||
contract_id=wuxi.id, node_code="prepayment", node_type="prepayment",
|
||||
amount=Decimal("18000"), anchor_type="oa_archive", status="active",
|
||||
),
|
||||
ContractPaymentNode(
|
||||
contract_id=suzhou.id, node_code="prepayment", node_type="prepayment",
|
||||
amount=Decimal("18000"), anchor_type="oa_archive", status="active",
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
generate_alerts(today=date(2026, 9, 2), send=False)
|
||||
wuxi_status = db.session.query(ContractPaymentNode).filter_by(contract_id=wuxi.id).one().status
|
||||
suzhou_status = db.session.query(ContractPaymentNode).filter_by(contract_id=suzhou.id).one().status
|
||||
|
||||
assert ("5202-2608270001", "无锡和宏智散热科技有限公司") in seen["orders"]
|
||||
assert ("5202-2608270001", "苏州和信精密科技有限公司") in seen["orders"]
|
||||
assert wuxi_status == "paid"
|
||||
assert suzhou_status == "active"
|
||||
Reference in new issue
Block a user