daily_report.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.12.10
  4. # Date : 2026/08/05
  5. """得卡 DECA · 已售每日统计报告(Excel 多 Sheet,每一大项一个 sheet)。
  6. 统计范围:成交完成时间 completed_at 落在 [昨天 17:00:00, 今天 06:00:00](含两端)的已售商品。
  7. 一个拼团商品 = 一个「组队」(组队售卖),故「每条明细」= 每个拼团商品。
  8. 报告结构(2026/08/14 由单 Sheet 分区改为多 Sheet,每 sheet 独立列宽、蓝条只覆盖本表宽度):
  9. Sheet 平台总览 :平台汇总 + 当日组齐环比(vs 昨日同窗口) + 商家 GMV 集中度(Top1/3/5/10) + 口径脚注
  10. Sheet 产品系列榜:当日各系列 GMV 榜(Top,含占比)
  11. Sheet 商家GMV榜 :当日组齐 GMV 前 N 商家(含占比)
  12. Sheet 运营节奏 :重点商家当日运营快照(新开团/已组齐/规格) + 平台组齐时段分布(近7日24h)
  13. Sheet 魔都明细 :881226408 汇总 + 每条明细(含「参与人数(购买记录)」与售卖进度里程碑列;
  14. 汇总下附「购买记录覆盖检测」= 成交团 vs 已采购买记录,标注漏采多少 T(团))
  15. Sheet 用户排行榜(魔都):881226408 买家榜(deca_buy_record 按 user_id 聚合,参与金额倒序,
  16. 含 参与车数 / 参与金额 / 车均消费)(2026/08/17 新增)
  17. Sheet 卡皇明细 :274584650 汇总 + 每条明细
  18. Sheet 其他商家 :其余商家各一行汇总(中卡近似口径)
  19. 注:原「魔都已售进度检测」独立 sheet 已于 2026/08/11 并入魔都明细(尾部到 25/50/75% 用时列)。
  20. 口径说明:
  21. - 销售额 = SUM(COALESCE(team_total_amount, sold_count * unit_price))
  22. 随机团(选队随机/剩余随机)按 teams 逐队精算(team_total_amount,2026/08/11 起,
  23. 见 docs/选队随机与剩余随机_总价口径与采集_20260811.md);固定价团回落原公式。
  24. - 成团数 = 该时段成交的拼团商品数
  25. - 参与人数(魔都汇总 & 明细口径) = deca_buy_record 去重买家 user_id(真实参团人头;仅 881226408
  26. 采了购买记录)。魔都汇总「参与人数(真实买家)」= 跨其全部成交团去重(2026/08/14 起由
  27. 中卡近似切为真实买家);明细「参与人数(本团)」= 各团单独去重,故明细逐团相加(人次) ≥ 汇总。
  28. - 中卡用户数(近似)(平台大盘/其他商家口径) = 拆卡报告 hit_user_nickname 去重(仅覆盖 report_state=1
  29. 有报告的商品;这些商家未采购买记录,只能用中卡用户近似,非真实参团人头,偏低)
  30. - 均拼单价 = 销售额 / 成团数
  31. - 人均消费 = 销售额 / 参与人数(魔都为真实买家;平台/其他商家为按中卡近似,偏高,仅供参考)
  32. - 卡密表 deca_kami_record 当前为空(FILL_KAMI 关),故无「球队」维度,明细按商品维度出。
  33. 从项目根目录运行:python stats/daily_report.py(cwd=根目录,读根目录 application.yml)
  34. """
  35. import os
  36. import sys
  37. import time
  38. # 把项目根目录加入 import 路径:企微发送模块 auto_send_wx_msg.py 只在根目录留一份(WEBHOOK_URL 单点维护)
  39. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  40. from datetime import date, datetime
  41. import schedule
  42. from loguru import logger
  43. from openpyxl import Workbook
  44. from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
  45. from mysql_pool import MySQLConnectionPool
  46. # 日志:按天切分文件,保留 7 天(常驻定时运行)
  47. logger.remove()
  48. logger.add("./logs/daily_report_{time:YYYYMMDD}.log", encoding="utf-8", rotation="00:00",
  49. format="[{time:YYYY-MM-DD HH:mm:ss.SSS}] {level} {message}", level="INFO", retention="7 day")
  50. # 企微发送:报告生成后把 Excel 发到企业微信群机器人(只发表格,不发图;群由 auto_send_wx_msg.WEBHOOK_URL 决定)
  51. SEND_WECHAT = True
  52. # 两个要出「汇总 + 明细」的重点商家;其余商家统一进「其他商家汇总」
  53. FOCUS_MERCHANTS = ["881226408", "274584650"]
  54. # 魔都兄弟球星卡:其每条明细走扩展版——多「参与人数」列(deca_buy_record 去重买家),
  55. # 尾部并入售卖进度里程碑(从 progress 表算到 25/50/75% 各用了多久;首张快照已越过阈值则留空)。仅本商家如此。
  56. MODDU_MID = "881226408"
  57. OUT_PREFIX = "得卡已售每日报告" # 输出文件名前缀,实际文件名后缀加运行当天日期
  58. # 时间窗过滤(p 别名):[昨天17:00, 今天06:00](2026/08/15 由 03:00 延到 06:00,凌晨仍在播)
  59. WIN_P = ("p.completed_at >= (CURDATE() - INTERVAL 1 DAY) + INTERVAL 17 HOUR "
  60. "AND p.completed_at <= CURDATE() + INTERVAL 6 HOUR")
  61. # 明细表列规格:(表头, 明细dict取值键, 是否千分位金额格式);取值键为「序号」时按行号自增填充。
  62. # 开售时间/成交时间/售卖时长 三列相邻:售卖时长=成交-开售。
  63. DETAIL_COLS = [
  64. ("序号", "序号", False), ("团名(商品标题)", "团名", False),
  65. ("系列", "系列", False), ("类型", "类型", False), ("单价", "单价", True),
  66. ("总份数", "总份数", False), ("进度%", "进度", False), ("总金额", "总金额", True),
  67. ("中卡人数", "中卡人数", False), # 该团拆卡报告 hit_user_nickname 去重(中卡近似),放开售时间前
  68. ("开售时间", "开售时间", False), ("成交时间", "成交时间", False), ("售卖时长", "售卖时长", False),
  69. ]
  70. # 魔都(881226408)专属明细:在「中卡人数」前插「参与人数」(deca_buy_record 去重买家 user_id),
  71. # 并在尾部并入售卖进度里程碑(到 25/50/75% 用时,源 deca_onsale_product_progress_record)。
  72. # 原「魔都已售进度检测」独立 sheet 于 2026/08/11 并入本明细,不再单独出 sheet。
  73. MODDU_DETAIL_COLS = [
  74. ("序号", "序号", False), ("团名(商品标题)", "团名", False),
  75. ("系列", "系列", False), ("类型", "类型", False), ("单价", "单价", True),
  76. ("总份数", "总份数", False), ("进度%", "进度", False), ("总金额", "总金额", True),
  77. ("参与人数(本团)", "参与人数", False),
  78. ("中卡人数", "中卡人数", False), # 该团拆卡报告 hit_user_nickname 去重(中卡近似),放开售时间前
  79. ("开售时间", "开售时间", False), ("成交时间", "成交时间", False), ("售卖时长", "售卖时长", False),
  80. ("到25%用时", "到25%用时", False), ("到50%用时", "到50%用时", False),
  81. ("到75%用时", "到75%用时", False),
  82. ]
  83. # 分区标题/大标题横向着色跨列数:取最宽的魔都明细,保证蓝条覆盖整表宽
  84. SECTION_SPAN = len(MODDU_DETAIL_COLS)
  85. # 汇总表指标键(商家/平台,dict 取值键,与显示标签解耦)
  86. SUMMARY_HEADERS = ["销售额", "成团数", "参与人数", "均拼单价", "人均消费"]
  87. # 平台大盘竖排汇总行:(显示标签, dict取值键)。参与人数为「魔都真实买家 + 其他商家中卡去重」
  88. # 的混合口径(2026/08/14 起,见 fetch_platform_summary),故标签显式标注,避免误当纯真实人头。
  89. PLATFORM_ROWS = [
  90. ("商家数", "商家数"), ("销售额", "销售额"), ("成团数", "成团数"),
  91. ("参与人数(魔都真实+其他中卡)", "参与人数"), ("均拼单价", "均拼单价"),
  92. ("人均消费", "人均消费"),
  93. ]
  94. # 其他商家汇总表列:(显示表头, dict取值键, 是否金额格式)。这些商家未采购买记录,参与人数
  95. # 只能用中卡用户近似,故表头标注「(近似)」,与魔都真实买家口径区分。
  96. OTHER_COLS = [
  97. ("商家名", "商家名", False), ("销售额", "销售额", True), ("成团数", "成团数", False),
  98. ("中卡用户数(近似)", "参与人数", False), ("均拼单价", "均拼单价", True),
  99. ("人均消费(按中卡近似)", "人均消费", True),
  100. ]
  101. # ---- 监测清单增强(2026/08/14):环比 / 排行 / 集中度 / 时段分布 配置 ----
  102. # 昨日同窗口(用于组齐环比):[前天17:00, 昨天06:00],与 WIN_P 整体平移一天、口径一致
  103. WIN_P_YDAY = ("p.completed_at >= (CURDATE() - INTERVAL 2 DAY) + INTERVAL 17 HOUR "
  104. "AND p.completed_at <= (CURDATE() - INTERVAL 1 DAY) + INTERVAL 6 HOUR")
  105. TOP_SERIES = 15 # 产品系列销售榜展示条数
  106. TOP_MERCHANT = 10 # 商家 GMV 榜展示条数(监测清单要「GMV前十商家」)
  107. TOP_USERS = None # 魔都用户排行榜展示条数(按参与金额倒序取前 N;仅魔都采了购买记录)
  108. CONC_TOPS = (1, 3, 5, 10) # GMV 集中度统计的 TopN 档(Top1/3/5/10 占平台总 GMV)
  109. HOUR_DIST_DAYS = 7 # 组齐时段分布回看天数(反映平台 24h 组齐节奏)
  110. # ---- 样式 ----
  111. FONT_TITLE = Font(name="Microsoft YaHei", bold=True, size=14, color="1F2A44")
  112. FONT_SECTION = Font(name="Microsoft YaHei", bold=True, size=12, color="FFFFFF")
  113. FONT_HEADER = Font(name="Microsoft YaHei", bold=True, color="1F3864") # 表头:深蓝字
  114. FONT_CELL = Font(name="Microsoft YaHei", size=10) # 正文
  115. FILL_SECTION = PatternFill("solid", fgColor="4472C4") # 分区标题:蓝底白字
  116. FILL_HEADER = PatternFill("solid", fgColor="D9E1F2") # 表头:浅蓝底
  117. FILL_SUBTOTAL = PatternFill("solid", fgColor="FCE4D6") # 汇总行:浅橙底
  118. FILL_ZEBRA = PatternFill("solid", fgColor="F5F8FC") # 明细隔行:淡蓝灰
  119. THIN = Side(style="thin", color="D6DCE5")
  120. BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
  121. MONEY_FMT = "#,##0.00"
  122. INT_FMT = "#,##0" # 计数列千分位
  123. ALIGN_LEFT = Alignment(horizontal="left", vertical="center") # 文字:左对齐
  124. ALIGN_RIGHT = Alignment(horizontal="right", vertical="center") # 数字/金额:右对齐
  125. ALIGN_CENTER = Alignment(horizontal="center", vertical="center", wrap_text=True) # 表头:居中换行
  126. FONT_UP = Font(name="Microsoft YaHei", bold=True, color="1E7D32") # 环比涨:绿
  127. FONT_DOWN = Font(name="Microsoft YaHei", bold=True, color="C62828") # 环比跌:红
  128. def _align_by_value(value) -> Alignment:
  129. """按单元格值类型选对齐方式:数字(含金额/占比)右对齐,其余(文字/时长/日期)左对齐。
  130. Args:
  131. value: 单元格值(int/float/str/None 等)。
  132. Returns:
  133. Alignment: 数字返回右对齐,其它返回左对齐(bool 视为非数字)。
  134. """
  135. if isinstance(value, bool):
  136. return ALIGN_LEFT
  137. return ALIGN_RIGHT if isinstance(value, (int, float)) else ALIGN_LEFT
  138. def _trend_font(text: str) -> Font:
  139. """按环比文本的正负号返回涨跌配色字体(涨绿、跌红、其它常规)。
  140. Args:
  141. text (str): 环比字符串(如 "+12.3%"/"-8.0%"/"新增"/"—")。
  142. Returns:
  143. Font: 以 "+" 开头或"新增"→绿;"-" 开头→红;否则常规正文字体。
  144. """
  145. if not text:
  146. return FONT_CELL
  147. if text.startswith("+") or text == "新增":
  148. return FONT_UP
  149. if text.startswith("-"):
  150. return FONT_DOWN
  151. return FONT_CELL
  152. def get_window(pool) -> tuple[str, str]:
  153. """取当前时间窗的起止边界(用于报告标题展示)。
  154. Args:
  155. pool (MySQLConnectionPool): MySQL 连接池。
  156. Returns:
  157. tuple[str, str]: (起点datetime字符串, 终点datetime字符串)。
  158. """
  159. row = pool.select_all(
  160. "SELECT (CURDATE() - INTERVAL 1 DAY) + INTERVAL 17 HOUR, "
  161. "CURDATE() + INTERVAL 6 HOUR")[0]
  162. return str(row[0]), str(row[1])
  163. def fetch_platform_summary(pool) -> dict:
  164. """统计平台大盘汇总(时间窗内全部已售商品)。
  165. 参与人数为混合口径(2026/08/14 起):魔都(881226408)采了真实购买记录,用 deca_buy_record
  166. 去重真实买家;其余商家未采购买记录,仍用拆卡报告 hit_user_nickname 去重的中卡用户近似。
  167. 两部分人群标识不同(魔都=user_id,其他=昵称)、无法跨口径去重,故直接相加,属近似上界。
  168. Args:
  169. pool (MySQLConnectionPool): MySQL 连接池。
  170. Returns:
  171. dict: 含 销售额/商家数/成团数/参与人数/均拼单价/人均消费 六项。
  172. """
  173. sql = f"""
  174. SELECT
  175. ROUND(SUM(COALESCE(p.team_total_amount, p.sold_count * p.unit_price)), 2) AS amount,
  176. COUNT(DISTINCT p.merchant_user_id) AS merchants,
  177. COUNT(*) AS grp,
  178. -- 其他商家(非魔都)中卡用户去重;魔都单独用真实买家,不计入此子查询
  179. (SELECT COUNT(DISTINCT r.hit_user_nickname)
  180. FROM deca_report_record r
  181. JOIN deca_product_record pp ON pp.product_code = r.product_code
  182. WHERE pp.merchant_user_id <> %s
  183. AND pp.completed_at >= (CURDATE() - INTERVAL 1 DAY) + INTERVAL 17 HOUR
  184. AND pp.completed_at <= CURDATE() + INTERVAL 6 HOUR
  185. AND r.hit_user_nickname IS NOT NULL AND r.hit_user_nickname <> '') AS others_people
  186. FROM deca_product_record p
  187. WHERE {WIN_P} AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  188. """
  189. amount, merchants, groups, others_people = pool.select_all(sql, (MODDU_MID,))[0]
  190. # 平台参与人数 = 魔都真实买家(deca_buy_record 去重) + 其他商家中卡用户去重
  191. people = _fetch_real_buyers(pool, MODDU_MID) + (others_people or 0)
  192. return _pack_summary(amount, groups, people, extra={"商家数": merchants})
  193. def fetch_merchant_summary(pool, mid: str) -> dict:
  194. """统计单个商家的汇总(时间窗内)。
  195. Args:
  196. pool (MySQLConnectionPool): MySQL 连接池。
  197. mid (str): 商家 merchant_user_id。
  198. Returns:
  199. dict: 含 商家名/销售额/成团数/参与人数/均拼单价/人均消费。
  200. """
  201. sql = f"""
  202. SELECT
  203. MAX(p.merchant_name) AS mname,
  204. ROUND(SUM(COALESCE(p.team_total_amount, p.sold_count * p.unit_price)), 2) AS amount,
  205. COUNT(*) AS grp,
  206. (SELECT COUNT(DISTINCT r.hit_user_nickname)
  207. FROM deca_report_record r
  208. JOIN deca_product_record pp ON pp.product_code = r.product_code
  209. WHERE pp.merchant_user_id = %s
  210. AND pp.completed_at >= (CURDATE() - INTERVAL 1 DAY) + INTERVAL 17 HOUR
  211. AND pp.completed_at <= CURDATE() + INTERVAL 6 HOUR
  212. AND r.hit_user_nickname IS NOT NULL AND r.hit_user_nickname <> '') AS people
  213. FROM deca_product_record p
  214. WHERE p.merchant_user_id = %s AND {WIN_P}
  215. AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  216. """
  217. row = pool.select_all(sql, (mid, mid))
  218. mname, amount, groups, people = row[0] if row else (None, None, 0, 0)
  219. # 魔都(881226408)采了真实购买记录:参与人数改用 deca_buy_record 去重真实买家,人均消费随之
  220. # 按真实人头计(覆盖上面 people 的中卡近似值);其余重点商家无购买记录,仍沿用中卡近似。
  221. if mid == MODDU_MID:
  222. people = _fetch_real_buyers(pool, mid)
  223. d = _pack_summary(amount, groups, people)
  224. d["商家名"] = mname or mid
  225. d["商家ID"] = mid
  226. return d
  227. def fetch_merchant_details(pool, mid: str) -> list[dict]:
  228. """取单个商家时间窗内每个拼团(组队)的明细,按总金额倒序。
  229. Args:
  230. pool (MySQLConnectionPool): MySQL 连接池。
  231. mid (str): 商家 merchant_user_id。
  232. Returns:
  233. list[dict]: 每元素为一条明细(团名/系列/类型/单价/份数/总份数/进度/总金额/中卡人数/开售时间/成交时间/售卖时长/回放)。
  234. """
  235. sql = f"""
  236. SELECT
  237. p.title, p.series_name, p.spec_name, p.unit_price, p.sold_count, p.card_count,
  238. ROUND(COALESCE(p.team_total_amount, p.sold_count * p.unit_price), 2) AS amount,
  239. p.completed_at, p.sale_start_at,
  240. TIMESTAMPDIFF(SECOND, p.sale_start_at, p.completed_at) AS duration_secs,
  241. -- 中卡人数:该团拆卡报告去重命中用户(hit_user_nickname),中卡近似口径
  242. (SELECT COUNT(DISTINCT r.hit_user_nickname) FROM deca_report_record r
  243. WHERE r.product_code = p.product_code
  244. AND r.hit_user_nickname IS NOT NULL AND r.hit_user_nickname <> '') AS hit_users,
  245. p.replay_url
  246. FROM deca_product_record p
  247. WHERE p.merchant_user_id = %s AND {WIN_P}
  248. AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  249. ORDER BY amount DESC
  250. """
  251. rows = pool.select_all(sql, (mid,)) or []
  252. result = []
  253. for (title, series, spec, price, sold, card, amount,
  254. completed, sale_start, duration_secs, hit_users, replay) in rows:
  255. progress = round(sold / card * 100, 1) if card else None # 售卖进度百分比
  256. result.append({
  257. "团名": title, "系列": series, "类型": spec, "单价": price,
  258. "份数": sold, "总份数": card, "进度": progress, "总金额": amount,
  259. "中卡人数": hit_users, # 该团拆卡报告去重命中用户(中卡近似)
  260. "开售时间": sale_start, "成交时间": completed, # 开售=sale_start_at,成交=completed_at
  261. "售卖时长": _fmt_duration(duration_secs), # 差值=成交-开售,反映多快卖完
  262. "回放": replay,
  263. })
  264. return result
  265. def fetch_other_merchants(pool, exclude: list) -> list[dict]:
  266. """统计除重点商家外的其他商家汇总(时间窗内),每商家一行,按销售额倒序。
  267. Args:
  268. pool (MySQLConnectionPool): MySQL 连接池。
  269. exclude (list[str]): 要排除的重点商家 ID 列表。
  270. Returns:
  271. list[dict]: 每元素为一个商家的汇总(商家名/销售额/成团数/参与人数/均拼单价/人均消费)。
  272. """
  273. placeholders = ",".join(["%s"] * len(exclude))
  274. sql = f"""
  275. SELECT
  276. p.merchant_user_id AS mid,
  277. MAX(p.merchant_name) AS mname,
  278. ROUND(SUM(COALESCE(p.team_total_amount, p.sold_count * p.unit_price)), 2) AS amount,
  279. COUNT(*) AS grp,
  280. (SELECT COUNT(DISTINCT r.hit_user_nickname)
  281. FROM deca_report_record r
  282. JOIN deca_product_record pp ON pp.product_code = r.product_code
  283. WHERE pp.merchant_user_id = p.merchant_user_id
  284. AND pp.completed_at >= (CURDATE() - INTERVAL 1 DAY) + INTERVAL 17 HOUR
  285. AND pp.completed_at <= CURDATE() + INTERVAL 6 HOUR
  286. AND r.hit_user_nickname IS NOT NULL AND r.hit_user_nickname <> '') AS people
  287. FROM deca_product_record p
  288. WHERE {WIN_P} AND p.merchant_user_id NOT IN ({placeholders})
  289. AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  290. GROUP BY p.merchant_user_id
  291. ORDER BY amount DESC
  292. """
  293. rows = pool.select_all(sql, tuple(exclude)) or []
  294. result = []
  295. for mid, mname, amount, groups, people in rows:
  296. d = _pack_summary(amount, groups, people)
  297. d["商家名"] = mname or mid
  298. result.append(d)
  299. return result
  300. def _pack_summary(amount, groups, people, extra: dict = None) -> dict:
  301. """把销售额/成团数/参与人数打包成统一汇总 dict,并算均拼单价、人均消费。
  302. Args:
  303. amount (Decimal | None): 销售额。
  304. groups (int | None): 成团数。
  305. people (int | None): 参与人数。
  306. extra (dict, optional): 额外要合并的字段(如商家数)。Defaults to None。
  307. Returns:
  308. dict: 含 销售额/成团数/参与人数/均拼单价/人均消费(+extra)。
  309. """
  310. amount = float(amount) if amount is not None else 0.0
  311. groups = groups or 0
  312. people = people or 0
  313. avg_group = round(amount / groups, 2) if groups else None # 均拼单价=销售额/成团数
  314. avg_person = round(amount / people, 2) if people else None # 人均消费=销售额/参与人数
  315. d = {"销售额": round(amount, 2), "成团数": groups, "参与人数": people,
  316. "均拼单价": avg_group, "人均消费": avg_person}
  317. if extra:
  318. d.update(extra)
  319. return d
  320. def _fetch_real_buyers(pool, mid: str) -> int:
  321. """查某商家时间窗内 deca_buy_record 去重真实买家数(跨其全部成交团)。
  322. 仅魔都(881226408)采了真实购买记录,故只有它能用此口径;其余商家该表无数据、返回 0。
  323. Args:
  324. pool (MySQLConnectionPool): MySQL 连接池。
  325. mid (str): 商家 merchant_user_id。
  326. Returns:
  327. int: 去重真实买家数;无数据时返回 0。
  328. """
  329. sql = """
  330. SELECT COUNT(DISTINCT b.user_id)
  331. FROM deca_buy_record b
  332. JOIN deca_product_record pp ON pp.product_code = b.product_code
  333. WHERE pp.merchant_user_id = %s
  334. AND pp.completed_at >= (CURDATE() - INTERVAL 1 DAY) + INTERVAL 17 HOUR
  335. AND pp.completed_at <= CURDATE() + INTERVAL 6 HOUR
  336. """
  337. row = pool.select_all(sql, (mid,))
  338. return int(row[0][0]) if row and row[0][0] is not None else 0
  339. def _summary_rows(is_real: bool) -> list[tuple]:
  340. """按参与人数口径生成重点商家竖排汇总的(显示标签, 取值键)行规格。
  341. Args:
  342. is_real (bool): True=该商家参与人数为 deca_buy_record 真实买家(魔都),标签用
  343. 「参与人数(真实买家)」;False=中卡用户近似,标签用「中卡用户数(近似)」,人均消费
  344. 标签相应标注「(按中卡近似)」。
  345. Returns:
  346. list[tuple[str, str]]: 每项 (显示标签, data 取值键)。
  347. """
  348. people = ("参与人数(真实买家)" if is_real else "中卡用户数(近似)", "参与人数")
  349. person_avg = ("人均消费" if is_real else "人均消费(按中卡近似)", "人均消费")
  350. return [("销售额", "销售额"), ("成团数", "成团数"), people,
  351. ("均拼单价", "均拼单价"), person_avg]
  352. def fetch_moddu_details(pool, mid: str) -> list[dict]:
  353. """取「魔都」商家(mid)时间窗内每个拼团(组队)的扩展明细,按总金额倒序。
  354. 在标准明细基础上多两类字段(原「魔都已售进度检测」独立 sheet 于 2026/08/11 并入此处):
  355. - 参与人数:deca_buy_record 去重买家 user_id(真实参团人头;仅本商家采了购买记录)。
  356. - 到 25/50/75% 用时:用 deca_onsale_product_progress_record(分钟级进度序列)里
  357. `MIN(captured_at) WHERE progress_pct >= X` 减开售时间 sale_start_at 得到。
  358. 仅当该商品在 tX 之前还有更早快照(证明从低于 X% 就开始观测)时才算真实穿越耗时;
  359. 若首张快照 pct 已 ≥ X(坍缩)则该列留空,不输出「首次被监控时刻−开售」的假值。
  360. 原「到100%用时」已于 2026/08/12 删除:满仓即下架、轮询抓不到 100% 快照,且与售卖时长重复。
  361. 进度里程碑仅"progress 表上线(2026/08/11)后覆盖到售卖过程"的团才有值;更早售卖或首张
  362. 快照已越过阈值的团查不到/不可信,相应列留空——商品行本身仍显示(总金额/成交时间等基础字段)。
  363. Args:
  364. pool (MySQLConnectionPool): MySQL 连接池。
  365. mid (str): 商家 merchant_user_id。
  366. Returns:
  367. list[dict]: 每条含 团名/系列/类型/单价/总份数/进度/总金额/参与人数(购买记录)/中卡人数/
  368. 开售时间/成交时间/售卖时长/到25%用时/到50%用时/到75%用时。
  369. """
  370. sql = f"""
  371. SELECT
  372. p.title, p.series_name, p.spec_name, p.unit_price, p.sold_count, p.card_count,
  373. ROUND(COALESCE(p.team_total_amount, p.sold_count * p.unit_price), 2) AS amount,
  374. p.sale_start_at, p.completed_at,
  375. TIMESTAMPDIFF(SECOND, p.sale_start_at, p.completed_at) AS duration_secs,
  376. (SELECT COUNT(DISTINCT b.user_id) FROM deca_buy_record b
  377. WHERE b.product_code = p.product_code) AS buyers,
  378. -- 中卡人数:该团拆卡报告去重命中用户(hit_user_nickname),中卡近似口径
  379. (SELECT COUNT(DISTINCT r.hit_user_nickname) FROM deca_report_record r
  380. WHERE r.product_code = p.product_code
  381. AND r.hit_user_nickname IS NOT NULL AND r.hit_user_nickname <> '') AS hit_users,
  382. -- 该商品最早一条进度快照时刻:用于判定里程碑是否「坍缩」(首张快照已越过阈值则该用时不可信)
  383. (SELECT MIN(pr.captured_at) FROM deca_onsale_product_progress_record pr
  384. WHERE pr.product_code = p.product_code) AS first_cap,
  385. (SELECT MIN(pr.captured_at) FROM deca_onsale_product_progress_record pr
  386. WHERE pr.product_code = p.product_code AND pr.progress_pct >= 25) AS t25,
  387. (SELECT MIN(pr.captured_at) FROM deca_onsale_product_progress_record pr
  388. WHERE pr.product_code = p.product_code AND pr.progress_pct >= 50) AS t50,
  389. (SELECT MIN(pr.captured_at) FROM deca_onsale_product_progress_record pr
  390. WHERE pr.product_code = p.product_code AND pr.progress_pct >= 75) AS t75
  391. FROM deca_product_record p
  392. WHERE p.merchant_user_id = %s AND {WIN_P}
  393. AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  394. ORDER BY amount DESC
  395. """
  396. rows = pool.select_all(sql, (mid,)) or []
  397. result = []
  398. for (title, series, spec, price, sold, card, amount, start, completed,
  399. duration_secs, buyers, hit_users, first_cap, t25, t50, t75) in rows:
  400. progress = round(sold / card * 100, 1) if card else None # 售卖进度百分比
  401. result.append({
  402. "团名": title, "系列": series, "类型": spec, "单价": price,
  403. "总份数": card, "进度": progress, "总金额": amount,
  404. "参与人数": buyers,
  405. "中卡人数": hit_users, # 该团拆卡报告去重命中用户(中卡近似)
  406. "开售时间": start, "成交时间": completed, # 开售=sale_start_at,成交=completed_at
  407. "售卖时长": _fmt_duration(duration_secs), # 成交-开售,也即整团总时长
  408. # 到 X% 用时:仅当该商品在 tX 之前还有更早快照(未坍缩)时才输出真实穿越耗时,否则留空
  409. "到25%用时": _milestone_used(t25, first_cap, start),
  410. "到50%用时": _milestone_used(t50, first_cap, start),
  411. "到75%用时": _milestone_used(t75, first_cap, start),
  412. })
  413. return result
  414. def fetch_moddu_user_ranking(pool, mid: str, top_n: int) -> tuple[list[dict], int]:
  415. """取「魔都」商家时间窗内的用户参与排行(按参与金额倒序,取前 top_n)。
  416. 「一个拼团商品 = 一辆车(组队)」,以 deca_buy_record 购买记录按买家 user_id 聚合:
  417. - 参与车数 = COUNT(DISTINCT product_code),该买家窗口内参与的不同团数。
  418. - 参与金额 = SUM(card_count × 该团 unit_price)。deca_buy_record 无金额字段,故用
  419. 「购买份数 × 团单价」估算;固定价团精确,随机团(选队随机/剩余随机)每队价不同,
  420. 此处按标称单价近似。同一买家在同一团的多条购买记录已由 SUM 累加。
  421. - 车均消费 = 参与金额 ÷ 参与车数。
  422. 仅魔都(881226408)采了购买记录,故只有它能出此榜。
  423. Args:
  424. pool (MySQLConnectionPool): MySQL 连接池。
  425. mid (str): 商家 merchant_user_id。
  426. top_n (int): 榜单展示上限(取金额倒序前 N)。
  427. Returns:
  428. tuple[list[dict], int]: (rows, total_users);rows 每项含 用户昵称/user_id/参与车数/
  429. 参与金额/车均消费(已按金额倒序并截断到 top_n);total_users 为窗口内全部参与
  430. 买家数(供榜单标题展示、判断截断了多少)。
  431. """
  432. sql = f"""
  433. SELECT b.user_id,
  434. MAX(b.nickname) AS nickname,
  435. COUNT(DISTINCT b.product_code) AS cars,
  436. ROUND(SUM(b.card_count * p.unit_price), 2) AS amount
  437. FROM deca_buy_record b
  438. JOIN deca_product_record p ON p.product_code = b.product_code
  439. WHERE p.merchant_user_id = %s AND {WIN_P}
  440. AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  441. GROUP BY b.user_id
  442. ORDER BY amount DESC
  443. """
  444. rows = pool.select_all(sql, (mid,)) or []
  445. result = []
  446. for uid, nickname, cars, amount in rows[:top_n]:
  447. amt = float(amount) if amount is not None else 0.0
  448. cars = int(cars or 0)
  449. result.append({
  450. "用户昵称": nickname or "(匿名)",
  451. "user_id": uid,
  452. "参与车数": cars,
  453. "参与金额": round(amt, 2),
  454. "车均消费": round(amt / cars, 2) if cars else None, # 车均=参与金额/参与车数
  455. })
  456. return result, len(rows)
  457. def fetch_moddu_missing_teams(pool, mid: str) -> dict:
  458. """对比「魔都」成交明细与购买记录覆盖,算出漏采购买记录的 T(团)。
  459. 魔都明细每条 = 一个成交拼团商品(T),来自 deca_product_record;购买记录 deca_buy_record
  460. 是另路采集的。个别团在采到购买记录前就满仓成交下架,会「漏采」——本函数以时间窗内成交
  461. 团为基准,找出 deca_buy_record 里没有对应 product_code 的团,供魔都明细标注覆盖缺口。
  462. Args:
  463. pool (MySQLConnectionPool): MySQL 连接池。
  464. mid (str): 商家 merchant_user_id。
  465. Returns:
  466. dict: 含 成交团数/有记录团数/漏采团数/漏采团列表(list[(product_code, title)])。
  467. """
  468. total = pool.select_all(f"""
  469. SELECT COUNT(*) FROM deca_product_record p
  470. WHERE p.merchant_user_id = %s AND {WIN_P}
  471. AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  472. """, (mid,))[0][0] or 0
  473. miss = pool.select_all(f"""
  474. SELECT p.product_code, p.title
  475. FROM deca_product_record p
  476. WHERE p.merchant_user_id = %s AND {WIN_P}
  477. AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  478. AND NOT EXISTS(SELECT 1 FROM deca_buy_record b WHERE b.product_code = p.product_code)
  479. ORDER BY p.completed_at
  480. """, (mid,)) or []
  481. return {"成交团数": total, "有记录团数": total - len(miss),
  482. "漏采团数": len(miss), "漏采团列表": [(pc, t) for pc, t in miss]}
  483. def _fmt_duration(secs) -> str | None:
  484. """把售卖时长(秒)格式化为可读中文字符串。
  485. 差值口径 = 成交完成时间 completed_at − 开售时间 sale_start_at,反映该团多快卖完/售罄。
  486. Args:
  487. secs (int | None): 成交与开售之差(秒);None 或负数(时间缺失/异常)视为无效。
  488. Returns:
  489. str | None: 形如 "2小时13分" / "45分07秒" / "38秒";无效时返回 None(单元格留空)。
  490. """
  491. if secs is None or secs < 0:
  492. return None
  493. secs = int(secs)
  494. h, rem = divmod(secs, 3600)
  495. m, s = divmod(rem, 60)
  496. if h:
  497. return f"{h}小时{m}分"
  498. if m:
  499. return f"{m}分{s:02d}秒"
  500. return f"{s}秒"
  501. def _diff_secs(later, earlier) -> int | None:
  502. """算两个时间点相隔的秒数,兼容 varchar 与 datetime 两种输入。
  503. Args:
  504. later (str | datetime | None): 较晚的时间点(如到达某进度的时刻)。
  505. earlier (str | datetime | None): 较早的时间点(如开售时间)。
  506. Returns:
  507. int | None: 相隔秒数;任一为空或解析失败时返回 None。
  508. """
  509. if not later or not earlier:
  510. return None
  511. try:
  512. if isinstance(earlier, str):
  513. earlier = datetime.strptime(earlier, "%Y-%m-%d %H:%M:%S")
  514. if isinstance(later, str):
  515. later = datetime.strptime(later, "%Y-%m-%d %H:%M:%S")
  516. return int((later - earlier).total_seconds())
  517. except Exception:
  518. return None
  519. def _milestone_used(tx, first_cap, start) -> str | None:
  520. """算「到某进度用时」,首张快照已越过该阈值(坍缩)时诚实留空。
  521. 到 X% 用时 = 首次 progress_pct ≥ X 的快照时刻 tx − 开售时间 start。但只有当该商品在
  522. tx 之前还存在更早的快照(即 tx 晚于该商品最早快照 first_cap)时,才证明我们是从低于 X%
  523. 的进度观测到它穿越 X% 的,tx 才是真实穿越点;若首张快照 pct 就已 ≥ X(tx == first_cap),
  524. tx 只是「首次被监控的时刻」,据此算出的是假耗时,一律留空,绝不输出坍缩值。
  525. Args:
  526. tx (datetime | str | None): 首次 progress_pct ≥ 阈值的快照时刻;None 表示从未达到该进度。
  527. first_cap (datetime | str | None): 该商品最早一条快照的时刻。
  528. start (datetime | str | None): 开售时间 sale_start_at。
  529. Returns:
  530. str | None: 可读用时字符串;未达到/坍缩/时间缺失时返回 None(单元格留空)。
  531. """
  532. if tx is None or first_cap is None:
  533. return None
  534. # tx 与首张快照同刻 → 第一次看到它就已越过该阈值,无法确定真实穿越时刻,坍缩留空
  535. if not _diff_secs(tx, first_cap): # None(解析失败) 或 0(同刻) 都视为不可信
  536. return None
  537. return _fmt_duration(_diff_secs(tx, start))
  538. def _style_row(ws, row_idx: int, ncol: int, font=None, fill=None, border=True):
  539. """给某一行的前 ncol 个单元格套字体/填充/边框。
  540. Args:
  541. ws: openpyxl worksheet。
  542. row_idx (int): 行号(1-based)。
  543. ncol (int): 要处理的列数(从第 1 列起)。
  544. font (Font, optional): 字体。Defaults to None。
  545. fill (PatternFill, optional): 填充。Defaults to None。
  546. border (bool, optional): 是否加边框。Defaults to True。
  547. """
  548. for c in range(1, ncol + 1):
  549. cell = ws.cell(row=row_idx, column=c)
  550. if font:
  551. cell.font = font
  552. if fill:
  553. cell.fill = fill
  554. if border:
  555. cell.border = BORDER
  556. def _write_summary_block(ws, r: int, rows: list, data: dict, start_col: int = 1) -> int:
  557. """在第 r 行起竖排写汇总(每指标一行:标签列 + 数值列),返回下一空闲行。
  558. 竖排避免与明细表共用列宽导致的错位与金额列过窄(######)。显示标签与 data 取值键解耦,
  559. 以便同一指标在不同口径下用不同标签(如「参与人数(真实买家)」vs「中卡用户数(近似)」)。
  560. start_col 可让整块右移(明细 sheet 里落到宽的 B/C 列,避开 A=序号 的窄列)。
  561. Args:
  562. ws: openpyxl worksheet。
  563. r (int): 起始行号。
  564. rows (list[tuple[str, str]]): 每项 (显示标签, data 取值键)。
  565. data (dict): 汇总数据 dict。
  566. start_col (int, optional): 标签列的列号(1-based),数值列为其右一列。Defaults to 1。
  567. Returns:
  568. int: 下一个空闲行号。
  569. """
  570. for label, key in rows:
  571. lc = ws.cell(row=r, column=start_col, value=label) # 标签(加粗深蓝、浅蓝底、左对齐)
  572. lc.font = FONT_HEADER
  573. lc.fill = FILL_HEADER
  574. lc.alignment = ALIGN_LEFT
  575. lc.border = BORDER
  576. value = data.get(key)
  577. val = ws.cell(row=r, column=start_col + 1, value=value) # 数值(浅橙底、右对齐)
  578. if key in ("销售额", "均拼单价", "人均消费"): # 金额格式按稳定的取值键判定
  579. val.number_format = MONEY_FMT
  580. elif isinstance(value, int) and not isinstance(value, bool):
  581. val.number_format = INT_FMT # 计数千分位(成团数/参与人数/商家数)
  582. val.font = FONT_CELL
  583. val.fill = FILL_SUBTOTAL
  584. val.alignment = _align_by_value(value) # 数字右对齐、文字左对齐
  585. val.border = BORDER
  586. r += 1
  587. return r
  588. def _write_section_title(ws, r: int, text: str, span: int = SECTION_SPAN) -> int:
  589. """在第 r 行写一行分区标题条(蓝底白字),蓝条只覆盖 span 列(贴合本表宽度、右侧不留空)。
  590. Args:
  591. ws: openpyxl worksheet。
  592. r (int): 起始行号。
  593. text (str): 标题文字。
  594. span (int, optional): 蓝条覆盖列数。Defaults to SECTION_SPAN。
  595. Returns:
  596. int: 下一个空闲行号。
  597. """
  598. ws.cell(row=r, column=1, value=text)
  599. _style_row(ws, r, span, font=FONT_SECTION, fill=FILL_SECTION, border=False)
  600. return r + 1
  601. def _write_details(ws, r: int, details: list, cols: list) -> int:
  602. """在第 r 行起写一个商家的明细表(表头 + 每条组队明细)。
  603. Args:
  604. ws: openpyxl worksheet。
  605. r (int): 起始行号。
  606. details (list[dict]): 明细数据,每元素为一条组队明细 dict(fetch_merchant_details
  607. 或 fetch_moddu_details 的返回)。
  608. cols (list[tuple]): 列规格列表,每项 (表头, 取值键, 是否金额格式);取值键为「序号」
  609. 时按行号自增填充(DETAIL_COLS 或 MODDU_DETAIL_COLS)。
  610. Returns:
  611. int: 下一个空闲行号。
  612. """
  613. for i, (header, _key, _money) in enumerate(cols):
  614. hc = ws.cell(row=r, column=1 + i, value=header)
  615. hc.alignment = ALIGN_CENTER # 表头居中换行
  616. _style_row(ws, r, len(cols), font=FONT_HEADER, fill=FILL_HEADER)
  617. r += 1
  618. if not details:
  619. ws.cell(row=r, column=1, value="(该时段无成交)").font = FONT_CELL
  620. return r + 1
  621. for idx, d in enumerate(details, 1):
  622. zebra = FILL_ZEBRA if idx % 2 == 0 else None # 偶数行淡蓝灰,便于横向读长行
  623. for i, (_header, key, is_money) in enumerate(cols):
  624. value = idx if key == "序号" else d.get(key) # 「序号」列用行号,其余按键取值
  625. cell = ws.cell(row=r, column=1 + i, value=value)
  626. if is_money:
  627. cell.number_format = MONEY_FMT
  628. elif isinstance(value, int) and not isinstance(value, bool):
  629. cell.number_format = INT_FMT # 计数千分位(序号/份数/总份数/参与人数)
  630. cell.font = FONT_CELL
  631. cell.alignment = _align_by_value(value) # 数字右、文字左(时长/日期/团名等)
  632. cell.border = BORDER
  633. if zebra:
  634. cell.fill = zebra
  635. r += 1
  636. return r
  637. def _window_metrics(pool, win: str) -> dict:
  638. """统计某成交时间窗内的组齐核心指标(GMV / 成团数 / 活跃商家数 / T均单价)。
  639. Args:
  640. pool (MySQLConnectionPool): MySQL 连接池。
  641. win (str): 完整的 completed_at 时间窗 WHERE 片段(如 WIN_P / WIN_P_YDAY)。
  642. Returns:
  643. dict: 含 组齐GMV/成团数/活跃商家数/T均单价(成团数为 0 时 T均单价为 None)。
  644. """
  645. sql = f"""
  646. SELECT ROUND(SUM(COALESCE(p.team_total_amount, p.sold_count * p.unit_price)), 2) AS gmv,
  647. COUNT(*) AS grp,
  648. COUNT(DISTINCT p.merchant_user_id) AS merchants
  649. FROM deca_product_record p
  650. WHERE {win} AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  651. """
  652. gmv, groups, merchants = pool.select_all(sql)[0]
  653. gmv = float(gmv) if gmv is not None else 0.0
  654. groups = groups or 0
  655. return {"组齐GMV": round(gmv, 2), "成团数": groups, "活跃商家数": merchants or 0,
  656. "T均单价": round(gmv / groups, 2) if groups else None} # T均单价=组齐GMV/成团数
  657. def fetch_groupbuy_compare(pool) -> dict:
  658. """取当日窗口与昨日同窗口的组齐指标,供「当日组齐环比」区展示。
  659. Args:
  660. pool (MySQLConnectionPool): MySQL 连接池。
  661. Returns:
  662. dict: {"today": {...}, "yday": {...}},各含 组齐GMV/成团数/活跃商家数/T均单价。
  663. """
  664. return {"today": _window_metrics(pool, WIN_P), "yday": _window_metrics(pool, WIN_P_YDAY)}
  665. def fetch_series_ranking(pool, top_n: int) -> tuple[list, float]:
  666. """取当日窗口内各产品系列的销售榜(按 GMV 倒序)及全窗口总 GMV(算占比用)。
  667. Args:
  668. pool (MySQLConnectionPool): MySQL 连接池。
  669. top_n (int): 取前 N 个系列。
  670. Returns:
  671. tuple[list, float]: (rows, total_gmv);rows 每项 (系列名, 成团数, GMV)。
  672. """
  673. sql = f"""
  674. SELECT COALESCE(NULLIF(p.series_name, ''), '(未标系列)') AS series,
  675. COUNT(*) AS grp,
  676. ROUND(SUM(COALESCE(p.team_total_amount, p.sold_count * p.unit_price)), 2) AS gmv
  677. FROM deca_product_record p
  678. WHERE {WIN_P} AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  679. GROUP BY series
  680. ORDER BY gmv DESC
  681. """
  682. rows = pool.select_all(sql) or []
  683. total = sum(float(r[2]) for r in rows if r[2] is not None) # 全部系列合计(算占比分母)
  684. return rows[:top_n], total
  685. def fetch_merchant_gmv_ranking(pool) -> tuple[list, float, dict]:
  686. """取当日窗口内全部商家的组齐 GMV 榜(倒序)及 Top1/3/5/10 集中度占比。
  687. 集中度 = 前 K 名商家 GMV 之和 ÷ 平台组齐总 GMV,反映头部商家对大盘的贡献集中程度。
  688. Args:
  689. pool (MySQLConnectionPool): MySQL 连接池。
  690. Returns:
  691. tuple[list, float, dict]: (rows, total_gmv, concentration);rows 每项
  692. (商家名, 成团数, GMV)(全量、倒序);concentration 形如 {1: 0.32, 3: 0.55, ...}。
  693. """
  694. sql = f"""
  695. SELECT MAX(p.merchant_name) AS mname,
  696. COUNT(*) AS grp,
  697. ROUND(SUM(COALESCE(p.team_total_amount, p.sold_count * p.unit_price)), 2) AS gmv
  698. FROM deca_product_record p
  699. WHERE {WIN_P} AND p.unit_price IS NOT NULL AND p.sold_count IS NOT NULL
  700. GROUP BY p.merchant_user_id
  701. ORDER BY gmv DESC
  702. """
  703. rows = pool.select_all(sql) or []
  704. gmvs = [float(r[2]) if r[2] is not None else 0.0 for r in rows]
  705. total = sum(gmvs)
  706. conc = {k: (sum(gmvs[:k]) / total if total else None) for k in CONC_TOPS}
  707. return rows, total, conc
  708. def fetch_focus_ops_snapshot(pool, mid: str) -> dict:
  709. """取重点商家「当日新开团 / 已组齐 / 规格分布」运营快照(口径:publish_at 落在报告时间窗 [昨17:00, 今06:00])。
  710. 「已组齐」= 当日新开团里 product_code 已出现在成交表(deca_product_record 有 completed_at)的数量;
  711. 「规格分布」按在售表 spec_name 聚合,形如 原箱×2 · 单盒×20。对应监测清单「魔都、卡皇当天销售细节」。
  712. Args:
  713. pool (MySQLConnectionPool): MySQL 连接池。
  714. mid (str): 商家 merchant_user_id。
  715. Returns:
  716. dict: 含 商家名/新开团数/已组齐数/规格分布(list[(规格, 数量)])。
  717. """
  718. # 口径对齐报告成交时间窗(2026/08/17):新开团/已组齐/规格均按 publish_at 落在[昨17:00,今06:00]统计。
  719. # 原为自然日 DATE(publish_at)=CURDATE(),会漏掉前一晚上新的团(如卡皇昨晚 22:42 上新→自然日今天为 0)。
  720. base = ("FROM deca_onsale_product_record o "
  721. "WHERE o.merchant_user_id = %s "
  722. "AND o.publish_at >= (CURDATE() - INTERVAL 1 DAY) + INTERVAL 17 HOUR "
  723. "AND o.publish_at <= CURDATE() + INTERVAL 6 HOUR")
  724. # 商家名单独取(不加「当日」条件):某商家当天没上新团时仍能显示名称,避免回退成纯 ID(2026/08/17)
  725. mname_row = pool.select_one(
  726. "SELECT MAX(merchant_name) FROM deca_onsale_product_record WHERE merchant_user_id = %s", (mid,))
  727. mname = mname_row[0] if mname_row else None
  728. total_new = pool.select_one(f"SELECT COUNT(*) {base}", (mid,))[0] or 0
  729. done = pool.select_one(
  730. f"SELECT COUNT(*) {base} "
  731. f"AND EXISTS(SELECT 1 FROM deca_product_record c "
  732. f"WHERE c.product_code = o.product_code AND c.completed_at IS NOT NULL)", (mid,))[0] or 0
  733. spec_rows = pool.select_all(
  734. f"SELECT COALESCE(NULLIF(o.spec_name, ''), '其它') sp, COUNT(*) c {base} "
  735. f"GROUP BY sp ORDER BY c DESC", (mid,)) or []
  736. return {"商家名": mname or mid, "新开团数": total_new, "已组齐数": done,
  737. "规格分布": [(r[0], int(r[1])) for r in spec_rows]}
  738. def fetch_completion_hour_dist(pool, days: int) -> list[int]:
  739. """统计近 N 天全部成交(组齐)按小时的 24 桶分布,反映平台 24h 组齐节奏。
  740. Args:
  741. pool (MySQLConnectionPool): MySQL 连接池。
  742. days (int): 回看天数(含今天)。
  743. Returns:
  744. list[int]: 长度 24 的列表,索引 = 小时(0~23),值 = 该小时成交团数。
  745. """
  746. sql = """
  747. SELECT HOUR(p.completed_at) AS h, COUNT(*) AS c
  748. FROM deca_product_record p
  749. WHERE p.completed_at >= CURDATE() - INTERVAL %s DAY AND p.completed_at IS NOT NULL
  750. GROUP BY h
  751. """
  752. dist = [0] * 24
  753. for h, c in pool.select_all(sql, (days,)) or []:
  754. if h is not None and 0 <= int(h) < 24:
  755. dist[int(h)] = int(c)
  756. return dist
  757. def _bar(value: int, max_value: int, width: int = 20) -> str:
  758. """把数值渲染成等宽条形字符串(Excel 内迷你直方图)。
  759. Args:
  760. value (int): 当前值。
  761. max_value (int): 该组最大值(归一化条长用)。
  762. width (int, optional): 满值时的条长(字符数)。Defaults to 20。
  763. Returns:
  764. str: 由 █ 组成的条;max_value<=0 或 value<=0 时返回空串。
  765. """
  766. if max_value <= 0 or value <= 0:
  767. return ""
  768. return "█" * max(1, round(value / max_value * width))
  769. def _fmt_pct_change(cur, prev) -> str:
  770. """把本期/上期数值算成带符号的环比字符串。
  771. Args:
  772. cur (float | int | None): 本期值。
  773. prev (float | int | None): 上期值。
  774. Returns:
  775. str: 形如 "+12.3%" / "-8.0%";上期为 0 时本期>0 返回 "新增"、否则 "—"。
  776. """
  777. c = float(cur) if cur is not None else 0.0
  778. p = float(prev) if prev is not None else 0.0
  779. if p == 0:
  780. return "新增" if c > 0 else "—"
  781. return f"{(c - p) / p * 100:+.1f}%"
  782. def _write_hgrid(ws, r: int, headers: list, rows: list, money_cols=(), pct_cols=(),
  783. start_col: int = 1, empty_hint: str = "(无数据)") -> int:
  784. """在第 r 行起写一张普通横向表(表头 + 数据行),套统一样式,返回下一空闲行。
  785. 可用 start_col 让表整体右移,把长文本列落在预设的宽列上(本 sheet B 列宽 50)。
  786. Args:
  787. ws: openpyxl worksheet。
  788. r (int): 起始行号。
  789. headers (list[str]): 列表头。
  790. rows (list[list]): 数据行,每行长度应 ≤ len(headers)。
  791. money_cols (tuple[int], optional): 需金额格式的列下标(0-based)。Defaults to ()。
  792. pct_cols (tuple[int], optional): 需百分比格式的列下标(0-based,存小数如 0.32)。Defaults to ()。
  793. start_col (int, optional): 起始列号(1-based)。Defaults to 1。
  794. empty_hint (str, optional): rows 为空时的占位文字。Defaults to "(无数据)"。
  795. Returns:
  796. int: 下一个空闲行号。
  797. """
  798. for i, h in enumerate(headers):
  799. cell = ws.cell(row=r, column=start_col + i, value=h)
  800. cell.font = FONT_HEADER
  801. cell.fill = FILL_HEADER
  802. cell.alignment = ALIGN_CENTER # 表头居中
  803. cell.border = BORDER
  804. r += 1
  805. if not rows:
  806. c = ws.cell(row=r, column=start_col, value=empty_hint)
  807. c.font = FONT_CELL
  808. c.border = BORDER
  809. return r + 1
  810. n = len(headers)
  811. for ri, row in enumerate(rows):
  812. zebra = FILL_ZEBRA if ri % 2 == 1 else None # 隔行淡蓝灰
  813. for i in range(n):
  814. v = row[i] if i < len(row) else None
  815. cell = ws.cell(row=r, column=start_col + i, value=v)
  816. if i in money_cols:
  817. cell.number_format = MONEY_FMT
  818. elif i in pct_cols:
  819. cell.number_format = "0.0%"
  820. elif isinstance(v, int) and not isinstance(v, bool):
  821. cell.number_format = INT_FMT # 计数千分位(成团数等)
  822. cell.font = FONT_CELL
  823. # 金额/占比/数字右对齐;条形图列(█ 文本)与名称等文字左对齐
  824. cell.alignment = ALIGN_RIGHT if (i in money_cols or i in pct_cols) else _align_by_value(v)
  825. cell.border = BORDER
  826. if zebra:
  827. cell.fill = zebra
  828. r += 1
  829. return r
  830. def _set_widths(ws, widths: list):
  831. """按列表顺序设置 A、B、C… 列宽(仅前 26 列,够覆盖本报告各 sheet)。
  832. Args:
  833. ws: openpyxl worksheet。
  834. widths (list[float]): 各列宽度,索引 0→A、1→B…。
  835. """
  836. for i, w in enumerate(widths):
  837. ws.column_dimensions[chr(65 + i)].width = w
  838. def _build_overview_sheet(ws, win: tuple, platform: dict, compare: dict,
  839. mrank_conc: dict, notes: list):
  840. """构建「平台总览」sheet:平台汇总 + 当日组齐环比 + 商家 GMV 集中度 + 口径脚注。
  841. Args:
  842. ws: openpyxl worksheet。
  843. win (tuple[str, str]): (成交窗起, 成交窗止)。
  844. platform (dict): 平台汇总数据。
  845. compare (dict): 组齐环比数据(today/yday)。
  846. mrank_conc (dict): Top1/3/5/10 集中度占比。
  847. notes (list[str]): 口径脚注文本。
  848. """
  849. _set_widths(ws, [32, 18, 18, 12])
  850. r = 1
  851. ws.cell(row=r, column=1, value="得卡 DECA · 已售每日统计报告")
  852. _style_row(ws, r, 4, font=FONT_TITLE, border=False)
  853. r += 1
  854. ws.cell(row=r, column=1, value=f"成交时间窗 {win[0]} ~ {win[1]}")
  855. _style_row(ws, r, 4, font=FONT_CELL, border=False)
  856. r += 2
  857. # 平台汇总(竖排 标签/数值)
  858. r = _write_section_title(ws, r, "平台汇总", span=4)
  859. r = _write_summary_block(ws, r, PLATFORM_ROWS, platform, start_col=1)
  860. r += 1
  861. # 当日组齐环比(金额行今日/昨日单独套金额格式;环比列涨绿跌红)
  862. r = _write_section_title(ws, r, "当日组齐环比(vs 昨日同窗口)", span=4)
  863. for i, h in enumerate(["指标", "今日", "昨日", "环比"]):
  864. c = ws.cell(row=r, column=1 + i, value=h)
  865. c.font = FONT_HEADER; c.fill = FILL_HEADER
  866. c.alignment = ALIGN_CENTER; c.border = BORDER
  867. r += 1
  868. t_now, t_yday = compare["today"], compare["yday"]
  869. for ri, (key, is_money) in enumerate((("组齐GMV", True), ("成团数", False),
  870. ("活跃商家数", False), ("T均单价", True))):
  871. zebra = FILL_ZEBRA if ri % 2 == 1 else None
  872. lc = ws.cell(row=r, column=1, value=key) # 指标名:左对齐
  873. lc.font = FONT_CELL; lc.alignment = ALIGN_LEFT
  874. cur = ws.cell(row=r, column=2, value=t_now.get(key))
  875. prev = ws.cell(row=r, column=3, value=t_yday.get(key))
  876. for cell in (cur, prev): # 今日/昨日:金额或计数、右对齐
  877. cell.number_format = MONEY_FMT if is_money else INT_FMT
  878. cell.font = FONT_CELL; cell.alignment = ALIGN_RIGHT
  879. chg = _fmt_pct_change(t_now.get(key), t_yday.get(key))
  880. cc = ws.cell(row=r, column=4, value=chg) # 环比:右对齐 + 涨绿跌红
  881. cc.font = _trend_font(chg); cc.alignment = ALIGN_RIGHT
  882. for col in range(1, 5):
  883. cell = ws.cell(row=r, column=col)
  884. cell.border = BORDER
  885. if zebra:
  886. cell.fill = zebra
  887. r += 1
  888. r += 1
  889. # 商家 GMV 集中度(详细榜单在「商家GMV榜」sheet)
  890. r = _write_section_title(ws, r, "商家 GMV 集中度(TopN 占平台组齐总 GMV)", span=4)
  891. conc_rows = [[f"Top{k} 集中度", mrank_conc.get(k)] for k in CONC_TOPS]
  892. r = _write_hgrid(ws, r, ["集中度档位", "占平台GMV"], conc_rows, pct_cols=(1,), start_col=1)
  893. r += 2
  894. # 口径脚注(长文本,向右溢出到空列显示)
  895. for note in notes:
  896. ws.cell(row=r, column=1, value=note).font = FONT_CELL
  897. r += 1
  898. def _build_series_sheet(ws, series_rows: list, series_total: float):
  899. """构建「产品系列榜」sheet:当日各系列 GMV 榜 + 占比。
  900. Args:
  901. ws: openpyxl worksheet。
  902. series_rows (list): [(系列名, 成团数, GMV)]。
  903. series_total (float): 全窗口总 GMV(算占比分母)。
  904. """
  905. _set_widths(ws, [36, 10, 16, 10])
  906. r = _write_section_title(ws, 1, f"产品系列销售榜(当日 Top{TOP_SERIES},按 GMV)", span=4)
  907. srows = [[name, int(g), float(gmv) if gmv is not None else 0,
  908. (float(gmv) / series_total if (series_total and gmv is not None) else None)]
  909. for name, g, gmv in series_rows]
  910. _write_hgrid(ws, r, ["系列", "成团数", "GMV", "占比"], srows,
  911. money_cols=(2,), pct_cols=(3,), start_col=1)
  912. ws.freeze_panes = "A3" # 冻结标题条 + 表头
  913. def _build_mrank_sheet(ws, mrank_rows: list, mrank_total: float):
  914. """构建「商家GMV榜」sheet:当日组齐 GMV 前 N 商家 + 占比。
  915. Args:
  916. ws: openpyxl worksheet。
  917. mrank_rows (list): [(商家名, 成团数, GMV)](全量倒序)。
  918. mrank_total (float): 平台组齐总 GMV(算占比分母)。
  919. """
  920. _set_widths(ws, [24, 10, 16, 10])
  921. r = _write_section_title(ws, 1, f"商家 GMV 榜(当日组齐口径,前 {TOP_MERCHANT})", span=4)
  922. mrows = [[name, int(g), float(gmv) if gmv is not None else 0,
  923. (float(gmv) / mrank_total if (mrank_total and gmv is not None) else None)]
  924. for name, g, gmv in mrank_rows[:TOP_MERCHANT]]
  925. _write_hgrid(ws, r, ["商家", "成团数", "GMV", "占比"], mrows,
  926. money_cols=(2,), pct_cols=(3,), start_col=1)
  927. ws.freeze_panes = "A3"
  928. def _build_ops_sheet(ws, ops: list, hour_dist: list):
  929. """构建「运营节奏」sheet:重点商家当日运营快照 + 平台组齐时段分布。
  930. Args:
  931. ws: openpyxl worksheet。
  932. ops (list[dict]): 各重点商家运营快照。
  933. hour_dist (list[int]): 24 桶组齐时段分布。
  934. """
  935. _set_widths(ws, [16, 12, 22, 44]) # C 兼容 已组齐(数字) 与 时段分布条;D 放规格分布长文本
  936. r = _write_section_title(ws, 1, "重点商家当日运营快照(新开团 / 已组齐 / 规格)", span=4)
  937. ops_rows = [[o["商家名"], o["新开团数"], o["已组齐数"],
  938. " · ".join(f"{sp}×{c}" for sp, c in o["规格分布"]) or "—"] for o in ops]
  939. r = _write_hgrid(ws, r, ["商家", "今日新开团", "已组齐", "规格分布"], ops_rows, start_col=1)
  940. r += 1
  941. r = _write_section_title(ws, r, f"平台组齐时段分布(近 {HOUR_DIST_DAYS} 日 24h 累计)", span=4)
  942. hmax = max(hour_dist) if hour_dist else 0
  943. hrows = [[f"{h:02d}时", hour_dist[h], _bar(hour_dist[h], hmax)] for h in range(24)]
  944. _write_hgrid(ws, r, ["时段", "成团数", "分布"], hrows, start_col=1)
  945. def _build_detail_sheet(ws, title: str, summ: dict, details: list, cols: list,
  946. is_real: bool, span: int, widths: list, miss_info: dict = None):
  947. """构建单个重点商家的明细 sheet:汇总(缩到 B/C 列) + 每条组队明细(从 A 列起)。
  948. Args:
  949. ws: openpyxl worksheet。
  950. title (str): sheet 顶部分区标题(含商家名与时间窗)。
  951. summ (dict): 该商家汇总数据。
  952. details (list[dict]): 每条组队明细。
  953. cols (list[tuple]): 明细列规格(DETAIL_COLS / MODDU_DETAIL_COLS)。
  954. is_real (bool): 参与人数是否真实买家口径(魔都 True,其余 False)。
  955. span (int): 标题条覆盖列数(= 明细列数)。
  956. widths (list[float]): 各列宽度。
  957. miss_info (dict, optional): 购买记录覆盖检测(fetch_moddu_missing_teams 返回);非 None
  958. 时在汇总块下方加「购买记录覆盖检测」小节,标注漏采多少 T 并列出漏团。仅魔都传入。
  959. Defaults to None。
  960. """
  961. _set_widths(ws, widths)
  962. r = _write_section_title(ws, 1, title, span=span)
  963. # 汇总缩到 B/C 列:标签落宽的 B(团名列)、数值落 C,避开 A=序号 的窄列
  964. r = _write_summary_block(ws, r, _summary_rows(is_real=is_real), summ, start_col=2)
  965. r += 1
  966. # 购买记录覆盖检测(仅魔都传入):成交团 vs 已采购买记录,漏采的 T 逐个列出(文本向右溢出显示)
  967. if miss_info is not None:
  968. r = _write_section_title(ws, r, "购买记录覆盖检测(成交团 vs 已采购买记录)", span=span)
  969. cov = (f"成交 {miss_info['成交团数']} 团 · 采到购买记录 {miss_info['有记录团数']} 团 · "
  970. f"漏采 {miss_info['漏采团数']} 团(用户排行见「用户排行榜(魔都)」sheet)")
  971. # 漏采 >0 时用深蓝加粗字提醒;0 时常规字
  972. ws.cell(row=r, column=1, value=cov).font = FONT_HEADER if miss_info["漏采团数"] else FONT_CELL
  973. r += 1
  974. if miss_info["漏采团数"]:
  975. ws.cell(row=r, column=1,
  976. value="漏采明细(下列团未采到购买记录,未计入用户排行):").font = FONT_CELL
  977. r += 1
  978. for pc, t in miss_info["漏采团列表"]:
  979. ws.cell(row=r, column=1, value=f" - {pc} {t or ''}").font = FONT_CELL
  980. r += 1
  981. r += 1
  982. r = _write_section_title(ws, r, f"每条组队明细(共 {len(details)} 条,按总金额倒序)", span=span)
  983. hdr_row = r # 明细表头行,用于冻结
  984. _write_details(ws, r, details, cols)
  985. ws.freeze_panes = f"A{hdr_row + 1}" # 冻结到明细表头,滚动时表头常驻
  986. def _build_user_ranking_sheet(ws, rows: list, total_users: int, top_n: int):
  987. """构建「用户排行榜(魔都)」sheet:按参与金额倒序的买家榜(参与车数/参与金额/车均消费)。
  988. Args:
  989. ws: openpyxl worksheet。
  990. rows (list[dict]): 用户排行数据(fetch_moddu_user_ranking 返回,已倒序截断)。
  991. total_users (int): 窗口内魔都全部参与买家数(用于标题展示)。
  992. top_n (int): 榜单展示上限(用于标题展示)。
  993. """
  994. _set_widths(ws, [8, 22, 16, 12, 16, 14])
  995. cap = "全部展示" if top_n is None else f"取前 {min(len(rows), top_n)}"
  996. r = _write_section_title(
  997. ws, 1, f"用户排行榜 · 魔都(共 {total_users} 人参与,{cap},按参与金额倒序)", span=6)
  998. grid = [[i + 1, d["用户昵称"], d["user_id"], d["参与车数"], d["参与金额"], d["车均消费"]]
  999. for i, d in enumerate(rows)]
  1000. r = _write_hgrid(ws, r, ["排名", "用户昵称", "user_id", "参与车数", "参与金额", "车均消费"],
  1001. grid, money_cols=(4, 5), start_col=1, empty_hint="(该时段无购买记录)")
  1002. r += 1
  1003. ws.cell(row=r, column=1,
  1004. value="注:参与金额 = Σ(购买份数 × 团单价)(deca_buy_record 无金额字段,按份数×单价估算;"
  1005. "固定价团精确、随机团按标称单价近似);参与车数=参与的不同团数;"
  1006. "车均消费 = 参与金额 ÷ 参与车数。").font = FONT_CELL
  1007. ws.freeze_panes = "A3" # 冻结标题条 + 表头
  1008. def _build_others_sheet(ws, others: list):
  1009. """构建「其他商家」sheet:除重点商家外各商家一行汇总(中卡近似口径)。
  1010. Args:
  1011. ws: openpyxl worksheet。
  1012. others (list[dict]): 每商家一行的汇总。
  1013. """
  1014. _set_widths(ws, [22, 14, 9, 15, 13, 16])
  1015. r = _write_section_title(ws, 1, f"其他商家汇总(共 {len(others)} 家,按销售额倒序)", span=6)
  1016. for i, (label, _key, _money) in enumerate(OTHER_COLS):
  1017. hc = ws.cell(row=r, column=1 + i, value=label)
  1018. hc.font = FONT_HEADER; hc.fill = FILL_HEADER
  1019. hc.alignment = ALIGN_CENTER; hc.border = BORDER
  1020. r += 1
  1021. for oi, o in enumerate(others):
  1022. zebra = FILL_ZEBRA if oi % 2 == 1 else None # 隔行淡蓝灰
  1023. for i, (_label, key, is_money) in enumerate(OTHER_COLS):
  1024. value = o.get(key)
  1025. cell = ws.cell(row=r, column=1 + i, value=value)
  1026. if is_money:
  1027. cell.number_format = MONEY_FMT
  1028. elif isinstance(value, int) and not isinstance(value, bool):
  1029. cell.number_format = INT_FMT # 成团数/中卡用户数千分位
  1030. cell.font = FONT_CELL
  1031. cell.alignment = _align_by_value(value) # 商家名左对齐、数字右对齐
  1032. cell.border = BORDER
  1033. if zebra:
  1034. cell.fill = zebra
  1035. r += 1
  1036. ws.freeze_panes = "A2"
  1037. # 明细 sheet 列宽(各自独立设,不再与其它表共享):
  1038. DETAIL_WIDTHS_MODDU = [8, 48, 16, 11, 13, 9, 8, 14, 14, 19, 19, 12, 11, 11, 11] # 15 列(含里程碑)
  1039. DETAIL_WIDTHS_STD = [8, 48, 16, 11, 13, 9, 8, 14, 19, 19, 12] # 11 列(标准)
  1040. # 重点商家 ID → 明细 sheet 名(其余走商家名兜底)
  1041. DETAIL_SHEET_NAMES = {"881226408": "魔都明细", "274584650": "卡皇明细"}
  1042. def build_report(pool, out: str):
  1043. """汇总各段数据并生成多 Sheet Excel 报告(每一大项一个 sheet,各自独立列宽)。
  1044. Sheet 顺序:平台总览 / 产品系列榜 / 商家GMV榜 / 运营节奏 / 魔都明细 / 用户排行榜(魔都) /
  1045. 卡皇明细 / 其他商家。
  1046. Args:
  1047. pool (MySQLConnectionPool): MySQL 连接池。
  1048. out (str): 导出的 xlsx 路径。
  1049. """
  1050. win = get_window(pool)
  1051. platform = fetch_platform_summary(pool)
  1052. compare = fetch_groupbuy_compare(pool) # 当日 vs 昨日组齐环比
  1053. series_rows, series_total = fetch_series_ranking(pool, TOP_SERIES) # 产品系列销售榜
  1054. mrank_rows, mrank_total, mrank_conc = fetch_merchant_gmv_ranking(pool) # 商家 GMV 榜 + 集中度
  1055. ops = [fetch_focus_ops_snapshot(pool, mid) for mid in FOCUS_MERCHANTS] # 重点商家运营快照
  1056. hour_dist = fetch_completion_hour_dist(pool, HOUR_DIST_DAYS) # 组齐时段 24h 分布
  1057. # 魔都(MODDU_MID)明细走扩展版(带参与人数 + 进度里程碑),其余重点商家走标准明细
  1058. focus = []
  1059. for mid in FOCUS_MERCHANTS:
  1060. summ = fetch_merchant_summary(pool, mid)
  1061. if mid == MODDU_MID:
  1062. focus.append((mid, summ, fetch_moddu_details(pool, mid), MODDU_DETAIL_COLS))
  1063. else:
  1064. focus.append((mid, summ, fetch_merchant_details(pool, mid), DETAIL_COLS))
  1065. others = fetch_other_merchants(pool, FOCUS_MERCHANTS)
  1066. # 魔都用户排行(仅魔都采了购买记录) + 购买记录覆盖检测(成交团 vs 已采购买记录,看漏几个 T)
  1067. moddu_user_rank, moddu_user_total = fetch_moddu_user_ranking(pool, MODDU_MID, TOP_USERS)
  1068. moddu_miss = fetch_moddu_missing_teams(pool, MODDU_MID)
  1069. # 口径脚注(放平台总览底部;解释两种「参与人数」口径的差别)
  1070. notes = [
  1071. "注:① 魔都兄弟球星卡「参与人数(真实买家)」= deca_buy_record 真实购买记录去重买家(跨其全部成交团);"
  1072. "各商家明细「参与人数(本团)」为各团单独去重买家,故明细逐团相加(人次) ≥ 汇总(跨团去重人头)。",
  1073. "  ② 平台大盘参与人数 = 魔都真实买家 + 其他商家中卡去重(两口径人群标识不同、无法跨口径去重,直接相加,属近似上界)。",
  1074. "  ③ 其他商家未采购买记录,「中卡用户数(近似)」= 拆卡报告 hit_user_nickname 去重(仅报告命中/中卡用户,"
  1075. "非真实参团人头,偏低),其「人均消费(按中卡近似)」据此计算、偏高,仅供参考。",
  1076. ]
  1077. wb = Workbook()
  1078. ws = wb.active
  1079. ws.title = "平台总览"
  1080. _build_overview_sheet(ws, win, platform, compare, mrank_conc, notes)
  1081. _build_series_sheet(wb.create_sheet("产品系列榜"), series_rows, series_total)
  1082. _build_mrank_sheet(wb.create_sheet("商家GMV榜"), mrank_rows, mrank_total)
  1083. _build_ops_sheet(wb.create_sheet("运营节奏"), ops, hour_dist)
  1084. # 每个重点商家单独一个明细 sheet(各自独立列宽,互不迁就)
  1085. for (mid, summ, details, cols) in focus:
  1086. sheet_name = DETAIL_SHEET_NAMES.get(mid, f"{summ['商家名'][:8]}明细")
  1087. ws_d = wb.create_sheet(sheet_name)
  1088. is_real = (mid == MODDU_MID)
  1089. widths = DETAIL_WIDTHS_MODDU if is_real else DETAIL_WIDTHS_STD
  1090. # 魔都明细尾部附「购买记录覆盖检测」(漏采团数);其余商家无购买记录、不检测
  1091. miss = moddu_miss if mid == MODDU_MID else None
  1092. _build_detail_sheet(ws_d, f"{summ['商家名']} · 汇总(成交时间窗 {win[0]} ~ {win[1]})",
  1093. summ, details, cols, is_real, len(cols), widths, miss_info=miss)
  1094. # 魔都明细后紧跟「用户排行榜(魔都)」sheet,让魔都相关表相邻
  1095. if mid == MODDU_MID:
  1096. _build_user_ranking_sheet(wb.create_sheet("用户排行榜(魔都)"),
  1097. moddu_user_rank, moddu_user_total, TOP_USERS)
  1098. _build_others_sheet(wb.create_sheet("其他商家"), others)
  1099. wb.save(out)
  1100. def run_once(log) -> str:
  1101. """连库生成已售每日报告并发送到微信群(只发 Excel)。
  1102. Args:
  1103. log: 日志对象。
  1104. Returns:
  1105. str: 生成的 xlsx 绝对路径;数据库连接池异常时返回空串。
  1106. """
  1107. pool = MySQLConnectionPool(log=log)
  1108. if not pool.check_pool_health():
  1109. log.error("数据库连接池异常")
  1110. return ""
  1111. # 绝对路径:不受运行目录影响、便于企微上传定位;文件名带当天日期避免覆盖
  1112. out_file = os.path.abspath(f"{OUT_PREFIX}_{date.today():%Y%m%d}.xlsx")
  1113. build_report(pool, out_file)
  1114. log.info(f"报告已生成 -> {out_file}")
  1115. # 发企微群(只发 Excel;失败仅告警,不影响报告产出)
  1116. if SEND_WECHAT:
  1117. try:
  1118. from auto_send_wx_msg import send_wechat_group_file
  1119. send_wechat_group_file(log=log, file_path=out_file) # 只发 Excel,不发图
  1120. except Exception as e:
  1121. log.warning(f"企微发送跳过: {e}")
  1122. return out_file
  1123. def main():
  1124. """命令行一次性生成 + 发送(手动/调试用)。"""
  1125. run_once(logger)
  1126. def schedule_task():
  1127. """定时入口:每天 09:10 生成已售报告并发送到微信群。
  1128. 错开在售报告(on_sale 09:00 发)10 分钟发送,两份报告到群时间分开、便于查阅(企微为 webhook 直发,无 UI 冲突)。
  1129. """
  1130. # run_once(logger) # 立即跑一次(调试时取消注释)
  1131. schedule.every().day.at("09:10").do(run_once, logger)
  1132. while True:
  1133. schedule.run_pending()
  1134. time.sleep(1)
  1135. if __name__ == "__main__":
  1136. schedule_task()