export_reconciliation_settlement.py 11.4 KB
import logging
import os
import sys
from datetime import datetime

from openpyxl import Workbook

from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect


# ============ 可配置参数 ============
# ★ 订单号列表:在此处填写需要处理的订单号,逗号/空格/分号/换行分隔均可
#   如果想从命令行传入,命令行参数会覆盖此处的值
ORDER_CODES = '''
260707092042959,260707091612944,260706213825276,260706205152727,260706205114469,260706203038224,260706200327201,260706200310607,260706200305482,260706200201862,260706195941705,260706195930834,260706195701655,260706195436425,260706195417532,260706191557503,260706190627941,260706190144810,260706184531434,260706184520843,260706184315133,260706184146757,260706183825411,260706182942425,260706182650531,260706182606724,260706182605450,260706182314372,260706182248409,260706181953365,260706181441183,260706181041173,260706180403829,260706180243974,260706180239931,260706180225564,260706175555440,260706175523126,260706175339258,260706175214438,260706174804237,260706174609131,260706174235416,260706173915976,260706173812789,260706173603116,260706173235910,260706172948286,260706172815217,260706172815882,260706172640536,260706172520690,260706172342197,260706172037597,260706171931304,260706171846122,260706171605128,260706170850810,260706170742873,260706170657643,260706170307294,260706170030528,260706165845797,260706165845660,260706165653760,260706165610722,260706165513172,260706165447183,260706165418881,260706165206800,260706165107726,260706163657767,260706163458800,260706163336476,260706163106995,260706162821464,260706162624293,260706162558457,260706161718129,260706161305271,260706160956341
'''

# 默认输出文件名(如果命令行没有指定 -o)
DEFAULT_OUTPUT_FILE = 'reconciliation_settlement_result.xlsx'

# 日志配置
LOG_NAME = './log/djcardrenewal/handlemain.log'
LOG_FORMAT = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
LOG_LEVEL = logging.DEBUG
LOG_MODE = 'a'
logging.basicConfig(filename=LOG_NAME, format=LOG_FORMAT, level=LOG_LEVEL, filemode=LOG_MODE)
# ==================================


class ReconciliationSettlementExport:
    """导出订单的对账id和分账id到Excel"""

    def __init__(self):
        self.db = MysqlHelper(DbConect.dj_release_slave)

    def close(self):
        if self.db:
            self.db.close_con()

    @staticmethod
    def _escape_sql(value):
        """SQL 值转义,防止注入"""
        return str(value).replace("'", "''")

    def _query_order_info(self, order_code):
        """
        查询1: 根据 order_code 获取 merchant_id, base_scene_code, out_trade_no
        """
        safe_code = self._escape_sql(order_code)
        sql = f"""
SELECT
  go.order_code,
  go.merchant_id,
  go.base_scene_code,
  po.out_trade_no
FROM
  dj_car_life_goods_order go
  LEFT JOIN dj_car_life_pay_order po ON po.order_code = go.order_code
  AND po.deleted_flag = 'N'
WHERE
  go.order_code = '{safe_code}'
"""
        result = self.db.execute_select(sql)
        if result and len(result) > 0:
            row = result[0]
            return {
                'order_code': row[0],
                'merchant_id': row[1],
                'base_scene_code': row[2],
                'out_trade_no': row[3],
            }
        return None

    def _query_rule_effect_id(self, merchant_id, base_scene_code, rule_type):
        """
        查询对账/分账 effect record id
        rule_type=1 → 对账id
        rule_type=3 → 分账id
        """
        safe_merchant = self._escape_sql(merchant_id)
        safe_scene = self._escape_sql(base_scene_code)
        sql = f"""
SELECT
  er.id
FROM
  dj_car_life_division_rule_effect_record er
WHERE
  er.deleted_flag = 'N'
  AND er.merchant_id = '{safe_merchant}'
  AND er.base_scene_code = '{safe_scene}'
  AND er.rule_type = {rule_type}
ORDER BY
  effect_start_date DESC
LIMIT 1
"""
        result = self.db.execute_select(sql)
        if result and len(result) > 0:
            return result[0][0]
        return None

    def export(self, order_codes, output_path):
        """
        批量查询并导出到 Excel

        Args:
            order_codes: 订单号列表
            output_path: 输出 Excel 文件路径
        """
        wb = Workbook()
        ws = wb.active
        ws.title = "对账分账结果"

        # 写表头
        headers = ["inputtedOrderCode", "outTradeNo", "settleDistributeEffectRuleId", "reconciliationRuleEffectRuleId"]
        ws.append(headers)

        # 设置表头加粗
        from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
        header_font = Font(bold=True)
        header_fill = PatternFill(start_color="D9E1F2", end_color="D9E1F2", fill_type="solid")
        for col_idx, header in enumerate(headers, 1):
            cell = ws.cell(row=1, column=col_idx)
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = Alignment(horizontal='center')

        total = len(order_codes)
        success_count = 0
        fail_count = 0

        for idx, order_code in enumerate(order_codes, start=1):
            order_code = order_code.strip()
            if not order_code:
                continue

            print(f"[{idx}/{total}] 处理订单: {order_code}")
            logging.info(f"processing order: {order_code}")

            # 查询1: 订单基本信息
            order_info = self._query_order_info(order_code)
            if not order_info:
                logging.warning(f"order not found: {order_code}")
                print(f"  ⚠ 订单未找到: {order_code}")
                ws.append([order_code, "", "订单未找到", "订单未找到"])
                fail_count += 1
                continue

            # 查询2: 财务分账id (rule_type=1)
            reconciliation_id = self._query_rule_effect_id(
                order_info['merchant_id'],
                order_info['base_scene_code'],
                rule_type=1
            )

            # 查询3: 对账id (rule_type=3)
            settlement_id = self._query_rule_effect_id(
                order_info['merchant_id'],
                order_info['base_scene_code'],
                rule_type=3
            )

            ws.append([
                order_info['order_code'],
                order_info['out_trade_no'] or "",
                reconciliation_id or "",
                settlement_id or "",
            ])

            success_count += 1
            print(f"  merchant_id={order_info['merchant_id']}, "
                  f"base_scene_code={order_info['base_scene_code']}, "
                  f"out_trade_no={order_info['out_trade_no']}, "
                  f"对账id={reconciliation_id}, "
                  f"分账id={settlement_id}")

        # 自动调整列宽
        for col_idx, header in enumerate(headers, 1):
            max_width = len(header) + 4  # 中文字符占宽更大,给一些余量
            for row_idx in range(2, ws.max_row + 1):
                cell_value = str(ws.cell(row=row_idx, column=col_idx).value or "")
                # 粗略估算:中文字符算2宽度,其他算1
                width = sum(2 if '一' <= c <= '鿿' else 1 for c in cell_value)
                max_width = max(max_width, width + 2)
            ws.column_dimensions[ws.cell(row=1, column=col_idx).column_letter].width = min(max_width, 50)

        # 添加汇总行
        summary_row = ws.max_row + 2
        ws.cell(row=summary_row, column=1, value="汇总").font = Font(bold=True)
        ws.cell(row=summary_row, column=2, value=f"总订单数: {total}")
        ws.cell(row=summary_row, column=3, value=f"成功: {success_count}")
        ws.cell(row=summary_row, column=4, value=f"失败: {fail_count}")

        # 保存文件
        wb.save(output_path)
        print(f"\n✅ Excel 导出完成: {output_path}")
        print(f"   总订单数: {total}, 成功: {success_count}, 失败: {fail_count}")
        logging.info(f"export finished: {output_path}, total={total}, success={success_count}, fail={fail_count}")


def _parse_order_codes(raw_input):
    """
    解析订单号输入,支持多种格式:
      - 逗号分隔: 'order1,order2,order3'
      - 空格/换行分隔: 'order1 order2 order3'
      - 分号分隔: 'order1;order2;order3'
      - 单个订单号
      - 文件路径: '@file.txt' 从文件读取,每行一个订单号
    """
    if not raw_input:
        return []

    raw_input = raw_input.strip()

    # 如果是 @文件路径,从文件读取
    if raw_input.startswith('@'):
        file_path = raw_input[1:]
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"订单号文件不存在: {file_path}")
        with open(file_path, 'r', encoding='utf-8') as f:
            codes = []
            for line in f:
                stripped = line.strip()
                if stripped:
                    codes.append(stripped)
            return codes

    # 尝试多种分隔符
    import re
    codes = re.split(r'[,;\s\n\r]+', raw_input)
    return [c for c in codes if c]


def _print_usage():
    print("""
用法:
  python export_reconciliation_settlement.py <订单号> [订单号...] [-o <输出文件>]

参数:
  订单号          一个或多个订单号,逗号/空格/分号分隔均可
                 也可以用 @文件路径 从文件读取(每行一个订单号)
  -o <输出文件>   指定输出 Excel 文件路径(默认: reconciliation_settlement_result.xlsx)

示例:
  python export_reconciliation_settlement.py 260629141714309
  python export_reconciliation_settlement.py 260629141714309,260629141714310
  python export_reconciliation_settlement.py 260629141714309 260629141714310 -o result.xlsx
  python export_reconciliation_settlement.py @orders.txt -o result.xlsx
""")


if __name__ == "__main__":
    # 解析命令行参数
    output_file = DEFAULT_OUTPUT_FILE
    order_args = []

    i = 1
    while i < len(sys.argv):
        arg = sys.argv[i]
        if arg in ('--help', '-h'):
            _print_usage()
            raise SystemExit(0)
        elif arg in ('-o', '--output'):
            if i + 1 < len(sys.argv):
                output_file = sys.argv[i + 1]
                i += 2
            else:
                print("错误: -o 需要指定输出文件路径")
                raise SystemExit(1)
        else:
            order_args.append(arg)
            i += 1

    # 如果命令行没有传订单号,则使用文件顶部的 ORDER_CODES 配置变量
    if not order_args:
        if ORDER_CODES.strip():
            order_args = [ORDER_CODES]
        else:
            print("错误: 请指定至少一个订单号(命令行传入,或在 ORDER_CODES 变量中填写)")
            _print_usage()
            raise SystemExit(1)

    # 批量解析订单号(支持逗号分隔的字符串)
    all_order_codes = []
    for arg in order_args:
        all_order_codes.extend(_parse_order_codes(arg))

    if not all_order_codes:
        print("错误: 没有解析到有效的订单号")
        raise SystemExit(1)

    # 去重并保持顺序
    seen = set()
    unique_orders = []
    for code in all_order_codes:
        if code not in seen:
            seen.add(code)
            unique_orders.append(code)

    print(f"共 {len(unique_orders)} 个订单号待处理")
    print(f"输出文件: {output_file}")
    print("-" * 50)

    exporter = ReconciliationSettlementExport()
    try:
        exporter.export(unique_orders, output_file)
    finally:
        exporter.close()