verify_excel_logic.py 6.8 KB
"""独立验证(直接读表版):镜像 processor._generate_and_upload_excel 当前逻辑——
全部列(含 毛利/F公司毛利/本月毛利率/上月毛利率)直接从 biz_budget_achieve 读取,不做任何重算。
确认 41 列 + 值与表中存储一致。
"""
import os, pymysql
from decimal import Decimal
import openpyxl
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill

conn = pymysql.connect(host='192.168.3.227', user='os_user', password='os#123',
                       database='data_report', charset='utf8mb4')
cur = conn.cursor(pymysql.cursors.DictCursor)

MONTH = '2026-06'
cur.execute("SELECT task_id FROM biz_budget_achieve WHERE stat_month=%s LIMIT 1", (MONTH,))
TASK_ID = cur.fetchone()['task_id']
cur.execute("SELECT COUNT(*) c FROM biz_budget_achieve WHERE task_id=%s AND stat_month=%s", (TASK_ID, MONTH))
n = cur.fetchone()['c']
print("task_id=", TASK_ID, "rows=", n)

# 与 _generate_and_upload_excel 中 ORDERED 完全一致(attr 全部指向表中已存字段)
COLS = ['is_multi_category','traffic_name','business_type','entity','brand','park_store','service_provider',
        'order_count','gmv','revenue','cost_gmv','cost_gmv_ratio_current','cost_gmv_ratio_previous',
        'traffic_fee_gmv','traffic_fee_gmv_ratio_current','traffic_fee_gmv_ratio_previous','service_fee',
        'service_fee_ratio_current','service_fee_ratio_previous','cost_revenue','traffic_fee_revenue',
        'dijia_profit_sharing','market_fee','market_fee_ratio_current','market_fee_ratio_previous',
        'personnel_salary','external_construction','technician_salary','technician_salary_ratio',
        'marketing_team_salary','marketing_team_salary_ratio','personnel_salary_ratio_current',
        'personnel_salary_ratio_previous','rent_utilities','renovation_amortization','store_consumables',
        'f_company_gross_profit','gross_profit','gross_profit_ratio_current','gross_profit_ratio_previous']

ORDERED = [("字段名称:",None),("是否为多品类","is_multi_category"),("流量方名称","traffic_name"),
 ("业务类型","business_type"),("主体","entity"),("品牌","brand"),("园区店","park_store"),("服务商","service_provider"),
 ("订单数","order_count"),("GMV","gmv"),("收入","revenue"),("成本\n(GMV口径)","cost_gmv"),("本月占比","cost_gmv_ratio_current"),
 ("上月占比","cost_gmv_ratio_previous"),("流量费\n(GMV口径)","traffic_fee_gmv"),("本月占比","traffic_fee_gmv_ratio_current"),
 ("上月占比","traffic_fee_gmv_ratio_previous"),("服务费","service_fee"),("本月占比","service_fee_ratio_current"),
 ("上月占比","service_fee_ratio_previous"),("成本\n(收入口径)","cost_revenue"),("流量费\n(收入口径)","traffic_fee_revenue"),
 ("嘀加分润","dijia_profit_sharing"),("市场费","market_fee"),("本月占比","market_fee_ratio_current"),("上月占比","market_fee_ratio_previous"),
 ("人员工资","personnel_salary"),("外援施工","external_construction"),("技师工资","technician_salary"),("技师工资占比","technician_salary_ratio"),
 ("营销团队工资","marketing_team_salary"),("营销团队工资占比","marketing_team_salary_ratio"),("本月占比","personnel_salary_ratio_current"),
 ("上月占比","personnel_salary_ratio_previous"),("房租及\n水电费","rent_utilities"),("装修摊销","renovation_amortization"),
 ("门店耗材","store_consumables"),("F公司毛利","f_company_gross_profit"),("毛利","gross_profit"),
 ("本月毛利率","gross_profit_ratio_current"),("上月毛利率","gross_profit_ratio_previous")]

HEADERS = [h for h,_ in ORDERED]
print("COLUMN COUNT =", len(HEADERS), "(应为41)")
assert len(HEADERS) == 41, "列数不为41!"

q = "SELECT " + ",".join(COLS) + " FROM biz_budget_achieve WHERE task_id=%s AND stat_month=%s"
cur.execute(q, (TASK_ID, MONTH))
rows = cur.fetchall()

AMOUNT_COLS = {'GMV','收入','成本(GMV口径)','流量费(GMV口径)','服务费','成本(收入口径)','流量费(收入口径)',
               '嘀加分润','市场费','人员工资','外援施工','技师工资','营销团队工资','房租及水电费','装修摊销','门店耗材',
               'F公司毛利','毛利'}
RATIO_COLS = {'本月占比','上月占比','技师工资占比','营销团队工资占比','本月毛利率','上月毛利率'}
INT_COLS = {'订单数'}

wb = openpyxl.Workbook(); ws = wb.active; ws.title="预算达成数据"
# 行1 表头
for c,h in enumerate(HEADERS,1):
    ws.cell(row=1,column=c,value=h).font = Font(bold=True)
# 数据行(从第3行开始,第2行为说明行,这里仅校验数据故直接写第2行起)
for i,r in enumerate(rows):
    ridx = i + 2
    for c,(h,attr) in enumerate(ORDERED,1):
        if h == "字段名称:":
            v = ""
        else:
            v = r[attr]   # 直接读表,不重算
        cell = ws.cell(row=ridx, column=c)
        if v is None:
            cell.value = ""
        elif h in AMOUNT_COLS:
            try: cell.value = float(v)
            except: cell.value = 0.0
            cell.number_format = "#,##0.00"
        elif h in RATIO_COLS:
            try: cell.value = float(v)
            except: cell.value = 0.0
            cell.number_format = "0.00"
        elif h in INT_COLS:
            try: cell.value = int(v)
            except: cell.value = 0
            cell.number_format = "#,##0"
        else:
            cell.value = "" if v is None else str(v)

# 抽样:对比"直接读表"与"重算"是否一致(仅用于人工核对,不影响导出口径)
def sf(v):
    if v is None: return 0.0
    try: return float(v)
    except: return 0.0
def compute_gp(d):
    sp=d.get('service_provider') or ''; is_d=('嘀加自营' in sp)
    sfee=sf(d.get('service_fee')); psal=sf(d.get('personnel_salary'))
    fc=(sfee-psal) if is_d else 0.0
    gp=sf(d.get('dijia_profit_sharing'))-sf(d.get('market_fee'))-sf(d.get('rent_utilities'))-sf(d.get('renovation_amortization'))-sf(d.get('store_consumables'))
    if is_d: gp+=fc
    return fc,gp

print("\n=== 抽样:表存值 vs 重算值(一致说明表内已算好;不一致则说明源数据本身待核实)===")
shown=0
for r in rows:
    sp=r['service_provider'] or ''
    if shown<4 and '嘀加' in sp:
        fc,gp=compute_gp(r); gmv=sf(r['gmv']); gr=gp/gmv*100 if gmv else 0
        print(f"[嘀加] {r['traffic_name']}/{r['business_type']} 服务商={sp}")
        print(f"   表存: F公司毛利={sf(r['f_company_gross_profit']):.2f} 毛利={sf(r['gross_profit']):.2f} 本月毛利率={sf(r['gross_profit_ratio_current']):.2f} 上月毛利率={sf(r['gross_profit_ratio_previous']):.2f}")
        print(f"   重算: F公司毛利={fc:.2f} 毛利={gp:.2f} 本月毛利率={gr:.2f}")
        shown+=1
    if shown>=4: break

out = os.path.join(os.path.dirname(__file__), f"verify_excel_direct_{MONTH}.xlsx")
wb.save(out)
print("\nVERIFY_OK,校验文件已生成:", out)
conn.close()