Commit b905a7d1 by 叶立庆

Merge remote-tracking branch 'origin/v1.1'

# Conflicts:
#	.workbuddy/memory/MEMORY.md
#	data-process/.gitignore
2 parents 7c523de5 f8aa2c2b
Showing 78 changed files with 1997 additions and 23 deletions
/data-process/backend_avita11.log
/data-process/backend_avita.log
/data-process/backend_avita2.log
/data-process/backend_avita3.log
/data-process/backend_avita4.log
/data-process/backend_avita5.log
/data-process/backend_avita6.log
/data-process/backend_avita7.log
/data-process/backend_avita8.log
/data-process/backend_avita9.log
/data-process/backend_avita10.log
/data-process/*.log
# VSCode Local History 插件
.history/
# IDE
.idea/
# 2026-09-09 工作日志
## scrm_account 账号补齐 + 新增门店品牌归类链路打通
- 用户给出 scrm_account 只读账号:`read_scrm_account` / `TnZobW2b` / `192.168.5.1:3310` / 库名 `scrm_account`。
- `config.py` 原 `SCRM_DATABASE_URL` 默认值(误用 read_dj_smartcarlife@192.168.5.23:3306)改为正确账号串:`mysql+pymysql://read_scrm_account:TnZobW2b@192.168.5.1:3310/scrm_account?charset=utf8mb4`。
- 实测 scrm_account 可达:`platform_merchant_brand` 58万行,列 `id/merchant_id/first_brand_id/sec_brand_id/del_flag/...`。cyb_os `platform_carbrand` 列 `bid/brand/brand_code/...`,品牌名在 **`brand`** 列(非 name/brand_name)。
- 修复 `fetch_new_stores` 三处口径错误:
1. `platform_merchant_brand` 加 `del_flag=0` 过滤(表有逻辑删除列)。
2. 品牌名字段由 `name`/`brand_name` 优先改取 `brand`(否则全空→豪华归0)。
3. 一个 `merchant_id` 多行 → 按商户 **union** 所有 first/sec 品牌 id(原 `brand_map[mid]=[r1,r2]` 覆盖只留最后一行)。
- 真实结果(链路全通):2026-08 → 新增41 豪华41 非豪华0;2026-06 → 新增90 豪华85 非豪华5。
- ⚠️ 豪华占比异常高的根因 = **用户 config_brand_category 配置本身**:69 条里把 比亚迪/吉利/广汽丰田/大众/零跑/长安/奇瑞/埃安 等大量主流/自主品牌都标成"豪华"。`brand_category` 双向子串匹配工作正常,归类是按用户配置正确得出,非代码 bug。已向用户说明,是否收窄豪华定义由用户决定(改 config 表即可,无需改代码)。
- 重启后端(PID 16560)生效。新代码+配置均可经页面"重新生成"跑通。
## 关键惯例(持续有效)
- 改 `build_store_effect_board.py` / `store_effect_summary_processor.py` / `processor.py` / `config.py` 任一文件后,**必须重启后端常驻进程**才能页面"重新生成"生效(调试重载不刷新动态 import 的模块缓存)。
- 页面"重新生成"路径(`store_effect_summary_processor.py`)统计月来自 `task.month`,非 CLI 的 `--month`;两路径需各自保证传 `month_start/month_end_excl`。
# 2026-09-16 工作日志
## 新增数据表类型:阿维塔专项
- `config.DATA_TABLE_TYPES` 新增 `avita_special`:`name='阿维塔专项'`、`need_period=True`、`forms=['主机厂数据表']`。
- 附件表名「主机厂数据表」为暂定,后续可能改名(改名只改 config 该处即可,前端动态渲染 forms)。
- 处理引擎未接入:`process_task` 白名单(SUPPORTED_PROCESS_TYPES)会拦截并提示"引擎尚未接入"(与 future_expansion 一致),不会误跑预算流水线、不崩溃。
- 改动仅 config.py;前端按 DATA_TABLE_TYPES 动态渲染上传区,重启后端后上传页出现"阿维塔专项"选项。
- need_period 已按用户要求改为 False(阿维塔专项不需要所属周期项)。仍待确认:是否需重启后端(PID 13536)让前端生效。
- 澄清(用户纠正):阿维塔专项的「主机厂数据表」为独立数据表,格式不保证与现有「鸿蒙主机厂数据表」/「广联主机厂数据表」一致,不可复用 report_utils.parse_delivery_table(鸿蒙/广联共用结构);后续接引擎时按用户实际提供的附件字段解析、写入阿维塔专属结果表。当前阶段仅配置类型+定义上传表名,解析逻辑未实现。已在 config.py 注释中标注此独立性。
## 阿维塔专项 引擎接入(task 37 实测落库)
- 用户已建两表:`avita_special_month_data`(明细,无 created_at/updated_at)/ `avita_special_month_summary_metrics`(汇总,仅 created_at)。
- 改动三处:`models.py` 加两 ORM 模型(对齐真实列,缺列会 INSERT 报 Unknown column);`avita_special_processor.py` 新建 `AvitaSpecialProcessor`(下载→解析双表头 Excel→按 task_id 先删后插→置 COMPLETED/result_file_url='');`processor.py` 的 `process_task` 在白名单**前**加 `avita_special` 路由分支。
- 源文件实测(task 37,7月样本「7月页签-字段取值说明」):2 行表头 + 8 家门店明细 + 末尾汇总段('阿维塔品牌汇总' + 售后门店数=3/售后场景开通率=0.38/售后订单数=0)。
- 解析坑:①store_name/store_short_name 是字符串列,不能走 `_to_dec` 数值转换(否则门店名全被置空);②明细表多声明的 created_at/updated_at 与实际表不符→已移除;③汇总表仅 created_at。已修正并落库成功。
- 结果:task 37 落库 COMPLETED,明细 8 行 + 汇总 1 行;汇总表 store_count/output_value/delivery_count 等源文件未提供→留空(待最终 Excel 生成或后续填充)。
- 当前无后端进程在跑(Get-Process 无 python),代码改动下次启动自动生效;前端页面"重新生成"需在后端运行新代码时才可用。
## 阿维塔专项 源文件新增门店模式/入驻时间两列(task 37 重跑)
- 用户更新源数据:月份明细新增「门店模式」(col2, 文本如服务商/直营) 与「入驻时间」(col3, Excel datetime) 两列,插入到原门店简称之后、主机厂指标之前 → 所有指标列整体右移 +2。
- `avita_special_processor.py` 改动:①`DETAIL_COL` 列索引整体右移(store_name=0/store_short_name=1/store_mode=2/entry_time=3/主机厂交付=4/延保=5/无忧=6/单车收入=7/总产值=8/广联交付=9/广联触客=10);②`_STR_COLS` 加 store_mode/entry_time,新增 `_to_date_str` 将入驻时间 datetime 格式化为 `YYYY-MM-DD` 写入 `varchar(10)`;③`_save` 由 `rec.get('store_mode'/'entry_time')` 写入(此前硬编码 None)。
- 重跑 task 37(run_avita37.py,app 上下文直接调用 AvitaSpecialProcessor):8 家门店门店模式/入驻时间全部填充成功,状态回 COMPLETED。临时脚本已清理。
- 重启后端:杀掉两个旧后端(24636/31508,监听 5000 的旧代码)后,以 `PYTHONPATH=用户site-packages` 重启(新 PID 30988,日志无报错,已加载新 avita 代码)。页面"重新生成"现在用新引擎,不会再清空这两列。
- 表列类型确认:`store_mode varchar(50)`、`entry_time varchar(10)`(均为文本,入驻时间存日期串)。
- 仍空缺:regional_operation/resident_name/广联延保成交数/广联无忧成交数 源文件未提供→留空。
## 阿维塔专项两表加 is_deleted 软删除(逻辑删除)
- 需求:avita_special_month_data 与 avita_special_month_summary_metrics 加 `is_deleted`(0正常/1已删除),后续不再物理删除,只逻辑删除(与项目偏好一致)。
- 改动三处:①`alter_avita_softdelete.py` 对两表 `ALTER TABLE ... ADD COLUMN is_deleted INT NOT NULL DEFAULT 0`(已跑,两表均加好);②`models.py` 两 ORM 模型加 `is_deleted = db.Column(db.Integer, nullable=False, default=0, comment='是否删除:0正常 / 1已删除(软删除)')`;③`avita_special_processor.py` 的 `_save` 由 `query.filter_by(task_id).delete()` 改为 `query.filter_by(task_id=..., is_deleted=0).update({is_deleted:1})` 逻辑删除旧行 + 新行 `is_deleted=0`(幂等),docstring 同步。
- 验证(重跑 task 37):明细 total=16(active=8 + 软删=8)、汇总 total=2(active=1 + 软删=1);门店模式/入驻时间写入无误,状态 COMPLETED。确认软删除生效、INSERT 未因新增列报错。
- 重启后端(杀 30988,新 PID 28164,日志无报错)加载新代码。临时脚本已清理。
- 注意:后续任何读这两张表的逻辑都需 `filter_by(is_deleted=0)`,否则会把历史软删行当活跃数据。
## 阿维塔专项 源文件新增驻店姓名一列(task 37 重跑)
- 用户更新源数据:月份明细再新增「驻店姓名」(col4, 文本如"创思/服务商"/"王永忠"),插入到入驻时间之后、主机厂指标之前 → 所有指标列整体右移 +1(累计右移 +3)。
- `avita_special_processor.py` 改动:①`DETAIL_COL` 列索引调整(resident_name=4,主机厂交付=5/延保=6/无忧=7/单车收入=8/总产值=9/广联交付=10/广联触客=11);②`_STR_COLS` 加 `resident_name`(字符串列勿走数值转换);③`_save` 由 `rec.get('resident_name')` 写入(此前硬编码 None);docstring 同步。
- 重跑 task 37(run_avita37.py,app 上下文):8 家门店驻店姓名全部填充成功(如 创思/服务商、王永忠、杨淑萍、林彩玲、刘秀锦),门店模式/入驻时间/数值无回退,软删除正确(active=8,历史 16 行 is_deleted=1),状态 COMPLETED。临时脚本已清理。
- 重启后端(杀 28164,新 PID 31244,日志无报错)加载新代码。页面"重新生成"现在用新引擎。
- 仍空缺:广联延保成交数/广联无忧成交数 源文件未提供→留空。
## 阿维塔专项 区域运营字段改由 dj_smartcarlife 查询(task 37 重跑)
- 需求:avita_special_month_data.regional_operation(区域运营)从 dj_smartcarlife 数据源读取,源文件无此列。
- 规则(两跳):①`select merchant_id from dj_car_life_service_merchant where merchant_name=门店名称 and deleted_flag='N'`;②用查到的 merchant_id `select director_name from dj_car_life_shop_merchant_director_config where deleted_flag='N' and merchant_id=:mid and director_type=9`,多条记录去重后 `/` 分隔。
- 改动(`avita_special_processor.py`):加 `from config import Config` + `create_engine(Config.BIZ_SQL_DATABASE_URL)` 引擎缓存 + `fetch_regional_operation(store_name)`(参数化 text 查询,模块级 `_BIZ_ENGINE` 缓存,异常不致命仅告警留空);`_save` 的 `regional_operation` 由 `None` 改为 `fetch_regional_operation(rec['store_name'])`;docstring 同步。
- 踩坑:`config` 模块无 `BIZ_SQL_DATABASE_URL` 属性(报 AttributeError),该连接串挂在 `Config` 类上 → 改用 `from config import Config` 取 `Config.BIZ_SQL_DATABASE_URL` 修复。
- 重跑 task 37(run_avita37.py):8 家门店区域运营全部填充成功(陈晓文/张爱豪/李明瑞/张浩锋/王孝樟/卓炯煜/刘淑君/李明瑞),状态从 FAILED 恢复 COMPLETED,软删除正确(active=8,历史 24 行 is_deleted=1)。临时脚本已清理。
- 重启后端(杀 31244 及幽灵 20340,新 PID 16536,日志 `Running on 5000` 无报错)加载新代码。注意 netstat 显示的 20340 是幽灵条目(PowerShell Get-Process 找不到),真实新进程为 16536。
- 仍空缺:广联延保成交数/广联无忧成交数 源文件未提供→留空。
# 2026-09-28 工作日志
## 营销人员成本计算逻辑调整(店中店/园区店轻改报表)
- 文件:`light_reform_inshop_processor.py:404`(`light_reform_park_processor.py` 若同口径需同步,待确认)。
- 原:`营销人员成本 = 直营人数 * 3500 + 门店总产值 * 4%`(底薪 3500 固定不折算)。
- 改:底薪 3500 元/人/月 **按统计周期天数折算** = `prorate_by_period(3500, period_start, period_end)`,即 `3500 * 周期天数 / 月份总天数`(周期天数=period_end-period_start+1 含首尾;月份总天数=period_start 所在月 `calendar.monthrange`)。
- 验证:2号~6号、30天月 → 3500*5/30=583.33;全月1~30号 → 3500.00;跨月9/28~10/5(按9月30天)→ 933.33,均符合预期。
- 4% 提成(门店总产值*4%)**不折算**,保持原样。非直营门店仍=0。
- `prorate_by_period` 在处理器 line27 已 import,复用即可;period_start/period_end 来自 task。
- ⚠ 仅改了 inshop(店中店)一处;用户问的「店中店汇总 sheet 营销人员成本」即此字段。park(园区店)同公式是否同步未确认,待用户指认。
## 园区店人员成本同步改为按天折算(已确认)
- 用户确认后,将 `light_reform_park_processor.py:393`(人员成本 `personnel_cost`)同步改为按天折算:`base_salary_prorated = prorate_by_period(Decimal('3500'), period_start, period_end)`。
- 字段名差异:店中店=`marketing_personnel_cost`(提成基数 `store_output_value`)、园区店=`personnel_cost`(提成基数 `store_sales_output`),比例均为 4%。
- park 处理器 line33 已 import `prorate_by_period`,且装修/房租/耗材(329/332/335)已用它折算,仅人员成本漏改 → 现已补。
- 验证:py_compile 通过;grep 命中行 395 确认落盘(沙箱丢写已复核)。
- 现状:**店中店 + 园区店**两处人员/营销人员成本口径已统一(均按天折算底薪)。两处均为处理器代码,需**重启后端**页面「重新生成」才生效;msoffcrypto 已装,解密无需重启。
## 后端缺 msoffcrypto 导致人力成本表解密失败(headcount 全 0)
- 现象:页面点「重新生成」后日志 `[人力成本表] msoffcrypto 未安装` + `Can't find workbook in OLE2 compound document`,headcount 退化为 0 → 营销人员成本只算 4% 提成,底薪整段缺失。
- 根因:后端 Flask 跑在 `C:/Users/66/AppData/Roaming/Python/Python314/site-packages`,该环境未装 msoffcrypto;managed venv 有但后端不用。
- 修复:`C:/Python314/python.exe -m pip install --target "C:/Users/66/AppData/Roaming/Python/Python314/site-packages" msoffcrypto-tool`(顺带 cryptography/cffi/olefile/pycparser)。已验证该解释器 `import msoffcrypto` 成功、解密 task 32 人力成本表得 `遵义广新智腾汽车销售有限公司=3`。
- 关键点:`parse_labor_cost` 在**函数内** `import msoffcrypto`(report_utils.py:1240),属运行时懒加载 → 装好包后**下次重新生成即用,无需重启后端**。
- 建议:重跑 task 32 整体重算,让新公式+正确 headcount 同时生效(此前所有直营店营销成本/毛利均被少算底薪段)。
# 2026-09-29 工作日志
## 总看板「2.3交车数」口径核查(14487 vs 17513)
- 字段:`build_store_effect_board.py:810` `m['2.3交车数'] = fetch_extended_warranty_23_sum('delivery_cnt', period_start, period_end)` → `_lr_sum_one('warranty','delivery_cnt',...)`(line557)。
- 真实口径:`report_extended_warranty` 表 `task_id==max(周期匹配或最新task), is_deleted=0` 的 `delivery_cnt` 之和。**只汇总单个 task_id,非跨所有 task 全量**。
- 用户报:结果表显示 14487、DB 查汇总 17513。实测当前代码算当前 DB(仅 task_id=32 一个任务)=17513;三种 period 取值(None / 整月 / 子集)均 17513;task32 无 NULL 行、75 行 0 值。
- 结论:14487 是**旧结果表快照**,DB 已更新 → 重跑生成结果表即对齐 17513。差异=数据时效,非逻辑 bug。
- ⚠ 设计提醒:看板只取**单个** task_id(周期匹配优先,否则 max(task_id))。当前仅 task32 故与全量等价;若未来并存多月/多 task 延保数据,看板只取最新一个 task,与"不限 task_id 全量"查询将不一致。
## 总看板执行顺序闸门(必须等前4个sheet完成)
- 用户要求:总看板(第5 sheet)必须在前 4 张 sheet(warranty/equity/inshop/park)执行完才执行。
- 根因:5 个调度器(warranty/equity/inshop/park/store_effect_summary)各自独立扫描同一 PROCESSING 主任务并发执行;原 `scan_store_effect_summary` 在跑 `_process_summary`(读前 4 张表的 ORM 数据)**前无闸门** → 竞态,总看板读到未落库/旧前置数据。
- 修复:`store_effect_summary_processor.py`
- `process()` 顶部加两道闸:① 自身已 COMPLETED → 幂等跳过;② `_preceding_sheets_all_completed(task_id)` 检查 `PRECEDING_CATEGORIES=['warranty','equity','inshop','park']` 是否**全部 == SUBTASK_COMPLETED**,否则 `return`(自身子任务保持 PENDING,等下轮调度重试;不置 FAILED)。
- 新增模块常量 `PRECEDING_CATEGORIES` + 方法 `_preceding_sheets_all_completed`(返回 (all_done, pending_list),未就绪态 PENDING/PROCESSING/None/FAILED 均视为等待)。
- 闸门放在 `process()` 内部(而非仅 scan),同时覆盖**两条入口**:调度器 `StoreEffectSummaryScheduler.scan_store_effect_summary` 与手动"处理"按钮 `processor.py:1437` 路由,均调用 `StoreEffectSummaryProcessor.process(task)`。
- 注:某前置 FAILED 时,主任务会被 `promote_subtask_failure_to_main_task` 置 FAILED,调度器不再扫到;手动按钮也因闸门(FAILED≠COMPLETED)而等待,不 deadlock。
- 验证:`py_compile` 通过;monkeypatch 5 用例全过(全完成→True;inshop PENDING/park PROCESSING/equity FAILED/inshop None→均 False+对应 pending 列表)。
......@@ -5,10 +5,10 @@
# ============================================
# ---------- 数据库(MySQL) ----------
MYSQL_HOST=192.168.3.227
MYSQL_PORT=3306
MYSQL_USER=os_user
MYSQL_PASSWORD=os#123
MYSQL_HOST=192.168.1.228
MYSQL_PORT=3307
MYSQL_USER=wechat_user
MYSQL_PASSWORD=b4WRTkl
MYSQL_DB=data_report
# ---------- 阿里云 OSS ----------
......
......@@ -6,3 +6,5 @@ uploads/
data/
.idea
.idea/*
.venv/
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="com.github.wanniwa.editorjumper.settings.EditorJumperProjectSettings">
<option name="projectEditorType" value="Trae" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="temurin-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/data-process.iml" filepath="$PROJECT_DIR$/.idea/data-process.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
\ No newline at end of file
......@@ -8,19 +8,24 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
g++ \
libffi-dev \
libssl-dev \
tzdata \
RUN sed -i \
-e 's@deb.debian.org@mirrors.aliyun.com@g' \
-e 's@security.debian.org@mirrors.aliyun.com@g' \
/etc/apt/sources.list.d/debian.sources \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
gcc \
g++ \
libffi-dev \
libssl-dev \
tzdata \
&& ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip setuptools wheel \
&& pip install --no-cache-dir -r requirements.txt
RUN pip install -i https://mirrors.aliyun.com/pypi/simple/ --no-cache-dir --upgrade pip setuptools wheel \
&& pip install -i https://mirrors.aliyun.com/pypi/simple/ --no-cache-dir -r requirements.txt
COPY . .
......@@ -29,5 +34,4 @@ ENV FLASK_HOST=0.0.0.0 \
EXPOSE 5000
CMD ["python", "app.py"]
CMD ["python", "app.py"]
\ No newline at end of file
"""扫店中店模板 row1+row2 窗膜/车衣/精品/踏板 相关表头"""
from openpyxl import load_workbook
wb = load_workbook(r'f:\360MoveData\Users\11\Desktop\企微SAAS\2026\09\0921\data-report\data-process\exporttemplete\红黄门店盈利测算 轻改 .xlsx')
ws = wb['店中店汇总']
print("=== 店中店 col18~32 (品类成交数区域) row1+row2+row4 ===")
for col in range(18, 33):
h1 = ws.cell(1, col).value or ''
h2 = ws.cell(2, col).value or ''
h4 = ws.cell(4, col).value or ''
print(f" col{col:2d}: row1={h1.strip()!r:25s} row2={h2.strip()!r:30s} fmt_row4={str(h4)[:60]}")
wb.close()
# -*- coding: utf-8 -*-
"""初始化"豪华品牌配置表"到数据库。
新建 config_brand_category 表(brand / category),从 xlsx 灌入,幂等。
"""
import sys
sys.stdout.reconfigure(encoding='utf-8')
import pymysql
import openpyxl
XLSX = 'D:/workspace_daily/日常数据处理需求/运营数据处理/配置表/豪华品牌配置表.xlsx'
DB = {
'host': '192.168.3.227', 'port': 3306,
'user': 'os_user', 'password': 'os#123',
'database': 'data_report', 'charset': 'utf8mb4',
}
def read_rows():
wb = openpyxl.load_workbook(XLSX, data_only=True, read_only=True)
ws = wb['Sheet1']
rows = []
header_skipped = False
for r in ws.iter_rows(values_only=True):
if not header_skipped:
header_skipped = True
continue # 跳过表头「品牌/品牌区分」
brand = (r[0] or '').strip() if r and len(r) > 0 else ''
cat = (r[1] or '').strip() if r and len(r) > 1 else ''
if not brand:
continue
rows.append((brand, cat or '豪华'))
return rows
def main():
rows = read_rows()
print(f'从 xlsx 读取到 {len(rows)} 行品牌配置')
conn = pymysql.connect(**DB)
try:
with conn.cursor() as cur:
# 1) 建表(幂等)
cur.execute('''
CREATE TABLE IF NOT EXISTS config_brand_category (
id BIGINT NOT NULL AUTO_INCREMENT,
brand VARCHAR(200) NOT NULL COMMENT '品牌',
category VARCHAR(50) NOT NULL DEFAULT '' COMMENT '品牌区分(如 豪华/非豪华)',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_brand (brand(191))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='豪华品牌配置表'
''')
print('[OK] 表 config_brand_category 就绪')
# 2) 灌入(幂等:品牌重复则更新 category)
inserted = 0
updated = 0
for brand, cat in rows:
cur.execute(
'SELECT id FROM config_brand_category WHERE brand=%s', (brand,))
if cur.fetchone():
cur.execute(
'UPDATE config_brand_category SET category=%s, update_time=NOW() WHERE brand=%s',
(cat, brand))
updated += 1
else:
cur.execute(
'INSERT INTO config_brand_category (brand, category) VALUES (%s, %s)',
(brand, cat))
inserted += 1
conn.commit()
print(f'[OK] 插入 {inserted} 行,更新 {updated} 行')
# 3) 校验
cur.execute('SELECT COUNT(*) FROM config_brand_category')
print('库内总行数:', cur.fetchone()[0])
cur.execute('SELECT brand, category FROM config_brand_category ORDER BY id')
for r in cur.fetchall():
print(' ', r)
finally:
conn.close()
if __name__ == '__main__':
main()
# -*- coding: utf-8 -*-
"""验证新增两个报表类型:meta 接口、新增(含周期校验)、调度跳过保护"""
import sys
sys.stdout.reconfigure(encoding='utf-8')
import requests, pymysql
BASE = 'http://localhost:5000'
s = requests.Session()
r = s.post(BASE + '/api/login', json={'username': 'admin', 'password': 'admin123'})
print('[1] 登录:', r.json()['msg'])
# 1. meta 返回类型与 need_period
r = s.get(BASE + '/api/meta/task-types').json()['data']
print('[2] 数据表类型:')
for t in r:
print(f" {t['code']} | {t['name']} | need_period={t['need_period']} | forms={len(t['forms'])}")
se = [t for t in r if t['code'] == 'store_effect_earnings'][0]
ov = [t for t in r if t['code'] == 'output_value'][0]
# 2. 店效人效新增(带周期)成功
files_se = [{'form_type': f, 'file_name': f + '.xlsx',
'file_url': f'https://jinrong-huidan-test.oss-cn-shenzhen.aliyuncs.com/data-process/test/{f}.xlsx',
'file_size': 17} for f in se['forms']]
payload = {'data_table_type': 'store_effect_earnings', 'month': '2026-08',
'period_start': '2026-08-01', 'period_end': '2026-08-31', 'files': files_se}
r = s.post(BASE + '/api/tasks', json=payload)
d = r.json()
print('[3] 店效人效新增:', d['msg'])
if d['code'] == 0:
print(' 周期:', d['data']['period_start'], '~', d['data']['period_end'], '| 表单数:', len(d['data']['files']))
se_task = d['data']
else:
se_task = None
# 3. 产值达成新增
files_ov = [{'form_type': f, 'file_name': f + '.xlsx',
'file_url': f'https://jinrong-huidan-test.oss-cn-shenzhen.aliyuncs.com/data-process/test/{f}.xlsx',
'file_size': 17} for f in ov['forms']]
payload = {'data_table_type': 'output_value', 'month': '2026-08',
'period_start': '2026-08-05', 'period_end': '2026-08-20', 'files': files_ov}
r = s.post(BASE + '/api/tasks', json=payload)
d = r.json()
print('[4] 产值达成新增:', d['msg'])
if d['code'] == 0:
print(' 周期:', d['data']['period_start'], '~', d['data']['period_end'], '| 表单数:', len(d['data']['files']))
# 4. 周期校验:缺失周期应拒绝
payload_no_period = {'data_table_type': 'output_value', 'month': '2026-09', 'files': files_ov}
r = s.post(BASE + '/api/tasks', json=payload_no_period)
print('[5] 缺周期提交:', r.json()['msg'])
# 5. 结束早于开始应拒绝
payload_bad = {'data_table_type': 'output_value', 'month': '2026-09',
'period_start': '2026-09-20', 'period_end': '2026-09-01', 'files': files_ov}
r = s.post(BASE + '/api/tasks', json=payload_bad)
print('[6] 结束<开始:', r.json()['msg'])
# 6. 预算达成新增不应要求周期(不带周期应成功)
r = s.get(BASE + '/api/meta/task-types').json()['data']
ba = [t for t in r if t['code'] == 'budget_achievement'][0]
files_ba = [{'form_type': f, 'file_name': f + '.xlsx',
'file_url': f'https://jinrong-huidan-test.oss-cn-shenzhen.aliyuncs.com/data-process/test/{f}.xlsx',
'file_size': 17} for f in ba['forms']]
payload = {'data_table_type': 'budget_achievement', 'month': '2026-10', 'files': files_ba}
r = s.post(BASE + '/api/tasks', json=payload)
print('[7] 预算达成(无周期):', r.json()['msg'], '| 周期字段:', r.json()['data'].get('period_start', '') if r.json()['code']==0 else '-')
# 7. 列表返回周期
r = s.get(BASE + '/api/tasks').json()['data']['list']
print('[8] 列表首条周期列:', [(x['data_table_type_name'], x['period_start'] + '~' + x['period_end'] if x['period_start'] else '-') for x in r[:3]])
# 8. 调度跳过:等 2 轮调度或直接调用 process_all 检查新类型不被误处理
r = s.post(BASE + '/api/tasks/process-all')
print('[9] 批量处理结果:', r.json()['msg'])
conn = pymysql.connect(host='192.168.3.227', port=3306, user='os_user', password='os#123',
database='data_report', charset='utf8mb4')
with conn.cursor() as cur:
cur.execute("SELECT data_table_type, month, status, period_start, period_end FROM data_process_task WHERE is_deleted=0 ORDER BY id DESC LIMIT 5")
print('[10] 数据库最新任务:')
for row in cur.fetchall():
print(' ', row)
conn.close()
import sys, types, datetime
from decimal import Decimal
def stub(name):
m = types.ModuleType(name); sys.modules[name] = m; return m
# requests 桩(indicator_client 仅用 requests.post,验证时由 fake_post 接管)
req = stub('requests'); req.post = lambda *a, **k: None; req.Timeout = Exception; req.ConnectionError = Exception
sys.modules['requests'] = req
# config
cfg = stub('config')
cfg.Config = type('C', (), {'INDICATOR_API_URL':'http://dc.glsx.com.cn/data',
'INDICATOR_API_TIMEOUT':10, 'INDICATOR_API_RETRY':1})()
# ================= Test A: indicator_client bizs 序列化 =================
import importlib.util
spec = importlib.util.spec_from_file_location('indicator_client', r'F:/data-report/data-process/indicator_client.py')
ic = importlib.util.module_from_spec(spec); spec.loader.exec_module(ic)
captured = {}
class FakeResp:
status_code = 200
def json(self): return {'code':200, 'content':[]}
def fake_post(url, json=None, timeout=None):
captured['url'] = url; captured['json'] = json; return FakeResp()
ic.requests.post = fake_post
client = ic.IndicatorClient()
client.fetch('2026-08-01', '2026-08-31', [1, 3], ['A036'])
print("A1 payload(bizs多值):", captured['json'])
assert captured['json'].get('bizs') == '1,3'; assert 'biz' not in captured['json']
client.fetch('2026-08-01', '2026-08-31', 2, ['A036'])
print("A2 payload(biz单值):", captured['json'])
assert captured['json'].get('biz') == 2; assert 'bizs' not in captured['json']
print(">>> Test A 通过:bizs 多值='1,3',单值 biz=2")
# ================= Test B: output_value_processor G/I/L 计算 =================
models = stub('models')
class FakeQuery:
def filter_by(self, **k): return self
def delete(self): return 0
def order_by(self, *a): return self
def all(self): return []
class SaasBusinessAchievement:
query = FakeQuery()
def __init__(self, **kw): self.__dict__.update(kw)
models.SaasBusinessAchievement = SaasBusinessAchievement
models.DataProcessTask = object
class FakeSession:
def __init__(self): self.added=[]
def add_all(self, rows): self.added.extend(rows)
def flush(self): pass
def commit(self): pass
def rollback(self): pass
class FakeDB: session = FakeSession()
models.db = FakeDB()
oss = stub('oss_utils'); oss.upload_file = lambda p,k: 'http://fake/'+k
ru = stub('report_utils')
ru.mark_task_failed = lambda *a,**k: None
ru.cleanup_tmp_dir = lambda *a,**k: None
ru.download_all_files = lambda *a,**k: {'SAAS门店预算分解表':'x', '关系表':'y'}
ru.parse_operator_relation = lambda *a,**k: {}
ru.safe_div_pct_decimal = lambda n,d: (round(n/d*100,2) if (n is not None and d) else None)
MOCK_213 = [
{'region_operator':'华东','store_name':'郑州鸿启汽车贸易有限公司','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('100000'),'biz_type':'2.1'},
{'region_operator':'华东','store_name':'新乡市天驰汽车销售有限公司','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('80000'),'biz_type':'2.1'},
{'region_operator':'华东','store_name':'上海XX店','resident_type':'服务商','store_kind':'新增','budget_corrected':Decimal('20000'),'biz_type':'2.3'},
{'region_operator':'华北','store_name':'北京YY店','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('60000'),'biz_type':'2.1'},
]
MOCK_11 = [
{'region_operator':'华南','store_name':'广州ZZ店','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('50000'),'biz_type':'1.1'},
{'region_operator':'华南','store_name':'深圳WW店','resident_type':'服务商','store_kind':'新增','budget_corrected':Decimal('10000'),'biz_type':'1.1'},
]
ru.parse_saas_achieve_details = lambda p,k,i: (MOCK_11 if '轻改' in k else MOCK_213)
API_DATA = {
'郑州鸿启汽车贸易有限公司': {'A036': Decimal('12225')},
'新乡市天驰汽车销售有限公司': {'A036': Decimal('3945')},
'上海XX店': {'A036': Decimal('555')},
# '北京YY店' 故意不返回 → 华北组应落 NULL
'广州ZZ店': {'A036': Decimal('888')},
'深圳WW店': {'A036': Decimal('999')},
}
def fake_fetch(start_str, end_str, biz_code, item_codes):
assert biz_code in ([1,3], [2]), f"biz_code 错误: {biz_code}"
return API_DATA
ru.fetch_indicator_data = fake_fetch
spec2 = importlib.util.spec_from_file_location('ovp', r'F:/data-report/data-process/output_value_processor.py')
ovp = importlib.util.module_from_spec(spec2); spec.loader.exec_module(ovp)
class FakeTask:
id=777; month='2026-08'
period_start=datetime.date(2026,8,1); period_end=datetime.date(2026,8,31)
proc = ovp.OutputValueProcessor()
proc._process_output_value(FakeTask())
rows = models.db.session.added
print(f"\n>>> 入库 {len(rows)} 行")
ok = True
for r in rows:
g=r.daily_new_gmv; i=r.existing_actual; l=r.new_actual
print(f" {r.business_type}/{r.region_operator:6s} G={g} I={i} L={l}")
if r.region_operator=='华东':
ok = ok and (i==Decimal('16170') and l==Decimal('555') and g==Decimal('16725'))
elif r.region_operator=='华北':
ok = ok and (i is None and l is None and g is None)
elif r.region_operator=='华南':
ok = ok and (i==Decimal('888') and l==Decimal('999') and g==Decimal('1887'))
assert ok, "G/I/L 数值不符预期"
print(">>> Test B 通过:store_name 匹配、G=I+L、未匹配门店(华北)落 NULL")
# -*- coding: utf-8 -*-
"""验证重复校验已改成 (类型+月份+周期) 4 维唯一"""
import sys
sys.stdout.reconfigure(encoding='utf-8')
import requests
BASE = 'http://localhost:5000'
s = requests.Session()
r = s.post(BASE + '/api/login', json={'username': 'admin', 'password': 'admin123'})
assert r.json()['code'] == 0, r.text
# 1. 拿表单清单
meta = s.get(BASE + '/api/meta/task-types').json()['data']
ov = [t for t in meta if t['code'] == 'output_value'][0]
se = [t for t in meta if t['code'] == 'store_effect_earnings'][0]
ba = [t for t in meta if t['code'] == 'budget_achievement'][0]
def files_for(forms):
return [{'form_type': f, 'file_name': f + '.xlsx',
'file_url': f'https://jinrong-huidan-test.oss-cn-shenzhen.aliyuncs.com/data-process/test/{f}.xlsx',
'file_size': 17} for f in forms]
# 2. 产值达成 2026-08 / 8/1~8/20 — 应成功
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'output_value', 'month': '2026-08',
'period_start': '2026-08-01', 'period_end': '2026-08-20',
'files': files_for(ov['forms']),
})
print('[1] 产值 2026-08 / 8/1~8/20:', r.json()['msg'])
assert r.json()['code'] == 0, r.text
task1 = r.json()['data']
# 3. 同月份+同周期 重提 — 应被拦
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'output_value', 'month': '2026-08',
'period_start': '2026-08-01', 'period_end': '2026-08-20',
'files': files_for(ov['forms']),
})
print('[2] 产值 2026-08 / 8/1~8/20 重提:', r.json()['msg'])
assert r.json()['code'] != 0, '应当被拦'
# 4. 同月份+不同周期 — 应允许(业务上分段上报)
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'output_value', 'month': '2026-08',
'period_start': '2026-08-21', 'period_end': '2026-08-31',
'files': files_for(ov['forms']),
})
print('[3] 产值 2026-08 / 8/21~8/31:', r.json()['msg'])
assert r.json()['code'] == 0, r.text
# 5. 店效人效 2026-08 / 8/1~8/31 — 应成功
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'store_effect_earnings', 'month': '2026-08',
'period_start': '2026-08-01', 'period_end': '2026-08-31',
'files': files_for(se['forms']),
})
print('[4] 店效 2026-08 / 8/1~8/31:', r.json()['msg'])
assert r.json()['code'] == 0, r.text
# 6. 预算达成 2026-08 / 不带周期 — 库内已有 17 号 (is_deleted=0), 应被 2 维拦
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'budget_achievement', 'month': '2026-08',
'files': files_for(ba['forms']),
})
print('[5] 预算达成 2026-08 (无周期):', r.json()['msg'])
assert r.json()['code'] != 0, '应当被 2 维拦'
# 7. 预算达成 2026-09 — 应成功
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'budget_achievement', 'month': '2026-09',
'files': files_for(ba['forms']),
})
print('[6] 预算达成 2026-09:', r.json()['msg'])
assert r.json()['code'] == 0, r.text
# 8. 错误消息是否含周期提示
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'output_value', 'month': '2026-08',
'period_start': '2026-08-01', 'period_end': '2026-08-20',
'files': files_for(ov['forms']),
})
msg = r.json()['msg']
print('[7] 错误消息:', msg)
assert '8/1' in msg or '2026-08-01' in msg, '周期应进入错误消息'
print('\n[全部通过] 4 维校验已生效;同月份不同周期可共存;周期进入提示。')
\ No newline at end of file
......@@ -85,16 +85,55 @@ class Config:
SCHEDULER_ENABLED = os.getenv('SCHEDULER_ENABLED', 'true').lower() == 'true'
SCHEDULER_INTERVAL_SECONDS = int(os.getenv('SCHEDULER_INTERVAL_SECONDS', '60'))
# ---------- 指标系统 API ----------
INDICATOR_API_URL = os.getenv('INDICATOR_API_URL', 'http://dc.glsx.com.cn/data')
INDICATOR_API_TIMEOUT = int(os.getenv('INDICATOR_API_TIMEOUT', '10')) # 秒
INDICATOR_API_RETRY = int(os.getenv('INDICATOR_API_RETRY', '2')) # 失败重试次数
# biz 编码:1=延保 2=轻改 3=权益
INDICATOR_BIZ_WARRANTY = 1
INDICATOR_BIZ_LIGHT_REFORM = 2
INDICATOR_BIZ_EQUITY = 3
# ---------- 通用+权益:直营判定基准商户号 ----------
COMMON_EQUITY_PARTNER_MERCHANT_ID = int(os.getenv('COMMON_EQUITY_PARTNER_MERCHANT_ID', '44206988'))
COMMON_EQUITY_GROUP_ID = int(os.getenv('COMMON_EQUITY_GROUP_ID', '12'))
# ---------- 业务系统 SQL 数据源(嘀加 dj_smartcarlife 库)----------
BIZ_SQL_ENABLED = os.getenv('BIZ_SQL_ENABLED', 'true').lower() == 'true'
BIZ_SQL_DATABASE_URL = os.getenv(
'BIZ_SQL_DATABASE_URL',
'mysql+pymysql://read_dj_smartcarlife:X9RNTOLr@192.168.5.23:3306/dj_smartcarlife?charset=utf8mb4'
)
# ---------- 商户关系 / 品牌数据源(新增门店判定,3 库关联)----------
# scrm_account:platform_merchant_brand(商户↔品牌,merchant_id=main_merchant_id)
# 用户提供的只读账号:read_scrm_account @ 192.168.5.1:3310
SCRM_DATABASE_URL = os.getenv(
'SCRM_DATABASE_URL',
'mysql+pymysql://read_scrm_account:TnZobW2b@192.168.5.1:3310/scrm_account?charset=utf8mb4'
)
# cyb_os:platform_carbrand(bid↔品牌名 字典表,bid 对应 first_brand_id / sec_brand_id)
# 用户提供的只读账号
CYB_OS_DATABASE_URL = os.getenv(
'CYB_OS_DATABASE_URL',
'mysql+pymysql://read_cyb_os:ebf6C0D6@192.168.5.5:3311/cyb_os?charset=utf8mb4'
)
# ---------- 文件上传 ----------
MAX_CONTENT_LENGTH = 100 * 1024 * 1024 # 单文件最大 100M
ALLOWED_EXTS = {'.xlsx', '.xls'} # 仅支持 Excel
UPLOAD_FOLDER = BASE_DIR / 'uploads'
# ---------- 数据表类型配置(第一期仅预算达成数据)----------
# ---------- 数据表类型配置 ----------
# forms: 该类型所需的表单类型清单,前端附件上传区据此动态渲染
# need_period: 是否需要「所属周期」(日期区间)字段;
# True => 新增/重新生成时展示并必填,默认当月1号~最后一天;
# False => 不展示该字段,默认取整月(如:预算达成数据)。
DATA_TABLE_TYPES = {
'budget_achievement': {
'name': '预算达成数据',
'need_period': False,
'support_week': False,
'forms': [
'结算数据汇总表',
'市场费总表',
......@@ -105,8 +144,68 @@ class Config:
'门店资产耗材明细表',
],
},
'future_expansion': {
'name': '未来拓展',
'store_effect_earnings': {
'name': '店效人效及盈利测算',
'need_period': True,
'support_week': False,
'forms': [
'SAAS门店预算分解表',
'关系表',
'店中店交车触客表',
'园区店交车触客表',
'广联主机厂数据表',
'鸿蒙主机厂数据表',
'商务政策表(园区店)',
'商务政策表(店中店)',
'人力成本表',
'二手车收购与销售台账',
'预算达成数据(商务)',
],
},
'output_value': {
'name': '产值达成表',
'need_period': True,
'support_week': False,
'forms': [
'SAAS门店预算分解表',
'关系表',
],
},
# 阿维塔专项:当前仅需上传主机厂数据表(表名暂定,后续若改名只改下方 forms)。
# 注意:此「主机厂数据表」为阿维塔专项独立数据表,格式不保证与现有
# 「鸿蒙主机厂数据表」/「广联主机厂数据表」一致,切勿复用
# report_utils.parse_delivery_table(鸿蒙/广联共用结构);
# 后续接入引擎时须按用户实际提供的附件字段解析并写入阿维塔专属结果表。
# 'avita_special': {
# 'name': '阿维塔专项',
# 'need_period': False,
# 'support_week': False,
# 'forms': [
# '主机厂数据表',
# ],
# },
# 零跑专项 / 岚图专项:无需上传 Excel,need_period=True 需要所属周期
'leapmotor_special': {
'name': '零跑专项',
'need_period': True,
'support_week': False,
'forms': [],
},
'voyah_special': {
'name': '岚图专项',
'need_period': True,
'support_week': False,
'forms': [],
},
# 通用+权益:支持按月/按周粒度,含 3 个附件
# 'common_equity': {
# 'name': '通用+权益',
# 'need_period': True,
# 'support_week': True,
# 'forms': [
# '区域维度数据',
# '汇总区数据',
# '红黄门店数据',
# ],
# },
}
import sys
sys.path.insert(0, "F:/data-report/data-process")
from app import app, db
from models import ReportLightReformInshop, ReportLightReformPark
from sqlalchemy import func, text
with app.app_context():
# how many rows / task linkage
print("== inshop rows ==")
inshop_all = db.session.query(ReportLightReformInshop).all()
print("inshop total rows:", len(inshop_all))
# distinct task_id / period
q = db.session.query(ReportLightReformInshop.task_id,
func.min(ReportLightReformInshop.period_start),
func.max(ReportLightReformInshop.period_end),
func.count(),
func.sum(ReportLightReformInshop.total_output_value))\
.group_by(ReportLightReformInshop.task_id).all()
for tid, ps, pe, cnt, s in q:
print(f" task_id={tid} period={ps}~{pe} rows={cnt} SUM(合计总产值)={float(s) if s is not None else None}")
print("== park rows ==")
park_all = db.session.query(ReportLightReformPark).all()
print("park total rows:", len(park_all))
q2 = db.session.query(ReportLightReformPark.task_id,
func.min(ReportLightReformPark.period_start),
func.max(ReportLightReformPark.period_end),
func.count(),
func.sum(ReportLightReformPark.total_output_value))\
.group_by(ReportLightReformPark.task_id).all()
for tid, ps, pe, cnt, s in q2:
print(f" task_id={tid} period={ps}~{pe} rows={cnt} SUM(合计总产值)={float(s) if s is not None else None}")
# Also check a few sample rows' total_output_value to see if non-zero
print("== sample inshop total_output_value (first 5) ==")
for r in inshop_all[:5]:
print(f" store={r.store_name!r} 合计总产值={float(r.total_output_value) if r.total_output_value is not None else None} 门店总产值={float(r.store_output_value) if r.store_output_value is not None else None}")
print("== sample park total_output_value (first 5) ==")
for r in park_all[:5]:
print(f" store={r.store_name!r} 合计总产值={float(r.total_output_value) if r.total_output_value is not None else None} 门店总产值={float(r.store_output_value) if r.store_output_value is not None else None}")
import openpyxl
path = r"F:/data-report/data-process/outputs/store_effect_summary/门店店效人效汇总表_2026-08.xlsx"
wb = openpyxl.load_workbook(path, data_only=True)
ws = wb['总看板']
# find 1.1产值 / 1.1预算 labels
targets = ['1.1产值','1.1预算','2.1产值','2.3产值','全国经营总产值']
for row in ws.iter_rows():
for c in row:
if c.value in targets:
# value is 2 cells to the right (label, value) per layout A=label B=value
col = c.column
valcell = ws.cell(row=c.row, column=col+1)
print(f"row{c.row} col{col} {c.value!r} -> {valcell.value!r}")
import sys
sys.path.insert(0, "F:/data-report/data-process")
from report_utils import fetch_indicator_data, INDICATOR_BIZ_MAP
bz_l = INDICATOR_BIZ_MAP.get('light_reform')
print("light_reform biz =", bz_l)
ind_11 = fetch_indicator_data('2026-08-01', '2026-08-31', [bz_l], ['A036', 'A075', 'A084']) or {}
print("ind_11 entries:", len(ind_11))
tot_A036 = sum(float((v or {}).get('A036') or 0) for v in ind_11.values())
print("SUM A036 over matched merchants:", tot_A036)
# also test A0018 full
ind_total = fetch_indicator_data('2026-08-01', '2026-08-31', None, ['A0018']) or {}
print("A0018 entries:", len(ind_total), "SUM:", sum(float((v or {}).get('A0018') or 0) for v in ind_total.values()))
import sys
sys.path.insert(0, "F:/data-report/data-process")
import build_store_effect_board as B
from report_utils import fetch_indicator_data, INDICATOR_BIZ_MAP
from decimal import Decimal
src = r"C:/Users/66/Desktop/2026-09报表/店效人效及盈利测算/数据源"
s1, s2 = B.parse_saas(src)
stores_11 = B.uniq(s2)
print("1.1 stores (sheet2 unique):", len(stores_11))
bz_l = INDICATOR_BIZ_MAP.get('light_reform')
ind_11 = fetch_indicator_data('2026-08-01', '2026-08-31', [bz_l], ['A036', 'A075', 'A084']) or {}
def ind_sum(ind_map, stores, code):
t = Decimal('0')
matched = []
for nm, vals in (ind_map or {}).items():
if B.match_any(nm, stores):
v = B.to_decimal((vals or {}).get(code))
t += v
matched.append((nm, float(v)))
return t, matched
t11, matched11 = ind_sum(ind_11, stores_11, 'A036')
print("BOARD 1.1产值 (indicator A036 matched to 1.1 stores) =", float(t11))
print(" matched merchants:", len(matched11))
for nm, v in matched11[:10]:
print(f" {nm!r}: {v}")
import sys
sys.path.insert(0, "F:/data-report/data-process")
import build_store_effect_board as B
from report_utils import fetch_indicator_data, INDICATOR_BIZ_MAP
from decimal import Decimal
src = r"C:/Users/66/Desktop/2026-09报表/店效人效及盈利测算/数据源"
s1, s2 = B.parse_saas(src)
stores_11 = {r['store'] for r in s2 if r['store']}
print("1.1 stores (sheet2 unique):", len(stores_11))
bz_l = INDICATOR_BIZ_MAP.get('light_reform')
ind_11 = fetch_indicator_data('2026-08-01', '2026-08-31', [bz_l], ['A036', 'A075', 'A084']) or {}
def ind_sum(ind_map, stores, code):
t = Decimal('0'); matched = []
for nm, vals in (ind_map or {}).items():
if B.match_any(nm, stores):
v = B.to_decimal((vals or {}).get(code)); t += v; matched.append((nm, float(v)))
return t, matched
t11, matched11 = ind_sum(ind_11, stores_11, 'A036')
print("BOARD 1.1产值 (indicator A036 matched to 1.1 stores) =", float(t11))
print(" matched merchants:", len(matched11))
for nm, v in matched11[:12]:
print(f" {nm!r}: {v}")
# -*- coding: utf-8 -*-
"""探查 taskId=37(阿维塔专项):任务信息 + 附件实际字段。"""
import os
import sys
# 用户级 site-packages(C:/Python314 默认未纳入 sys.path)
SP = r"C:\Users\66\AppData\Roaming\Python\Python314\site-packages"
if SP not in sys.path:
sys.path.insert(0, SP)
import pymysql
import openpyxl
import oss2
from oss_utils import download_file
BASE = r"F:\data-report\data-process"
# ---- 解析 .env ----
def load_env(path):
env = {}
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
env[k.strip()] = v.strip()
return env
env = load_env(os.path.join(BASE, ".env"))
DB = env["data_report"] if False else None
host, port, user, pwd, db = (
env["MYSQL_HOST"], int(env["MYSQL_PORT"]),
env["MYSQL_USER"], env["MYSQL_PASSWORD"], env["MYSQL_DB"],
)
conn = pymysql.connect(host=host, port=port, user=user, password=pwd,
database=db, charset="utf8mb4")
try:
with conn.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute(
"SELECT id,data_table_type,data_table_type_name,month,status,"
"result_file_url,period_start,period_end,creator FROM data_process_task WHERE id=37")
print("=== TASK 37 ===")
for r in cur.fetchall():
print(r)
cur.execute(
"SELECT id,task_id,form_type,file_name,file_url,file_size,clean_status "
"FROM data_process_file WHERE task_id=37 AND is_deleted=0")
print("\n=== FILES ===")
files = cur.fetchall()
for f in files:
print(f)
finally:
conn.close()
# ---- 下载第一个附件并读表头 ----
if files:
f0 = files[0]
local = os.path.join(BASE, "uploads", "explore", "task37.xlsx")
os.makedirs(os.path.dirname(local), exist_ok=True)
download_file(f0["file_url"], local)
print(f"\n=== 下载完成: {local} ===")
wb = openpyxl.load_workbook(local, read_only=True, data_only=True)
print("SHEETS:", wb.sheetnames)
for sn in wb.sheetnames:
ws = wb[sn]
print(f"\n--- SHEET: {sn} (max_row={ws.max_row}, max_col={ws.max_column}) ---")
rows = list(ws.iter_rows(values_only=True))
for i, r in enumerate(rows[:12]):
print(f"r{i}:", r)
print("... total rows:", len(rows))
"""导出 SAAS 门店预算分解表 全量去重门店清单(合并 sheet1+sheet2,按门店名去重,无过滤)。
输出: outputs/store_effect_summary/门店清单_2026-08.xlsx
"""
import os
import sys
import logging
logging.disable(logging.CRITICAL)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from build_store_effect_board import parse_saas, load_brand_category, brand_category
SRC = r'C:/Users/66/Desktop/2026-09报表/店效人效及盈利测算/数据源/'
OUT = r'F:/data-report/data-process/outputs/store_effect_summary/门店清单_2026-08.xlsx'
def main():
s1, s2 = parse_saas(SRC)
exact_map, keys = load_brand_category() # (brand->category, [brand keys])
# 汇总每个门店: 出现sheet、业务类型集合、驻店类型集合、品牌集合
rec = {} # store -> dict
def add(rows, sheet):
for r in rows:
st = r['store']
d = rec.setdefault(st, {'sheets': set(), 'biz': set(), 'res': set(), 'brand': set()})
d['sheets'].add(sheet)
if r['biz_type']:
d['biz'].add(r['biz_type'])
if r['resident_type']:
d['res'].add(r['resident_type'])
if r['brand']:
d['brand'].add(r['brand'])
add(s1, 'sheet1')
add(s2, 'sheet2')
wb = Workbook()
ws = wb.active
ws.title = '门店清单'
head = ['序号', '门店名称', '出现sheet', '业务类型', '驻店类型', '品牌', '豪华/非豪华']
ws.append(head)
head_font = Font(bold=True)
thin = Side(style='thin')
border = Border(left=thin, right=thin, top=thin, bottom=thin)
for c in range(1, len(head) + 1):
ws.cell(row=1, column=c).font = head_font
ws.cell(row=1, column=c).border = border
ws.cell(row=1, column=c).alignment = Alignment(horizontal='center')
for i, store in enumerate(sorted(rec.keys()), 1):
d = rec[store]
biz = '/'.join(sorted(d['biz'])) or '-'
res = '/'.join(sorted(d['res'])) or '-'
brand = '/'.join(sorted(d['brand'])) or '-'
sheets = '+'.join(sorted(d['sheets']))
# 豪华判定: 用与汇总表一致的模糊匹配逻辑
cat = '非豪华'
for b in d['brand']:
if brand_category(b, exact_map, keys) == '豪华':
cat = '豪华'
break
ws.append([i, store, sheets, biz, res, brand, cat])
# 列宽
widths = [6, 46, 12, 12, 14, 22, 12]
for i, w in enumerate(widths, 1):
ws.column_dimensions[get_column_letter(i)].width = w
os.makedirs(os.path.dirname(OUT), exist_ok=True)
wb.save(OUT)
# 统计
both = sum(1 for d in rec.values() if d['sheets'] == {'sheet1', 'sheet2'})
only1 = sum(1 for d in rec.values() if d['sheets'] == {'sheet1'})
only2 = sum(1 for d in rec.values() if d['sheets'] == {'sheet2'})
lux = sum(1 for d in rec.values()
if any(brand_category(b, exact_map, keys) == '豪华' for b in d['brand']))
print(f'去重门店总数: {len(rec)}')
print(f' 仅sheet1: {only1} | 仅sheet2: {only2} | 两表都有: {both}')
print(f' 豪华: {lux} | 非豪华: {len(rec) - lux}')
print(f'已导出 -> {OUT}')
if __name__ == '__main__':
main()
-- ============================================================
-- 红黄门店盈利测算 - 子任务表 DDL
-- 一张主任务对应 4 条子任务,各自追踪 1 张输出表的处理状态
-- ============================================================
DROP TABLE IF EXISTS `data_process_subtask`;
CREATE TABLE `data_process_subtask` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` INT NOT NULL COMMENT '主任务ID(关联 data_process_task.id)',
`output_category` VARCHAR(30) NOT NULL COMMENT '输出类别:warranty=延保 / equity=权益 / inshop=轻改店中店 / park=轻改园区店',
`status` VARCHAR(20) NOT NULL DEFAULT 'PENDING'
COMMENT '子任务状态:PENDING待处理 / PROCESSING处理中 / COMPLETED已完成 / FAILED失败',
`error_msg` VARCHAR(500) DEFAULT '' COMMENT '失败时的错误信息',
`row_count` INT DEFAULT 0 COMMENT '实际写入行数(处理完成后更新)',
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` INT NOT NULL DEFAULT 0 COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` DATETIME DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_subtask_task_category` (`task_id`, `output_category`),
CONSTRAINT `fk_subtask_task` FOREIGN KEY (`task_id`) REFERENCES `data_process_task` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-子任务表(追踪 4 张输出表的独立处理状态)';
-- ============================================================
-- 豪华品牌配置表 DDL
-- 轻改店中店/园区店用于判断门店品牌属于豪华 or 非豪华
-- ============================================================
DROP TABLE IF EXISTS `luxury_brand_config`;
CREATE TABLE `luxury_brand_config` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`brand_name` VARCHAR(100) NOT NULL COMMENT '品牌名称(如 问界/鸿蒙/奔驰/宝马 等)',
`is_luxury` INT NOT NULL DEFAULT 1 COMMENT '是否豪华品牌:1豪华 / 0非豪华',
`remark` VARCHAR(200) DEFAULT '' COMMENT '备注',
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` INT NOT NULL DEFAULT 0 COMMENT '是否删除:0正常 / 1已删除',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_luxury_brand_name` (`brand_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='豪华品牌配置表';
-- 初始化数据(可按需调整 is_luxury 值)
INSERT INTO `luxury_brand_config` (`brand_name`, `is_luxury`, `remark`) VALUES
('问界', 1, 'AITO 旗下豪华品牌'),
('鸿蒙', 1, 'AITO 旗下'),
('智界', 1, '奇瑞合作'),
('享界', 1, '北汽合作'),
('尚界', 1, '江淮合作'),
('尊界', 1, '豪华系列'),
('AITO', 1, '华为高端汽车品牌');
-- =====================================================
-- 2. 轻改日报:新车交付数
-- Python函数: fetch_park_daily_report() SQL 1
-- 场景: scene_type=1 轻改, scene_type=0 延保/权益
-- =====================================================
SELECT merchant_name, SUM(IFNULL(delivery_count, 0)) AS delivery_cnt
FROM dj_car_life_merchant_daily_report_huawei
WHERE deleted_flag = 'N'
AND report_date >= '{{start_date}}'
AND report_date <= '{{end_date}}'
AND scene_type = {{scene_type}}
GROUP BY merchant_name;
-- =====================================================
-- 3. 轻改日报:权益到店 + 售后权益到店
-- Python函数: fetch_park_daily_report() SQL 2
-- 场景: scene_type=1 轻改, scene_type=0 延保/权益
-- =====================================================
SELECT merchant_name,
SUM(IFNULL(equity_to_shop_count, 0)) AS equity_to_shop_count,
SUM(IFNULL(after_sale_equity_to_shop_count, 0)) AS after_sale_equity_to_shop_count
FROM dj_car_life_staff_daily_report_huawei
WHERE deleted_flag = 'N'
AND report_date >= '{{start_date}}'
AND report_date <= '{{end_date}}'
AND scene_type = {{scene_type}}
GROUP BY merchant_name;
-- =====================================================
-- 6. 预估交车数(静态配置表)
-- Python函数: fetch_est_delivery_count()
-- 场景: base_scene_code='100101' 轻改
-- =====================================================
SELECT traffic_party_name,
IF(estimated_delivery_count_per_month IS NULL,
delivery_count,
estimated_delivery_count_per_month) AS final_delivery_count
FROM dj_car_life_merchant_store_info
WHERE base_scene_code = '100101'
AND deleted_flag = 'N'
ORDER BY created_date DESC;
-- =====================================================
-- 7. 查询园区店
-- 场景: base_scene_code='100101' 轻改
-- =====================================================
select traffic_party_name,parking_store_name from dj_car_life_merchant_store_info where base_scene_code ='100101' and deleted_flag ='N'
\ No newline at end of file
No preview for this file type
# 门店自建商品销售数据
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
/* 窗膜 */
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
-- AND t1.supplier_name = '第三方'
AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
THEN t2.order_code END) AS `窗膜(原厂)`,
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
-- AND t1.supplier_name = '广联直营'
AND (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
THEN t2.order_code END) AS `窗膜(副厂)`,
/* 车衣 */
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('车衣','改色膜')
-- AND t1.supplier_name = '第三方'
AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
THEN t2.order_code END) AS `车衣(原厂)`,
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('车衣','改色膜')
-- AND t1.supplier_name = '广联直营'
AND (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
THEN t2.order_code END) AS `车衣(副厂)`,
/* 踏板 */
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name = '踏板'
THEN t2.order_code END) AS `踏板`,
/* 精品 */
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name NOT IN (
'自建商品-太阳膜','天窗冰甲','车衣','改色膜',
'踏板','充电桩','验收一级类目','太阳膜'
)
-- AND t1.supplier_name = '第三方'
AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
THEN t2.order_code END) AS `精品(原厂)`,
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name NOT IN (
'自建商品-太阳膜','天窗冰甲','车衣','改色膜',
'踏板','充电桩','验收一级类目','太阳膜'
)
-- AND t1.supplier_name = '广联直营'
AND (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
THEN t2.order_code END) AS `精品(副厂)`
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
AND t1.upgrade_goods_name NOT LIKE '%(赠)%'
GROUP BY
t2.merchant_id,
t2.merchant_name
# 总成交数
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
count(distinct t1.order_code)
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1 and t1.del_flag='N'
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6
GROUP BY
t2.merchant_id,
t2.merchant_name
#门店总产值
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
SUM(IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0))
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6
GROUP BY
t2.merchant_id,
t2.merchant_name
# 内部结算产值
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
SUM(IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0))
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type =6
GROUP BY
t2.merchant_id,
t2.merchant_name
# 原厂总产值
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
SUM(IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0))
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6 AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
GROUP BY
t2.merchant_id,
t2.merchant_name
# 副厂总产值
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
SUM(IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0))
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6 and (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
GROUP BY
t2.merchant_id,
t2.merchant_name
-- ============================================================================
-- 延保 财务成本分项批量查询
-- 业务系统: dj_smartcarlife
-- 场景: scene_type = 0 (延保/权益)
-- 业务: business_type = 2 (延保)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
-- 关联表:
-- gopa 利润分配主表 (子订单级, order_flag='N' 非汇总)
-- gopa2 利润分配汇总记录 (order_flag='Y', grain_size_type=1, 拿服务费/施工收入/产值)
-- gso 子订单表 (拿嘀加与第三方成本)
-- go 订单表 (scene_type / business_type / merchant_name)
-- po 支付单表 (success_date 周期过滤)
-- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901))
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY, order 级字段用 MAX 取单次值
-- 外层按 merchant_name GROUP BY, 全部 SUM 跨订单聚合
--
-- 字段口径:
-- 商品成本 = upgrade_dj_cost + (shop_traffic_money_calculate_type=1 时才加 upgrade_third_party_cost)
-- 第三方成本仅在 GMV 口径算流量费时才计入
-- 门店分成/流量费 = shop_traffic_money (来自 gopa 主表)
-- 市场费 = 四项费用累计 (fee 子查询, 内层用 MAX 取单次值)
-- 服务费用 = 服务商金额 franchisee_profit_money (来自 gopa2, 内层用 MAX)
-- 门店产值 = total_price (来自 gopa2, 内层用 MAX)
-- 其他费用 = custom_common_cost (来自 gopa2, 内层用 MAX)
-- ============================================================================
-- ========= 查询参数 =========
SET @start_time = '2026-08-01 00:00:00';
SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 0; -- 固定: 0=延保/权益
SET @business_type = 2; -- 2=延保 (1=权益, 另见 权益_财务成本分项.sql)
SELECT
t.merchant_name AS `门店名称`,
-- 商品成本 = 嘀加成本 + 第三方成本(仅 GMV 口径 shop_traffic_money_calculate_type=1)
SUM(t.product_cost) AS `商品成本`,
-- 门店分成/流量费
SUM(t.shop_traffic_money) AS `门店分成`,
-- 市场费 = 四项费用累计 (内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合)
SUM(t.market_fee) AS `市场费`,
-- 服务费用 = 服务商金额
SUM(t.service_fee) AS `服务费用`,
-- 门店产值
SUM(t.store_output_value) AS `门店产值`,
-- 其他费用
SUM(t.other_cost) AS `其他费用`
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(IFNULL(gso.upgrade_dj_cost, 0)
+ IF(gopa.shop_traffic_money_calculate_type = 1,
IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
MAX(IFNULL(gopa2.total_price, 0)) AS store_output_value,
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- 四项费用累计子查询: 日期 + scene_type + business_type 必须与外层同步!
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
AND go.business_type = @business_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND go.business_type = @business_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
-- ============================================================================
-- 权益 财务成本分项批量查询
-- 业务系统: dj_smartcarlife
-- 场景: scene_type = 0 (延保/权益)
-- 业务: business_type = 1 (权益)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
-- 关联表: 同 延保_财务成本分项.sql
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY, order 级字段用 MAX 取单次值
-- 外层按 merchant_name GROUP BY, 全部 SUM 跨订单聚合
--
-- 字段口径: 同延保 (仅 business_type 不同)
-- ============================================================================
-- ========= 查询参数 =========
SET @start_time = '2026-08-01 00:00:00';
SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 0; -- 固定: 0=延保/权益
SET @business_type = 1; -- 1=权益 (2=延保, 另见 延保_财务成本分项.sql)
SELECT
t.merchant_name AS `门店名称`,
-- 商品成本 = 嘀加成本 + 第三方成本(仅 GMV 口径 shop_traffic_money_calculate_type=1)
SUM(t.product_cost) AS `商品成本`,
-- 门店分成/流量费
SUM(t.shop_traffic_money) AS `门店分成`,
-- 市场费 = 四项费用累计 (内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合)
SUM(t.market_fee) AS `市场费`,
-- 服务费用 = 服务商金额
SUM(t.service_fee) AS `服务费用`,
-- 门店产值
SUM(t.store_output_value) AS `门店产值`,
-- 其他费用
SUM(t.other_cost) AS `其他费用`
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(IFNULL(gso.upgrade_dj_cost, 0)
+ IF(gopa.shop_traffic_money_calculate_type = 1,
IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
MAX(IFNULL(gopa2.total_price, 0)) AS store_output_value,
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type + business_type 与外层同步
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
AND go.business_type = @business_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND go.business_type = @business_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
-- ============================================================================
-- 轻改(园区店) 财务成本分项批量查询
-- 业务系统: dj_smartcarlife
-- 场景: scene_type = 1 (轻改)
-- 业务: business_type = 1 OR 2 (轻改不区分)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积 (同店中店)
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY
-- - gopa/gso 级字段 → SUM(同订单多 sub_order_code 要累加)
-- - order 级字段(fee.total) → MAX(避免 JOIN 膨胀)
-- 外层按 merchant_name GROUP BY → 全部 SUM 跨订单聚合
--
-- 与"轻改店中店"的区别:
-- 园区店只消费 4 个字段 (不需要窗膜/车衣/精品/原厂/副厂/施工收入等):
-- 产品成本(财务列表) = dj_order_type != 6 → upgrade_shop_price - base_shop_price
-- 内部结算成本(财务列表) = dj_order_type = 6 → upgrade_shop_price - base_shop_price
-- 流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money
-- 市场费(加权测算) = 四项费用累计 (fee 子查询, 内层用 MAX)
-- 字段口径/表关联与店中店完全相同
-- ============================================================================
-- ========= 查询参数 =========
SET @start_time = '2026-08-01 00:00:00';
SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 1; -- 固定: 1=轻改
SELECT
t.merchant_name AS `门店名称`,
-- ===== 产品成本口径: upgrade_shop_price - base_shop_price =====
-- 外层 SUM 跨订单聚合, 内层已按 merchant_name + order_code 聚合好
SUM(t.product_cost_finance) AS `产品成本(财务列表)`,
SUM(t.internal_settle_cost) AS `内部结算成本(财务列表)`,
SUM(t.store_share) AS `流量费(财务列表)`,
-- order 级字段: 内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合
SUM(t.market_fee) AS `市场费`
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- ===== 内层: 按 merchant_name + order_code GROUP BY =====
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(CASE WHEN gso.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS product_cost_finance,
SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS internal_settle_cost,
SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS store_share,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤)
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
-- ============================================================================
-- 轻改(店中店) 财务成本分项批量查询
-- 业务系统: dj_smartcarlife
-- 场景: scene_type = 1 (轻改)
-- 业务: business_type = 1 OR 2 (轻改不区分权益/延保, 都算)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
-- 关联表:
-- gopa 利润分配主表 (子订单级, order_flag='N' 非汇总)
-- gopa2 利润分配汇总记录 (order_flag='Y', grain_size_type=1)
-- gso 子订单表 (dj_order_type 区分 内部结算=6 / 非内部结算!=6)
-- go 订单表 (scene_type / merchant_name)
-- po 支付单表 (success_date 周期过滤)
-- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901))
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY
-- - gopa/gso 级字段 → SUM(同订单多 sub_order_code 要累加)
-- - order 级字段(fee.total, gopa2.custom_common_cost) → MAX(避免 JOIN 膨胀)
-- 外层按 merchant_name GROUP BY → 全部 SUM 跨订单聚合
--
-- 字段口径 (店中店消费全部 10 项):
-- 产品成本(财务列表) = dj_order_type != 6 (非内部结算) 的 upgrade_shop_price - base_shop_price
-- 内部结算成本(财务列表) = dj_order_type = 6 (内部结算) 的 upgrade_shop_price - base_shop_price
-- 原厂产品成本(财务列表) = dj_order_type != 6 + goods_name LIKE '%AITO%' OR '%HIMA%'
-- 副厂产品成本(财务列表) = dj_order_type != 6 + goods_name NOT LIKE '%AITO%' AND NOT LIKE '%HIMA%'
-- 窗膜成本 = upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
-- 车衣成本 = upgrade_goods_type_name IN ('车衣','改色膜')
-- 精品成本 = upgrade_goods_type_name NOT IN (窗膜/车衣 所有类型)
-- 门店分成/流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money
-- 施工收入 = custom_common_cost (汇总记录 gopa2, 内层用 MAX)
-- 市场费 = 四项费用累计 (fee 子查询, 内层用 MAX)
-- ============================================================================
-- ========= 查询参数 =========
SET @start_time = '2026-08-01 00:00:00';
SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 1; -- 固定: 1=轻改
SELECT
t.merchant_name AS `门店名称`,
-- ===== 产品成本口径: upgrade_shop_price - base_shop_price =====
-- 外层 SUM 跨订单聚合, 内层已按 merchant_name + order_code 聚合好
SUM(t.product_cost_finance) AS `产品成本(财务列表)`,
SUM(t.internal_settle_cost) AS `内部结算成本(财务列表)`,
SUM(t.oe_product_cost) AS `原厂产品成本(财务列表)`,
SUM(t.nonoe_product_cost) AS `副厂产品成本(财务列表)`,
SUM(t.window_film_cost) AS `窗膜成本`,
SUM(t.car_wrap_cost) AS `车衣成本`,
SUM(t.premium_cost) AS `精品成本`,
SUM(t.store_share) AS `门店分成/流量费(财务列表)`,
-- order 级字段: 内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合
SUM(t.construction_income) AS `施工收入`,
SUM(t.market_fee) AS `市场费`
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- ===== 内层: 按 merchant_name + order_code GROUP BY =====
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(CASE WHEN gso.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS product_cost_finance,
SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS internal_settle_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND (gso.upgrade_goods_name LIKE '%AITO%'
OR gso.upgrade_goods_name LIKE '%HIMA%')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS oe_product_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND gso.upgrade_goods_name NOT LIKE '%AITO%'
AND gso.upgrade_goods_name NOT LIKE '%HIMA%'
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS nonoe_product_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS window_film_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN ('车衣','改色膜')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS car_wrap_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN ('自建商品-太阳膜','天窗冰甲','太阳膜','车衣','改色膜','踏板','充电桩','验收一级类目')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS premium_cost,
SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS store_share,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS construction_income,
MAX(IFNULL(fee.total, 0)) AS market_fee
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤)
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
No preview for this file type
# -*- coding: utf-8 -*-
"""
门店店效人效汇总表 - 结果输出独立脚本(第5个 sheet)
============================================================================
用途:不依赖完整调度链路,直接产出「门店店效人效汇总表」单 sheet Excel。
用法:
1) 本地骨架/样例(不需要数据库、不需要任何凭证):
python generate_store_effect_summary.py --demo
python generate_store_effect_summary.py --demo --month 2026-08
2) 基于已计算的任务结果(需要应用运行环境,读取 report_store_effect_summary):
python generate_store_effect_summary.py --task-id <ID> # 本地落盘
python generate_store_effect_summary.py --task-id <ID> --oss # 上传 OSS 并回填
输出位置:
--demo / --task-id(默认): data-process/outputs/store_effect_summary/门店店效人效汇总表_<月份>.xlsx
--oss:上传 OSS,返回 URL,并回填 task.result_file_url
"""
import argparse
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# 与 store_effect_summary_processor.RESULT_COLUMNS 保持一致
RESULT_COLUMNS = [
('门店数', 'store_count', 'int'),
('交车数', 'delivery_total', 'int'),
('触客数', 'touch_total', 'int'),
('成交数', 'deal_total', 'int'),
('产值合计', 'output_value_total', 'amount'),
('成本合计', 'cost_total', 'amount'),
('毛利合计', 'gross_profit_total', 'amount'),
('毛利率', 'gross_profit_rate', 'rate'),
('人力成本', 'labor_cost_total', 'amount'),
('人员数', 'headcount_total', 'int'),
('人均产值', 'per_capita_output', 'amount'),
('人均毛利', 'per_capita_profit', 'amount'),
]
NOTE_TEXT = ('注:整体合计,不分组;业务系统SQL字段在 BIZ_SQL_ENABLED=false 时'
'为0,数字待校准。')
FONT_NAME = '微软雅黑'
def build_workbook(stat_month, end_date_str, values):
"""纯 openpyxl 构建结果表(与处理器 generate_result_excel 同布局)。"""
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
wb = Workbook()
ws = wb.active
ws.title = '门店店效人效汇总表'
header_font = Font(name=FONT_NAME, size=11, bold=True, color='FFFFFF')
header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
title_font = Font(name=FONT_NAME, size=12, bold=True)
cell_font = Font(name=FONT_NAME, size=10)
center = Alignment(horizontal='center', vertical='center', wrap_text=True)
right = Alignment(horizontal='right', vertical='center')
thin = Border(left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin'))
ncol = len(RESULT_COLUMNS)
# 行1 标题
title_cell = ws.cell(
row=1, column=1,
value=f'{stat_month}月门店店效人效汇总表(整体合计,截止"{end_date_str}")')
title_cell.font = title_font
title_cell.alignment = center
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=ncol)
# 行2 表头
for c, (header, _attr, _kind) in enumerate(RESULT_COLUMNS, 1):
cell = ws.cell(row=2, column=c, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = center
cell.border = thin
# 行3 数据(整体合计一行)
for c, (_header, attr, kind) in enumerate(RESULT_COLUMNS, 1):
val = values.get(attr)
cell = ws.cell(row=3, column=c)
if kind == 'int':
try:
cell.value = int(val) if val is not None else 0
cell.number_format = '#,##0'
except (ValueError, TypeError):
cell.value = ''
elif kind == 'amount':
try:
cell.value = float(val) if val is not None else 0.0
cell.number_format = '#,##0.00'
except (ValueError, TypeError):
cell.value = ''
elif kind == 'rate':
try:
cell.value = float(val) if val is not None else 0.0
cell.number_format = '0.00"%"'
except (ValueError, TypeError):
cell.value = ''
else:
cell.value = str(val) if val is not None else ''
cell.font = cell_font
cell.border = thin
cell.alignment = right if kind in ('int', 'amount', 'rate') else center
# 行4 说明
note = ws.cell(row=4, column=1, value=NOTE_TEXT)
note.font = Font(name=FONT_NAME, size=9, italic=True, color='999999')
note.alignment = Alignment(horizontal='left', vertical='center')
ws.merge_cells(start_row=4, start_column=1, end_row=4, end_column=ncol)
for c in range(1, ncol + 1):
from openpyxl.utils import get_column_letter
ws.column_dimensions[get_column_letter(c)].width = 13
ws.freeze_panes = 'A3'
return wb
def run_demo(month):
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'outputs', 'store_effect_summary')
os.makedirs(out_dir, exist_ok=True)
path = os.path.join(out_dir, f'门店店效人效汇总表_{month}.xlsx')
values = {attr: 0 for _, attr, _ in RESULT_COLUMNS}
wb = build_workbook(month, '', values)
wb.save(path)
print(f'[demo] 已生成骨架结果表: {path}')
return path
def run_task(task_id, use_oss):
from app import app
with app.app_context():
from models import DataProcessTask, ReportStoreEffectSummary
from store_effect_summary_processor import StoreEffectSummaryProcessor
task = DataProcessTask.query.filter_by(id=task_id).first()
if not task:
raise SystemExit(f'任务 {task_id} 不存在')
row = ReportStoreEffectSummary.query.filter_by(task_id=task_id).first()
if not row:
raise SystemExit(f'任务 {task_id} 尚未计算(report_store_effect_summary 无数据),'
f'请先由调度器/手动触发计算')
processor = StoreEffectSummaryProcessor()
if use_oss:
url = processor.generate_result_excel(task, row, local_only=False)
task.result_file_url = url
from models import db
db.session.commit()
print(f'[task] 已上传 OSS 并回填 result_file_url: {url}')
else:
path = processor.generate_result_excel(task, row, local_only=True)
print(f'[task] 已生成本地结果表: {path}')
def main():
parser = argparse.ArgumentParser(description='生成门店店效人效汇总表(第5个sheet)')
parser.add_argument('--task-id', type=int, help='基于已计算任务结果生成')
parser.add_argument('--demo', action='store_true', help='生成骨架样例(无需数据库)')
parser.add_argument('--month', default='2026-08', help='--demo 使用的统计月份')
parser.add_argument('--oss', action='store_true', help='--task-id 模式下上传 OSS 并回填')
args = parser.parse_args()
if args.demo:
run_demo(args.month)
elif args.task_id:
run_task(args.task_id, args.oss)
else:
parser.print_help()
if __name__ == '__main__':
main()
......@@ -21,6 +21,8 @@ TASK_COLUMNS = [
('data_table_type', "varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL", '数据表类型编码(如 budget_achievement)'),
('data_table_type_name', "varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT ''", '数据表类型中文名(如 预算达成数据)'),
('month', "varchar(7) COLLATE utf8mb4_unicode_ci NOT NULL", '所属月份,格式 YYYY-MM'),
('period_start', 'date DEFAULT NULL', '所属周期-开始日期(need_period 类型使用,如 2026-08-01)'),
('period_end', 'date DEFAULT NULL', '所属周期-结束日期(need_period 类型使用,如 2026-08-31)'),
('status', "varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'PROCESSING'", '状态:PROCESSING处理中 / COMPLETED已完成 / FAILED失败'),
('error_msg', "varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT ''", '失败原因(状态为 FAILED 时记录)'),
('result_file_url', "varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT ''", '结果 Excel 的 OSS 链接(完成后回填)'),
......@@ -105,6 +107,20 @@ def migrate():
# 回填已有数据的中文名
cur.execute("UPDATE data_process_task SET data_table_type_name='预算达成数据' WHERE data_table_type='budget_achievement'")
# ---- 唯一索引治理(2026-09-02 修订) ----
# 历史:原 uq_task_type_month 仅约束 (data_table_type, month),对"店效/产值"等
# 带所属周期的类型过严——同月份分周期上报会被误拒。改为 (4 维 + 软删感知):
# MariaDB 10.0 不支持 STORED 列上的索引(不支持函数索引),最终方案 = 删除 UNIQUE 约束,
# 仅靠应用层 (app.py task_create) 去重;校验已带 is_deleted=0 过滤,软删行不参与。
# 风险:极端并发下理论可能穿透,但实际用户手点操作可忽略。
cur.execute("SHOW INDEX FROM data_process_task WHERE Key_name LIKE 'uq_%'")
existing_uq = cur.fetchall()
for r in existing_uq:
kname = r[2]
cur.execute(f"ALTER TABLE data_process_task DROP INDEX {kname}")
print(f'[DROP UNIQUE] {kname}')
conn.commit()
print('迁移完成')
finally:
......
No preview for this file type
......@@ -61,6 +61,12 @@ REQUIRED_FORM_TYPES = ['市场费总表', '人力成本统计表', '外施施工
# 该清洗负责建立 biz_budget_achieve 基础行与 GMV,供本脚本成本计算消费。
CLEAN_DATA_TABLE_TYPE = 'budget_achievement'
# 当前处理引擎支持的数据表类型白名单:
# 仅这些类型的 PROCESSING 任务会被调度器自动处理;
# 其余类型(如店效人效及盈利测算、产值达成表等新接入的报表)在单据层创建后
# 保持 PROCESSING 状态,等待对应处理引擎接入后再启用,避免被误判为处理失败。
SUPPORTED_PROCESS_TYPES = {CLEAN_DATA_TABLE_TYPE}
# 市场费 Title 与业务类型的映射关系
TITLE_TO_BIZ = {
"Title2": BIZ_TYPE_1_1,
......@@ -204,12 +210,11 @@ def decrypt_excel_if_needed(file_path):
office_file = msoffcrypto.OfficeFile(f)
if office_file.is_encrypted():
office_file.load_key(password=password)
decrypted = office_file.decrypt()
# 写入临时文件
# 写入临时文件(新版 API: decrypt(outfile=文件对象))
tmp_fd, tmp_path = tempfile.mkstemp(suffix='.xlsx', prefix='decrypted_')
with os.fdopen(tmp_fd, 'wb') as tmp_f:
tmp_f.write(decrypted)
office_file.decrypt(outfile=tmp_f)
logger.info(f"[解密] 成功解密文件,密码: {password}")
return tmp_path, True
......@@ -1309,6 +1314,8 @@ class DataProcessor:
def scan_processing_tasks(self):
"""
查询 data_process_task 表中 status='PROCESSING' 且 is_deleted=0 的任务列表。
仅返回当前引擎支持的数据表类型(SUPPORTED_PROCESS_TYPES);
其余类型(新接入报表等)暂不自动处理,保持 PROCESSING 待对应引擎接入。
返回:任务列表(按创建时间升序)
"""
logger.info("[扫描] 开始扫描待处理任务...")
......@@ -1316,8 +1323,13 @@ class DataProcessor:
DataProcessTask.status == 'PROCESSING',
DataProcessTask.is_deleted == 0
).order_by(DataProcessTask.created_at.asc()).all()
logger.info(f"[扫描] 共发现 {len(tasks)} 个待处理任务")
return tasks
supported = [t for t in tasks if getattr(t, 'data_table_type', None) in SUPPORTED_PROCESS_TYPES]
skipped = [t for t in tasks if getattr(t, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES]
if skipped:
logger.info(f"[扫描] 跳过 {len(skipped)} 个暂不支持自动处理的类型任务: "
f"{sorted({getattr(t, 'data_table_type_name', None) or getattr(t, 'data_table_type', '') for t in skipped})}")
logger.info(f"[扫描] 共发现 {len(tasks)} 个待处理任务,本次处理 {len(supported)} 个")
return supported
def _run_clean_pipeline(self, task):
"""
......@@ -1412,6 +1424,42 @@ class DataProcessor:
if not task:
raise Exception(f"任务不存在: {task_id}")
# 按 data_table_type 路由到对应处理器,避免非预算任务误跑预算达成流水线
if getattr(task, 'data_table_type', None) == 'output_value':
from output_value_processor import OutputValueProcessor
logger.info(f"[处理任务] 路由 output_value 任务 {task_id} 至 OutputValueProcessor")
OutputValueProcessor(app=self.app).process(task)
return
if getattr(task, 'data_table_type', None) == 'store_effect_earnings':
from store_effect_summary_processor import StoreEffectSummaryProcessor
logger.info(f"[处理任务] 路由 store_effect_earnings 任务 {task_id} 至 StoreEffectSummaryProcessor")
StoreEffectSummaryProcessor(app=self.app).process(task)
return
if getattr(task, 'data_table_type', None) == 'avita_special':
from avita_special_processor import AvitaSpecialProcessor
logger.info(f"[处理任务] 路由 avita_special 任务 {task_id} 至 AvitaSpecialProcessor")
AvitaSpecialProcessor(app=self.app).process(task)
return
if getattr(task, 'data_table_type', None) == 'voyah_special':
from voyah_processor import VoyahProcessor
logger.info(f"[处理任务] 路由 voyah_special 任务 {task_id} 至 VoyahProcessor")
VoyahProcessor(app=self.app).process(task)
return
if getattr(task, 'data_table_type', None) == 'leapmotor_special':
from leapmotor_processor import LeapmotorProcessor
logger.info(f"[处理任务] 路由 leapmotor_special 任务 {task_id} 至 LeapmotorProcessor")
LeapmotorProcessor(app=self.app).process(task)
return
# 类型白名单保护:当前引擎仅支持 SUPPORTED_PROCESS_TYPES
if getattr(task, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES:
raise Exception(
f"数据表类型「{task.data_table_type_name or task.data_table_type}」的处理引擎尚未接入,暂不支持自动处理")
logger.info(f"[处理任务] 任务: {task.month} ({task.data_table_type_name})")
# ========== 步骤 a: 将关联文件的 clean_status 从 1 更新为 2(清洗中) ==========
......
This diff could not be displayed because it is too large.
......@@ -390,6 +390,17 @@ tbody tr:hover { background: #f8fafd; }
.modal-file .tip { flex: 1 1 100%; padding-top: 0; }
}
/* 所属周期选择器 */
.period-picker { display: flex; align-items: center; gap: 8px; }
.period-picker input[type=date] {
height: 32px; padding: 0 8px;
border: 1px solid #d0d3da; border-radius: 4px; outline: none;
font-size: 13px; background: #fff;
}
.period-picker input[type=date]:focus { border-color: #185fa5; }
.period-sep { color: #999; font-size: 13px; }
.period-hint { margin-top: 4px; font-size: 12px; color: #999; }
/* 上传 Loading 遮罩 */
.loading-mask {
position: fixed; inset: 0;
......@@ -413,3 +424,29 @@ tbody tr:hover { background: #f8fafd; }
animation: spin .8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* 周期粒度分段按钮(按月/按周 切换) */
.seg-group {
display: inline-flex;
border: 1px solid #dcdfe6;
border-radius: 4px;
overflow: hidden;
background: #fff;
}
.seg-group .seg-btn {
padding: 4px 12px;
font-size: 13px;
border: none;
background: #fff;
color: #606266;
cursor: pointer;
border-right: 1px solid #dcdfe6;
transition: all .15s;
white-space: nowrap;
}
.seg-group .seg-btn:last-child { border-right: none; }
.seg-group .seg-btn:hover { color: #185fa5; }
.seg-group .seg-btn.active {
background: #185fa5;
color: #fff;
}
......@@ -53,6 +53,14 @@
</div>
</div>
<div class="filter-item">
<label>粒度</label>
<div class="seg-group" id="fPeriodTypeGroup">
<button type="button" class="seg-btn active" data-type="">全部</button>
<button type="button" class="seg-btn" data-type="month">按月</button>
<button type="button" class="seg-btn" data-type="week">按周</button>
</div>
</div>
<div class="filter-item">
<label>创建人</label>
<input id="fCreator" maxlength="20" placeholder="请输入">
</div>
......@@ -78,6 +86,7 @@
<th style="width:60px">序号</th>
<th>数据表类型</th>
<th>所属月份</th>
<th>所属周期</th>
<th>创建人</th>
<th>创建时间</th>
<th>更新人</th>
......@@ -146,6 +155,29 @@
</div>
</div>
</div>
<div class="modal-row" id="mPeriodTypeRow" style="display:none">
<label>周期粒度</label>
<div class="modal-control">
<div class="seg-group" id="mPeriodTypeGroup">
<button type="button" class="seg-btn active" data-type="month">按月</button>
<button type="button" class="seg-btn" data-type="week">按周</button>
</div>
<select id="mWeekSelect" style="display:none; margin-left:10px; min-width:140px;">
<!-- 由 JS 动态渲染 W1~W5 -->
</select>
</div>
</div>
<div class="modal-row" id="mPeriodRow" style="display:none">
<label class="required">所属周期</label>
<div class="modal-control">
<div class="period-picker">
<input type="date" id="mPeriodStart">
<span class="period-sep">至</span>
<input type="date" id="mPeriodEnd">
</div>
<div class="period-hint" id="mPeriodHint"></div>
</div>
</div>
<div id="mFiles"></div>
</div>
</div>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!