326 lines
13 KiB
Python
326 lines
13 KiB
Python
"""
|
|
backend/tests/voucher_check/test_notify_config.py
|
|
|
|
用途:按文件类型配置缺件接收人,以及把缺件类型拆成每人一封。
|
|
依赖:pytest、Flask client、notify_config_service、notification.send_batch_missing_summary。
|
|
逻辑:GET/PUT 仅 is_platform_admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型,并收到同一份 Excel。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date
|
|
from types import SimpleNamespace
|
|
|
|
from tests.conftest import parse_api_data, parse_api_error
|
|
|
|
from app import db
|
|
from app.models import ScheduleRun, ScheduleTask, User
|
|
from app.models.voucher_check import VoucherCheckNotification, VoucherCheckNotifyConfig, VoucherCheckRun
|
|
from app.services.voucher_check.notify_config_service import (
|
|
normalize_recipients_json,
|
|
plan_missing_recipient_messages,
|
|
)
|
|
from app.services.voucher_check.notification import send_batch_missing_summary
|
|
|
|
|
|
def _ensure_user(
|
|
*,
|
|
username: str,
|
|
role: str = "user",
|
|
wecom_userid: str | None = None,
|
|
department: str | None = None,
|
|
) -> User:
|
|
"""
|
|
测试用户幂等创建。
|
|
|
|
Args:
|
|
username: 登录名。
|
|
role: 角色,默认普通用户。
|
|
wecom_userid: 企微 userid,有值即视为已绑定。
|
|
department: 部门名,供候选人接口与选人弹窗分组。
|
|
"""
|
|
user = db.session.query(User).filter_by(username=username).first()
|
|
if user:
|
|
user.role = role
|
|
user.status = "active"
|
|
user.wecom_userid = wecom_userid
|
|
if department is not None:
|
|
user.department = department
|
|
db.session.commit()
|
|
return user
|
|
user = User(
|
|
username=username,
|
|
email=f"{username}@example.com",
|
|
role=role,
|
|
status="active",
|
|
real_name=username,
|
|
wecom_userid=wecom_userid,
|
|
department=department,
|
|
)
|
|
user.set_password("test")
|
|
db.session.add(user)
|
|
db.session.commit()
|
|
return user
|
|
|
|
|
|
def test_plan_merges_types_per_user_and_tracks_unmapped():
|
|
"""同一人管多类时合并到一封;有缺件但无人接收的类型进入 unmapped。"""
|
|
plan = plan_missing_recipient_messages(
|
|
by_file_type={
|
|
"po_order": {
|
|
"rule_code": "po_order",
|
|
"rule_name": "PO订单",
|
|
"missing_file_count": 2,
|
|
"missing_invoice_count": 1,
|
|
},
|
|
"tax_invoice": {
|
|
"rule_code": "tax_invoice",
|
|
"rule_name": "发票",
|
|
"missing_file_count": 3,
|
|
"missing_invoice_count": 2,
|
|
},
|
|
"bill_of_lading": {
|
|
"rule_code": "bill_of_lading",
|
|
"rule_name": "提单",
|
|
"missing_file_count": 1,
|
|
"missing_invoice_count": 1,
|
|
},
|
|
"customs_pack": {
|
|
"rule_code": "customs_pack",
|
|
"rule_name": "报关资料",
|
|
"missing_file_count": 0,
|
|
"missing_invoice_count": 0,
|
|
},
|
|
},
|
|
recipients_by_rule={
|
|
"po_order": [11, 12],
|
|
"tax_invoice": [11],
|
|
"bill_of_lading": [],
|
|
},
|
|
)
|
|
# 关键断言:11 同时收到 PO 与发票;提单无人配置。
|
|
assert plan["unmapped_codes"] == ["bill_of_lading"]
|
|
assert [item["code"] for item in plan["user_rules"][11]] == ["po_order", "tax_invoice"]
|
|
assert [item["code"] for item in plan["user_rules"][12]] == ["po_order"]
|
|
|
|
|
|
def test_normalize_drops_unknown_rule_codes():
|
|
"""提交里的未知规则码必须丢弃,不能写进配置表。"""
|
|
cleaned = normalize_recipients_json(
|
|
{"po_order": [1, 1, "2", 0, "x"], "unknown": [9]},
|
|
profile_code="sales",
|
|
)
|
|
assert cleaned["po_order"] == [1, 2]
|
|
assert "unknown" not in cleaned
|
|
assert "tax_invoice" in cleaned
|
|
|
|
|
|
def test_admin_can_get_and_save_notify_config(app, client, admin_headers):
|
|
"""管理员可读取六行规则并保存接收人。"""
|
|
with app.app_context():
|
|
admin = _ensure_user(username="admin", role="admin")
|
|
owner = _ensure_user(username="vc_po_owner", wecom_userid="wx-po", department="财务部")
|
|
owner_id = owner.id
|
|
admin_id = admin.id
|
|
|
|
listed = client.get(
|
|
"/api/workspace/accounting-voucher-check/notify-config",
|
|
headers=admin_headers,
|
|
)
|
|
assert listed.status_code == 200
|
|
payload = parse_api_data(listed.get_json())
|
|
owner_row = next(row for row in payload["users"] if row["id"] == owner_id)
|
|
# 关键断言:候选人带部门,供公共选人弹窗左侧分组。
|
|
assert owner_row["department"] == "财务部"
|
|
assert owner_row["wecom_bound"] is True
|
|
codes = [row["code"] for row in payload["rules"]]
|
|
# 关键断言:页面行来自销售 Profile 六类必检文件。
|
|
assert codes == [
|
|
"po_order",
|
|
"customs_pack",
|
|
"sales_release",
|
|
"tax_invoice",
|
|
"customs_declaration",
|
|
"bill_of_lading",
|
|
]
|
|
|
|
saved = client.put(
|
|
"/api/workspace/accounting-voucher-check/notify-config",
|
|
headers=admin_headers,
|
|
json={
|
|
"profile_code": "sales",
|
|
"recipients": {"po_order": [owner_id], "unknown": [admin_id]},
|
|
},
|
|
)
|
|
assert saved.status_code == 200
|
|
saved_payload = parse_api_data(saved.get_json())
|
|
po_row = next(row for row in saved_payload["rules"] if row["code"] == "po_order")
|
|
assert po_row["user_ids"] == [owner_id]
|
|
unknown_codes = [row["code"] for row in saved_payload["rules"] if row["code"] == "unknown"]
|
|
assert unknown_codes == []
|
|
|
|
with app.app_context():
|
|
row = db.session.query(VoucherCheckNotifyConfig).filter_by(profile_code="sales").one()
|
|
assert row.recipients_json["po_order"] == [owner_id]
|
|
assert "unknown" not in row.recipients_json
|
|
|
|
|
|
def test_notify_config_rejects_non_admin_headers(app, client, user_headers):
|
|
"""仅凭普通用户 header 不能改通知配置。"""
|
|
with app.app_context():
|
|
_ensure_user(username="user", role="user")
|
|
|
|
res = client.get("/api/workspace/accounting-voucher-check/notify-config", headers=user_headers)
|
|
assert res.status_code == 403
|
|
assert parse_api_error(res.get_json())["code"] in {
|
|
"VOUCHER_CHECK.FORBIDDEN",
|
|
"VOUCHER_CHECK.ADMIN_REQUIRED",
|
|
}
|
|
|
|
|
|
def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
|
"""缺件通知按人拆信,正文只含该人负责的缺失类型,并给每人附上同一份 Excel。"""
|
|
sent: list[tuple[str, str, str]] = []
|
|
uploaded: list[tuple[bytes, str]] = []
|
|
files: list[tuple[str, str]] = []
|
|
|
|
def _fake_send(wecom_userid, title, description, jump_url):
|
|
sent.append((wecom_userid, title, description))
|
|
return {"errcode": 0}
|
|
|
|
def _fake_upload(data, filename):
|
|
uploaded.append((data, filename))
|
|
return "media-vc-1"
|
|
|
|
def _fake_file(wecom_userid, media_id):
|
|
files.append((wecom_userid, media_id))
|
|
return {"errcode": 0}
|
|
|
|
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_textcard_message", _fake_send)
|
|
monkeypatch.setattr("app.services.integrations.wecom.notify.upload_wecom_temp_media", _fake_upload)
|
|
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_file_message", _fake_file)
|
|
monkeypatch.setattr(
|
|
"app.services.integrations.wecom.notify._create_audit",
|
|
lambda *args, **kwargs: SimpleNamespace(
|
|
jump_url=None, status=None, error_code=None, error_message=None
|
|
),
|
|
)
|
|
monkeypatch.setattr("app.services.integrations.wecom.notify._build_jump_url", lambda *args, **kwargs: "https://jump")
|
|
|
|
with app.app_context():
|
|
app.config["WECOM_NOTIFY_ENABLED"] = True
|
|
owner = _ensure_user(username="vc_notify_owner", role="admin", wecom_userid="wx-owner")
|
|
po_user = _ensure_user(username="vc_po_recv", wecom_userid="wx-po-recv")
|
|
bl_user = _ensure_user(username="vc_bl_recv", wecom_userid="wx-bl-recv")
|
|
task = ScheduleTask(
|
|
schedule_no="SCH-VC-NOTIFY-SPLIT",
|
|
name="立账凭证检核",
|
|
schedule_type="platform_job",
|
|
platform_api_path="accounting-voucher-check",
|
|
owner_user_id=owner.id,
|
|
cron_expr="0 6 * * 2",
|
|
notify_enabled=True,
|
|
notify_user_ids_json=[],
|
|
)
|
|
db.session.add(task)
|
|
db.session.flush()
|
|
schedule_run = ScheduleRun(
|
|
schedule_task_id=task.id,
|
|
run_no="RUN-VC-NOTIFY-SPLIT",
|
|
trigger_type="cron",
|
|
status="success",
|
|
)
|
|
db.session.add(schedule_run)
|
|
db.session.flush()
|
|
engine_run = VoucherCheckRun(
|
|
id=1,
|
|
schedule_run_id=schedule_run.id,
|
|
run_no="VC-NOTIFY-SPLIT",
|
|
profile_code="sales",
|
|
profile_version="1",
|
|
profile_snapshot_json={"profile_code": "sales"},
|
|
period_month=date(2026, 8, 1),
|
|
mode="incremental",
|
|
status="missing",
|
|
subject_count=4,
|
|
missing_file_count=3,
|
|
missing_invoice_count=2,
|
|
)
|
|
db.session.add(engine_run)
|
|
db.session.flush()
|
|
notify_row = (
|
|
db.session.query(VoucherCheckNotifyConfig).filter_by(profile_code="sales").one_or_none()
|
|
)
|
|
if notify_row is None:
|
|
notify_row = VoucherCheckNotifyConfig(profile_code="sales")
|
|
db.session.add(notify_row)
|
|
notify_row.recipients_json = {
|
|
"po_order": [po_user.id],
|
|
"bill_of_lading": [bl_user.id],
|
|
}
|
|
db.session.commit()
|
|
status = send_batch_missing_summary(
|
|
task=task,
|
|
schedule_run=schedule_run,
|
|
engine_run_id=engine_run.id,
|
|
profile_code="sales",
|
|
period_month="2026-08",
|
|
stats={
|
|
"subject_count": 4,
|
|
"missing_file_count": 3,
|
|
"missing_invoice_count": 2,
|
|
"by_file_type": {
|
|
"po_order": {
|
|
"rule_code": "po_order",
|
|
"rule_name": "PO订单",
|
|
"missing_file_count": 2,
|
|
"missing_invoice_count": 1,
|
|
},
|
|
"bill_of_lading": {
|
|
"rule_code": "bill_of_lading",
|
|
"rule_name": "提单",
|
|
"missing_file_count": 1,
|
|
"missing_invoice_count": 1,
|
|
},
|
|
"tax_invoice": {
|
|
"rule_code": "tax_invoice",
|
|
"rule_name": "发票",
|
|
"missing_file_count": 1,
|
|
"missing_invoice_count": 1,
|
|
},
|
|
},
|
|
},
|
|
excel_filename="voucher_check_sales_2026-08.xlsx",
|
|
excel_bytes=b"voucher-xlsx",
|
|
enabled=True,
|
|
)
|
|
assert status == "sent"
|
|
audit = db.session.query(VoucherCheckNotification).filter_by(run_id=engine_run.id).one()
|
|
# 关键断言:仍是一批一条审计;skip_reason 记录未配置类型。
|
|
assert audit.send_status == "sent"
|
|
assert audit.skip_reason == "部分文件类型未配置接收人"
|
|
assert set(audit.recipient_user_ids_json or []) == {po_user.id, bl_user.id}
|
|
assert "tax_invoice" in (audit.summary_json or {}).get("unmapped_rule_codes", [])
|
|
|
|
wecom_ids = {item[0] for item in sent}
|
|
assert wecom_ids == {"wx-po-recv", "wx-bl-recv"}
|
|
po_title, po_body = next((item[1], item[2]) for item in sent if item[0] == "wx-po-recv")
|
|
bl_body = next(item[2] for item in sent if item[0] == "wx-bl-recv")
|
|
# 关键断言:卡片面向销售开票附件,不暴露业务方代号和批次号。
|
|
assert po_title == "销售开票附件缺件提醒"
|
|
assert "2026年8月" in po_body
|
|
assert "缺 2 份,涉及 1 张发票" in po_body
|
|
assert "业务方" not in po_body
|
|
assert "sales" not in po_body
|
|
assert "RUN-VC-NOTIFY-SPLIT" not in po_body
|
|
assert "PO订单" in po_body
|
|
# 关键断言:「张发票」是计量用语,类型是否出现要看「发票:缺」。
|
|
assert "提单:缺" not in po_body
|
|
assert "发票:缺" not in po_body
|
|
assert "提单" in bl_body
|
|
assert "PO订单:缺" not in bl_body
|
|
# 关键断言:同一份 Excel 只上传一次,两个收件人都收到文件消息。
|
|
assert uploaded == [(b"voucher-xlsx", "voucher_check_sales_2026-08.xlsx")]
|
|
assert files == [("wx-po-recv", "media-vc-1"), ("wx-bl-recv", "media-vc-1")]
|
|
assert "下一条 Excel" in po_body
|