feat(invoice check): 立账凭证检核优化部分代码

This commit is contained in:
sophie committed 2026-09-08 10:25:11 +08:00
1 parent 21d41acf50
commit d123d9cdf6
45 files changed
+498 -2508

No files matched your search

@@ -0,0 +1,133 @@
"""
backend/migrations/versions/vc2b3c4d5e6f_drop_legacy_voucher_check_tables.py
用途:删除旧共享盘方案的 voucher_check_invoice_states / voucher_check_run_items。
依赖:Alembic revision na0b1c2d3e4f5。
逻辑:先删 run_items(外键指向 states),再删 states;引擎表不受影响。
Revision ID: vc2b3c4d5e6f
Revises: na0b1c2d3e4f5
Create Date: 2026-09-08 09:20:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "vc2b3c4d5e6f"
down_revision = "na0b1c2d3e4f5"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删除旧一票一状态表;检核结果以 voucher_check_file_results 为准。"""
op.drop_index("ix_voucher_check_run_items_period_result", table_name="voucher_check_run_items")
op.drop_index("ix_voucher_check_run_items_run_result", table_name="voucher_check_run_items")
op.drop_index("ix_voucher_check_run_items_schedule_run_id", table_name="voucher_check_run_items")
op.drop_table("voucher_check_run_items")
op.drop_index("ix_voucher_check_invoice_states_notified_on", table_name="voucher_check_invoice_states")
op.drop_index("ix_voucher_check_invoice_states_invoice_no", table_name="voucher_check_invoice_states")
op.drop_index("ix_voucher_check_invoice_states_period_status", table_name="voucher_check_invoice_states")
op.drop_table("voucher_check_invoice_states")
def downgrade() -> None:
"""回建旧表结构,不恢复历史数据。"""
op.create_table(
"voucher_check_invoice_states",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column("scope_code", sa.String(length=32), nullable=False),
sa.Column("period_month", sa.Date(), nullable=False),
sa.Column("invoice_no", sa.String(length=128), nullable=False),
sa.Column("invoice_date", sa.Date(), nullable=True),
sa.Column("status", sa.String(length=24), nullable=False),
sa.Column("folder_path", sa.String(length=1024), nullable=True),
sa.Column("folder_exists", sa.Boolean(), nullable=False, server_default=sa.text("false")),
sa.Column("material_fingerprint", sa.String(length=64), nullable=True),
sa.Column("matched_files_json", sa.JSON(), nullable=True),
sa.Column("missing_materials_json", sa.JSON(), nullable=True),
sa.Column(
"last_actual_run_id",
sa.BigInteger(),
sa.ForeignKey("schedule_runs.id", ondelete="SET NULL"),
nullable=True,
),
sa.Column("last_checked_at", sa.DateTime(), nullable=True),
sa.Column("last_seen_erp_at", sa.DateTime(), nullable=True),
sa.Column("last_missing_notified_on", sa.Date(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint(
"scope_code",
"period_month",
"invoice_no",
name="uq_voucher_check_invoice_states_scope_period_invoice",
),
)
op.create_index(
"ix_voucher_check_invoice_states_period_status",
"voucher_check_invoice_states",
["period_month", "status"],
)
op.create_index(
"ix_voucher_check_invoice_states_invoice_no",
"voucher_check_invoice_states",
["invoice_no"],
)
op.create_index(
"ix_voucher_check_invoice_states_notified_on",
"voucher_check_invoice_states",
["last_missing_notified_on"],
)
op.create_table(
"voucher_check_run_items",
sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
sa.Column(
"schedule_run_id",
sa.BigInteger(),
sa.ForeignKey("schedule_runs.id", ondelete="CASCADE"),
nullable=False,
),
sa.Column(
"invoice_state_id",
sa.BigInteger(),
sa.ForeignKey("voucher_check_invoice_states.id", ondelete="SET NULL"),
nullable=True,
),
sa.Column("scope_code", sa.String(length=32), nullable=False),
sa.Column("period_month", sa.Date(), nullable=False),
sa.Column("invoice_no", sa.String(length=128), nullable=False),
sa.Column("invoice_date", sa.Date(), nullable=True),
sa.Column("result", sa.String(length=24), nullable=False),
sa.Column("folder_path", sa.String(length=1024), nullable=True),
sa.Column("folder_exists", sa.Boolean(), nullable=False, server_default=sa.text("false")),
sa.Column("material_fingerprint", sa.String(length=64), nullable=True),
sa.Column("matched_files_json", sa.JSON(), nullable=True),
sa.Column("missing_materials_json", sa.JSON(), nullable=True),
sa.Column("error_code", sa.String(length=64), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("checked_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.UniqueConstraint(
"schedule_run_id",
"invoice_no",
name="uq_voucher_check_run_items_run_invoice",
),
)
op.create_index(
"ix_voucher_check_run_items_schedule_run_id",
"voucher_check_run_items",
["schedule_run_id"],
)
op.create_index(
"ix_voucher_check_run_items_run_result",
"voucher_check_run_items",
["schedule_run_id", "result"],
)
op.create_index(
"ix_voucher_check_run_items_period_result",
"voucher_check_run_items",
["period_month", "result"],
)
@@ -0,0 +1,146 @@
"""
backend/migrations/versions/vc3d4e5f6a7b_strip_legacy_voucher_job_params.py
用途:清掉立账凭证检核排程里共享盘时代的 job_params,避免 worker 报 unknown params。
依赖:Alembic revision vc2b3c4d5e6f;schedule_tasks 已存在。
逻辑:保留 scope_code / profile_code / 通知开关 / _advanced;日批 cron 改为周二。
Revision ID: vc3d4e5f6a7b
Revises: vc2b3c4d5e6f
Create Date: 2026-09-08 10:10:00.000000
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
import sqlalchemy as sa
from alembic import op
revision = "vc3d4e5f6a7b"
down_revision = "vc2b3c4d5e6f"
branch_labels = None
depends_on = None
_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-CHECK"
_WEEKLY_CRON = "0 6 * * 2"
_WEEKLY_NAME = "立账凭证检核(周批)"
_DAILY_CRON = "0 6 * * *"
_DAILY_NAME = "立账凭证检核(日批)"
_TZ_NAME = "Asia/Shanghai"
_DEFAULTS = {
"profile_code": "sales",
"scope_code": "HXJM",
"notify_missing_enabled": True,
"notify_failure_enabled": True,
}
def _as_dict(raw) -> dict:
"""把 JSON 列读成 dict;驱动可能返回 dict 或字符串。"""
if raw is None:
return {}
if isinstance(raw, dict):
return dict(raw)
if isinstance(raw, str):
text = raw.strip()
if not text:
return {}
loaded = json.loads(text)
return dict(loaded) if isinstance(loaded, dict) else {}
return {}
def _clean_job_params(raw) -> dict:
"""只保留当前 schema 字段,丢掉 directory_template / required_files 等旧键。"""
current = _as_dict(raw)
cleaned = {}
for key, default in _DEFAULTS.items():
value = current.get(key)
cleaned[key] = default if value is None else value
advanced = current.get("_advanced")
if isinstance(advanced, dict):
cleaned["_advanced"] = advanced
return cleaned
def _next_weekly_run_utc_naive() -> datetime:
"""计算下一个周二 06:00 Asia/Shanghai,写入 naive UTC。"""
try:
from croniter import croniter
from zoneinfo import ZoneInfo
tz = ZoneInfo(_TZ_NAME)
next_local = croniter(_WEEKLY_CRON, datetime.now(tz)).get_next(datetime)
if next_local.tzinfo is None:
next_local = next_local.replace(tzinfo=tz)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
except Exception:
tz = timezone(timedelta(hours=8))
now_local = datetime.now(tz)
days = (1 - now_local.weekday()) % 7
next_local = (now_local + timedelta(days=days)).replace(
hour=6, minute=0, second=0, microsecond=0
)
if next_local <= now_local:
next_local = next_local + timedelta(days=7)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
def upgrade() -> None:
"""清洗 accounting-voucher-check 排程参数;无任务时跳过。"""
conn = op.get_bind()
rows = conn.execute(
sa.text(
"""
SELECT id, job_params, cron_expr, name
FROM schedule_tasks
WHERE schedule_no = :sno
OR platform_api_path = 'accounting-voucher-check'
"""
),
{"sno": _SCHEDULE_NO},
).mappings().all()
now = datetime.utcnow()
next_run = _next_weekly_run_utc_naive()
for row in rows:
cleaned = _clean_job_params(row["job_params"])
cron_expr = row["cron_expr"]
name = row["name"]
next_run_at = None
if cron_expr == _DAILY_CRON:
cron_expr = _WEEKLY_CRON
next_run_at = next_run
if name == _DAILY_NAME:
name = _WEEKLY_NAME
conn.execute(
sa.text(
"""
UPDATE schedule_tasks
SET job_params = CAST(:job_params AS JSONB),
cron_expr = :cron_expr,
name = :name,
next_run_at = COALESCE(:next_run_at, next_run_at),
updated_at = :now
WHERE id = :id
"""
).bindparams(
sa.bindparam("job_params", type_=sa.String()),
sa.bindparam("next_run_at", type_=sa.DateTime(), required=False),
),
{
"id": int(row["id"]),
"job_params": json.dumps(cleaned, ensure_ascii=False),
"cron_expr": cron_expr,
"name": name,
"now": now,
"next_run_at": next_run_at,
},
)
def downgrade() -> None:
"""旧共享盘字段无法无损恢复,downgrade 为空操作。"""
return