Commit 152eef42 by 周立明

产值达成表基础数据

1 parent 88614b4b
...@@ -30,6 +30,7 @@ from scheduler import ( ...@@ -30,6 +30,7 @@ from scheduler import (
EquityReportScheduler, EquityReportScheduler,
LightReformInshopScheduler, LightReformInshopScheduler,
LightReformParkScheduler, LightReformParkScheduler,
OutputValueScheduler,
) )
app = Flask(__name__, static_folder='static', static_url_path='') app = Flask(__name__, static_folder='static', static_url_path='')
...@@ -513,6 +514,7 @@ warranty_scheduler = WarrantyReportScheduler(app=app) ...@@ -513,6 +514,7 @@ warranty_scheduler = WarrantyReportScheduler(app=app)
equity_scheduler = EquityReportScheduler(app=app) equity_scheduler = EquityReportScheduler(app=app)
light_reform_inshop_scheduler = LightReformInshopScheduler(app=app) light_reform_inshop_scheduler = LightReformInshopScheduler(app=app)
light_reform_park_scheduler = LightReformParkScheduler(app=app) light_reform_park_scheduler = LightReformParkScheduler(app=app)
output_value_scheduler = OutputValueScheduler(app=app)
ALL_SCHEDULERS = [ ALL_SCHEDULERS = [
('budget_achievement', scheduler), ('budget_achievement', scheduler),
...@@ -520,6 +522,7 @@ ALL_SCHEDULERS = [ ...@@ -520,6 +522,7 @@ ALL_SCHEDULERS = [
('equity_report', equity_scheduler), ('equity_report', equity_scheduler),
('light_reform_inshop', light_reform_inshop_scheduler), ('light_reform_inshop', light_reform_inshop_scheduler),
('light_reform_park', light_reform_park_scheduler), ('light_reform_park', light_reform_park_scheduler),
('output_value', output_value_scheduler),
] ]
......
...@@ -525,6 +525,70 @@ class ReportLightReformInshop(db.Model): ...@@ -525,6 +525,70 @@ class ReportLightReformInshop(db.Model):
deleted_at = db.Column(db.DateTime, nullable=True) deleted_at = db.Column(db.DateTime, nullable=True)
class SaasBusinessAchievement(db.Model):
"""产值达成表(data_table_type=output_value 的输出表,对应结果表 A~O 列)"""
__tablename__ = 'saas_business_achievement'
__table_args__ = (
db.UniqueConstraint('task_id', 'business_type', 'region_operator',
name='uk_saas_task_biz_operator'),
{'comment': '产值达成表'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='自增主键')
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
stat_month = db.Column(db.String(7), nullable=False, comment='统计月份 YYYY-MM')
start_date = db.Column(db.String(10), nullable=False, comment='统计周期开始时间 YYYY-MM-DD')
end_date = db.Column(db.String(10), nullable=False, comment='统计周期结束时间 YYYY-MM-DD')
business_type = db.Column(db.String(20), nullable=False, comment='业务类型(A列):2.1+2.3 或 1.1')
manager = db.Column(db.String(50), comment='大区经理(B列):由 C 列查关系表 E→D 得到')
region_operator = db.Column(db.String(50), nullable=False, comment='区域运营(C列):SAAS表区域运营')
online_operator = db.Column(db.String(50), comment='线上运营(D列):默认为空')
operated_stores = db.Column(db.Integer, default=0, comment='运营门店数(E列):按门店去重')
direct_stores = db.Column(db.Integer, default=0, comment='直营门店数(F列):驻店类型=直营,按门店去重')
daily_new_gmv = db.Column(db.DECIMAL(15, 2), comment='当日新增GMV(G列):接口获取,暂未接入')
existing_budget = db.Column(db.DECIMAL(15, 2), comment='存量门店预算(H列):存量明细的预估产值(纠偏)合计')
existing_actual = db.Column(db.DECIMAL(15, 2), comment='存量门店实际达成(I列):接口获取,暂未接入')
existing_rate = db.Column(db.DECIMAL(5, 2), comment='存量目标达成率%(J列)=I/H*100')
new_budget = db.Column(db.DECIMAL(15, 2), comment='新店预算(K列):新增明细的预估产值(纠偏)合计')
new_actual = db.Column(db.DECIMAL(15, 2), comment='新店实际达成(L列):接口获取,暂未接入')
new_rate = db.Column(db.DECIMAL(5, 2), comment='新店目标达成率%(M列)=L/K*100')
total_actual_gmv = db.Column(db.DECIMAL(15, 2), comment='实际达成GMV合计(N列)=I+L')
total_rate = db.Column(db.DECIMAL(5, 2), comment='总预算达成率%(O列)=(I+L)/(H+K)*100')
created_at = db.Column(db.DateTime, default=datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
def to_dict(self):
def _f(v):
return float(v) if v is not None else None
return {
'id': self.id,
'task_id': self.task_id,
'stat_month': self.stat_month,
'start_date': self.start_date,
'end_date': self.end_date,
'business_type': self.business_type,
'manager': self.manager,
'region_operator': self.region_operator,
'online_operator': self.online_operator,
'operated_stores': self.operated_stores,
'direct_stores': self.direct_stores,
'daily_new_gmv': _f(self.daily_new_gmv),
'existing_budget': _f(self.existing_budget),
'existing_actual': _f(self.existing_actual),
'existing_rate': _f(self.existing_rate),
'new_budget': _f(self.new_budget),
'new_actual': _f(self.new_actual),
'new_rate': _f(self.new_rate),
'total_actual_gmv': _f(self.total_actual_gmv),
'total_rate': _f(self.total_rate),
}
class ReportLightReformPark(db.Model): class ReportLightReformPark(db.Model):
"""轻改-园区店汇总表(Excel Sheet「园区店汇总」69 列全量存储)""" """轻改-园区店汇总表(Excel Sheet「园区店汇总」69 列全量存储)"""
__tablename__ = 'report_light_reform_park' __tablename__ = 'report_light_reform_park'
......
...@@ -1423,6 +1423,13 @@ class DataProcessor: ...@@ -1423,6 +1423,13 @@ class DataProcessor:
if not task: if not task:
raise Exception(f"任务不存在: {task_id}") 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
# 类型白名单保护:当前引擎仅支持 SUPPORTED_PROCESS_TYPES # 类型白名单保护:当前引擎仅支持 SUPPORTED_PROCESS_TYPES
if getattr(task, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES: if getattr(task, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES:
raise Exception( raise Exception(
......
...@@ -1326,6 +1326,48 @@ def fuzzy_match_store(store_name, biz_sql_map): ...@@ -1326,6 +1326,48 @@ def fuzzy_match_store(store_name, biz_sql_map):
if store_name in mn or mn in store_name: if store_name in mn or mn in store_name:
return val return val
return None return None
# 产值达成表(output_value)解析辅助
# =====================================================
def find_header_row_by_keyword(df_raw, keyword='区域运营', max_scan=6):
"""在前 max_scan 行中查找包含 keyword 的表头行索引,找不到返回 0。
比 find_header_row 更精准:产值表的标题行也含「门店」,用「区域运营」定位表头更可靠。
"""
for i in range(min(max_scan, len(df_raw))):
row_vals = [str(v) for v in df_raw.iloc[i].tolist() if v is not None]
if any(keyword in v for v in row_vals):
return i
return 0
def pick_sheet_by_keywords(file_path, keywords, fallback_index=0):
"""按 sheet 名关键字挑选工作表;未命中则按索引回退(兼容月份变化的表名)。"""
try:
xls = pd.ExcelFile(file_path)
except Exception as e:
logger.warning(f"[产值达成] 打开 Excel 失败 {file_path}: {e}")
return fallback_index
for name in xls.sheet_names:
if all(kw in str(name) for kw in keywords):
logger.info(f"[产值达成] 命中 sheet: {name}")
return name
names = xls.sheet_names
if len(names) > fallback_index:
logger.warning(f"[产值达成] 未按关键字 {keywords} 命中 sheet,回退索引 {fallback_index} → {names[fallback_index]}")
return names[fallback_index]
return names[0]
def _locate_store_column(columns):
"""定位「门店」列:优先精确同名,其次含「门店」但排除「门店类型/门店数量」。"""
for c in columns:
if str(c).strip() == '门店':
return c
for c in columns:
s = str(c)
if '门店' in s and '类型' not in s and '数量' not in s:
return c
return None
def fetch_park_daily_report(start_date, end_date, scene_type=1): def fetch_park_daily_report(start_date, end_date, scene_type=1):
...@@ -1413,3 +1455,110 @@ def fetch_park_daily_report(start_date, end_date, scene_type=1): ...@@ -1413,3 +1455,110 @@ def fetch_park_daily_report(start_date, end_date, scene_type=1):
conn.close() conn.close()
except Exception: except Exception:
pass pass
def parse_saas_achieve_details(file_path, sheet_keywords, fallback_index=0):
"""
解析 SAAS门店预算分解表 的指定 sheet,返回门店明细列表。
参数:
sheet_keywords: sheet 名需同时包含的关键字,如 ['权益延保', '门店'] / ['轻改', '门店']
fallback_index: 关键字未命中时的 sheet 索引回退
返回 list[dict],每条字段:
region_operator 区域运营(结果表 C 列取值来源)
store_name 门店(E/F 列按此列去重计数)
resident_type 驻店类型(直营 / 服务商 …)
store_kind 存量 / 新增(sheet1「存量/新店」列、sheet2「性质」列)
budget_corrected 预估产值(纠偏)—— H/K 列预算求和口径
biz_type 业务类型明细值(2.1 / 2.3 / 1.1)
"""
sheet = pick_sheet_by_keywords(file_path, sheet_keywords, fallback_index)
try:
df_raw = pd.read_excel(file_path, sheet_name=sheet, header=None)
header_row = find_header_row_by_keyword(df_raw, '区域运营')
df = pd.read_excel(file_path, sheet_name=sheet, header=header_row)
except Exception as e:
logger.warning(f"[产值达成] 读取 sheet[{sheet}] 失败: {e}")
return []
df.columns = [str(c).replace('\n', '').strip() for c in df.columns]
cols = list(df.columns)
col_region = next((c for c in cols if '区域运营' in c), None)
col_resident = next((c for c in cols if '驻店类型' in c), None)
col_store = _locate_store_column(cols)
col_kind = next((c for c in cols if ('存量/新店' in c) or ('性质' in c)), None)
col_budget = next((c for c in cols if '纠偏' in c), None)
col_biz = next((c for c in cols if c.strip() == '业务类型'), None)
if not col_region:
logger.warning(f"[产值达成] sheet[{sheet}] 未找到「区域运营」列,跳过")
return []
if not col_budget:
logger.warning(f"[产值达成] sheet[{sheet}] 未找到「预估产值(纠偏)」列,预算将按 0 计")
records = []
for _, row in df.iterrows():
ro = str(row.get(col_region, '') or '').strip()
if not ro or ro in ('nan', 'None'):
continue
store = str(row.get(col_store, '') or '').strip() if col_store else ''
kind_raw = str(row.get(col_kind, '') or '').strip() if col_kind else ''
if '新增' in kind_raw or '新店' in kind_raw:
kind = '新增'
elif '存量' in kind_raw:
kind = '存量'
else:
kind = kind_raw
records.append({
'region_operator': ro,
'store_name': store,
'resident_type': str(row.get(col_resident, '') or '').strip() if col_resident else '',
'store_kind': kind,
'budget_corrected': _to_decimal(row.get(col_budget, 0)) if col_budget else Decimal('0'),
'biz_type': str(row.get(col_biz, '') or '').strip() if col_biz else '',
})
logger.info(f"[产值达成] sheet[{sheet}] 解析 {len(records)} 行明细,"
f"区域运营 {len(set(r['region_operator'] for r in records))} 个")
return records
def parse_operator_relation(file_path):
"""
解析关系表,返回 {业务线: {区域经理(E列): 大区经理(D列)}}。
仅用于产值达成表:按 C 列区域运营 → 关系表 E 列(区域经理) 匹配 → 取 D 列(大区经理) 作为结果表 B 列。
"""
try:
df = pd.read_excel(file_path)
except Exception as e:
logger.warning(f"[产值达成-关系表] 读取失败 {file_path}: {e}")
return {}
df.columns = [str(c).replace('\n', '').strip() for c in df.columns]
cols = list(df.columns)
col_line = next((c for c in cols if '业务线' in c), None)
col_manager = next((c for c in cols if '大区经理' in c), None)
col_operator = next((c for c in cols if '区域经理' in c), None)
if not (col_manager and col_operator):
logger.warning("[产值达成-关系表] 未找到「大区经理」或「区域经理」列")
return {}
result = {}
for _, row in df.iterrows():
operator = str(row.get(col_operator, '') or '').strip()
if not operator or operator in ('nan', 'None'):
continue
manager = str(row.get(col_manager, '') or '').strip()
line = str(row.get(col_line, '') or '').strip() if col_line else ''
result.setdefault(line, {})
# 同一区域经理可能对应多省份多行,保留首个非空大区经理
if operator not in result[line] or not result[line][operator] or result[line][operator] in ('/', 'nan'):
result[line][operator] = manager
total = sum(len(v) for v in result.values())
logger.info(f"[产值达成-关系表] 解析 {total} 个区域经理,业务线: {list(result.keys())}")
return result
...@@ -328,4 +328,37 @@ class LightReformInshopScheduler(NewReportScheduler): ...@@ -328,4 +328,37 @@ class LightReformInshopScheduler(NewReportScheduler):
class LightReformParkScheduler(NewReportScheduler): class LightReformParkScheduler(NewReportScheduler):
"""轻改-园区店汇总独立调度器""" """轻改-园区店汇总独立调度器"""
OUTPUT_CATEGORY = 'park' OUTPUT_CATEGORY = 'park'
JOB_NAME = 'light_reform_park_scan'
\ No newline at end of file \ No newline at end of file
JOB_NAME = 'light_reform_park_scan'
class OutputValueScheduler(NewReportScheduler):
"""产值达成表独立调度器(扫描 output_value 类型任务)"""
OUTPUT_CATEGORY = 'output_value'
JOB_NAME = 'output_value_scan'
def _execute_scan(self):
if not self._lock.acquire(blocking=False):
logger.debug(f"[{self.JOB_NAME}] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info(f"[{self.JOB_NAME}] 开始扫描 output_value 待处理任务")
with self.app.app_context():
from output_value_processor import OutputValueProcessor
processor = OutputValueProcessor(app=self.app)
result = processor.scan_output_value()
self._last_run_result = result
logger.info(f"[{self.JOB_NAME}] 扫描完成:成功 {result.get('success', 0)} 个,"
f"失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 扫描执行异常: {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!