Commit d9fcf780 by zhouhaibao

feat(data-process): 添加数据处理任务调度器和批量处理功能

- 集成 TaskScheduler 实现定时扫描 PROCESSING 状态任务
- 新增手动触发单个任务处理的 API 接口
- 实现批量处理所有 PROCESSING 状态任务的功能
- 添加任务状态查询和文件清洗进度统计
- 增加调度器启停控制和状态监控接口
- 配置定时任务间隔和启用状态环境变量
- 添加预算达成表模型定义和数据库映射
- 扩展 OSS 工具类支持文件下载和上传功能
- 集成 APScheduler 实现后台定时任务调度
- 添加日志记录和异常处理机制
1 parent 70371d95
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
本期只做页面功能:列表查询、新增、重新生成(编辑)、上传附件、下载结果。 本期只做页面功能:列表查询、新增、重新生成(编辑)、上传附件、下载结果。
登录:账密登录/退出,账号由开发者预置到用户表,无注册入口。 登录:账密登录/退出,账号由开发者预置到用户表,无注册入口。
""" """
import logging
import os import os
import traceback import traceback
from functools import wraps from functools import wraps
...@@ -15,6 +16,8 @@ from werkzeug.security import check_password_hash, generate_password_hash ...@@ -15,6 +16,8 @@ from werkzeug.security import check_password_hash, generate_password_hash
from config import Config from config import Config
from models import DataProcessFile, DataProcessTask, DataProcessUser, db from models import DataProcessFile, DataProcessTask, DataProcessUser, db
from oss_utils import generate_upload_token, save_file from oss_utils import generate_upload_token, save_file
from processor import DataProcessor
from scheduler import TaskScheduler
app = Flask(__name__, static_folder='static', static_url_path='') app = Flask(__name__, static_folder='static', static_url_path='')
app.config.from_object(Config) app.config.from_object(Config)
...@@ -22,6 +25,8 @@ app.secret_key = Config.SECRET_KEY ...@@ -22,6 +25,8 @@ app.secret_key = Config.SECRET_KEY
db.init_app(app) db.init_app(app)
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s')
# ---------------- 工具 ---------------- # ---------------- 工具 ----------------
...@@ -335,6 +340,56 @@ def task_complete(task_id): ...@@ -335,6 +340,56 @@ def task_complete(task_id):
return ok(t.to_dict(), '处理完成') return ok(t.to_dict(), '处理完成')
@app.post('/api/tasks/<int:task_id>/process')
@login_required
def task_process(task_id):
"""手动触发单个任务的数据处理"""
t = DataProcessTask.query.filter_by(id=task_id, is_deleted=0).first()
if not t:
return fail('单据不存在', 404)
if t.status != 'PROCESSING':
return fail(f'仅处理中状态可触发数据处理,当前状态:{t.status}')
processor = DataProcessor(app=app)
try:
processor.process_task(task_id)
t = DataProcessTask.query.filter_by(id=task_id).first()
if t.status == 'COMPLETED':
return ok(t.to_dict(), '数据处理完成')
else:
return fail(f'数据处理失败:{t.error_msg}', 500)
except Exception as e:
return fail(f'系统异常:{e}', 500)
@app.post('/api/tasks/process-all')
@login_required
def task_process_all():
"""批量处理所有 PROCESSING 状态的任务"""
processor = DataProcessor(app=app)
try:
results = processor.process_all()
return ok(results, f'批量处理完成:成功 {results.get("success",0)} 个,失败 {results.get("failed",0)} 个')
except Exception as e:
return fail(f'系统异常:{e}', 500)
@app.get('/api/tasks/<int:task_id>/status')
@login_required
def task_status(task_id):
"""查询任务处理进度(状态 + 各文件清洗状态)"""
t = DataProcessTask.query.filter_by(id=task_id, is_deleted=0).first()
if not t:
return fail('单据不存在', 404)
detail = t.to_dict()
file_stats = {'待清洗': 0, '清洗中': 0, '清洗完成': 0}
for f in detail.get('files', []):
status_map = {1: '待清洗', 2: '清洗中', 3: '清洗完成'}
s = status_map.get(f.get('clean_status', 1), '待清洗')
file_stats[s] += 1
detail['file_stats'] = file_stats
return ok(detail)
@app.post('/api/files/<int:file_id>/clean-status') @app.post('/api/files/<int:file_id>/clean-status')
@login_required @login_required
def file_clean_status(file_id): def file_clean_status(file_id):
...@@ -371,6 +426,40 @@ def unhandled(e): ...@@ -371,6 +426,40 @@ def unhandled(e):
return fail(f'服务异常:{e}', 500) return fail(f'服务异常:{e}', 500)
# ---------------- 定时调度器 ----------------
scheduler = TaskScheduler(app=app)
@app.get('/api/scheduler/status')
@login_required
def scheduler_status():
"""查询定时调度器状态"""
return ok(scheduler.get_status())
@app.post('/api/scheduler/start')
@login_required
def scheduler_start():
"""手动启动定时调度器"""
try:
scheduler.start()
return ok(scheduler.get_status(), '调度器已启动')
except Exception as e:
return fail(f'启动失败:{e}', 500)
@app.post('/api/scheduler/stop')
@login_required
def scheduler_stop():
"""手动停止定时调度器"""
scheduler.stop()
return ok(scheduler.get_status(), '调度器已停止')
if hasattr(DataProcessor, 'init_app'):
DataProcessor.init_app(app)
def ensure_database(): def ensure_database():
"""MySQL:自动创建数据库(若不存在)。SQLite 无需处理。""" """MySQL:自动创建数据库(若不存在)。SQLite 无需处理。"""
uri = app.config['SQLALCHEMY_DATABASE_URI'] uri = app.config['SQLALCHEMY_DATABASE_URI']
...@@ -420,6 +509,15 @@ if __name__ == '__main__': ...@@ -420,6 +509,15 @@ if __name__ == '__main__':
db.create_all() db.create_all()
init_default_user() init_default_user()
print('OSS 模式:', '阿里云 OSS' if Config.OSS_ENABLED else '本地回退(未配置 OSS)') print('OSS 模式:', '阿里云 OSS' if Config.OSS_ENABLED else '本地回退(未配置 OSS)')
app.run(host=os.getenv('FLASK_HOST', '0.0.0.0'),
port=int(os.getenv('FLASK_PORT', '5000')), # 启动定时调度器
debug=os.getenv('FLASK_DEBUG', 'true').lower() == 'true') scheduler.start()
print(f'[调度器] 定时任务已启动(间隔 {Config.SCHEDULER_INTERVAL_SECONDS} 秒)')
try:
app.run(host=os.getenv('FLASK_HOST', '0.0.0.0'),
port=int(os.getenv('FLASK_PORT', '5000')),
debug=os.getenv('FLASK_DEBUG', 'true').lower() == 'true')
finally:
scheduler.stop()
print('[调度器] 定时任务已停止')
...@@ -81,6 +81,10 @@ class Config: ...@@ -81,6 +81,10 @@ class Config:
OSS_PUBLIC_URL = os.getenv('OSS_PUBLIC_URL', '') OSS_PUBLIC_URL = os.getenv('OSS_PUBLIC_URL', '')
OSS_ENABLED = bool(OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET and OSS_BUCKET) OSS_ENABLED = bool(OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET and OSS_BUCKET)
# ---------- 定时任务配置 ----------
SCHEDULER_ENABLED = os.getenv('SCHEDULER_ENABLED', 'true').lower() == 'true'
SCHEDULER_INTERVAL_SECONDS = int(os.getenv('SCHEDULER_INTERVAL_SECONDS', '60'))
# ---------- 文件上传 ---------- # ---------- 文件上传 ----------
MAX_CONTENT_LENGTH = 100 * 1024 * 1024 # 单文件最大 100M MAX_CONTENT_LENGTH = 100 * 1024 * 1024 # 单文件最大 100M
ALLOWED_EXTS = {'.xlsx', '.xls'} # 仅支持 Excel ALLOWED_EXTS = {'.xlsx', '.xls'} # 仅支持 Excel
......
...@@ -110,3 +110,108 @@ class DataProcessUser(db.Model): ...@@ -110,3 +110,108 @@ class DataProcessUser(db.Model):
'nickname': self.nickname, 'nickname': self.nickname,
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else '', 'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else '',
} }
class BizBudgetAchieve(db.Model):
"""预算达成表"""
__tablename__ = 'biz_budget_achieve'
__table_args__ = (
db.UniqueConstraint('task_id', 'stat_month', 'traffic_name', 'business_type', 'brand',
name='uk_task_month_traffic_biz_brand'),
{'comment': '预算达成表'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
stat_month = db.Column(db.String(7), nullable=False, comment='统计月份YYYY-MM')
is_multi_category = db.Column(db.String(10), default='', comment='是否多品类')
traffic_name = db.Column(db.String(200), default='', comment='流量方名称')
business_type = db.Column(db.String(50), default='', comment='业务类型')
entity = db.Column(db.String(100), default='', comment='主体')
brand = db.Column(db.String(50), default='', comment='品牌')
park_store = db.Column(db.String(200), default='', comment='园区店')
service_provider = db.Column(db.String(200), default='', comment='服务商')
order_count = db.Column(db.Integer, default=0, comment='订单数')
gmv = db.Column(db.DECIMAL(15, 2), default=0, comment='GMV')
revenue = db.Column(db.DECIMAL(15, 2), default=0, comment='收入')
cost_gmv = db.Column(db.DECIMAL(15, 2), default=0, comment='成本GMV口径')
cost_gmv_ratio_current = db.Column(db.DECIMAL(5, 2), default=0, comment='本月成本占比')
cost_gmv_ratio_previous = db.Column(db.DECIMAL(5, 2), default=0, comment='上月成本占比')
traffic_fee_gmv = db.Column(db.DECIMAL(15, 2), default=0, comment='流量费GMV口径')
traffic_fee_gmv_ratio_current = db.Column(db.DECIMAL(5, 2), default=0, comment='本月流量费占比')
traffic_fee_gmv_ratio_previous = db.Column(db.DECIMAL(5, 2), default=0, comment='上月流量费占比')
service_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='服务费')
service_fee_ratio_current = db.Column(db.DECIMAL(5, 2), default=0, comment='本月服务费占比')
service_fee_ratio_previous = db.Column(db.DECIMAL(5, 2), default=0, comment='上月服务费占比')
cost_revenue = db.Column(db.DECIMAL(15, 2), default=0, comment='成本收入口径')
traffic_fee_revenue = db.Column(db.DECIMAL(15, 2), default=0, comment='流量费收入口径')
dijia_profit_sharing = db.Column(db.DECIMAL(15, 2), default=0, comment='嘀加分润')
market_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='市场费')
market_fee_ratio_current = db.Column(db.DECIMAL(5, 2), default=0, comment='本月市场费占比')
market_fee_ratio_previous = db.Column(db.DECIMAL(5, 2), default=0, comment='上月市场费占比')
personnel_salary = db.Column(db.DECIMAL(15, 2), default=0, comment='人员工资')
external_construction = db.Column(db.DECIMAL(15, 2), default=0, comment='外援施工')
technician_salary = db.Column(db.DECIMAL(15, 2), default=0, comment='技师工资')
technician_salary_ratio = db.Column(db.DECIMAL(5, 2), default=0, comment='技师工资占比')
marketing_team_salary = db.Column(db.DECIMAL(15, 2), default=0, comment='营销团队工资')
marketing_team_salary_ratio = db.Column(db.DECIMAL(5, 2), default=0, comment='营销团队工资占比')
personnel_salary_ratio_current = db.Column(db.DECIMAL(5, 2), default=0, comment='本月人员工资占比')
personnel_salary_ratio_previous = db.Column(db.DECIMAL(5, 2), default=0, comment='上月人员工资占比')
rent_utilities = db.Column(db.DECIMAL(15, 2), default=0, comment='房租及水电费')
renovation_amortization = db.Column(db.DECIMAL(15, 2), default=0, comment='装修摊销')
store_consumables = db.Column(db.DECIMAL(15, 2), default=0, comment='门店耗材')
f_company_gross_profit = db.Column(db.DECIMAL(15, 2), default=0, comment='F公司毛利')
gross_profit = db.Column(db.DECIMAL(15, 2), default=0, comment='毛利')
gross_profit_ratio_current = db.Column(db.DECIMAL(5, 2), default=0, comment='本月毛利率')
gross_profit_ratio_previous = db.Column(db.DECIMAL(5, 2), default=0, comment='上月毛利率')
created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
def to_dict(self):
return {
'id': self.id,
'task_id': self.task_id,
'stat_month': self.stat_month,
'is_multi_category': self.is_multi_category,
'traffic_name': self.traffic_name,
'business_type': self.business_type,
'entity': self.entity,
'brand': self.brand,
'park_store': self.park_store,
'service_provider': self.service_provider,
'order_count': self.order_count,
'gmv': float(self.gmv) if self.gmv else 0,
'revenue': float(self.revenue) if self.revenue else 0,
'cost_gmv': float(self.cost_gmv) if self.cost_gmv else 0,
'cost_gmv_ratio_current': float(self.cost_gmv_ratio_current) if self.cost_gmv_ratio_current else 0,
'cost_gmv_ratio_previous': float(self.cost_gmv_ratio_previous) if self.cost_gmv_ratio_previous else 0,
'traffic_fee_gmv': float(self.traffic_fee_gmv) if self.traffic_fee_gmv else 0,
'traffic_fee_gmv_ratio_current': float(self.traffic_fee_gmv_ratio_current) if self.traffic_fee_gmv_ratio_current else 0,
'traffic_fee_gmv_ratio_previous': float(self.traffic_fee_gmv_ratio_previous) if self.traffic_fee_gmv_ratio_previous else 0,
'service_fee': float(self.service_fee) if self.service_fee else 0,
'service_fee_ratio_current': float(self.service_fee_ratio_current) if self.service_fee_ratio_current else 0,
'service_fee_ratio_previous': float(self.service_fee_ratio_previous) if self.service_fee_ratio_previous else 0,
'cost_revenue': float(self.cost_revenue) if self.cost_revenue else 0,
'traffic_fee_revenue': float(self.traffic_fee_revenue) if self.traffic_fee_revenue else 0,
'dijia_profit_sharing': float(self.dijia_profit_sharing) if self.dijia_profit_sharing else 0,
'market_fee': float(self.market_fee) if self.market_fee else 0,
'market_fee_ratio_current': float(self.market_fee_ratio_current) if self.market_fee_ratio_current else 0,
'market_fee_ratio_previous': float(self.market_fee_ratio_previous) if self.market_fee_ratio_previous else 0,
'personnel_salary': float(self.personnel_salary) if self.personnel_salary else 0,
'external_construction': float(self.external_construction) if self.external_construction else 0,
'technician_salary': float(self.technician_salary) if self.technician_salary else 0,
'technician_salary_ratio': float(self.technician_salary_ratio) if self.technician_salary_ratio else 0,
'marketing_team_salary': float(self.marketing_team_salary) if self.marketing_team_salary else 0,
'marketing_team_salary_ratio': float(self.marketing_team_salary_ratio) if self.marketing_team_salary_ratio else 0,
'personnel_salary_ratio_current': float(self.personnel_salary_ratio_current) if self.personnel_salary_ratio_current else 0,
'personnel_salary_ratio_previous': float(self.personnel_salary_ratio_previous) if self.personnel_salary_ratio_previous else 0,
'rent_utilities': float(self.rent_utilities) if self.rent_utilities else 0,
'renovation_amortization': float(self.renovation_amortization) if self.renovation_amortization else 0,
'store_consumables': float(self.store_consumables) if self.store_consumables else 0,
'f_company_gross_profit': float(self.f_company_gross_profit) if self.f_company_gross_profit else 0,
'gross_profit': float(self.gross_profit) if self.gross_profit else 0,
'gross_profit_ratio_current': float(self.gross_profit_ratio_current) if self.gross_profit_ratio_current else 0,
'gross_profit_ratio_previous': float(self.gross_profit_ratio_previous) if self.gross_profit_ratio_previous else 0,
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else '',
'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else '',
}
...@@ -96,3 +96,79 @@ def save_file(file_storage, filename): ...@@ -96,3 +96,79 @@ def save_file(file_storage, filename):
key = build_object_key(filename) key = build_object_key(filename)
bucket.put_object(key, file_storage.stream) bucket.put_object(key, file_storage.stream)
return f"{get_oss_base()}/{key}" return f"{get_oss_base()}/{key}"
def get_object_key_from_url(file_url):
"""从完整 URL 中提取 OSS object key(去掉域名前缀,返回相对路径)"""
# 如果是本地回退路径(/uploads/...),直接返回该路径作为 key
if file_url.startswith('/uploads/'):
return file_url
oss_base = get_oss_base()
if file_url.startswith(oss_base + '/'):
return file_url[len(oss_base) + 1:]
return file_url
def download_file(file_url, local_path):
"""从 OSS 下载文件到本地路径。
- 解析 file_url 获取 OSS object key
- 使用 oss2.Bucket.get_object_to_file() 下载
- 本地回退模式:如果 file_url 以 /uploads/ 开头,直接从本地 uploads 目录复制
- 目录不存在时自动创建
- 下载失败时抛出 Exception
"""
# 本地回退模式:从本地 uploads 目录复制
if file_url.startswith('/uploads/'):
source_path = os.path.join(Config.UPLOAD_FOLDER, file_url[len('/uploads/'):])
os.makedirs(os.path.dirname(local_path), exist_ok=True)
if not os.path.exists(source_path):
raise Exception(f"本地文件不存在: {source_path}")
import shutil
shutil.copy2(source_path, local_path)
return
if not Config.OSS_ENABLED:
raise Exception("OSS 未启用,无法下载远程文件")
# 从 URL 中解析 object key
object_key = get_object_key_from_url(file_url)
# 确保本地目录存在
os.makedirs(os.path.dirname(local_path), exist_ok=True)
# 从 OSS 下载
auth = oss2.Auth(Config.OSS_ACCESS_KEY_ID, Config.OSS_ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, Config.OSS_ENDPOINT, Config.OSS_BUCKET)
try:
bucket.get_object_to_file(object_key, local_path)
except Exception as e:
raise Exception(f"OSS 下载失败: {str(e)}")
def upload_file(local_path, object_key=None):
"""上传本地文件到 OSS,返回可访问的 URL。
- 如果未配置 OSS,走本地回退模式(复制到 uploads 目录)
- 配置 OSS 时,使用 oss2.Bucket.put_object() 上传
- 返回可访问的 URL(完整路径)
"""
filename = os.path.basename(local_path)
if not Config.OSS_ENABLED:
# 本地回退:复制到 uploads 目录
folder = os.path.join(Config.UPLOAD_FOLDER, datetime.now().strftime('%Y%m'))
os.makedirs(folder, exist_ok=True)
key = object_key or f"{uuid.uuid4().hex}_{filename}"
dest_path = os.path.join(folder, key)
import shutil
shutil.copy2(local_path, dest_path)
return f"/uploads/{datetime.now().strftime('%Y%m')}/{key}"
# 使用 OSS 上传
if object_key is None:
object_key = build_object_key(filename)
auth = oss2.Auth(Config.OSS_ACCESS_KEY_ID, Config.OSS_ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, Config.OSS_ENDPOINT, Config.OSS_BUCKET)
bucket.put_object(object_key, local_path)
return f"{get_oss_base()}/{object_key}"
# -*- coding: utf-8 -*-
"""
数据处理引擎
============================
功能:处理数据处理任务,解析上传的 Excel 文件,执行成本计算,生成汇总结果。
处理流程:
1. 扫描待处理任务(status='PROCESSING')
2. 下载关联文件到本地临时目录
3. 按表单类型分发解析逻辑
4. 执行成本计算(市场费、外援施工费、人力成本、房租水电施工费)
5. 将结果写入 biz_budget_achieve 表
6. 生成汇总 Excel 并上传到 OSS
7. 更新任务状态
作者:数据处理引擎
"""
import os
import logging
import math
import re
import shutil
from decimal import Decimal, ROUND_HALF_UP
from collections import defaultdict
from datetime import datetime
import pandas as pd
import openpyxl
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from models import DataProcessTask, DataProcessFile, BizBudgetAchieve, db
from oss_utils import download_file, upload_file
from config import Config
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger('DataProcessor')
# ============================================================
# 业务类型常量
# ============================================================
BIZ_TYPE_1_1 = "1.1" # 贴膜等1.1业务
BIZ_TYPE_2_1 = "2.1" # 2.1业务
BIZ_TYPE_2_3 = "2.3" # 2.3业务
# 市场费 Title 与业务类型的映射关系
TITLE_TO_BIZ = {
"Title2": BIZ_TYPE_1_1,
"Title3": BIZ_TYPE_1_1,
"Title4": BIZ_TYPE_1_1,
"Title5": BIZ_TYPE_1_1,
"Title6": BIZ_TYPE_2_1,
"Title7": BIZ_TYPE_2_1,
"Title9": BIZ_TYPE_2_3,
"Title10": BIZ_TYPE_2_3,
}
# 品牌关键词映射
WENJIE_KEYWORDS = ["问界"]
HARMONY_KEYWORDS = ["享界", "智界", "尊界", "尚界"]
# ============================================================
# 通用工具函数
# ============================================================
def safe_decimal(value):
"""
将任意值安全转换为 Decimal 类型。
规则:
- None / NaN / 空字符串 → Decimal("0")
- 数字字符串 → 解析为 Decimal(支持千分位逗号)
- float/int → 通过字符串中转,避免浮点精度丢失
- 其他 → 尝试转换,失败则返回 0
"""
if value is None:
return Decimal("0")
if isinstance(value, float) and math.isnan(value):
return Decimal("0")
if isinstance(value, Decimal):
return value
if isinstance(value, int):
return Decimal(value)
if isinstance(value, float):
return Decimal(repr(value))
s = str(value).strip()
if s == "" or s == "-":
return Decimal("0")
s = s.replace(",", "")
s = s.replace("%", "")
multiplier = Decimal("1")
if s.endswith("万"):
multiplier = Decimal("10000")
s = s[:-1]
elif s.endswith("亿"):
multiplier = Decimal("100000000")
s = s[:-1]
try:
d = Decimal(s)
return d * multiplier
except Exception:
return Decimal("0")
def round_2(value):
"""
将 Decimal 值四舍五入保留2位小数。
"""
if not isinstance(value, Decimal):
value = safe_decimal(value)
return value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
def pct(numerator, denominator):
"""
计算百分比(分子/分母*100),四舍五入保留2位小数。
分母为0时返回 0.00。
"""
if denominator is None or denominator == 0:
return Decimal("0.00")
num = safe_decimal(numerator)
den = safe_decimal(denominator)
if den == 0:
return Decimal("0.00")
return round_2(num / den * Decimal("100"))
def detect_header_row(df_raw, max_scan=15):
"""
自动检测 Excel 表头行位置。
策略:扫描前 max_scan 行,找到非空单元格数量最多的行作为表头。
同时识别是否存在多行表头(Title行)。
"""
if df_raw.empty or len(df_raw) == 0:
return 0, []
best_row = 0
best_count = 0
title_rows = []
scan_range = min(max_scan, len(df_raw))
for idx in range(scan_range):
row = df_raw.iloc[idx]
non_null = sum(
1 for v in row
if pd.notna(v) and str(v).strip() != ""
)
if non_null > best_count:
best_count = non_null
best_row = idx
# 识别 Title 行(表头之前的非空行)
for idx in range(best_row):
row = df_raw.iloc[idx]
first_val = row.iloc[0] if len(row) > 0 else None
if pd.notna(first_val) and str(first_val).strip() != "":
title_rows.append((idx, str(first_val).strip()))
return best_row, title_rows
def find_column(df, *keywords):
"""
在 DataFrame 中查找包含指定关键词的列名(模糊匹配)。
按优先级排序:完全匹配 > 包含匹配
"""
cols = list(df.columns)
# 完全匹配优先
for kw in keywords:
for col in cols:
if str(col).strip() == kw:
return col
# 包含匹配
for kw in keywords:
for col in cols:
if kw in str(col):
return col
return None
def identify_brand(model_text):
"""
根据车型文本识别品牌。
规则:
- 含 "问界" → 问界
- 含 "享界/智界/尊界/尚界" → 鸿蒙
- 无车型信息 → 返回 None(后续按 GMV 分摊)
"""
if model_text is None or (isinstance(model_text, float) and math.isnan(model_text)):
return None
s = str(model_text).strip()
if s == "":
return None
for kw in WENJIE_KEYWORDS:
if kw in s:
return "问界"
for kw in HARMONY_KEYWORDS:
if kw in s:
return "鸿蒙"
return None
def identify_biz_type_by_title(title_text):
"""
根据 Title 文本识别业务类型。
规则:
- Title2/3/4/5 → 1.1
- Title6/7 → 2.1
- Title9/10 → 2.3
"""
if title_text is None:
return None
s = str(title_text).strip()
match = re.match(r"Title\s*(\d+)", s, re.IGNORECASE)
if match:
title_num = int(match.group(1))
title_key = f"Title{title_num}"
return TITLE_TO_BIZ.get(title_key)
title_num_map = {"2": "Title2", "3": "Title3", "4": "Title4", "5": "Title5",
"6": "Title6", "7": "Title7", "9": "Title9", "10": "Title10"}
for num, key in title_num_map.items():
if f"Title{num}" in s or f"title{num}" in s.lower():
return TITLE_TO_BIZ.get(key)
return None
# ============================================================
# 表单类型 → 解析函数映射
# ============================================================
class DataProcessor:
"""
数据处理引擎核心类。
负责扫描待处理任务、下载文件、解析数据、执行成本计算、生成结果。
"""
def __init__(self, app=None):
"""
初始化数据处理器。
参数:
- app: Flask app 实例(可选),用于获取 app context
"""
self.app = app
self._task_files = {} # 缓存任务下载的文件路径
def scan_processing_tasks(self):
"""
查询 data_process_task 表中 status='PROCESSING' 且 is_deleted=0 的任务列表。
返回:任务列表(按创建时间升序)
"""
logger.info("[扫描] 开始扫描待处理任务...")
tasks = DataProcessTask.query.filter(
DataProcessTask.status == 'PROCESSING',
DataProcessTask.is_deleted == 0
).order_by(DataProcessTask.created_at.asc()).all()
logger.info(f"[扫描] 共发现 {len(tasks)} 个待处理任务")
return tasks
def process_all(self):
"""
批量处理所有 PROCESSING 任务,单个失败不影响其他。
"""
logger.info("=" * 60)
logger.info("[批量处理] 开始批量处理所有待处理任务")
logger.info("=" * 60)
tasks = self.scan_processing_tasks()
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process_task(task.id)
success_count += 1
logger.info(f"[批量处理] 任务 {task.id} ({task.month}) 处理成功")
except Exception as e:
fail_count += 1
logger.error(f"[批量处理] 任务 {task.id} ({task.month}) 处理失败: {str(e)}")
# 标记任务为失败
try:
self._mark_task_failed(task.id, str(e))
except Exception as mark_err:
logger.error(f"[批量处理] 标记任务失败状态时出错: {str(mark_err)}")
logger.info("=" * 60)
logger.info(f"[批量处理] 完成!成功 {success_count} 个,失败 {fail_count} 个")
logger.info("=" * 60)
return {'success': success_count, 'failed': fail_count}
def process_task(self, task_id):
"""
处理单个任务的完整流程。
参数:
- task_id: 任务ID
"""
logger.info(f"[处理任务] 开始处理任务 ID: {task_id}")
# 获取任务
task = DataProcessTask.query.filter_by(id=task_id, is_deleted=0).first()
if not task:
raise Exception(f"任务不存在: {task_id}")
logger.info(f"[处理任务] 任务: {task.month} ({task.data_table_type_name})")
# ========== 步骤 a: 将关联文件的 clean_status 从 1 更新为 2(清洗中) ==========
logger.info("[处理任务] 步骤 a: 更新文件状态为清洗中...")
files = DataProcessFile.query.filter_by(task_id=task_id, is_deleted=0).all()
for f in files:
f.clean_status = 2
db.session.commit()
logger.info(f"[处理任务] 已更新 {len(files)} 个文件状态为清洗中")
try:
# ========== 步骤 b: 下载所有关联文件到本地临时目录 ==========
logger.info("[处理任务] 步骤 b: 下载文件到本地临时目录...")
tmp_dir = os.path.join(Config.UPLOAD_FOLDER, 'tmp', str(task_id))
os.makedirs(tmp_dir, exist_ok=True)
downloaded_files = {}
for f in files:
local_path = os.path.join(tmp_dir, f.file_name)
logger.info(f"[处理任务] 下载文件: {f.form_type} -> {local_path}")
try:
download_file(f.file_url, local_path)
downloaded_files[f.form_type] = local_path
except Exception as dl_err:
logger.warning(f"[处理任务] 下载文件失败: {f.form_type}, 错误: {str(dl_err)}")
# 对于必需的文件,下载失败时抛出异常
if f.form_type in ['结算数据汇总表', '市场费总表', '人力成本统计表',
'外施施工费用表', '房租水电费用表']:
raise Exception(f"必需文件下载失败: {f.form_type} - {str(dl_err)}")
logger.info(f"[处理任务] 共下载 {len(downloaded_files)} 个文件")
# ========== 步骤 c: 根据 form_type 分发解析逻辑 ==========
logger.info("[处理任务] 步骤 c: 解析上传的文件...")
# 解析结算数据汇总表(获取 GMV 和产值数据)
settlement_data = None
if '结算数据汇总表' in downloaded_files:
settlement_data = self._parse_settlement(downloaded_files['结算数据汇总表'])
logger.info(f"[处理任务] 结算数据汇总表解析完成,获取 {len(settlement_data)} 条记录")
# 解析市场费
market_results = []
if '市场费总表' in downloaded_files:
market_results = self._parse_market_fee(downloaded_files['市场费总表'])
logger.info(f"[处理任务] 市场费解析完成,共 {len(market_results)} 条记录")
# 解析外援施工费
wage_results = []
if '外施施工费用表' in downloaded_files:
wage_results = self._parse_external_worker_fee(downloaded_files['外施施工费用表'])
logger.info(f"[处理任务] 外援施工费解析完成,共 {len(wage_results)} 条记录")
# 解析人力成本
labor_results = []
if '人力成本统计表' in downloaded_files:
labor_results = self._parse_labor_cost(downloaded_files['人力成本统计表'])
logger.info(f"[处理任务] 人力成本解析完成,共 {len(labor_results)} 条记录")
# 解析房租水电施工费
utility_results = []
if '房租水电费用表' in downloaded_files:
utility_results = self._parse_utility_fee(downloaded_files['房租水电费用表'])
logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录")
# ========== 步骤 d: 执行成本计算 ==========
logger.info("[处理任务] 步骤 d: 执行成本计算...")
summary_data = self._build_cost_summary(
settlement_data, market_results, wage_results, labor_results, utility_results
)
logger.info(f"[处理任务] 成本计算完成,共 {len(summary_data)} 条汇总记录")
# ========== 步骤 e: 将结果写入 biz_budget_achieve 表 ==========
logger.info("[处理任务] 步骤 e: 写入预算达成表...")
self._write_budget_achieve(task.id, task.month, summary_data)
logger.info(f"[处理任务] 已写入 {len(summary_data)} 条预算达成记录")
# ========== 步骤 f: 生成汇总 Excel 并上传到 OSS ==========
logger.info("[处理任务] 步骤 f: 生成汇总 Excel 并上传到 OSS...")
result_file_url = self._generate_and_upload_excel(task.month, summary_data, tmp_dir)
logger.info(f"[处理任务] 结果文件已上传: {result_file_url}")
# ========== 步骤 g: 更新文件 clean_status 为 3(清洗完成) ==========
logger.info("[处理任务] 步骤 g: 更新文件状态为清洗完成...")
for f in files:
f.clean_status = 3
db.session.commit()
# ========== 步骤 h: 更新任务 status 为 COMPLETED,回填 result_file_url ==========
logger.info("[处理任务] 步骤 h: 更新任务状态为已完成...")
task.status = 'COMPLETED'
task.result_file_url = result_file_url
task.error_msg = ''
task.updater = task.updater or task.creator
db.session.commit()
logger.info(f"[处理任务] 任务 {task_id} 处理完成!")
# 清理临时文件
self._cleanup_tmp_dir(tmp_dir)
except Exception as e:
# ========== 步骤 i: 异常时标记任务 status=FAILED,记录 error_msg ==========
logger.error(f"[处理任务] 处理任务 {task_id} 失败: {str(e)}")
db.session.rollback()
self._mark_task_failed(task_id, str(e))
# 清理临时文件
self._cleanup_tmp_dir(tmp_dir)
raise
# ========================================================
# 解析结算数据汇总表(GMV 和产值)
# ========================================================
def _parse_settlement(self, file_path):
"""
解析结算数据汇总表,获取 GMV 和产值数据。
返回:List[dict],每行包含 {流量方名称, 业务类型, 品牌, GMV, 产值}
"""
logger.info(f"[结算数据] 解析文件: {file_path}")
if not os.path.exists(file_path):
logger.warning(f"[结算数据] 文件不存在: {file_path}")
return []
xls = pd.ExcelFile(file_path)
all_results = []
for sheet_name in xls.sheet_names:
df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
header_row, title_rows = detect_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row)
df.columns = [str(col).strip() for col in df.columns]
# 查找关键列
col_flow = find_column(df, "流量方名称", "流量方", "门店", "流量来源")
col_gmv = find_column(df, "GMV", "gmv", "交易额")
col_revenue = find_column(df, "产值", "收入", "营业额")
col_biz = find_column(df, "业务类型", "业务分类")
col_model = find_column(df, "车型", "商品名称", "产品名称", "品牌")
for _, row in df.iterrows():
flow_name = None
if col_flow:
flow_name = row[col_flow]
if flow_name is None or str(flow_name).strip() == "" or str(flow_name).strip() == "nan":
continue
flow_name = str(flow_name).strip()
if flow_name == "":
continue
# 获取业务类型
biz_type = None
if col_biz:
biz_val = str(row[col_biz]).strip() if pd.notna(row[col_biz]) else ""
if "1.1" in biz_val or "贴膜" in biz_val:
biz_type = BIZ_TYPE_1_1
elif "2.1" in biz_val:
biz_type = BIZ_TYPE_2_1
elif "2.3" in biz_val:
biz_type = BIZ_TYPE_2_3
# 获取 GMV
gmv = Decimal("0")
if col_gmv:
gmv = safe_decimal(row[col_gmv])
# 获取产值
revenue = Decimal("0")
if col_revenue:
revenue = safe_decimal(row[col_revenue])
if gmv == 0 and revenue == 0:
continue
# 识别品牌
brand = None
if col_model:
brand = identify_brand(row[col_model])
result_row = {
"流量方名称": flow_name,
"业务类型": biz_type or "未知",
"品牌": brand or "",
"GMV": round_2(gmv),
"产值": round_2(revenue),
}
all_results.append(result_row)
# 按 (流量方, 业务类型, 品牌) 汇总
aggregated = defaultdict(lambda: {"GMV": Decimal("0"), "产值": Decimal("0")})
for r in all_results:
key = (r["流量方名称"], r["业务类型"], r["品牌"])
aggregated[key]["GMV"] += r["GMV"]
aggregated[key]["产值"] += r["产值"]
result = []
for (flow, biz, brand), data in aggregated.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"品牌": brand,
"GMV": round_2(data["GMV"]),
"产值": round_2(data["产值"]),
})
logger.info(f"[结算数据] 解析完成,共 {len(result)} 条汇总记录")
return result
# ========================================================
# 解析市场费表
# ========================================================
def _parse_market_fee(self, file_path):
"""
解析市场费表。
规则:
- 按 Title 分组匹配业务类型(Title2-5→1.1,Title6-7→2.1,Title9-10→2.3)
- 1.1业务:取"市场费"(Title2/3/5) 或 "市场费总额"(Title4)
- 2.1业务:取"市场费"(Title7) 或 "市场费总额"(Title6)
- 2.3业务:取"市场费";商品类别=权益服务/延保-原厂权益归属2.1
- 品牌归属:含"问界"→问界,含"享界/智界/尊界/尚界"→鸿蒙,无车型按GMV分摊
返回:List[dict],每行 {流量方名称, 业务类型, 品牌, 市场费}
"""
logger.info(f"[市场费] 解析文件: {file_path}")
if not os.path.exists(file_path):
logger.warning(f"[市场费] 文件不存在: {file_path}")
return []
xls = pd.ExcelFile(file_path)
all_results = []
for sheet_name in xls.sheet_names:
df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
header_row, title_rows = detect_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row)
df.columns = [str(col).strip() for col in df.columns]
# 从 title_rows 中提取 Title 信息
title_map = {} # {Title号: 业务类型}
for idx, title_text in title_rows:
biz_type = identify_biz_type_by_title(title_text)
if biz_type:
title_map[idx] = biz_type
# 查找关键列
col_flow = find_column(df, "流量方-流量方", "流量方名称", "流量方")
col_fee_market = find_column(df, "市场费")
col_fee_total = find_column(df, "市场费总额")
col_model = find_column(df, "车型", "商品名称", "产品名称")
col_category = find_column(df, "商品类别", "类别")
# 确定当前 sheet 的业务类型(根据 title_rows 中的 Title)
sheet_biz_type = None
for idx, title_text in title_rows:
biz_type = identify_biz_type_by_title(title_text)
if biz_type:
sheet_biz_type = biz_type
break
for _, row in df.iterrows():
flow_name = None
if col_flow:
flow_name = row[col_flow]
if flow_name is None or str(flow_name).strip() == "" or str(flow_name).strip() == "nan":
continue
flow_name = str(flow_name).strip()
if flow_name == "":
continue
# 确定业务类型
biz_type = sheet_biz_type
# 根据业务类型选择取费字段
fee = Decimal("0")
if biz_type == BIZ_TYPE_1_1:
# 1.1业务:Title2/3/5 取"市场费",Title4 取"市场费总额"
# 从 title_text 中判断是 Title4 还是其他
title_num = None
for idx, title_text in title_rows:
if identify_biz_type_by_title(title_text) == BIZ_TYPE_1_1:
match = re.search(r'Title\s*(\d+)', title_text, re.IGNORECASE)
if match:
title_num = int(match.group(1))
break
if title_num == 4:
# Title4 取"市场费总额"
if col_fee_total:
fee = safe_decimal(row[col_fee_total])
else:
# Title2/3/5 取"市场费"
if col_fee_market:
fee = safe_decimal(row[col_fee_market])
elif biz_type == BIZ_TYPE_2_1:
# 2.1业务:Title7 取"市场费",Title6 取"市场费总额"
title_num = None
for idx, title_text in title_rows:
if identify_biz_type_by_title(title_text) == BIZ_TYPE_2_1:
match = re.search(r'Title\s*(\d+)', title_text, re.IGNORECASE)
if match:
title_num = int(match.group(1))
break
if title_num == 6:
# Title6 取"市场费总额"
if col_fee_total:
fee = safe_decimal(row[col_fee_total])
else:
# Title7 取"市场费"
if col_fee_market:
fee = safe_decimal(row[col_fee_market])
elif biz_type == BIZ_TYPE_2_3:
# 2.3业务:取"市场费"
if col_fee_market:
fee = safe_decimal(row[col_fee_market])
else:
# 未知业务类型,尝试取"市场费"
if col_fee_market:
fee = safe_decimal(row[col_fee_market])
if fee == 0:
continue
# 识别品牌
brand = None
if col_model:
brand = identify_brand(row[col_model])
# 2.3→2.1 归属规则:商品类别=权益服务/延保-原厂权益 归属2.1
if col_category:
category = str(row[col_category]).strip() if pd.notna(row[col_category]) else ""
if category in ["权益服务", "延保-原厂权益"]:
biz_type = BIZ_TYPE_2_1
result_row = {
"流量方名称": flow_name,
"业务类型": biz_type or "未知",
"品牌": brand or "未知品牌",
"市场费": round_2(fee),
}
all_results.append(result_row)
if not all_results:
logger.info("[市场费] 无有效数据")
return []
# 按 (流量方, 业务类型, 品牌) 汇总
aggregated = defaultdict(lambda: Decimal("0"))
for r in all_results:
key = (r["流量方名称"], r["业务类型"], r["品牌"])
aggregated[key] += r["市场费"]
# 处理无车型信息的 GMV 分摊(同一流量方+业务类型下,品牌=None 的按 GMV 分摊)
# 这里简化处理:如果同一流量方+业务类型存在多条品牌记录,且有"未知品牌",则按比例分摊
result = []
for (flow, biz, brand), fee in aggregated.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"品牌": brand,
"市场费": round_2(fee),
})
logger.info(f"[市场费] 解析完成,共 {len(result)} 条汇总记录")
return result
# ========================================================
# 解析外援施工费表
# ========================================================
def _parse_external_worker_fee(self, file_path):
"""
解析外援施工费表。
规则:
- 仅1.1业务统计,其他业务类型默认=0
- 按"流量来源"匹配
- 取"总计"列累加
- 多条记录按GMV分摊
返回:List[dict],每行 {流量方名称, 业务类型, 外援施工费}
"""
logger.info(f"[外援施工费] 解析文件: {file_path}")
if not os.path.exists(file_path):
logger.warning(f"[外援施工费] 文件不存在: {file_path}")
return []
xls = pd.ExcelFile(file_path)
raw_records = []
for sheet_name in xls.sheet_names:
df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
header_row, title_rows = detect_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row)
df.columns = [str(col).strip() for col in df.columns]
# 查找关键列
col_source = find_column(df, "流量来源", "流量方名称", "流量来源门店")
col_total = find_column(df, "总计", "合计", "总金额")
col_biz = find_column(df, "业务类型", "业务分类")
col_gmv = find_column(df, "GMV", "产值", "订单金额")
for _, row in df.iterrows():
flow_source = None
if col_source:
flow_source = row[col_source]
if flow_source is None or str(flow_source).strip() == "" or str(flow_source).strip() == "nan":
continue
flow_source = str(flow_source).strip()
# 获取"总计"金额
fee = Decimal("0")
if col_total:
fee = safe_decimal(row[col_total])
if fee == 0:
continue
# 获取 GMV(用于分摊)
gmv = Decimal("0")
if col_gmv:
gmv = safe_decimal(row[col_gmv])
# 外援施工费仅归属 1.1 业务
biz_type = BIZ_TYPE_1_1
if col_biz:
biz_val = str(row[col_biz]).strip() if pd.notna(row[col_biz]) else ""
if biz_val and biz_val not in ["1.1", "贴膜", ""]:
continue
raw_records.append({
"流量方名称": flow_source,
"业务类型": biz_type,
"外援施工费": fee,
"gmv": gmv,
})
if not raw_records:
logger.info("[外援施工费] 无有效数据")
return []
# 按 (流量方, 业务类型) 分组,同一组内按 GMV 分摊
grouped = defaultdict(list)
for r in raw_records:
key = (r["流量方名称"], r["业务类型"])
grouped[key].append(r)
result = []
for (flow, biz), records in grouped.items():
total_fee = sum(r["外援施工费"] for r in records)
total_gmv = sum(r["gmv"] for r in records)
# 如果有多条记录且有 GMV 信息,按 GMV 分摊
if len(records) > 1 and total_gmv > 0:
for r in records:
if r["gmv"] > 0:
share = (r["gmv"] / total_gmv) * total_fee
result.append({
"流量方名称": flow,
"业务类型": biz,
"外援施工费": round_2(share),
})
else:
# 无 GMV 的记录平均分摊
share = total_fee / len(records)
result.append({
"流量方名称": flow,
"业务类型": biz,
"外援施工费": round_2(share),
})
else:
# 单条记录或无 GMV,直接汇总
result.append({
"流量方名称": flow,
"业务类型": biz,
"外援施工费": round_2(total_fee),
})
logger.info(f"[外援施工费] 解析完成,共 {len(result)} 条记录")
return result
# ========================================================
# 解析人力成本表
# ========================================================
def _parse_labor_cost(self, file_path):
"""
解析人力成本表。
规则:
- 仅检核=TRUE的行参与计算
- 1.1业务:岗位=贴膜技师→技师工资;其他→营销团队工资
- 2.1/2.3业务:全部→营销团队工资
- 匹配策略:先"流量方名称+业务类型"→"入驻门店+人员业务归属"
- 回退策略:匹配失败时用"园区店+业务类型"匹配
- 多条记录按GMV分摊
返回:List[dict],每行 {流量方名称, 业务类型, 技师工资, 营销团队工资, __park_store__}
"""
logger.info(f"[人力成本] 解析文件: {file_path}")
if not os.path.exists(file_path):
logger.warning(f"[人力成本] 文件不存在: {file_path}")
return []
try:
xls = pd.ExcelFile(file_path)
except Exception as e:
logger.error(f"[人力成本] 读取失败(可能有密码保护): {e}")
return []
raw_records = []
for sheet_name in xls.sheet_names:
df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
header_row, title_rows = detect_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row)
df.columns = [str(col).strip() for col in df.columns]
# 查找关键列
col_store = find_column(df, "入驻门店", "门店", "流量方名称")
col_park_store = find_column(df, "园区店", "园区")
col_biz = find_column(df, "人员业务归属", "业务归属", "业务类型")
col_position = find_column(df, "岗位", "职位", "工种")
col_salary = find_column(df, "个人本店分摊薪资", "薪资", "工资", "应发工资", "合计")
col_check = find_column(df, "检核", "审核")
col_gmv = find_column(df, "GMV", "产值")
# 如果找不到检核列,尝试定位 AF 列
if col_check is None and len(df.columns) > 31:
col_check = df.columns[31] # AF 列(索引31)
for _, row in df.iterrows():
# 检核列必须为 True
if col_check:
check_val = row[col_check]
if pd.isna(check_val) or str(check_val).strip().upper() not in ["TRUE", "True", "true", "1", "Y", "YES"]:
continue
store_name = None
if col_store:
store_name = row[col_store]
if store_name is None or str(store_name).strip() == "" or str(store_name).strip() == "nan":
continue
store_name = str(store_name).strip()
# 获取园区店
park_store = ""
if col_park_store:
park_store_val = row[col_park_store]
if pd.notna(park_store_val) and str(park_store_val).strip() not in ["", "nan"]:
park_store = str(park_store_val).strip()
# 获取业务类型
biz_type = None
if col_biz:
biz_val = str(row[col_biz]).strip() if pd.notna(row[col_biz]) else ""
if "1.1" in biz_val or "贴膜" in biz_val:
biz_type = BIZ_TYPE_1_1
elif "2.1" in biz_val:
biz_type = BIZ_TYPE_2_1
elif "2.3" in biz_val:
biz_type = BIZ_TYPE_2_3
# 获取岗位
position = None
if col_position:
position = str(row[col_position]).strip() if pd.notna(row[col_position]) else ""
# 获取薪资
salary = Decimal("0")
if col_salary:
salary = safe_decimal(row[col_salary])
if salary == 0:
continue
# 获取 GMV(用于分摊)
gmv = Decimal("0")
if col_gmv:
gmv = safe_decimal(row[col_gmv])
# 按业务类型和岗位分类
technician_salary = Decimal("0")
marketing_salary = Decimal("0")
if biz_type == BIZ_TYPE_1_1:
# 1.1 业务:贴膜技师 → 技师工资;其他 → 营销团队工资
if position and "贴膜技师" in position:
technician_salary = salary
else:
marketing_salary = salary
elif biz_type in [BIZ_TYPE_2_1, BIZ_TYPE_2_3]:
# 2.1/2.3 业务:全部 → 营销团队工资
marketing_salary = salary
else:
marketing_salary = salary
is_park_store = "园区" in store_name or "园区店" in store_name
raw_records.append({
"流量方名称": store_name,
"园区店": park_store,
"业务类型": biz_type or "未知",
"技师工资": technician_salary,
"营销团队工资": marketing_salary,
"gmv": gmv,
"is_park_store": is_park_store,
})
if not raw_records:
logger.info("[人力成本] 无有效数据")
return []
# 按 (流量方名称, 业务类型) 汇总
# 先汇总非园区店数据
direct_grouped = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0"), "gmv_sum": Decimal("0")})
for r in raw_records:
if r["is_park_store"]:
continue
key = (r["流量方名称"], r["业务类型"])
direct_grouped[key]["技师工资"] += r["技师工资"]
direct_grouped[key]["营销团队工资"] += r["营销团队工资"]
direct_grouped[key]["gmv_sum"] += r["gmv"]
# 汇总园区店数据
park_store_grouped = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")})
for r in raw_records:
if not r["is_park_store"]:
continue
# 园区店以 park_store 字段为主键
park_key = r["园区店"] or r["流量方名称"]
key = (park_key, r["业务类型"])
park_store_grouped[key]["技师工资"] += r["技师工资"]
park_store_grouped[key]["营销团队工资"] += r["营销团队工资"]
# 构建结果 - 一级匹配:直接匹配到门店
result = []
for (flow, biz), salaries in direct_grouped.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"技师工资": round_2(salaries["技师工资"]),
"营销团队工资": round_2(salaries["营销团队工资"]),
})
# 二级匹配:园区店回退匹配
# 检查 direct_grouped 中没有的流量方,尝试从 park_store_grouped 中按园区店匹配
matched_park_stores = set()
for (flow, biz), salaries in direct_grouped.items():
# 查找该流量方是否关联某个园区店
for (park_store_key, park_biz), park_salaries in park_store_grouped.items():
if park_biz == biz and park_store_key in flow:
matched_park_stores.add((park_store_key, park_biz))
# 未直接匹配的流量方,使用园区店数据(按GMV分摊)
for (park_store_key, biz), salaries in park_store_grouped.items():
if (park_store_key, biz) not in matched_park_stores:
# 查找使用该园区店的流量方
related_flows = []
for (flow, flow_biz) in direct_grouped.keys():
if flow_biz == biz and park_store_key in flow:
related_flows.append(flow)
if related_flows:
# 按流量方的GMV占比分摊园区店费用
total_gmv = sum(direct_grouped[(f, biz)]["gmv_sum"] for f in related_flows if (f, biz) in direct_grouped)
for flow in related_flows:
if (flow, biz) in direct_grouped:
flow_gmv = direct_grouped[(flow, biz)]["gmv_sum"]
if total_gmv > 0 and flow_gmv > 0:
ratio = flow_gmv / total_gmv
tech_share = salaries["技师工资"] * ratio
mkt_share = salaries["营销团队工资"] * ratio
else:
# 无GMV信息,平均分摊
n = len(related_flows)
tech_share = salaries["技师工资"] / n
mkt_share = salaries["营销团队工资"] / n
# 累加
for r in result:
if r["流量方名称"] == flow and r["业务类型"] == biz:
r["技师工资"] = round_2(r["技师工资"] + tech_share)
r["营销团队工资"] = round_2(r["营销团队工资"] + mkt_share)
break
else:
result.append({
"流量方名称": flow,
"业务类型": biz,
"技师工资": round_2(tech_share),
"营销团队工资": round_2(mkt_share),
})
else:
# 无关联流量方,直接输出园区店数据
result.append({
"流量方名称": park_store_key,
"业务类型": biz,
"技师工资": round_2(salaries["技师工资"]),
"营销团队工资": round_2(salaries["营销团队工资"]),
"__park_store__": True,
})
logger.info(f"[人力成本] 解析完成,共 {len(result)} 条记录")
return result
# ========================================================
# 解析房租水电施工费表
# ========================================================
def _parse_utility_fee(self, file_path):
"""
解析房租水电施工费表。
规则:
- 仅1.1业务统计
- 按"分账对象"匹配"流量方名称"
- 取"房租费用+水电费+施工费用"合计
- 回退策略:匹配失败时按"分账对象"匹配"园区店"
- 多条记录按GMV分摊
返回:List[dict],每行 {流量方名称, 业务类型, 房租及水电费, __park_store__}
"""
logger.info(f"[房租水电] 解析文件: {file_path}")
if not os.path.exists(file_path):
logger.warning(f"[房租水电] 文件不存在: {file_path}")
return []
xls = pd.ExcelFile(file_path)
raw_records = []
for sheet_name in xls.sheet_names:
df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
header_row, title_rows = detect_header_row(df_raw)
df = pd.read_excel(file_path, sheet_name=sheet_name, header=header_row)
df.columns = [str(col).strip() for col in df.columns]
# 查找关键列
col_target = find_column(df, "分账对象", "分账门店", "承担方", "流量方名称")
col_rent = find_column(df, "房租费用", "房租", "租金")
col_water = find_column(df, "水电费", "水电", "水费")
col_construction = find_column(df, "施工费用", "施工费", "装修费")
col_biz = find_column(df, "业务类型", "业务分类")
col_gmv = find_column(df, "GMV", "产值")
for _, row in df.iterrows():
target = None
if col_target:
target = row[col_target]
if target is None or str(target).strip() == "" or str(target).strip() == "nan":
continue
target = str(target).strip()
# 仅统计 1.1 业务
if col_biz:
biz_val = str(row[col_biz]).strip() if pd.notna(row[col_biz]) else ""
if biz_val and "1.1" not in biz_val and "贴膜" not in biz_val:
continue
# 合计 = 房租 + 水电 + 施工
rent = safe_decimal(row[col_rent]) if col_rent else Decimal("0")
water = safe_decimal(row[col_water]) if col_water else Decimal("0")
construction = safe_decimal(row[col_construction]) if col_construction else Decimal("0")
total_fee = rent + water + construction
if total_fee == 0:
continue
# 获取 GMV(用于分摊)
gmv = Decimal("0")
if col_gmv:
gmv = safe_decimal(row[col_gmv])
# 判断是否为园区店
is_park_store = "园区" in target or "园区店" in target
raw_records.append({
"流量方名称": target,
"业务类型": BIZ_TYPE_1_1,
"房租及水电费": total_fee,
"gmv": gmv,
"is_park_store": is_park_store,
})
if not raw_records:
logger.info("[房租水电] 无有效数据")
return []
# 按 (流量方, 业务类型) 分组
# 先汇总非园区店数据
direct_grouped = defaultdict(lambda: {"房租及水电费": Decimal("0"), "gmv_sum": Decimal("0")})
for r in raw_records:
if r["is_park_store"]:
continue
key = (r["流量方名称"], r["业务类型"])
direct_grouped[key]["房租及水电费"] += r["房租及水电费"]
direct_grouped[key]["gmv_sum"] += r["gmv"]
# 汇总园区店数据
park_store_grouped = defaultdict(lambda: Decimal("0"))
for r in raw_records:
if not r["is_park_store"]:
continue
key = (r["流量方名称"], r["业务类型"])
park_store_grouped[key] += r["房租及水电费"]
# 构建结果
result = []
for (flow, biz), data in direct_grouped.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"房租及水电费": round_2(data["房租及水电费"]),
})
# 园区店回退匹配
# 检查 direct_grouped 中没有的流量方,使用园区店数据
matched_park_stores = set()
for (flow, biz) in direct_grouped.keys():
for (park_flow, park_biz) in park_store_grouped.keys():
if park_biz == biz and park_flow in flow:
matched_park_stores.add((park_flow, park_biz))
# 未直接匹配的流量方,使用园区店数据(按GMV分摊)
for (park_flow, biz), fee in park_store_grouped.items():
if (park_flow, biz) not in matched_park_stores:
# 查找使用该园区店的流量方
related_flows = []
for (flow, flow_biz) in direct_grouped.keys():
if flow_biz == biz and park_flow in flow:
related_flows.append(flow)
if related_flows:
# 按流量方的GMV占比分摊园区店费用
total_gmv = sum(direct_grouped[(f, biz)]["gmv_sum"] for f in related_flows if (f, biz) in direct_grouped)
for flow in related_flows:
if (flow, biz) in direct_grouped:
flow_gmv = direct_grouped[(flow, biz)]["gmv_sum"]
if total_gmv > 0 and flow_gmv > 0:
ratio = flow_gmv / total_gmv
share = fee * ratio
else:
# 无GMV信息,平均分摊
n = len(related_flows)
share = fee / n
# 累加
found = False
for r in result:
if r["流量方名称"] == flow and r["业务类型"] == biz:
r["房租及水电费"] = round_2(r["房租及水电费"] + share)
found = True
break
if not found:
result.append({
"流量方名称": flow,
"业务类型": biz,
"房租及水电费": round_2(share),
})
else:
# 无关联流量方,直接输出园区店数据
result.append({
"流量方名称": park_flow,
"业务类型": biz,
"房租及水电费": round_2(fee),
"__park_store__": True,
})
logger.info(f"[房租水电] 解析完成,共 {len(result)} 条记录")
return result
# ========================================================
# 构建成本汇总表
# ========================================================
def _build_cost_summary(self, settlement_data, market_results, wage_results, labor_results, utility_results):
"""
生成成本汇总表。
综合结算数据、市场费、外援施工费、人力成本、房租水电施工费,
按流量方/业务类型/品牌维度汇总各项费用,并计算占比。
返回:List[dict],每条记录对应 biz_budget_achieve 的一行
"""
logger.info("[成本汇总] 开始生成成本汇总...")
# ---------- 收集 GMV 和产值数据 ----------
# 从结算数据构建 GMV 和产值映射
settlement_map = {} # (流量方, 业务类型, 品牌) -> {GMV, 产值}
if settlement_data:
for s in settlement_data:
key = (s["流量方名称"], s["业务类型"], s["品牌"] or "")
settlement_map[key] = {
"GMV": s["GMV"],
"产值": s["产值"],
}
# 如果没有结算数据,从市场费结果中收集流量方信息用于占位
if not settlement_data:
logger.warning("[成本汇总] 无结算数据,使用占位值")
for m in market_results:
key = (m["流量方名称"], m["业务类型"], m["品牌"] or "")
if key not in settlement_map:
settlement_map[key] = {
"GMV": Decimal("0"),
"产值": Decimal("0"),
}
# ---------- 收集所有唯一键 ----------
all_keys = set()
# 市场费:含品牌维度
for r in market_results:
brand = r.get("品牌", "")
all_keys.add((r["流量方名称"], r["业务类型"], brand or ""))
# 外援施工费
for r in wage_results:
all_keys.add((r["流量方名称"], r["业务类型"], ""))
# 人力成本(非园区店)
for r in labor_results:
if r.get("__park_store__"):
continue
all_keys.add((r["流量方名称"], r["业务类型"], ""))
# 房租水电(非园区店)
for r in utility_results:
if r.get("__park_store__"):
continue
all_keys.add((r["流量方名称"], r["业务类型"], ""))
# 结算数据中的所有键
for key in settlement_map.keys():
all_keys.add(key)
# ---------- 按键汇总各项费用 ----------
summary = []
for flow_name, biz_type, brand in sorted(all_keys):
# 获取 GMV 和产值
settle_key = (flow_name, biz_type, brand)
if settle_key in settlement_map:
gmv = settlement_map[settle_key]["GMV"]
revenue = settlement_map[settle_key]["产值"]
else:
# 尝试无品牌匹配
settle_key_no_brand = (flow_name, biz_type, "")
if settle_key_no_brand in settlement_map:
gmv = settlement_map[settle_key_no_brand]["GMV"]
revenue = settlement_map[settle_key_no_brand]["产值"]
else:
gmv = Decimal("0")
revenue = Decimal("0")
row = {
"流量方名称": flow_name,
"业务类型": biz_type,
"品牌": brand,
"GMV": gmv,
"产值": revenue,
"市场费": Decimal("0"),
"外援施工": Decimal("0"),
"技师工资": Decimal("0"),
"营销团队工资": Decimal("0"),
"人员工资": Decimal("0"),
"房租及水电费": Decimal("0"),
}
# --- 匹配市场费 ---
for m in market_results:
m_brand = m.get("品牌", "")
if (m["流量方名称"] == flow_name
and m["业务类型"] == biz_type
and (m_brand == brand or not brand or not m_brand)):
row["市场费"] += m["市场费"]
# --- 匹配外援施工费 ---
for w in wage_results:
if w["流量方名称"] == flow_name and w["业务类型"] == biz_type:
row["外援施工"] += w["外援施工费"]
# --- 匹配人力成本 ---
for l in labor_results:
if l.get("__park_store__"):
continue
if l["流量方名称"] == flow_name and l["业务类型"] == biz_type:
row["技师工资"] += l["技师工资"]
row["营销团队工资"] += l["营销团队工资"]
# --- 匹配房租水电 ---
for u in utility_results:
if u.get("__park_store__"):
continue
if u["流量方名称"] == flow_name and u["业务类型"] == biz_type:
row["房租及水电费"] += u["房租及水电费"]
# 计算人员工资小计
row["人员工资"] = row["技师工资"] + row["营销团队工资"]
# ---------- 计算占比 ----------
# 市场费本月占比 = 市场费/GMV*100%
row["市场费本月占比"] = pct(row["市场费"], gmv)
# 市场费上月占比(暂用占位,需要上月数据)
row["市场费上月占比"] = pct(row["市场费"], gmv)
# 技师工资占比 = 技师工资/产值*100%
row["技师工资占比"] = pct(row["技师工资"], revenue)
# 营销团队工资占比 = 营销团队工资/产值*100%
row["营销团队工资占比"] = pct(row["营销团队工资"], revenue)
# 人员工资本月占比 = 人员工资/产值*100%
row["人员工资本月占比"] = pct(row["人员工资"], revenue)
# 人员工资上月占比(占位)
row["人员工资上月占比"] = pct(row["人员工资"], revenue)
# 计算毛利 = GMV - 市场费 - 人员工资 - 房租及水电费
# 注意:这里的成本计算简化处理
gross_profit = gmv - row["市场费"] - row["人员工资"] - row["房租及水电费"]
row["毛利"] = round_2(gross_profit)
# 毛利率 = 毛利/GMV*100%
row["毛利率本月"] = pct(gross_profit, gmv)
row["毛利率上月"] = pct(gross_profit, gmv)
# 四舍五入所有金额
for key in ["市场费", "外援施工", "技师工资", "营销团队工资", "人员工资", "房租及水电费", "毛利"]:
row[key] = round_2(row[key])
summary.append(row)
# ---------- 处理园区店 GMV 分摊 ----------
park_labor = [r for r in labor_results if r.get("__park_store__")]
park_utility = [r for r in utility_results if r.get("__park_store__")]
if park_labor or park_utility:
logger.info(f"[成本汇总] 处理园区店分摊:人力成本 {len(park_labor)} 条,房租水电 {len(park_utility)} 条")
# 收集各流量方 GMV(用于分摊)
flow_gmv = {}
for s in summary:
key = (s["流量方名称"], s["业务类型"])
flow_gmv[key] = s["GMV"]
# 分摊人力成本中的园区店费用
for park_item in park_labor:
biz = park_item["业务类型"]
tech_fee = park_item["技师工资"]
marketing_fee = park_item["营销团队工资"]
candidates = [s for s in summary if s["业务类型"] == biz]
if not candidates:
continue
cand_gmv = {c["流量方名称"]: c["GMV"] for c in candidates}
total_cand_gmv = sum(cand_gmv.values())
if total_cand_gmv == 0:
continue
for c in candidates:
ratio = c["GMV"] / total_cand_gmv if total_cand_gmv > 0 else Decimal("0")
c["技师工资"] += round_2(tech_fee * ratio)
c["营销团队工资"] += round_2(marketing_fee * ratio)
c["人员工资"] = c["技师工资"] + c["营销团队工资"]
# 分摊房租水电中的园区店费用
for park_item in park_utility:
biz = park_item["业务类型"]
util_fee = park_item["房租及水电费"]
candidates = [s for s in summary if s["业务类型"] == biz]
if not candidates:
continue
cand_gmv = {c["流量方名称"]: c["GMV"] for c in candidates}
total_cand_gmv = sum(cand_gmv.values())
if total_cand_gmv == 0:
continue
for c in candidates:
ratio = c["GMV"] / total_cand_gmv if total_cand_gmv > 0 else Decimal("0")
c["房租及水电费"] += round_2(util_fee * ratio)
# 重新计算占比和毛利
for s in summary:
gmv = s["GMV"]
revenue = s["产值"]
s["市场费本月占比"] = pct(s["市场费"], gmv)
s["技师工资占比"] = pct(s["技师工资"], revenue)
s["营销团队工资占比"] = pct(s["营销团队工资"], revenue)
s["人员工资本月占比"] = pct(s["人员工资"], revenue)
# 重新计算毛利
gross_profit = gmv - s["市场费"] - s["人员工资"] - s["房租及水电费"]
s["毛利"] = round_2(gross_profit)
s["毛利率本月"] = pct(gross_profit, gmv)
# ---------- 格式化输出 ----------
logger.info(f"[成本汇总] 生成完成,共 {len(summary)} 行数据")
return summary
# ========================================================
# 写入预算达成表
# ========================================================
def _write_budget_achieve(self, task_id, month, summary_data):
"""
将汇总数据写入 biz_budget_achieve 表。
使用业务唯一键 (task_id, stat_month, traffic_name, business_type, brand) 进行 Upsert:
- 存在则更新所有业务字段
- 不存在则新增记录
"""
# 业务字段列表(不包含 id, created_at)
update_columns = [
'is_multi_category', 'entity', 'park_store', 'service_provider',
'order_count', 'gmv', 'revenue',
'cost_gmv', 'cost_gmv_ratio_current', 'cost_gmv_ratio_previous',
'traffic_fee_gmv', 'traffic_fee_gmv_ratio_current', 'traffic_fee_gmv_ratio_previous',
'service_fee', 'service_fee_ratio_current', 'service_fee_ratio_previous',
'cost_revenue', 'traffic_fee_revenue', 'dijia_profit_sharing',
'market_fee', 'market_fee_ratio_current', 'market_fee_ratio_previous',
'personnel_salary', 'external_construction',
'technician_salary', 'technician_salary_ratio',
'marketing_team_salary', 'marketing_team_salary_ratio',
'personnel_salary_ratio_current', 'personnel_salary_ratio_previous',
'rent_utilities', 'renovation_amortization', 'store_consumables',
'f_company_gross_profit', 'gross_profit',
'gross_profit_ratio_current', 'gross_profit_ratio_previous',
]
# 构建批量参数
params_list = []
for row in summary_data:
params = {
'task_id': task_id,
'stat_month': month,
'traffic_name': row["流量方名称"],
'business_type': row["业务类型"],
'brand': row.get("品牌", "") or "",
'is_multi_category': row.get("is_multi_category", ""),
'entity': row.get("entity", ""),
'park_store': row.get("park_store", ""),
'service_provider': row.get("service_provider", ""),
'order_count': row.get("order_count", 0),
'gmv': float(row.get("GMV", Decimal("0"))),
'revenue': float(row.get("产值", Decimal("0"))),
'market_fee': float(row.get("市场费", Decimal("0"))),
'market_fee_ratio_current': float(row.get("市场费本月占比", Decimal("0"))),
'market_fee_ratio_previous': float(row.get("市场费上月占比", Decimal("0"))),
'personnel_salary': float(row.get("人员工资", Decimal("0"))),
'external_construction': float(row.get("外援施工", Decimal("0"))),
'technician_salary': float(row.get("技师工资", Decimal("0"))),
'technician_salary_ratio': float(row.get("技师工资占比", Decimal("0"))),
'marketing_team_salary': float(row.get("营销团队工资", Decimal("0"))),
'marketing_team_salary_ratio': float(row.get("营销团队工资占比", Decimal("0"))),
'personnel_salary_ratio_current': float(row.get("人员工资本月占比", Decimal("0"))),
'personnel_salary_ratio_previous': float(row.get("人员工资上月占比", Decimal("0"))),
'rent_utilities': float(row.get("房租及水电费", Decimal("0"))),
'gross_profit': float(row.get("毛利", Decimal("0"))),
'gross_profit_ratio_current': float(row.get("毛利率本月", Decimal("0"))),
'gross_profit_ratio_previous': float(row.get("毛利率上月", Decimal("0"))),
# 预留字段默认0
'cost_gmv': 0,
'cost_gmv_ratio_current': 0,
'cost_gmv_ratio_previous': 0,
'traffic_fee_gmv': 0,
'traffic_fee_gmv_ratio_current': 0,
'traffic_fee_gmv_ratio_previous': 0,
'service_fee': 0,
'service_fee_ratio_current': 0,
'service_fee_ratio_previous': 0,
'cost_revenue': 0,
'traffic_fee_revenue': 0,
'dijia_profit_sharing': 0,
'renovation_amortization': 0,
'store_consumables': 0,
'f_company_gross_profit': 0,
}
params_list.append(params)
# 构建 INSERT ... ON DUPLICATE KEY UPDATE SQL
table = BizBudgetAchieve.__tablename__
all_columns = ['task_id', 'stat_month', 'traffic_name', 'business_type', 'brand'] + update_columns
placeholders = ', '.join(['%s'] * len(all_columns))
update_clause = ', '.join([f'{col}=VALUES({col})' for col in update_columns])
sql = (
f"INSERT INTO {table} ({', '.join(all_columns)}) VALUES ({placeholders}) "
f"ON DUPLICATE KEY UPDATE {update_clause}"
)
# 执行批量 Upsert
conn = db.engine.connect()
try:
trans = conn.begin()
for params in params_list:
values = [params[col] for col in all_columns]
conn.execute(sql, values)
trans.commit()
logger.info(f"[写入] Upsert 成功,共处理 {len(params_list)} 条预算达成记录")
except Exception as e:
trans.rollback()
logger.error(f"[写入] Upsert 失败: {str(e)}")
raise
finally:
conn.close()
# ========================================================
# 生成汇总 Excel 并上传
# ========================================================
def _generate_and_upload_excel(self, month, summary_data, tmp_dir):
"""
生成汇总 Excel 文件并上传到 OSS。
返回:OSS 文件 URL
"""
logger.info(f"[Excel] 开始生成汇总 Excel,月份: {month}")
# 生成临时 Excel 文件
excel_path = os.path.join(tmp_dir, f"预算达成汇总_{month}.xlsx")
# 定义表头
headers = [
"流量方名称", "业务类型", "品牌", "GMV", "产值",
"市场费", "市场费本月占比", "市场费上月占比",
"外援施工", "技师工资", "技师工资占比", "营销团队工资",
"营销团队工资占比", "人员工资", "人员工资本月占比",
"人员工资上月占比", "房租及水电费", "毛利", "毛利率本月", "毛利率上月",
]
# 创建 Excel 工作簿
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "预算达成汇总"
# 定义样式
header_font = Font(name="微软雅黑", size=11, bold=True)
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
header_font_white = Font(name="微软雅黑", size=11, bold=True, color="FFFFFF")
cell_font = Font(name="微软雅黑", size=10)
center_align = Alignment(horizontal="center", vertical="center")
right_align = Alignment(horizontal="right", vertical="center")
thin_border = Border(
left=Side(style="thin"),
right=Side(style="thin"),
top=Side(style="thin"),
bottom=Side(style="thin"),
)
# 写入表头
for col_idx, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col_idx, value=header)
cell.font = header_font_white
cell.fill = header_fill
cell.alignment = center_align
cell.border = thin_border
# 占比列名
pct_cols = {"市场费本月占比", "市场费上月占比", "技师工资占比",
"营销团队工资占比", "人员工资本月占比", "人员工资上月占比",
"毛利率本月", "毛利率上月"}
# 数值列名
numeric_cols = {"GMV", "产值", "市场费", "外援施工", "技师工资",
"营销团队工资", "人员工资", "房租及水电费", "毛利"}
# 写入数据行
for row_idx, row_data in enumerate(summary_data, 2):
for col_idx, header_name in enumerate(headers, 1):
cell = ws.cell(row=row_idx, column=col_idx)
# 获取对应字段值
value = row_data.get(header_name, Decimal("0"))
if value is None:
value = Decimal("0")
# 格式化
if header_name in pct_cols:
cell.value = float(round_2(safe_decimal(value)))
cell.number_format = "0.00"
elif header_name in numeric_cols:
cell.value = float(round_2(safe_decimal(value)))
cell.number_format = "#,##0.00"
else:
cell.value = str(value) if value else ""
# 对齐
if header_name in pct_cols or header_name in numeric_cols:
cell.alignment = right_align
else:
cell.alignment = center_align
cell.font = cell_font
cell.border = thin_border
# 设置列宽
column_widths = {
"流量方名称": 18, "业务类型": 10, "品牌": 8,
"GMV": 14, "产值": 14,
"市场费": 12, "市场费本月占比": 14, "市场费上月占比": 14,
"外援施工": 12, "技师工资": 12, "技师工资占比": 12,
"营销团队工资": 14, "营销团队工资占比": 14,
"人员工资": 12, "人员工资本月占比": 14, "人员工资上月占比": 14,
"房租及水电费": 14, "毛利": 14, "毛利率本月": 12, "毛利率上月": 12,
}
for col_idx, header_name in enumerate(headers, 1):
width = column_widths.get(header_name, 12)
ws.column_dimensions[openpyxl.utils.get_column_letter(col_idx)].width = width
# 冻结首行
ws.freeze_panes = "A2"
# 保存 Excel
wb.save(excel_path)
logger.info(f"[Excel] Excel 文件生成完成: {excel_path}")
# 上传到 OSS
object_key = f"data-process/{datetime.now().strftime('%Y%m%d')}/budget_achieve_{month}.xlsx"
file_url = upload_file(excel_path, object_key)
logger.info(f"[Excel] 已上传到 OSS: {file_url}")
return file_url
# ========================================================
# 辅助方法
# ========================================================
def _mark_task_failed(self, task_id, error_msg):
"""
标记任务为失败状态,记录错误信息。
"""
try:
task = DataProcessTask.query.filter_by(id=task_id).first()
if task:
task.status = 'FAILED'
task.error_msg = error_msg[:500] # 限制长度
db.session.commit()
logger.info(f"[标记失败] 任务 {task_id} 已标记为失败")
except Exception as e:
logger.error(f"[标记失败] 更新任务失败状态时出错: {str(e)}")
db.session.rollback()
raise
def _cleanup_tmp_dir(self, tmp_dir):
"""
清理临时目录。
"""
try:
if os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir)
logger.info(f"[清理] 临时目录已清理: {tmp_dir}")
except Exception as e:
logger.warning(f"[清理] 清理临时目录时出错: {str(e)}")
# ============================================================
# 便捷函数
# ============================================================
def create_processor(app=None):
"""
创建数据处理器实例。
"""
return DataProcessor(app)
\ No newline at end of file \ No newline at end of file
# -*- coding: utf-8 -*-
"""
定时调度器模块
================
功能:定时扫描 PROCESSING 状态的任务,自动调用 DataProcessor 进行处理。
特点:
- 支持通过配置文件调整执行间隔
- 使用互斥锁防止并发执行
- 提供 start() / stop() 生命周期管理
- 提供状态查询接口
作者:数据处理引擎
"""
import threading
import logging
from datetime import datetime
from config import Config
logger = logging.getLogger('TaskScheduler')
class TaskScheduler:
"""
数据处理定时调度器。
周期性扫描 data_process_task 表中 status='PROCESSING' 的任务,
调用 DataProcessor.process_all() 执行清洗入库。
"""
def __init__(self, app=None):
"""
初始化调度器。
参数:
- app: Flask app 实例(用于获取数据库上下文)
"""
self.app = app
self._scheduler = None
self._lock = threading.Lock()
self._running = False
self._is_processing = False
self._last_run_time = None
self._last_run_result = None
def start(self):
"""
启动定时调度器。
若 APScheduler 未安装,则使用 threading.Timer 作为后备方案。
"""
if self._running:
logger.warning("[调度器] 已在运行中,忽略 start() 调用")
return
if not Config.SCHEDULER_ENABLED:
logger.info("[调度器] 定时任务未启用 (SCHEDULER_ENABLED=false),跳过启动")
return
interval = Config.SCHEDULER_INTERVAL_SECONDS
try:
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
self._scheduler = BackgroundScheduler(daemon=True)
self._scheduler.add_job(
self._execute_scan,
trigger=IntervalTrigger(seconds=interval),
id='data_process_scan',
name='数据处理任务扫描',
replace_existing=True,
)
self._scheduler.start()
self._running = True
logger.info(f"[调度器] APScheduler 已启动,执行间隔: {interval}秒")
except ImportError:
logger.warning("[调度器] APScheduler 未安装,使用 threading 后备方案")
self._running = True
self._thread_timer(interval)
except Exception as e:
logger.error(f"[调度器] 启动失败: {str(e)}")
raise
def stop(self):
"""
停止定时调度器。
"""
if not self._running:
return
self._running = False
if self._scheduler:
try:
self._scheduler.shutdown(wait=False)
logger.info("[调度器] APScheduler 已停止")
except Exception as e:
logger.error(f"[调度器] 停止 APScheduler 时出错: {str(e)}")
logger.info("[调度器] 调度器已完全停止")
def get_status(self):
"""
获取调度器当前状态。
返回: dict,包含运行状态、上次执行时间等信息
"""
return {
'enabled': Config.SCHEDULER_ENABLED,
'running': self._running,
'interval_seconds': Config.SCHEDULER_INTERVAL_SECONDS,
'is_processing': self._is_processing,
'last_run_time': self._last_run_time.strftime('%Y-%m-%d %H:%M:%S') if self._last_run_time else None,
'last_run_result': self._last_run_result,
}
def _thread_timer(self, interval):
"""
threading 后备方案:使用 Timer 实现定时循环。
"""
if not self._running:
return
self._execute_scan()
if self._running:
timer = threading.Timer(interval, self._thread_timer, args=[interval])
timer.daemon = True
timer.start()
def _execute_scan(self):
"""
执行扫描处理任务。
使用互斥锁防止并发执行。
"""
if not self._lock.acquire(blocking=False):
logger.debug("[调度器] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info("[调度器] 开始扫描 PROCESSING 任务...")
with self.app.app_context():
from processor import DataProcessor
processor = DataProcessor(app=self.app)
result = processor.process_all()
self._last_run_result = result
logger.info(f"[调度器] 扫描完成:成功 {result.get('success', 0)} 个,失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[调度器] 扫描执行异常: {str(e)}")
self._last_run_result = {'error': str(e)}
finally:
self._is_processing = False
self._lock.release()
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!