feat(invoice-check): ww OA下载销货放行单
This commit is contained in:
1 parent
f25f59142a
commit
d13f1035cc
40 files changed
+2284
-103
No files matched your search
@@ -219,6 +219,7 @@ def test_get_platform_jobs_api(client, admin_jwt_headers):
|
||||
assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
|
||||
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
|
||||
assert by_key["accounting-voucher-po-print"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherPoPrint"
|
||||
assert by_key["accounting-voucher-oa-sales-release"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherOaSalesRelease"
|
||||
|
||||
defs = client.get("/api/admin/platform-tasks/definitions", headers=admin_jwt_headers)
|
||||
assert defs.status_code == 200
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_oa_sales_release_schedule.py
|
||||
|
||||
用途:销货放行单周批早于检核,且不走 oa_sales_release.fetch。
|
||||
依赖:pytest、app fixture;不连 E10 SQL / OpenAPI / 文档库。
|
||||
逻辑:断言 cron 05:30、种子幂等、下载后上传、无 PDF 跳过、检核 fetch 仍关闭。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
|
||||
from app.services.voucher_check.oa_e10_client import (
|
||||
OaE10OpenApiClient,
|
||||
pick_pdf_file_id,
|
||||
reset_oa_e10_token_cache,
|
||||
)
|
||||
from app.services.voucher_check.oa_e10_repository import SalesReleaseRow, map_sales_release_row
|
||||
from app.services.voucher_check.oa_e10_settings import OaE10Settings, load_oa_e10_settings
|
||||
from app.services.voucher_check.oa_sales_release_filename import build_sales_release_filename
|
||||
from app.services.voucher_check.oa_sales_release_runner import run_oa_sales_release_batch
|
||||
from app.services.voucher_check.schedule_seed import (
|
||||
DEFAULT_VOUCHER_CHECK_CRON,
|
||||
DEFAULT_VOUCHER_OA_SALES_RELEASE_CRON,
|
||||
DEFAULT_VOUCHER_OA_SALES_RELEASE_PLATFORM_PATH,
|
||||
DEFAULT_VOUCHER_OA_SALES_RELEASE_SCHEDULE_NO,
|
||||
DEFAULT_VOUCHER_PO_PRINT_CRON,
|
||||
ensure_default_voucher_check_schedule,
|
||||
ensure_default_voucher_oa_sales_release_schedule,
|
||||
ensure_default_voucher_po_print_schedule,
|
||||
)
|
||||
|
||||
|
||||
def _settings(**overrides) -> OaE10Settings:
|
||||
payload = dict(
|
||||
openapi_base_url="http://e10.test/papi/openapi",
|
||||
corpid="corp-1",
|
||||
app_key="key-1",
|
||||
app_secret="secret-1",
|
||||
userid="1001",
|
||||
timeout_seconds=10,
|
||||
token_refresh_skew_seconds=300,
|
||||
sql_host="sql.test",
|
||||
sql_port="1433",
|
||||
sql_database="ecology10",
|
||||
sql_username="reader",
|
||||
sql_password="hidden",
|
||||
sql_driver="",
|
||||
sql_encrypt="no",
|
||||
sql_trust_cert="yes",
|
||||
sql_timeout=10,
|
||||
)
|
||||
payload.update(overrides)
|
||||
return OaE10Settings(**payload)
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
def __init__(self, payload=None, content=b"", status=200, content_type="application/json"):
|
||||
self._payload = payload
|
||||
self.content = content
|
||||
self.status_code = status
|
||||
self.headers = {"Content-Type": content_type}
|
||||
|
||||
def json(self):
|
||||
if self._payload is None:
|
||||
raise ValueError("no json")
|
||||
return self._payload
|
||||
|
||||
|
||||
class _FakeSession:
|
||||
def __init__(self, routes: dict[str, list[_FakeResponse]]):
|
||||
self.routes = routes
|
||||
self.calls: list[str] = []
|
||||
|
||||
def request(self, method, url, **kwargs):
|
||||
path = url.split("openapi", 1)[-1] if "openapi" in url else url
|
||||
key = f"{method.upper()} {path.split('?')[0]}"
|
||||
self.calls.append(key)
|
||||
queue = self.routes.get(key)
|
||||
if not queue:
|
||||
raise AssertionError(f"unexpected request {key}")
|
||||
return queue.pop(0)
|
||||
|
||||
|
||||
def test_oa_sales_release_cron_is_between_po_and_check():
|
||||
"""周二 05:30 介于 PO 05:00 与检核 06:00。"""
|
||||
assert DEFAULT_VOUCHER_PO_PRINT_CRON == "0 5 * * 2"
|
||||
assert DEFAULT_VOUCHER_OA_SALES_RELEASE_CRON == "30 5 * * 2"
|
||||
assert DEFAULT_VOUCHER_CHECK_CRON == "0 6 * * 2"
|
||||
|
||||
|
||||
def test_ensure_oa_sales_release_schedule_is_idempotent(app):
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
if db.session.query(User).first() is None:
|
||||
user = User(
|
||||
username="oa-sales-seed-admin",
|
||||
email="oa-sales-seed-admin@example.com",
|
||||
role="admin",
|
||||
status="active",
|
||||
)
|
||||
user.set_password("test")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
check = ensure_default_voucher_check_schedule(commit=True)
|
||||
po = ensure_default_voucher_po_print_schedule(commit=True)
|
||||
first = ensure_default_voucher_oa_sales_release_schedule(commit=True)
|
||||
second = ensure_default_voucher_oa_sales_release_schedule(commit=True)
|
||||
assert check is not None
|
||||
assert po is not None
|
||||
assert first is not None
|
||||
assert first.id == second.id
|
||||
assert first.schedule_no == DEFAULT_VOUCHER_OA_SALES_RELEASE_SCHEDULE_NO
|
||||
assert first.platform_api_path == DEFAULT_VOUCHER_OA_SALES_RELEASE_PLATFORM_PATH
|
||||
assert first.cron_expr == DEFAULT_VOUCHER_OA_SALES_RELEASE_CRON
|
||||
assert first.platform_api_path != check.platform_api_path
|
||||
assert first.platform_api_path != po.platform_api_path
|
||||
|
||||
|
||||
def test_pick_pdf_file_id_skips_html():
|
||||
"""只要 PDF 的 fileid,忽略 html。"""
|
||||
file_id = pick_pdf_file_id(
|
||||
[
|
||||
{"type": "html", "fileid": "111"},
|
||||
{"extName": "pdf", "fileid": "1317512696036114467"},
|
||||
]
|
||||
)
|
||||
assert file_id == "1317512696036114467"
|
||||
assert pick_pdf_file_id([{"type": "html", "fileid": "111"}]) is None
|
||||
|
||||
|
||||
def test_map_sales_release_row_skips_incomplete():
|
||||
assert map_sales_release_row(("INV-1", "XH-1", "8448")) == SalesReleaseRow(
|
||||
invoice_no="INV-1",
|
||||
delivery_no="XH-1",
|
||||
doc_id="8448",
|
||||
)
|
||||
assert map_sales_release_row(("", "XH-1", "8448")) is None
|
||||
assert map_sales_release_row(("INV-1", "", "8448")) is None
|
||||
|
||||
|
||||
def test_build_sales_release_filename():
|
||||
assert build_sales_release_filename(invoice_no="EWZZ01", delivery_no="XH-9") == "EWZZ01-XH-9.pdf"
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
build_sales_release_filename(invoice_no="a/b", delivery_no="XH-9")
|
||||
assert exc.value.code == "VOUCHER_CHECK.OA_SALES_RELEASE_INVALID"
|
||||
|
||||
|
||||
def test_load_settings_rejects_e9_ecology(app):
|
||||
with app.app_context():
|
||||
app.config["OA_E10_OPENAPI_BASE_URL"] = "http://e10.test/papi/openapi"
|
||||
app.config["OA_E10_CORPID"] = "corp"
|
||||
app.config["OA_E10_APP_KEY"] = "key"
|
||||
app.config["OA_E10_APP_SECRET"] = "secret"
|
||||
app.config["OA_E10_USERID"] = "1"
|
||||
app.config["OA_E10_SQLSERVER_HOST"] = "sql"
|
||||
app.config["OA_E10_SQLSERVER_USERNAME"] = "reader"
|
||||
app.config["OA_E10_SQLSERVER_PASSWORD"] = "hidden"
|
||||
app.config["OA_E10_SQLSERVER_DATABASE"] = "ecology"
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
load_oa_e10_settings()
|
||||
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
|
||||
|
||||
def test_token_cached_then_refresh_on_200007():
|
||||
"""任务内缓存 accessToken;业务口 200007 时刷新一次再试。"""
|
||||
reset_oa_e10_token_cache()
|
||||
session = _FakeSession(
|
||||
{
|
||||
"POST /oauth2/authorize": [
|
||||
_FakeResponse({"errcode": "0", "code": "once-code"}),
|
||||
],
|
||||
"POST /oauth2/access_token": [
|
||||
_FakeResponse(
|
||||
{
|
||||
"errcode": "0",
|
||||
"accessToken": "atk-1",
|
||||
"refreshToken": "rtk-1",
|
||||
"expires_in": 7200,
|
||||
}
|
||||
),
|
||||
],
|
||||
"POST /oauth2/refresh_token": [
|
||||
_FakeResponse(
|
||||
{
|
||||
"errcode": "0",
|
||||
"accessToken": "atk-2",
|
||||
"refreshToken": "rtk-2",
|
||||
"expires_in": 7200,
|
||||
}
|
||||
),
|
||||
],
|
||||
"GET /api/doc/v2/attList/8448": [
|
||||
_FakeResponse({"errcode": "200007", "errmsg": "invalid token"}),
|
||||
_FakeResponse(
|
||||
{
|
||||
"errcode": "0",
|
||||
"data": [{"type": "pdf", "fileid": "1317"}],
|
||||
}
|
||||
),
|
||||
],
|
||||
}
|
||||
)
|
||||
client = OaE10OpenApiClient(_settings(), session=session)
|
||||
first = client.ensure_access_token()
|
||||
second = client.ensure_access_token()
|
||||
assert first == second == "atk-1"
|
||||
file_id = client.list_pdf_file_id("8448")
|
||||
assert file_id == "1317"
|
||||
assert any(item.startswith("POST /oauth2/refresh_token") for item in session.calls)
|
||||
reset_oa_e10_token_cache()
|
||||
|
||||
|
||||
def test_oa_sales_release_batch_uploads_and_skips_no_pdf(app, monkeypatch):
|
||||
"""有 PDF 的行上传;attList 无 PDF 记 skipped_no_pdf;不调用 fetch()。"""
|
||||
uploaded: list[str] = []
|
||||
rows = [
|
||||
SalesReleaseRow(invoice_no="EWZZ26090002", delivery_no="XH-1", doc_id="8448"),
|
||||
SalesReleaseRow(invoice_no="EWZZ26090099", delivery_no="XH-2", doc_id="8449"),
|
||||
]
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.load_oa_e10_settings",
|
||||
lambda: _settings(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.SalesDmsClient.ensure_configured",
|
||||
lambda: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.previous_period_bounds",
|
||||
lambda now=None: (date(2026, 8, 1), date(2026, 9, 1), None, None),
|
||||
)
|
||||
|
||||
class _DummyClient:
|
||||
def ensure_access_token(self):
|
||||
return "atk"
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.OaE10OpenApiClient.from_config",
|
||||
lambda: _DummyClient(),
|
||||
)
|
||||
monkeypatch.setattr(OaSalesReleaseAdapter, "fetch_rows", lambda self, period_month, scope_code="HXJM": rows)
|
||||
|
||||
def fake_download(self, row, *, client):
|
||||
if row.delivery_no == "XH-2":
|
||||
return None
|
||||
return b"%PDF-1.4 fake"
|
||||
|
||||
monkeypatch.setattr(OaSalesReleaseAdapter, "download_pdf", fake_download)
|
||||
|
||||
def fake_upload(self, row, content, *, period_month):
|
||||
uploaded.append(row.delivery_no)
|
||||
return SimpleNamespace(
|
||||
skipped_same_name=False,
|
||||
file=SimpleNamespace(filename=f"{row.invoice_no}-{row.delivery_no}.pdf"),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(OaSalesReleaseAdapter, "upload_given", fake_upload)
|
||||
monkeypatch.setattr("app.services.voucher_check.oa_sales_release_runner.send_failure_alert", lambda **kwargs: None)
|
||||
|
||||
with app.app_context():
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-TEST-OA",
|
||||
name="oa sales",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="accounting-voucher-oa-sales-release",
|
||||
owner_user_id=1,
|
||||
cron_expr="30 5 * * 2",
|
||||
job_params={"profile_code": "sales", "scope_code": "HXJM", "notify_failure_enabled": False},
|
||||
)
|
||||
run = ScheduleRun(run_no="RUN-OA-1", schedule_task_id=1, status="running")
|
||||
total, success, failed, skipped, details, errors, logs = run_oa_sales_release_batch(task, run)
|
||||
|
||||
assert total == 2
|
||||
assert success == 1
|
||||
assert failed == 0
|
||||
assert skipped == 1
|
||||
assert uploaded == ["XH-1"]
|
||||
assert any(item.get("status") == "skipped_no_pdf" for item in details)
|
||||
assert OaSalesReleaseAdapter.wired is False
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
OaSalesReleaseAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
|
||||
assert exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
|
||||
|
||||
|
||||
def test_oa_sales_release_batch_counts_upload_failure(app, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.load_oa_e10_settings",
|
||||
lambda: _settings(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.SalesDmsClient.ensure_configured",
|
||||
lambda: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.previous_period_bounds",
|
||||
lambda now=None: (date(2026, 8, 1), date(2026, 9, 1), None, None),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.OaE10OpenApiClient.from_config",
|
||||
lambda: SimpleNamespace(ensure_access_token=lambda: "atk"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
OaSalesReleaseAdapter,
|
||||
"fetch_rows",
|
||||
lambda self, period_month, scope_code="HXJM": [
|
||||
SalesReleaseRow(invoice_no="EWZZ26090002", delivery_no="XH-FAIL", doc_id="8448")
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
OaSalesReleaseAdapter,
|
||||
"download_pdf",
|
||||
lambda self, row, *, client: b"%PDF-1.4 fail",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
OaSalesReleaseAdapter,
|
||||
"upload_given",
|
||||
lambda self, row, content, *, period_month: (_ for _ in ()).throw(RuntimeError("dms down")),
|
||||
)
|
||||
alerts: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.send_failure_alert",
|
||||
lambda **kwargs: alerts.append(kwargs.get("stage") or ""),
|
||||
)
|
||||
with app.app_context():
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-TEST-OA2",
|
||||
name="oa sales",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="accounting-voucher-oa-sales-release",
|
||||
owner_user_id=1,
|
||||
cron_expr="30 5 * * 2",
|
||||
job_params={},
|
||||
)
|
||||
run = ScheduleRun(run_no="RUN-OA-2", schedule_task_id=1, status="running")
|
||||
total, success, failed, skipped, details, errors, logs = run_oa_sales_release_batch(task, run)
|
||||
assert total == 1
|
||||
assert success == 0
|
||||
assert failed == 1
|
||||
assert "download_or_upload" in alerts
|
||||
assert errors
|
||||
|
||||
|
||||
def test_platform_job_registered():
|
||||
from app.services.schedule.job_registry import get_platform_job
|
||||
|
||||
job = get_platform_job("accounting-voucher-oa-sales-release")
|
||||
assert job is not None
|
||||
assert job.label_key == "admin.schedule.form.platformJobAccountingVoucherOaSalesRelease"
|
||||
assert job.handler is not None
|
||||
|
||||
|
||||
def test_probe_writes_one_local_pdf(app, monkeypatch, tmp_path):
|
||||
"""联调命令默认只落本地 PDF,不上传文档库。"""
|
||||
from app.services.voucher_check.oa_sales_release_probe import main
|
||||
|
||||
row = SalesReleaseRow(invoice_no="EWZZ26090002", delivery_no="XH-1", doc_id="8448")
|
||||
monkeypatch.setattr("app.create_app", lambda *a, **k: app)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_e10_settings.load_oa_e10_settings",
|
||||
lambda: _settings(),
|
||||
)
|
||||
monkeypatch.setattr(OaSalesReleaseAdapter, "fetch_rows", lambda self, period_month, scope_code="HXJM": [row])
|
||||
monkeypatch.setattr(
|
||||
OaSalesReleaseAdapter,
|
||||
"download_pdf",
|
||||
lambda self, item, *, client: b"%PDF-1.4 probe",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_e10_client.OaE10OpenApiClient.from_config",
|
||||
lambda: SimpleNamespace(ensure_access_token=lambda: "atk"),
|
||||
)
|
||||
uploaded: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
OaSalesReleaseAdapter,
|
||||
"upload_given",
|
||||
lambda self, item, content, *, period_month: uploaded.append(item.delivery_no),
|
||||
)
|
||||
code = main(["--out-dir", str(tmp_path), "--period", "2026-08", "--limit", "1"])
|
||||
dest = tmp_path / "EWZZ26090002-XH-1.pdf"
|
||||
assert code == 0
|
||||
assert dest.read_bytes().startswith(b"%PDF")
|
||||
assert uploaded == []
|
||||
Reference in new issue
Block a user