dy-dashboard/backfill_arrival_sync.py
2026-10-28 11:14:17 +08:00

70 lines
2.7 KiB
Python

#!/usr/bin/env python3
"""回溯同步:对所有有到货批次或历史批次关联的订单重新计算实际到货数量/未到货数"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from services.db import query
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s [SYNC] %(message)s')
def sync_order_arrival_totals(order_id, order_type):
"""Rebuild one order's summary fields strictly from its own batch rows."""
table_map = {
'domestic': ('domestic_orders', '实际到货日期'),
'overseas': ('overseas_orders', '实际到货日期'),
'packaging': ('packaging_orders', '到货日期'),
}
table_info = table_map[order_type]
table, date_col = table_info
rows = query("SELECT `数量` FROM " + table + " WHERE id=%s", (order_id,))
if not rows:
return False
aggregate = query("""SELECT COUNT(*) AS batch_count,
COALESCE(SUM(arrival_qty), 0) AS total,
MAX(arrival_date) AS latest_date
FROM arrival_batches
WHERE order_id=%s AND order_type=%s""", (order_id, order_type))[0]
order_qty = int(rows[0].get('数量') or 0)
if int(aggregate.get('batch_count') or 0) > 0:
total = int(aggregate.get('total') or 0)
latest_date = aggregate.get('latest_date')
else:
current_rows = query(
"SELECT `实际到货数量`, `" + date_col + "` AS current_arrival_date FROM " + table + " WHERE id=%s",
(order_id,)
)
current = current_rows[0] if current_rows else {}
total = int(current.get('实际到货数量') or 0)
latest_date = current.get('current_arrival_date')
unfinished = order_qty - total
query("UPDATE " + table + " SET `实际到货数量`=%s, `未到货数`=%s, `" + date_col + "`=%s WHERE id=%s",
(total, unfinished, latest_date, order_id))
logging.info(f'{order_type}.id={order_id}: 到货合计={total}, 未完结={unfinished}, 最近日期={latest_date}')
return True
def backfill_all():
print("=" * 60)
print("按订单类型全量同步到货批次汇总")
print("=" * 60)
table_map = {
'domestic': 'domestic_orders',
'overseas': 'overseas_orders',
'packaging': 'packaging_orders',
}
for order_type, table in table_map.items():
rows = query("SELECT id FROM " + table + " ORDER BY id")
count = 0
for row in rows:
if sync_order_arrival_totals(row['id'], order_type):
count += 1
print(f" {order_type}: 完成 {count}/{len(rows)} 个订单")
print("全量回溯同步完成!")
if __name__ == '__main__':
backfill_all()