fix: 清除采购单号多余的汉字和空格

This commit is contained in:
sophie committed 2026-09-24 17:19:28 +08:00
1 parent 89c8da2990
commit 2df9bdda0d
8 files changed
+99 -17

No files matched your search

+2 -2
View File
@@ -38,7 +38,7 @@ from app.services.contract_payment.ledger_focus import (
apply_ledger_focus, apply_ledger_focus,
ledger_focus_counts, ledger_focus_counts,
) )
from app.services.contract_payment.erp_payment_service import erp_schema_for_company from app.services.contract_payment.erp_payment_service import erp_schema_for_company, normalize_purchase_order_no
from app.services.contract_payment.parse_service import unique_parse_issues 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.review_service import apply_manual_review
from app.services.contract_payment.sync_service import ( from app.services.contract_payment.sync_service import (
@@ -159,7 +159,7 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
"id": row.id, "id": row.id,
"contract_no": row.contract_no, "contract_no": row.contract_no,
"workflow_no": row.workflow_no, "workflow_no": row.workflow_no,
"purchase_order_no": row.purchase_order_no, "purchase_order_no": normalize_purchase_order_no(row.purchase_order_no) or None,
"company_name": row.company_name, "company_name": row.company_name,
"erp_schema": erp_schema_for_company(row.company_name), "erp_schema": erp_schema_for_company(row.company_name),
"supplier_name": row.supplier_name, "supplier_name": row.supplier_name,
@@ -34,7 +34,12 @@ from app.services.integrations.wecom.notify import (
send_wecom_file_message, send_wecom_file_message,
upload_wecom_temp_media, upload_wecom_temp_media,
) )
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.erp_payment_service import (
erp_schema_for_company,
fetch_paid_records,
normalize_purchase_order_no,
resolve_paid_node_dates,
)
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
from app.services.schedule.timezone_util import compute_next_run_at from app.services.schedule.timezone_util import compute_next_run_at
@@ -78,15 +83,15 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
.all() .all()
) )
payable_orders = [ payable_orders = [
(str(contract.purchase_order_no or "").strip(), contract.company_name) (normalize_purchase_order_no(contract.purchase_order_no), contract.company_name)
for node, contract in rows for node, contract in rows
if node.node_type in {"prepayment", "shipment"} and str(contract.purchase_order_no or "").strip() if node.node_type in {"prepayment", "shipment"} and normalize_purchase_order_no(contract.purchase_order_no)
] ]
paid_records = fetch_paid_records(payable_orders) paid_records = fetch_paid_records(payable_orders)
paid_node_dates: dict[int, str | None] = {} paid_node_dates: dict[int, str | None] = {}
nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list) nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list)
for node, contract in rows: for node, contract in rows:
purchase_order_no = str(contract.purchase_order_no or "").strip() purchase_order_no = normalize_purchase_order_no(contract.purchase_order_no)
if node.node_type in {"prepayment", "shipment"} and purchase_order_no: if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
nodes_by_ledger[(erp_schema_for_company(contract.company_name), purchase_order_no)].append(node) 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(): for ledger_key, payment_nodes in nodes_by_ledger.items():
@@ -9,6 +9,7 @@ backend/app/services/contract_payment/erp_payment_service.py
from __future__ import annotations from __future__ import annotations
import itertools import itertools
import re
from dataclasses import dataclass from dataclasses import dataclass
from decimal import Decimal, InvalidOperation from decimal import Decimal, InvalidOperation
from typing import Iterable from typing import Iterable
@@ -33,6 +34,28 @@ def normalize_company_name(company_name: str | None) -> str:
return text.replace("(", "(").replace(")", ")") return text.replace("(", "(").replace(")", ")")
# 采购单号首尾可能粘上 OA 单元格里的空格或供应商简称,ERP 的 apaud03 不含汉字。
_PURCHASE_ORDER_EDGE_RE = re.compile(r"^[\s\u3000\u4e00-\u9fff]+|[\s\u3000\u4e00-\u9fff]+$")
def normalize_purchase_order_no(value: str | None) -> str:
"""
去掉采购单号首尾的空格和汉字。
核心逻辑:真正的采购单号没有汉字。只剥两端,中间的数字和横杠保留。
Args:
value: OA 或台账上的采购单号原文,可为空。
Returns:
去掉首尾空格和汉字后的采购单号;空值返回空字符串。
"""
text = str(value or "")
previous = None
while text and text != previous:
previous = text
text = _PURCHASE_ORDER_EDGE_RE.sub("", text)
return text
def erp_schema_for_company(company_name: str | None) -> str: def erp_schema_for_company(company_name: str | None) -> str:
""" """
按 OA 合同申请单上的公司确定 ERP 账套。 按 OA 合同申请单上的公司确定 ERP 账套。
@@ -89,7 +112,7 @@ def fetch_paid_records(orders: Iterable[tuple[str, str | None]]) -> dict[tuple[s
""" """
grouped: dict[str, set[str]] = {} grouped: dict[str, set[str]] = {}
for purchase_order_no, company_name in orders: for purchase_order_no, company_name in orders:
po = str(purchase_order_no or "").strip() po = normalize_purchase_order_no(purchase_order_no)
if not po: if not po:
continue continue
grouped.setdefault(erp_schema_for_company(company_name), set()).add(po) grouped.setdefault(erp_schema_for_company(company_name), set()).add(po)
@@ -2,7 +2,7 @@
services/contract_payment/oa_client.py services/contract_payment/oa_client.py
用途:读取 OA 中已归档的合同申请单,提取表单字段和合同附件供付款预警同步。 用途:读取 OA 中已归档的合同申请单,提取表单字段和合同附件供付款预警同步。
依赖:requests、lxml、Flask 配置;由 sync_service 负责将本客户端的标准化结果落库。 依赖:requests、lxml、Flask 配置、normalize_purchase_order_no;由 sync_service 负责将本客户端的标准化结果落库。
逻辑:同一登录会话顺序扫描待办和已办归档列表并翻页;满页大小以 OA 实际返回行数为准(泛微默认 10 条/页), 逻辑:同一登录会话顺序扫描待办和已办归档列表并翻页;满页大小以 OA 实际返回行数为准(泛微默认 10 条/页),
不得用配置页大小把首页短页误判为到底;首次全量翻到短页为止,增量触顶页上限时标记截断供同步层不推进断点。 不得用配置页大小把首页短页误判为到底;首次全量翻到短页为止,增量触顶页上限时标记截断供同步层不推进断点。
合同原文被临时文件清理删掉后,可按流程 ID 与附件 ID 重新打开详情并下载。 合同原文被临时文件清理删掉后,可按流程 ID 与附件 ID 重新打开详情并下载。
@@ -23,6 +23,8 @@ import requests
from flask import current_app from flask import current_app
from lxml import html as lxml_html from lxml import html as lxml_html
from app.services.contract_payment.erp_payment_service import normalize_purchase_order_no
# OA 列表若始终返回满页,用硬上限防止死循环;首次全量也受此保护。 # OA 列表若始终返回满页,用硬上限防止死循环;首次全量也受此保护。
_WORKLIST_HARD_MAX_PAGES = 1000 _WORKLIST_HARD_MAX_PAGES = 1000
@@ -708,7 +710,9 @@ class ContractOaClient:
"status": _ARCHIVED_TEXT if _ARCHIVED_TEXT in full_text else "", "status": _ARCHIVED_TEXT if _ARCHIVED_TEXT in full_text else "",
"contract_no": contract_no, "contract_no": contract_no,
"workflow_no": workflow_no, "workflow_no": workflow_no,
"purchase_order_no": _field_value(labels, "采购单号") or _purchase_order_no_from_title(_field_value(labels, "标题")), "purchase_order_no": normalize_purchase_order_no(
_field_value(labels, "采购单号") or _purchase_order_no_from_title(_field_value(labels, "标题"))
),
"company_name": _field_value(labels, "公司"), "company_name": _field_value(labels, "公司"),
"supplier_name": _field_value(labels, "合同单位", "供应商"), "supplier_name": _field_value(labels, "合同单位", "供应商"),
"applicant_name": _field_value(labels, "申请人", "申请人员", "申请人姓名"), "applicant_name": _field_value(labels, "申请人", "申请人员", "申请人姓名"),
@@ -16,6 +16,7 @@ from typing import Any
from app import db from app import db
from app.core.errors import NotFoundError, ValidationError from app.core.errors import NotFoundError, ValidationError
from app.models import ContractPaymentContract, ContractPaymentEvent, ContractPaymentNode from app.models import ContractPaymentContract, ContractPaymentEvent, ContractPaymentNode
from app.services.contract_payment.erp_payment_service import normalize_purchase_order_no
_STAGE_TYPES = ("prepayment", "shipment", "acceptance", "warranty") _STAGE_TYPES = ("prepayment", "shipment", "acceptance", "warranty")
_DATE_REQUIRED = {"prepayment", "shipment"} _DATE_REQUIRED = {"prepayment", "shipment"}
@@ -115,7 +116,7 @@ def _normalize_review(contract: ContractPaymentContract, payload: dict[str, Any]
Raises: Raises:
ValidationError: 任一进入台账的条件不满足。 ValidationError: 任一进入台账的条件不满足。
""" """
purchase_order_no = str(payload.get("purchase_order_no") or "").strip() purchase_order_no = normalize_purchase_order_no(payload.get("purchase_order_no"))
if not purchase_order_no: if not purchase_order_no:
raise ValidationError("请填写采购单号") raise ValidationError("请填写采购单号")
if len(purchase_order_no) > 128: if len(purchase_order_no) > 128:
@@ -5,7 +5,7 @@ backend/app/services/contract_payment/sync_service.py
依赖:ContractOaClient、acceptance_oa_service、ContractPayment* 模型、parse_service、file_assets.service。 依赖:ContractOaClient、acceptance_oa_service、ContractPayment* 模型、parse_service、file_assets.service。
逻辑:合同申请单走 HTTP 待办/已办;验收归档走 OA SQL(formtable_main_324.cgdh × workflow_requestbase.currentnodetype=3); 逻辑:合同申请单走 HTTP 待办/已办;验收归档走 OA SQL(formtable_main_324.cgdh × workflow_requestbase.currentnodetype=3);
通知按 source_event_id 幂等;合同编号与采购单号以 OA 为准;列表翻页截断时入库但不推进增量断点; 通知按 source_event_id 幂等;合同编号与采购单号以 OA 为准;列表翻页截断时入库但不推进增量断点;
付款状态不再读取 OA 请款作业;合同 owner_user_id 由申请人真实姓名匹配系统用户,附件存储所有者仍可回退默认账号。 付款状态不再读取 OA 请款作业;采购单号去掉首尾空格和汉字后再与 ERP 匹配。合同 owner_user_id 由申请人真实姓名匹配系统用户,附件存储所有者仍可回退默认账号。
OA 合同金额为 0 或空时不当有效总额;正文抽出的正数在解析时回写台账,强制覆盖也不能把正数总额改成 0。 OA 合同金额为 0 或空时不当有效总额;正文抽出的正数在解析时回写台账,强制覆盖也不能把正数总额改成 0。
OA/DMS 合同原文落库后标为已引用;临时清理删掉对象后,下载和重解析按附件 ID 重新下载。 OA/DMS 合同原文落库后标为已引用;临时清理删掉对象后,下载和重解析按附件 ID 重新下载。
""" """
@@ -37,6 +37,7 @@ from app.services.contract_payment.acceptance_oa_service import (
) )
from app.services.contract_payment.oa_client import ContractOaClient from app.services.contract_payment.oa_client import ContractOaClient
from app.services.contract_payment.dms_client import ContractDmsClient from app.services.contract_payment.dms_client import ContractDmsClient
from app.services.contract_payment.erp_payment_service import normalize_purchase_order_no
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text, positive_amount from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text, positive_amount
from app.services.contract_payment.alert_service import bind_contract_owner_from_applicant from app.services.contract_payment.alert_service import bind_contract_owner_from_applicant
from app.services.file_assets.service import ( from app.services.file_assets.service import (
@@ -166,7 +167,7 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
if contract is None and contract_no: if contract is None and contract_no:
contract = db.session.query(ContractPaymentContract).filter_by(contract_no=contract_no).first() contract = db.session.query(ContractPaymentContract).filter_by(contract_no=contract_no).first()
if contract is None and event_type == "acceptance_archive": if contract is None and event_type == "acceptance_archive":
purchase_order_no = str(item.get("purchase_order_no") or "").strip() purchase_order_no = normalize_purchase_order_no(item.get("purchase_order_no"))
if purchase_order_no: if purchase_order_no:
contract = ( contract = (
db.session.query(ContractPaymentContract) db.session.query(ContractPaymentContract)
@@ -177,7 +178,7 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
if contract is None: if contract is None:
contract = ContractPaymentContract( contract = ContractPaymentContract(
contract_no=contract_no, contract_no=contract_no,
purchase_order_no=str(item.get("purchase_order_no") or "").strip() or None, purchase_order_no=normalize_purchase_order_no(item.get("purchase_order_no")) or None,
company_name=str(item.get("company_name") 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, supplier_name=str(item.get("supplier_name") or "").strip() or None,
applicant_name=str(item.get("applicant_name") or "").strip() or None, applicant_name=str(item.get("applicant_name") or "").strip() or None,
@@ -198,7 +199,10 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
else: else:
if force: if force:
overwritten += _overwrite_oa_fields(contract, item, operator_id=operator_id) 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 stored_po = normalize_purchase_order_no(contract.purchase_order_no) or None
if stored_po != (str(contract.purchase_order_no or "").strip() or None):
contract.purchase_order_no = stored_po
contract.purchase_order_no = contract.purchase_order_no or normalize_purchase_order_no(item.get("purchase_order_no")) or None
incoming_company = str(item.get("company_name") or "").strip() incoming_company = str(item.get("company_name") or "").strip()
stored_company = str(contract.company_name or "").strip() stored_company = str(contract.company_name or "").strip()
# 早期解析把下拉框全部选项拼进了公司。选中项是其中一段时,用选中项替换整段。 # 早期解析把下拉框全部选项拼进了公司。选中项是其中一段时,用选中项替换整段。
@@ -406,7 +410,7 @@ def ingest_acceptance_archives(items: list[dict[str, Any]]) -> tuple[int, int]:
created = skipped = 0 created = skipped = 0
touched_ids: set[int] = set() touched_ids: set[int] = set()
for item in items: for item in items:
purchase_order_no = str(item.get("purchase_order_no") or "").strip() purchase_order_no = normalize_purchase_order_no(item.get("purchase_order_no"))
request_id = str(item.get("request_id") or "").strip() request_id = str(item.get("request_id") or "").strip()
if not purchase_order_no or not request_id: if not purchase_order_no or not request_id:
skipped += 1 skipped += 1
@@ -480,7 +484,7 @@ def _overwrite_oa_fields(contract: ContractPaymentContract, item: dict[str, Any]
实际发生覆盖的字段数量。 实际发生覆盖的字段数量。
""" """
field_parsers = { field_parsers = {
"purchase_order_no": lambda value: str(value).strip() or None, "purchase_order_no": lambda value: normalize_purchase_order_no(value) or None,
"company_name": 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, "supplier_name": lambda value: str(value).strip() or None,
"applicant_name": lambda value: str(value).strip() or None, "applicant_name": lambda value: str(value).strip() or None,
@@ -586,7 +590,7 @@ def sync_vendor_prepayment_requests(*, client: ContractOaClient) -> tuple[int, i
skipped += 1 skipped += 1
continue continue
contract_no = str(item.get("contract_no") or "").strip() contract_no = str(item.get("contract_no") or "").strip()
purchase_order_no = str(item.get("purchase_order_no") or "").strip() purchase_order_no = normalize_purchase_order_no(item.get("purchase_order_no"))
if not contract_no and not purchase_order_no: if not contract_no and not purchase_order_no:
skipped += 1 skipped += 1
continue continue
@@ -0,0 +1,35 @@
"""strip purchase order edge spaces and chinese
Revision ID: cp3a4b5c6d7e
Revises: cp2f3a4b5c6d
用途:清掉合同台账采购单号首尾的空格和汉字,使 ERP apaud03 能精确匹配。
依赖:合同公司字段迁移 cp2f3a4b5c6d。
逻辑:只改已有数据,不改表结构。中间的数字和横杠保留;清完为空则写成 NULL。
"""
from alembic import op
revision = "cp3a4b5c6d7e"
down_revision = "cp2f3a4b5c6d"
branch_labels = None
depends_on = None
_EDGE = "^[[:space:] 一-龥]+|[[:space:] 一-龥]+$"
def upgrade() -> None:
"""去掉存量采购单号两端的空格和汉字。"""
op.execute(
f"""
UPDATE contract_payment_contracts
SET purchase_order_no = NULLIF(regexp_replace(purchase_order_no, '{_EDGE}', '', 'g'), '')
WHERE purchase_order_no ~ '{_EDGE}'
"""
)
def downgrade() -> None:
"""首尾汉字已被去掉,无法从剩余单号还原原文。"""
pass
@@ -922,6 +922,16 @@ def test_oa_contract_detail_reads_company_not_supplier(app):
assert result["purchase_order_no"] == "5202-2608270001" assert result["purchase_order_no"] == "5202-2608270001"
def test_purchase_order_no_strips_edge_spaces_and_chinese():
"""关键断言:采购单号只去掉首尾空格和汉字,中间的数字与横杠保留。"""
from app.services.contract_payment.erp_payment_service import normalize_purchase_order_no
assert normalize_purchase_order_no("5203-2608270001 杰创") == "5203-2608270001"
assert normalize_purchase_order_no(" 杰创 5203-2608270001 ") == "5203-2608270001"
assert normalize_purchase_order_no("5203-2608270001") == "5203-2608270001"
assert normalize_purchase_order_no(" ") == ""
def test_company_name_selects_erp_schema(): def test_company_name_selects_erp_schema():
"""关键断言:指定公司走对应账套,全角括号与其余公司(含空公司)走 HXJM。""" """关键断言:指定公司走对应账套,全角括号与其余公司(含空公司)走 HXJM。"""
from app.services.contract_payment.erp_payment_service import erp_schema_for_company, _paid_records_sql from app.services.contract_payment.erp_payment_service import erp_schema_for_company, _paid_records_sql