Commit e33f8378 by 江名洋

feat(harmony): 产值数据改为数据库查询并拆分赔付系数字段

1 parent fcb97ad0
# -*- coding: utf-8 -*-
"""
文件名: app/api/auth.py
职责: 用户认证相关 API 路由(登录、验证码、登出、当前用户信息)。
注意: 不要删除这个注释。
"""
import base64
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from app.core.security import create_access_token, token_remaining_seconds
from app.db.session import get_db
from app.schemas.user import CaptchaRequiredResponse, LoginRequest, LoginResponse, UserResponse
from app.services.auth_service import AuthService
router = APIRouter()
def _get_client_ip(request: Request) -> Optional[str]:
"""获取客户端真实 IP"""
forwarded = request.headers.get("x-forwarded-for")
if forwarded:
return forwarded.split(",")[0].strip()
return request.client.host if request.client else None
@router.post("/auth/login", response_model=LoginResponse)
async def login(
request: Request,
response: Response,
data: LoginRequest,
db: Session = Depends(get_db),
):
"""账号密码登录接口"""
user, message = AuthService.authenticate(
db,
username=data.username,
password=data.password,
captcha_code=data.captcha_code,
captcha_token=data.captcha_token,
ip=_get_client_ip(request),
)
need_captcha = AuthService.is_captcha_required(db, data.username)
if not user:
return JSONResponse(
status_code=200,
content={
"status": "error",
"message": message,
"need_captcha": need_captcha,
"username": data.username,
},
)
# 登录成功,创建并设置 Cookie
access_token = create_access_token(user.username, remember=data.remember)
max_age = token_remaining_seconds(access_token)
response.set_cookie(
key="access_token",
value=access_token,
httponly=True,
max_age=max_age,
samesite="lax",
path="/",
)
return {
"status": "success",
"message": message,
"need_captcha": False,
"username": user.username,
}
@router.post("/auth/logout")
async def logout(response: Response):
"""登出接口"""
response.delete_cookie(key="access_token", path="/")
return {"status": "success", "message": "已退出登录"}
@router.get("/auth/me", response_model=UserResponse)
async def me(request: Request, db: Session = Depends(get_db)):
"""获取当前登录用户信息"""
token = request.cookies.get("access_token")
user = AuthService.get_current_user_from_token(db, token)
if not user:
raise HTTPException(status_code=401, detail="未登录或登录已过期")
return user
@router.get("/auth/captcha-required")
async def captcha_required(username: Optional[str] = None, db: Session = Depends(get_db)):
"""查询账号是否需要验证码"""
required = AuthService.is_captcha_required(db, username)
return CaptchaRequiredResponse(required=required)
@router.get("/auth/captcha")
async def get_captcha(db: Session = Depends(get_db)):
"""获取图形验证码"""
token, image_bytes = AuthService.generate_captcha(db)
b64 = base64.b64encode(image_bytes).decode("utf-8")
return {
"status": "success",
"token": token,
"image": f"data:image/png;base64,{b64}",
}
...@@ -410,17 +410,15 @@ async def download_harmony_template(template_type: str): ...@@ -410,17 +410,15 @@ async def download_harmony_template(template_type: str):
_harmony_store_file = None _harmony_store_file = None
_harmony_factory_file = None _harmony_factory_file = None
_harmony_value_file = None
@router.post("/harmony/upload") @router.post("/harmony/upload")
async def harmony_upload( async def harmony_upload(
store_file: Optional[UploadFile] = File(None), store_file: Optional[UploadFile] = File(None),
factory_file: Optional[UploadFile] = File(None), factory_file: Optional[UploadFile] = File(None),
value_file: Optional[UploadFile] = File(None),
): ):
"""上传鸿蒙门店兜底配置、主机厂数据、产值表""" """上传鸿蒙门店兜底配置、主机厂数据(产值表数据从数据库自动查询)"""
global _harmony_store_file, _harmony_factory_file, _harmony_value_file global _harmony_store_file, _harmony_factory_file
result = {"status": "success", "messages": []} result = {"status": "success", "messages": []}
if store_file and store_file.filename: if store_file and store_file.filename:
...@@ -437,13 +435,6 @@ async def harmony_upload( ...@@ -437,13 +435,6 @@ async def harmony_upload(
_harmony_factory_file = file_path _harmony_factory_file = file_path
result["messages"].append(f"主机厂数据已上传: {factory_file.filename}") result["messages"].append(f"主机厂数据已上传: {factory_file.filename}")
if value_file and value_file.filename:
file_path = os.path.join(UPLOAD_DIR, f"harmony_value_{value_file.filename}")
with open(file_path, "wb") as f:
shutil.copyfileobj(value_file.file, f)
_harmony_value_file = file_path
result["messages"].append(f"产值表已上传: {value_file.filename}")
if not result["messages"]: if not result["messages"]:
raise HTTPException(status_code=400, detail="请至少上传一个文件") raise HTTPException(status_code=400, detail="请至少上传一个文件")
...@@ -455,8 +446,8 @@ async def harmony_generate( ...@@ -455,8 +446,8 @@ async def harmony_generate(
start_date: str = Form(None), start_date: str = Form(None),
end_date: str = Form(None), end_date: str = Form(None),
): ):
"""根据已上传的数据生成鸿蒙生态分析报表""" """根据已上传的数据生成鸿蒙生态分析报表(产值数据从数据库自动查询)"""
global _harmony_store_file, _harmony_factory_file, _harmony_value_file global _harmony_store_file, _harmony_factory_file
# 门店兜底配置:未上传时使用默认模板 # 门店兜底配置:未上传时使用默认模板
if not _harmony_store_file or not os.path.exists(_harmony_store_file): if not _harmony_store_file or not os.path.exists(_harmony_store_file):
...@@ -467,23 +458,15 @@ async def harmony_generate( ...@@ -467,23 +458,15 @@ async def harmony_generate(
raise HTTPException(status_code=400, detail="请先上传门店兜底配置文件") raise HTTPException(status_code=400, detail="请先上传门店兜底配置文件")
factory_df = None factory_df = None
value_df = None
if _harmony_factory_file and os.path.exists(_harmony_factory_file): if _harmony_factory_file and os.path.exists(_harmony_factory_file):
factory_df = HarmonyAnalysisService.read_factory_data(_harmony_factory_file) factory_df = HarmonyAnalysisService.read_factory_data(_harmony_factory_file)
if _harmony_value_file and os.path.exists(_harmony_value_file):
value_df = HarmonyAnalysisService.read_value_table(_harmony_value_file)
if factory_df is None and value_df is None:
raise HTTPException(status_code=400, detail="请至少上传主机厂数据或产值表文件")
try: try:
store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file) store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
output_path = HarmonyAnalysisService.build_report( output_path = HarmonyAnalysisService.build_report(
store_df, store_df,
factory_df=factory_df, factory_df=factory_df,
value_df=value_df,
start_date=start_date, start_date=start_date,
end_date=end_date, end_date=end_date,
) )
...@@ -495,7 +478,7 @@ async def harmony_generate( ...@@ -495,7 +478,7 @@ async def harmony_generate(
"download_url": f"api/harmony/download?file={os.path.basename(output_path)}", "download_url": f"api/harmony/download?file={os.path.basename(output_path)}",
"store_count": len(store_df), "store_count": len(store_df),
"factory_count": len(factory_df) if factory_df is not None else 0, "factory_count": len(factory_df) if factory_df is not None else 0,
"value_count": len(value_df) if value_df is not None else 0, "db_store_count": len(store_df),
} }
except Exception as e: except Exception as e:
logger.error(f"Harmony analysis generate failed: {e}", exc_info=True) logger.error(f"Harmony analysis generate failed: {e}", exc_info=True)
......
...@@ -16,6 +16,9 @@ class Settings(BaseSettings): ...@@ -16,6 +16,9 @@ class Settings(BaseSettings):
APP_DEBUG: bool = False APP_DEBUG: bool = False
APP_PORT: int = 9500 APP_PORT: int = 9500
# Security
SECRET_KEY: str = "change-me-in-production-32-char-long-key" # 用于 JWT 签名,生产环境务必修改
# MySQL Settings # MySQL Settings
DB_HOST: str = "192.168.2.155" DB_HOST: str = "192.168.2.155"
DB_PORT: int = 3308 DB_PORT: int = 3308
......
# -*- coding: utf-8 -*-
"""
文件名: app/core/security.py
职责: 认证安全工具:密码哈希、JWT 生成与校验、账号/密码规则校验。
注意: 不要删除这个注释。
"""
import re
from datetime import datetime, timedelta, timezone
from typing import Optional
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import ValidationError
from app.core.config import settings
from app.schemas.user import TokenPayload
# JWT 配置
SECRET_KEY = getattr(settings, "SECRET_KEY", "change-me-in-production-32-char-long-key")
if len(SECRET_KEY) < 32:
SECRET_KEY = SECRET_KEY.ljust(32, "x")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
REMEMBER_TOKEN_EXPIRE_DAYS = 7
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# ========== 账号/密码规则 ==========
def validate_username(value: str) -> bool:
"""账号规则:字母+数字,长度大于6小于15"""
if not value:
return False
return bool(re.fullmatch(r"^[a-zA-Z0-9]{7,14}$", value))
def validate_password(value: str) -> bool:
"""密码规则:包含大小写字母+数字+特殊符号,长度大于8位小于20"""
if not value:
return False
if len(value) <= 8 or len(value) >= 20:
return False
if not re.search(r"[a-z]", value):
return False
if not re.search(r"[A-Z]", value):
return False
if not re.search(r"\d", value):
return False
if not re.search(r"[!@#$%^&*()_+\-=\[\]{}|;':\",./<>?]", value):
return False
return True
# ========== 密码哈希 ==========
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
# ========== JWT Token ==========
def create_access_token(username: str, remember: bool = False) -> str:
if remember:
expire = datetime.now(timezone.utc) + timedelta(days=REMEMBER_TOKEN_EXPIRE_DAYS)
else:
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode = {"sub": username, "exp": int(expire.timestamp())}
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def decode_access_token(token: str) -> Optional[TokenPayload]:
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return TokenPayload(**payload)
except (JWTError, ValidationError):
return None
def token_remaining_seconds(token: str) -> int:
payload = decode_access_token(token)
if not payload:
return 0
now = int(datetime.now(timezone.utc).timestamp())
return max(0, payload.exp - now)
File mode changed
# -*- coding: utf-8 -*-
"""
文件名: app/models/user.py
职责: 用户、登录尝试、验证码等认证相关 ORM 模型。
注意: 不要删除这个注释。
"""
from datetime import datetime
from sqlalchemy import BigInteger, Boolean, Column, DateTime, String, Integer
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class User(Base):
"""系统用户表"""
__tablename__ = "sys_user"
id = Column(BigInteger, primary_key=True, autoincrement=True, comment="主键ID")
username = Column(String(50), nullable=False, unique=True, comment="账号")
hashed_password = Column(String(255), nullable=False, comment="加密密码")
is_active = Column(Boolean, nullable=False, default=True, comment="是否启用")
is_superuser = Column(Boolean, nullable=False, default=False, comment="是否超级管理员")
failed_attempts = Column(Integer, nullable=False, default=0, comment="连续失败次数")
locked_until = Column(DateTime, nullable=True, comment="锁定截止时间")
created_at = Column(DateTime, nullable=False, default=datetime.utcnow, comment="创建时间")
updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, comment="更新时间")
def __repr__(self):
return f"<User(id={self.id}, username={self.username})>"
class LoginAttempt(Base):
"""登录尝试记录表"""
__tablename__ = "sys_login_attempt"
id = Column(BigInteger, primary_key=True, autoincrement=True, comment="主键ID")
username = Column(String(50), nullable=False, comment="账号")
ip_address = Column(String(64), nullable=True, comment="IP地址")
success = Column(Boolean, nullable=False, default=False, comment="是否成功")
fail_reason = Column(String(255), nullable=True, comment="失败原因")
attempted_at = Column(DateTime, nullable=False, default=datetime.utcnow, comment="尝试时间")
def __repr__(self):
return f"<LoginAttempt(id={self.id}, username={self.username}, success={self.success})>"
class Captcha(Base):
"""图形验证码表"""
__tablename__ = "sys_captcha"
token = Column(String(64), primary_key=True, comment="验证码令牌")
code = Column(String(10), nullable=False, comment="验证码内容")
expire_at = Column(DateTime, nullable=False, comment="过期时间")
created_at = Column(DateTime, nullable=False, default=datetime.utcnow, comment="创建时间")
def __repr__(self):
return f"<Captcha(token={self.token})>"
File mode changed
# -*- coding: utf-8 -*-
"""
文件名: app/schemas/user.py
职责: 用户认证相关 Pydantic 校验模型。
注意: 不要删除这个注释。
"""
from typing import Optional
from pydantic import BaseModel, Field, field_validator
class UserBase(BaseModel):
username: str = Field(..., min_length=1, max_length=50)
class UserResponse(UserBase):
id: int
is_active: bool
is_superuser: bool
class Config:
from_attributes = True
class LoginRequest(BaseModel):
username: str = Field(..., min_length=1, max_length=50)
password: str = Field(..., min_length=1, max_length=50)
captcha_code: Optional[str] = Field(None, max_length=10)
captcha_token: Optional[str] = Field(None, max_length=64)
remember: bool = Field(False)
class LoginResponse(BaseModel):
status: str
message: str
need_captcha: bool = False
username: Optional[str] = None
class CaptchaRequiredResponse(BaseModel):
required: bool
class TokenPayload(BaseModel):
sub: str
exp: int
...@@ -191,7 +191,8 @@ class AnalysisService: ...@@ -191,7 +191,8 @@ class AnalysisService:
STORE_REQUIRED_COLS = [ STORE_REQUIRED_COLS = [
"门店名", "兜底指标", "兜底类型", "门店名", "兜底指标", "兜底类型",
"特殊情况1", "特殊情况2", "特殊情况1", "特殊情况2",
"赔付系数_整车延保", "赔付系数_安心包", "赔付系数_电池", "达标转化率_整车延保", "达标转化率_安心包", "达标转化率_电池",
"每单赔付金额_整车", "每单赔付金额_安心包", "每单赔付金额_电池",
"兜底截止日期", "兜底截止日期",
] ]
...@@ -200,9 +201,9 @@ class AnalysisService: ...@@ -200,9 +201,9 @@ class AnalysisService:
"""读取门店列表Excel,根据表头名称自动定位列(不依赖列号)""" """读取门店列表Excel,根据表头名称自动定位列(不依赖列号)"""
df_raw = pd.read_excel(file_path, header=None) df_raw = pd.read_excel(file_path, header=None)
# Row 0: 一级表头,前向填充处理合并单元格(如"赔付系数"F1:H1) # Row 0: 一级表头,前向填充处理合并单元格(如"达标转化率"F1:H1, "每单赔付金额"I1:K1)
header_main = df_raw.iloc[0].ffill().astype(str).str.strip() header_main = df_raw.iloc[0].ffill().astype(str).str.strip()
# Row 1: 二级表头(赔付系数的子列:整车延保/安心包/电池) # Row 1: 二级表头(达标转化率子列:整车延保/安心包/电池;每单赔付金额子列:整车/安心包/电池)
header_sub = df_raw.iloc[1].fillna("").astype(str).str.strip() header_sub = df_raw.iloc[1].fillna("").astype(str).str.strip()
# 按名称构建列映射 # 按名称构建列映射
...@@ -211,9 +212,14 @@ class AnalysisService: ...@@ -211,9 +212,14 @@ class AnalysisService:
col_map = {} col_map = {}
for i in range(len(df_raw.columns)): for i in range(len(df_raw.columns)):
h0 = header_main.iloc[i] h0 = header_main.iloc[i]
if h0 == "赔付系数":
sub = header_sub.iloc[i] sub = header_sub.iloc[i]
sub = SUB_HEADER_NORMALIZE.get(sub, sub) sub = SUB_HEADER_NORMALIZE.get(sub, sub)
if h0 == "达标转化率":
col_map[i] = f"达标转化率_{sub}" if sub else f"达标转化率_{i}"
elif h0 == "每单赔付金额":
col_map[i] = f"每单赔付金额_{sub}" if sub else f"每单赔付金额_{i}"
# 向后兼容旧模板"赔付系数"格式
elif h0 == "赔付系数":
col_map[i] = f"赔付系数_{sub}" if sub else f"赔付系数_{i}" col_map[i] = f"赔付系数_{sub}" if sub else f"赔付系数_{i}"
elif h0 == "门店": elif h0 == "门店":
col_map[i] = "门店名" col_map[i] = "门店名"
...@@ -226,6 +232,35 @@ class AnalysisService: ...@@ -226,6 +232,35 @@ class AnalysisService:
df = df_raw.iloc[data_start:].copy() df = df_raw.iloc[data_start:].copy()
df = df.rename(columns=col_map) df = df.rename(columns=col_map)
# 向后兼容:旧模板"赔付系数_X"合并格式 → 拆分为"达标转化率_X" + "每单赔付金额_X"
for product, amount_col in [("整车延保", "整车"), ("安心包", "安心包"), ("电池", "电池")]:
old_col = f"赔付系数_{product}"
new_threshold_col = f"达标转化率_{product}"
new_amount_col = f"每单赔付金额_{amount_col}"
if old_col in df.columns:
def _split_coeff(val):
if val is None or (isinstance(val, float) and pd.isna(val)):
return pd.Series([None, None])
s = str(val).strip()
if not s:
return pd.Series([None, None])
thresholds, amounts = [], []
for part in s.split(";"):
part = part.strip()
if not part:
continue
m = re.match(r'(\d+(?:\.\d+)?)%?,(\d+(?:\.\d+)?)', part)
if m:
thresholds.append(f"{m.group(1)}%")
amounts.append(m.group(2))
return pd.Series([";".join(thresholds) if thresholds else None,
";".join(amounts) if amounts else None])
split_result = df[old_col].apply(_split_coeff)
if new_threshold_col not in df.columns or df[new_threshold_col].isna().all():
df[new_threshold_col] = split_result[0]
if new_amount_col not in df.columns or df[new_amount_col].isna().all():
df[new_amount_col] = split_result[1]
# 确保必需列都存在,缺失的置 None # 确保必需列都存在,缺失的置 None
for c in AnalysisService.STORE_REQUIRED_COLS: for c in AnalysisService.STORE_REQUIRED_COLS:
if c not in df.columns: if c not in df.columns:
...@@ -605,21 +640,44 @@ class AnalysisService: ...@@ -605,21 +640,44 @@ class AnalysisService:
return "25" in s return "25" in s
@staticmethod @staticmethod
def _parse_compensation_coefficient(coeff_str) -> list: def _parse_compensation_coefficient(coeff_str=None, threshold_str=None, amount_str=None) -> list:
"""解析赔付系数字符串,返回 [(threshold, amount), ...] 按阈值升序排列。 """解析赔付系数,返回 [(threshold, amount), ...] 按阈值升序排列。
旧格式(保留兼容): coeff_str="60%,1500;65%,1000"
新格式: threshold_str="60%;65%" amount_str="1500;1000"
格式示例: 格式示例:
"60%,1500;65%,1000" → [(0.60, 1500.0), (0.65, 1000.0)] threshold_str="60%;65%", amount_str="1500;1000" → [(0.60, 1500.0), (0.65, 1000.0)]
"50%,1148.4" → [(0.50, 1148.4)] threshold_str="50%", amount_str="1148.4" → [(0.50, 1148.4)]
"17%,0" → [(0.17, 0.0)] 旧 coeff_str="50%,1148.4" → [(0.50, 1148.4)]
含义: 当前转化率2低于threshold时,每单赔amount; 含义: 当前转化率低于threshold时,每单赔amount;
存在多级时,取当前转化率2所在区间对应的amount。 存在多级时,取当前转化率所在区间对应的amount。
""" """
# 新格式:分开的达标转化率和赔付金额
if threshold_str is not None and amount_str is not None:
t_str = str(threshold_str).strip() if threshold_str is not None else ''
a_str = str(amount_str).strip() if amount_str is not None else ''
if not t_str or not a_str or t_str in ('None', 'nan') or a_str in ('None', 'nan'):
return []
thresholds = [x.strip() for x in t_str.replace('%', '').split(';') if x.strip()]
amounts = [x.strip() for x in a_str.split(';') if x.strip()]
levels = []
for i in range(min(len(thresholds), len(amounts))):
try:
t = float(thresholds[i]) / 100.0
a = float(amounts[i])
levels.append((t, a))
except (ValueError, TypeError):
continue
levels.sort(key=lambda x: x[0])
return levels
# 旧格式:合并字符串(向后兼容)
if coeff_str is None or (isinstance(coeff_str, float) and pd.isna(coeff_str)): if coeff_str is None or (isinstance(coeff_str, float) and pd.isna(coeff_str)):
return [] return []
s = str(coeff_str).strip() s = str(coeff_str).strip()
if not s: if not s or s in ('None', 'nan'):
return [] return []
levels = [] levels = []
for part in s.split(";"): for part in s.split(";"):
...@@ -1036,10 +1094,16 @@ class AnalysisService: ...@@ -1036,10 +1094,16 @@ class AnalysisService:
current_rate_battery = battery_orders / base_for_rate if base_for_rate > 0 else 0 current_rate_battery = battery_orders / base_for_rate if base_for_rate > 0 else 0
# ========== 需达标转化率 (AK-AM, cols 37-39) ========== # ========== 需达标转化率 (AK-AM, cols 37-39) ==========
# 从门店数据赔付系数中提取最高阈值 # 从门店数据中提取(新格式:达标转化率_* 和 每单赔付金额_* 分开)
coeff_yb = AnalysisService._parse_compensation_coefficient(store_row.get("赔付系数_整车延保")) coeff_yb = AnalysisService._parse_compensation_coefficient(
coeff_axb = AnalysisService._parse_compensation_coefficient(store_row.get("赔付系数_安心包")) threshold_str=store_row.get("达标转化率_整车延保"),
coeff_battery = AnalysisService._parse_compensation_coefficient(store_row.get("赔付系数_电池")) amount_str=store_row.get("每单赔付金额_整车"))
coeff_axb = AnalysisService._parse_compensation_coefficient(
threshold_str=store_row.get("达标转化率_安心包"),
amount_str=store_row.get("每单赔付金额_安心包"))
coeff_battery = AnalysisService._parse_compensation_coefficient(
threshold_str=store_row.get("达标转化率_电池"),
amount_str=store_row.get("每单赔付金额_电池"))
target_yb = max([t for t, _ in coeff_yb], default=0.0) target_yb = max([t for t, _ in coeff_yb], default=0.0)
target_axb = max([t for t, _ in coeff_axb], default=0.0) target_axb = max([t for t, _ in coeff_axb], default=0.0)
......
/*
文件名: app/static/js/auth.js
职责: 全局认证状态管理:校验登录、显示用户信息、自动处理 401、退出登录。
注意: 不要删除这个注释。
*/
(function() {
// 拦截全局 fetch,自动携带 Cookie 并处理 401
const originalFetch = window.fetch;
window.fetch = async function(...args) {
const options = args[1] || {};
options.credentials = 'include';
args[1] = options;
try {
const response = await originalFetch.apply(this, args);
if (response.status === 401 && !window.location.pathname.includes('/login')) {
window.location.href = '/login';
}
return response;
} catch (err) {
throw err;
}
};
// 计算 API 基础路径(兼容 /login 等根级页面)
(function() {
var p = window.location.pathname;
if (p.endsWith('/')) p = p.slice(0, -1);
var idx = p.lastIndexOf('/');
window.API_BASE = p.substring(0, idx) + '/api';
// 如果当前就是根路径(如 /login 直接访问),兜底为 /api
if (!window.API_BASE || window.API_BASE === '/api') {
window.API_BASE = '/api';
}
})();
// 登录页不执行后续逻辑
if (window.location.pathname.includes('/login')) {
return;
}
// 获取当前用户信息
async function loadCurrentUser() {
try {
const res = await fetch(window.API_BASE + '/auth/me', { credentials: 'include' });
if (res.status === 401) {
window.location.href = '/login';
return;
}
if (!res.ok) {
console.error('获取用户信息失败:', res.status);
return;
}
const user = await res.json();
renderUserInfo(user.username);
} catch (err) {
console.error('加载用户信息失败:', err);
}
}
// 渲染右上角用户信息
function renderUserInfo(username) {
const userInfo = document.getElementById('user-info') || document.querySelector('.user-info');
if (!userInfo) return;
userInfo.innerHTML = '';
const nameSpan = document.createElement('span');
nameSpan.textContent = username || '管理员';
nameSpan.style.marginRight = '10px';
const logoutLink = document.createElement('a');
logoutLink.href = '#';
logoutLink.textContent = '退出';
logoutLink.style.color = '#ff6b6b';
logoutLink.style.textDecoration = 'none';
logoutLink.style.fontSize = '13px';
logoutLink.addEventListener('click', async (e) => {
e.preventDefault();
try {
await fetch(window.API_BASE + '/auth/logout', { method: 'POST', credentials: 'include' });
} catch (err) {
console.error('退出请求失败:', err);
}
window.location.href = '/login';
});
userInfo.appendChild(nameSpan);
userInfo.appendChild(logoutLink);
}
document.addEventListener('DOMContentLoaded', loadCurrentUser);
})();
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
<a class="nav-item active" href="./analysis">问界生态系数分析</a> <a class="nav-item active" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
</nav> </nav>
<div class="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
<main> <main>
...@@ -222,5 +222,6 @@ ...@@ -222,5 +222,6 @@
} }
}); });
</script> </script>
<script src="./static/js/auth.js"></script>
</body> </body>
</html> </html>
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
</nav> </nav>
<div class="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
<main> <main>
...@@ -96,6 +96,7 @@ ...@@ -96,6 +96,7 @@
<script>var APP_ROOT = '..';</script> <script>var APP_ROOT = '..';</script>
<script src="./static/js/common.js"></script> <script src="./static/js/common.js"></script>
<script src="./static/js/auth.js"></script>
<script> <script>
const DW_FILTER = item => item.task_id.includes('sync'); const DW_FILTER = item => item.task_id.includes('sync');
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item active" href="./harmony">鸿蒙生态分析</a> <a class="nav-item active" href="./harmony">鸿蒙生态分析</a>
</nav> </nav>
<div class="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
<main> <main>
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
<div style="display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px;"> <div style="display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px;">
<!-- 步骤1: 上传门店兜底配置 --> <!-- 步骤1: 上传门店兜底配置 -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 16px;"> <div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 16px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">步骤1: 门店兜底配置</span> <span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">门店兜底配置</span>
<div id="hm-store-drop-zone" style="flex:1; border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;"> <div id="hm-store-drop-zone" style="flex:1; border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="hm-store-file-input" style="display:none;" accept=".xlsx,.xls"> <input type="file" id="hm-store-file-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">&#x1f3ea;</span> <span style="font-size:16px;">&#x1f3ea;</span>
...@@ -39,9 +39,9 @@ ...@@ -39,9 +39,9 @@
</div> </div>
<!-- 步骤2: 上传主机厂数据 --> <!-- 步骤2: 上传主机厂数据 -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 12px;"> <div style="background: #f0f5ff; padding: 8px 16px; border-radius: 6px; border: 1px solid #adc6ff; display: flex; align-items: center; gap: 12px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">步骤2: 主机厂数据</span> <span style="font-size:14px; font-weight:600; color:#1890ff; white-space:nowrap;">主机厂数据</span>
<div id="hm-factory-drop-zone" style="flex:1; border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;"> <div id="hm-factory-drop-zone" style="flex:1; border: 1px dashed #1890ff; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;">
<input type="file" id="hm-factory-file-input" style="display:none;" accept=".xlsx,.xls"> <input type="file" id="hm-factory-file-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">&#x1f3ed;</span> <span style="font-size:16px;">&#x1f3ed;</span>
<p id="hm-factory-file-name" style="margin:0; font-size:12px; color:#999;">点击选择主机厂数据(含交付数)</p> <p id="hm-factory-file-name" style="margin:0; font-size:12px; color:#999;">点击选择主机厂数据(含交付数)</p>
...@@ -49,14 +49,10 @@ ...@@ -49,14 +49,10 @@
<a href="./api/harmony/template/factory" style="font-size:12px; color:#1890ff; text-decoration:none; white-space:nowrap;">&#x1f4e5; 下载模板</a> <a href="./api/harmony/template/factory" style="font-size:12px; color:#1890ff; text-decoration:none; white-space:nowrap;">&#x1f4e5; 下载模板</a>
</div> </div>
<!-- 步骤3: 上传产值表 --> <!-- 说明: 产值表数据从数据库自动查询 -->
<div style="background: #f0f5ff; padding: 8px 16px; border-radius: 6px; border: 1px solid #adc6ff; display: flex; align-items: center; gap: 12px;"> <div style="background: #e6f7ff; padding: 6px 16px; border-radius: 6px; border: 1px solid #91d5ff; display: flex; align-items: center; gap: 8px;">
<span style="font-size:14px; font-weight:600; color:#1890ff; white-space:nowrap;">步骤3: 产值表 (核心数据)</span> <span style="font-size:13px; color:#1890ff;">&#x1f6c8;</span>
<div id="hm-value-drop-zone" style="flex:1; border: 1px dashed #1890ff; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;"> <span style="font-size:12px; color:#666;">产值表数据(触客数、成交数、渗透率等)将自动从数据库查询,无需上传。</span>
<input type="file" id="hm-value-file-input" style="display:none;" accept=".xlsx,.xls">
<span style="font-size:16px;">&#x1f4ca;</span>
<p id="hm-value-file-name" style="margin:0; font-size:12px; color:#999;">点击选择鸿蒙产值表(含触客数、成交数、渗透率等)</p>
</div>
</div> </div>
<!-- 日期范围 --> <!-- 日期范围 -->
...@@ -73,7 +69,7 @@ ...@@ -73,7 +69,7 @@
<button id="btn-hm-generate" style="padding: 12px 48px; background: #1890ff; color: white; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; transition: all 0.3s;"> <button id="btn-hm-generate" style="padding: 12px 48px; background: #1890ff; color: white; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; transition: all 0.3s;">
&#x1f680; 生成鸿蒙生态分析报表 &#x1f680; 生成鸿蒙生态分析报表
</button> </button>
<p style="font-size:12px; color:#999; margin-top:8px;">合并门店兜底配置 + 主机厂交付数据 + 产值表指标,计算渗透率达标系数和赔付金额</p> <p style="font-size:12px; color:#999; margin-top:8px;">合并门店兜底配置 + 主机厂交付数据 + 数据库产值指标,计算渗透率达标系数和赔付金额</p>
<p style="font-size:11px; color:#faad14;">&#x1f4cc; 使用模板: 输出-鸿蒙生态系数-模板.xlsx</p> <p style="font-size:11px; color:#faad14;">&#x1f4cc; 使用模板: 输出-鸿蒙生态系数-模板.xlsx</p>
</div> </div>
...@@ -137,19 +133,6 @@ ...@@ -137,19 +133,6 @@
}); });
} }
// 产值表上传
const valueDropZone = document.getElementById('hm-value-drop-zone');
const valueFileInput = document.getElementById('hm-value-file-input');
if (valueDropZone) {
valueDropZone.addEventListener('click', () => valueFileInput.click());
valueFileInput.addEventListener('change', () => {
if (valueFileInput.files.length > 0) {
document.getElementById('hm-value-file-name').textContent = '\u2705 已选择: ' + valueFileInput.files[0].name;
document.getElementById('hm-value-file-name').style.color = '#52c41a';
}
});
}
// 生成报表 // 生成报表
const btnGenerate = document.getElementById('btn-hm-generate'); const btnGenerate = document.getElementById('btn-hm-generate');
if (btnGenerate) { if (btnGenerate) {
...@@ -159,12 +142,6 @@ ...@@ -159,12 +142,6 @@
const hasStore = storeFileInput && storeFileInput.files.length > 0; const hasStore = storeFileInput && storeFileInput.files.length > 0;
const hasFactory = factoryFileInput && factoryFileInput.files.length > 0; const hasFactory = factoryFileInput && factoryFileInput.files.length > 0;
const hasValue = valueFileInput && valueFileInput.files.length > 0;
if (!hasFactory && !hasValue) {
alert('请至少上传主机厂数据或产值表文件');
return;
}
btnGenerate.disabled = true; btnGenerate.disabled = true;
btnGenerate.textContent = '\u23f3 正在上传文件...'; btnGenerate.textContent = '\u23f3 正在上传文件...';
...@@ -174,7 +151,6 @@ ...@@ -174,7 +151,6 @@
const uploadForm = new FormData(); const uploadForm = new FormData();
if (hasStore) uploadForm.append('store_file', storeFileInput.files[0]); if (hasStore) uploadForm.append('store_file', storeFileInput.files[0]);
if (hasFactory) uploadForm.append('factory_file', factoryFileInput.files[0]); if (hasFactory) uploadForm.append('factory_file', factoryFileInput.files[0]);
if (hasValue) uploadForm.append('value_file', valueFileInput.files[0]);
const uploadRes = await fetch(window.API_BASE + '/harmony/upload', { method: 'POST', body: uploadForm }); const uploadRes = await fetch(window.API_BASE + '/harmony/upload', { method: 'POST', body: uploadForm });
const uploadData = await uploadRes.json(); const uploadData = await uploadRes.json();
...@@ -199,7 +175,7 @@ ...@@ -199,7 +175,7 @@
document.getElementById('hm-result-info').innerHTML = document.getElementById('hm-result-info').innerHTML =
'门店数: <strong>' + genData.store_count + '</strong> | ' + '门店数: <strong>' + genData.store_count + '</strong> | ' +
'主机厂门店: <strong>' + genData.factory_count + '</strong> | ' + '主机厂门店: <strong>' + genData.factory_count + '</strong> | ' +
'产值表门店: <strong>' + genData.value_count + '</strong>'; 'DB产值数据: <strong>' + genData.db_store_count + '</strong> 家门店';
document.getElementById('btn-hm-download').href = genData.download_url; document.getElementById('btn-hm-download').href = genData.download_url;
} else { } else {
throw new Error(genData.detail || '报表生成失败'); throw new Error(genData.detail || '报表生成失败');
...@@ -216,5 +192,6 @@ ...@@ -216,5 +192,6 @@
} }
}); });
</script> </script>
<script src="./static/js/auth.js"></script>
</body> </body>
</html> </html>
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
</nav> </nav>
<div class="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
<main> <main>
...@@ -53,5 +53,7 @@ ...@@ -53,5 +53,7 @@
</div> </div>
</section> </section>
</main> </main>
<script src="./static/js/auth.js"></script>
</body> </body>
</html> </html>
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
</nav> </nav>
<div class="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
<main> <main>
...@@ -79,6 +79,7 @@ ...@@ -79,6 +79,7 @@
<script>var APP_ROOT = '..';</script> <script>var APP_ROOT = '..';</script>
<script src="./static/js/common.js"></script> <script src="./static/js/common.js"></script>
<script src="./static/js/auth.js"></script>
<script> <script>
const ODS_FILTER = item => item.task_id.includes('ods'); const ODS_FILTER = item => item.task_id.includes('ods');
......
...@@ -8,14 +8,21 @@ ...@@ -8,14 +8,21 @@
import uvicorn import uvicorn
import os import os
import asyncio import asyncio
from fastapi import FastAPI, Request from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates from fastapi.templating import Jinja2Templates
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from sqlalchemy.orm import Session
from app.core.scheduler import SchedulerManager from app.core.scheduler import SchedulerManager
from app.core.config import settings from app.core.config import settings
from app.api.auth import router as auth_router
from app.api.endpoints import router as api_router from app.api.endpoints import router as api_router
from app.core.logging_config import setup_logging from app.core.logging_config import setup_logging
from app.db.session import get_db, SessionLocal, engine
from app.services.auth_service import AuthService
from app.models.user import Base as AuthBase
# 初始化日志 # 初始化日志
setup_logging() setup_logging()
...@@ -23,10 +30,28 @@ setup_logging() ...@@ -23,10 +30,28 @@ setup_logging()
# 基础目录 # 基础目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def _init_auth_tables_sync():
"""同步创建认证相关表( lifespan 中异步调用)"""
AuthBase.metadata.create_all(bind=engine)
def _init_default_users_sync():
"""同步初始化默认账号( lifespan 中异步调用)"""
db = SessionLocal()
try:
AuthService.init_default_users(db)
finally:
db.close()
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
# 启动时执行 # 启动时执行
print("[*] Starting Data Analyze WebUI...") print("[*] Starting Data Analyze WebUI...")
# 创建认证表(若不存在)并初始化默认账号
await asyncio.to_thread(_init_auth_tables_sync)
await asyncio.to_thread(_init_default_users_sync)
# 启动定时任务调度器 # 启动定时任务调度器
await SchedulerManager.start() await SchedulerManager.start()
yield yield
...@@ -40,6 +65,7 @@ async def lifespan(app: FastAPI): ...@@ -40,6 +65,7 @@ async def lifespan(app: FastAPI):
except Exception as e: except Exception as e:
print(f"[!] Error during stop: {e}") print(f"[!] Error during stop: {e}")
app = FastAPI( app = FastAPI(
title="问界门店运营数据分析平台", title="问界门店运营数据分析平台",
description="支持 ODS/DWS/DWM/DWA 各层数据同步任务及分析模版展示", description="支持 ODS/DWS/DWM/DWA 各层数据同步任务及分析模版展示",
...@@ -53,8 +79,33 @@ app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "app/static")) ...@@ -53,8 +79,33 @@ app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "app/static"))
# 配置模板引擎 # 配置模板引擎
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates")) templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app/templates"))
# 注册 API 路由
app.include_router(api_router, prefix="/api") # ========== 认证依赖 ==========
async def get_current_user_for_page(request: Request, db: Session = Depends(get_db)):
"""页面路由使用的当前用户校验"""
token = request.cookies.get("access_token")
user = AuthService.get_current_user_from_token(db, token)
if not user:
raise HTTPException(status_code=401, detail="未登录")
return user
async def get_current_user_for_api(request: Request, db: Session = Depends(get_db)):
"""API 路由使用的当前用户校验"""
token = request.cookies.get("access_token")
user = AuthService.get_current_user_from_token(db, token)
if not user:
raise HTTPException(status_code=401, detail="未登录或登录已过期")
return user
# 注册公开认证路由
app.include_router(auth_router, prefix="/api")
# 注册受保护 API 路由
app.include_router(api_router, prefix="/api", dependencies=[Depends(get_current_user_for_api)])
# 页面路由映射:路径 → 模板文件名 # 页面路由映射:路径 → 模板文件名
PAGE_ROUTES = { PAGE_ROUTES = {
...@@ -65,20 +116,34 @@ PAGE_ROUTES = { ...@@ -65,20 +116,34 @@ PAGE_ROUTES = {
"/harmony": "harmony.html", "/harmony": "harmony.html",
} }
def _page_handler(template_name: str):
def _page_handler(template_name: str, require_auth: bool = True):
"""闭包工厂:为指定模板生成页面处理函数""" """闭包工厂:为指定模板生成页面处理函数"""
async def handler(request: Request): async def handler(request: Request, db: Session = Depends(get_db)):
if require_auth:
token = request.cookies.get("access_token")
user = AuthService.get_current_user_from_token(db, token)
if not user:
# 未登录重定向到登录页
return RedirectResponse(url="/login", status_code=302)
return templates.TemplateResponse(request=request, name=template_name, context={}) return templates.TemplateResponse(request=request, name=template_name, context={})
return handler return handler
# 登录页(公开)
app.get("/login")(_page_handler("login.html", require_auth=False))
# 受保护业务页面
for path, tpl in PAGE_ROUTES.items(): for path, tpl in PAGE_ROUTES.items():
app.get(path)(_page_handler(tpl)) app.get(path)(_page_handler(tpl, require_auth=True))
@app.get("/api/health") @app.get("/api/health")
async def health(): async def health():
"""健康检查接口""" """健康检查接口(公开)"""
return {"status": "ok", "message": "Welcome to Data Analyze WebUI API"} return {"status": "ok", "message": "Welcome to Data Analyze WebUI API"}
if __name__ == "__main__": if __name__ == "__main__":
# 端口指定 9500 # 端口指定 9500
uvicorn.run( uvicorn.run(
......
...@@ -15,3 +15,7 @@ jinja2>=3.1.0 ...@@ -15,3 +15,7 @@ jinja2>=3.1.0
python-multipart>=0.0.9 python-multipart>=0.0.9
apscheduler>=3.10.0 apscheduler>=3.10.0
httpx>=0.27.0 httpx>=0.27.0
passlib>=1.7.4
python-jose[cryptography]>=3.3.0
bcrypt>=4.0.0,<4.1.0
pillow>=10.0.0
...@@ -71,6 +71,44 @@ CREATE TABLE IF NOT EXISTS `_dynamic_table_meta` ( ...@@ -71,6 +71,44 @@ CREATE TABLE IF NOT EXISTS `_dynamic_table_meta` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='动态生成的表元数据'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='动态生成的表元数据';
-- ============================================================================ -- ============================================================================
-- 0.4 用户认证表
-- ============================================================================
CREATE TABLE IF NOT EXISTS `sys_user` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`username` VARCHAR(50) NOT NULL COMMENT '账号',
`hashed_password` VARCHAR(255) NOT NULL COMMENT '加密密码',
`is_active` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用: 1启用 0禁用',
`is_superuser` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否超级管理员: 1是 0否',
`failed_attempts` INT NOT NULL DEFAULT 0 COMMENT '连续失败次数',
`locked_until` DATETIME DEFAULT NULL COMMENT '锁定截止时间',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_username` (`username`),
INDEX `idx_locked_until` (`locked_until`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统用户表';
CREATE TABLE IF NOT EXISTS `sys_login_attempt` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`username` VARCHAR(50) NOT NULL COMMENT '账号',
`ip_address` VARCHAR(64) DEFAULT NULL COMMENT 'IP地址',
`success` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否成功: 1成功 0失败',
`fail_reason` VARCHAR(255) DEFAULT NULL COMMENT '失败原因',
`attempted_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '尝试时间',
PRIMARY KEY (`id`),
INDEX `idx_username_time` (`username`, `attempted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='登录尝试记录';
CREATE TABLE IF NOT EXISTS `sys_captcha` (
`token` VARCHAR(64) NOT NULL COMMENT '验证码令牌',
`code` VARCHAR(10) NOT NULL COMMENT '验证码内容',
`expire_at` DATETIME NOT NULL COMMENT '过期时间',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`token`),
INDEX `idx_expire_at` (`expire_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='图形验证码';
-- ============================================================================
-- 1. ODS 层 — 贴源层 -- 1. ODS 层 — 贴源层
-- ============================================================================ -- ============================================================================
......
...@@ -93,22 +93,35 @@ def parse_ladder_coefficient(formula_text, group_id): ...@@ -93,22 +93,35 @@ def parse_ladder_coefficient(formula_text, group_id):
except Exception: except Exception:
return formula_text return formula_text
# 阶梯分组 → 赔付系数映射 # 阶梯分组 → 达标转化率 + 每单赔付金额映射
LADDER_COEFF = { LADDER_COEFF = {
# Group 0: 骏业/骏智系列 (Row 3-6) # Group 0: 骏业/骏智系列 (Row 3-6)
0: {'整车延保': '60%,1500;65%,1000', '安心包': '15%,800;20%,600', '电池': '11%,800;15%,600'}, 0: {
'整车延保': ('60%;65%', '1500;1000'),
'安心包': ('15%;20%', '800;600'),
'电池': ('11%;15%', '800;600'),
},
# Group 1: 山西聚驰 (Row 10) # Group 1: 山西聚驰 (Row 10)
1: {'整车延保': '45%,3420;50%,1500', '安心包': '40%,1154;50%,1000', '电池': '15%,500'}, 1: {
'整车延保': ('45%;50%', '3420;1500'),
'安心包': ('40%;50%', '1154;1000'),
'电池': ('15%', '500'),
},
# Group 2: 山西聚锦驰/长治聚鑫驰 (Row 13-14) # Group 2: 山西聚锦驰/长治聚鑫驰 (Row 13-14)
2: {'整车延保': '50%,2000;60%,1000', '安心包': '20%,800', '电池': '15%,500'}, 2: {
'整车延保': ('50%;60%', '2000;1000'),
'安心包': ('20%', '800'),
'电池': ('15%', '500'),
},
} }
for sn, gid in step_store_group.items(): for sn, gid in step_store_group.items():
print(f' 阶梯赔付: {sn} → 组{gid}: {LADDER_COEFF.get(gid)}') print(f' 阶梯赔付: {sn} → 组{gid}: {LADDER_COEFF.get(gid)}')
# ── 4. 合并数据,输出模板 ── # ── 4. 合并数据,输出模板 ──
# 9列: A=门店, B=兜底指标, C=兜底类型, D=特殊情况1, E=特殊情况2, # 12列: A=门店, B=兜底指标, C=兜底类型, D=特殊情况1, E=特殊情况2,
# F=整车延保, G=安心包, H=电池电池(赔付系数 F1:H1), I=兜底截止日期 # F-H=达标转化率(整车延保/安心包/电池), I-K=每单赔付金额(整车/安心包/电池),
# L=兜底截止日期
header_fill = PatternFill('solid', fgColor='4472C4') header_fill = PatternFill('solid', fgColor='4472C4')
header_font = Font(name='微软雅黑', bold=True, color='FFFFFF', size=10) header_font = Font(name='微软雅黑', bold=True, color='FFFFFF', size=10)
sub_fill = PatternFill('solid', fgColor='D6E4F0') sub_fill = PatternFill('solid', fgColor='D6E4F0')
...@@ -149,22 +162,27 @@ owb = Workbook() ...@@ -149,22 +162,27 @@ owb = Workbook()
ows = owb.active ows = owb.active
ows.title = '门店信息-赔付信息' ows.title = '门店信息-赔付信息'
# Row1 表头: A-E 合并 A1:A2 .. E1:E2, F1:H1 合并为"赔付系数", I1:I2 合并 # Row1 表头: A-E 合并, F1:H1 合并为"达标转化率", I1:K1 合并为"每单赔付金额", L 合并
write_header_cell(ows, 1, 1, '门店') write_header_cell(ows, 1, 1, '门店')
write_header_cell(ows, 1, 2, '兜底指标') write_header_cell(ows, 1, 2, '兜底指标')
write_header_cell(ows, 1, 3, '兜底类型') write_header_cell(ows, 1, 3, '兜底类型')
write_header_cell(ows, 1, 4, '特殊情况1') write_header_cell(ows, 1, 4, '特殊情况1')
write_header_cell(ows, 1, 5, '特殊情况2') write_header_cell(ows, 1, 5, '特殊情况2')
write_header_cell(ows, 1, 6, '赔付系数') write_header_cell(ows, 1, 6, '达标转化率')
ows.merge_cells('F1:H1') ows.merge_cells('F1:H1')
write_header_cell(ows, 1, 9, '兜底截止日期') write_header_cell(ows, 1, 9, '每单赔付金额')
for col_letter in ['A', 'B', 'C', 'D', 'E', 'I']: ows.merge_cells('I1:K1')
write_header_cell(ows, 1, 12, '兜底截止日期')
for col_letter in ['A', 'B', 'C', 'D', 'E', 'L']:
ows.merge_cells(f'{col_letter}1:{col_letter}2') ows.merge_cells(f'{col_letter}1:{col_letter}2')
# Row2 子表头 # Row2 子表头
write_sub_cell(ows, 2, 6, '整车延保') write_sub_cell(ows, 2, 6, '整车延保')
write_sub_cell(ows, 2, 7, '安心包') write_sub_cell(ows, 2, 7, '安心包')
write_sub_cell(ows, 2, 8, '电池') write_sub_cell(ows, 2, 8, '电池')
write_sub_cell(ows, 2, 9, '整车')
write_sub_cell(ows, 2, 10, '安心包')
write_sub_cell(ows, 2, 11, '电池')
# 列宽 # 列宽
ows.column_dimensions['A'].width = 35 ows.column_dimensions['A'].width = 35
...@@ -172,10 +190,13 @@ ows.column_dimensions['B'].width = 30 ...@@ -172,10 +190,13 @@ ows.column_dimensions['B'].width = 30
ows.column_dimensions['C'].width = 10 ows.column_dimensions['C'].width = 10
ows.column_dimensions['D'].width = 14 ows.column_dimensions['D'].width = 14
ows.column_dimensions['E'].width = 14 ows.column_dimensions['E'].width = 14
ows.column_dimensions['F'].width = 18 ows.column_dimensions['F'].width = 14
ows.column_dimensions['G'].width = 18 ows.column_dimensions['G'].width = 14
ows.column_dimensions['H'].width = 18 ows.column_dimensions['H'].width = 14
ows.column_dimensions['I'].width = 14 ows.column_dimensions['I'].width = 14
ows.column_dimensions['J'].width = 14
ows.column_dimensions['K'].width = 14
ows.column_dimensions['L'].width = 14
# Row3+: 写入数据 # Row3+: 写入数据
missing = 0 missing = 0
...@@ -190,44 +211,53 @@ for s in stores: ...@@ -190,44 +211,53 @@ for s in stores:
write_data_cell(ows, row_num, 4, s['特殊情况1'] if s['特殊情况1'] and s['特殊情况1'] != 'None' else '') write_data_cell(ows, row_num, 4, s['特殊情况1'] if s['特殊情况1'] and s['特殊情况1'] != 'None' else '')
write_data_cell(ows, row_num, 5, s['特殊情况2'] if s['特殊情况2'] and s['特殊情况2'] != 'None' else '') write_data_cell(ows, row_num, 5, s['特殊情况2'] if s['特殊情况2'] and s['特殊情况2'] != 'None' else '')
# 赔付系数 # 赔付系数拆成两列: 达标转化率(6-8) + 每单赔付金额(9-11)
is_ladder = s['特殊情况1'] and '阶梯' in s['特殊情况1'] is_ladder = s['特殊情况1'] and '阶梯' in s['特殊情况1']
if is_ladder and sn in step_store_group: if is_ladder and sn in step_store_group:
gid = step_store_group[sn] gid = step_store_group[sn]
coeff = LADDER_COEFF.get(gid, {}) coeff = LADDER_COEFF.get(gid, {})
write_data_cell(ows, row_num, 6, coeff.get('整车延保', '')) for idx, cat in enumerate(['整车延保', '安心包', '电池']):
write_data_cell(ows, row_num, 7, coeff.get('安心包', '')) threshold_str, amount_str = coeff.get(cat, ('', ''))
write_data_cell(ows, row_num, 8, coeff.get('电池', '')) write_data_cell(ows, row_num, 6 + idx, threshold_str)
write_data_cell(ows, row_num, 9 + idx, amount_str)
step_count += 1 step_count += 1
else: else:
# 从主表取 需达标转化率 (AK/AL/AM) 和 赔付金额 (AR/AS/AT) # 从主表取 需达标转化率 (AK/AL/AM) 和 赔付金额 (AR/AS/AT)
target_yb = s.get('需达标_整车', '').replace('None', '') targets = [
target_axb = s.get('需达标_安心包', '').replace('None', '') s.get('需达标_整车', '').replace('None', ''),
target_bat = s.get('需达标_电池', '').replace('None', '') s.get('需达标_安心包', '').replace('None', ''),
pf_yb = s.get('赔付_整车', '').replace('None', '') s.get('需达标_电池', '').replace('None', ''),
pf_axb = s.get('赔付_安心包', '').replace('None', '') ]
pf_bat = s.get('赔付_电池', '').replace('None', '') amounts = [
s.get('赔付_整车', '').replace('None', ''),
# 构造 "阈值%,金额" 格式 (target 是小数如0.5, 需转为50%) s.get('赔付_安心包', '').replace('None', ''),
def fmt_coeff(target, amount): s.get('赔付_电池', '').replace('None', ''),
if not amount or amount in ('', '0', '0.0'): ]
return '0%,0'
if '阶段赔付' in amount: def fmt_threshold(target):
return '阶段赔付' """达标转化率 (target 是小数如0.5, 转为百分比字符串如 50%)"""
if not target or target in ('', '0', '0.0'):
return '0%'
try: try:
t_pct = str(round(float(target) * 100, 1)).rstrip('0').rstrip('.') t_pct = str(round(float(target) * 100, 1)).rstrip('0').rstrip('.')
return f'{t_pct}%'
except (ValueError, TypeError): except (ValueError, TypeError):
t_pct = ''
if not t_pct:
return '' return ''
return f'{t_pct}%,{amount}'.rstrip('.,')
write_data_cell(ows, row_num, 6, fmt_coeff(target_yb, pf_yb)) def fmt_amount(amount):
write_data_cell(ows, row_num, 7, fmt_coeff(target_axb, pf_axb)) """每单赔付金额"""
write_data_cell(ows, row_num, 8, fmt_coeff(target_bat, pf_bat)) if not amount or amount in ('', '0', '0.0'):
return '0'
if '阶段赔付' in amount:
return '阶段赔付'
return amount
for i in range(3):
write_data_cell(ows, row_num, 6 + i, fmt_threshold(targets[i]))
write_data_cell(ows, row_num, 9 + i, fmt_amount(amounts[i]))
write_data_cell(ows, row_num, 9, s.get('兜底月份', '')) write_data_cell(ows, row_num, 12, s.get('兜底月份', ''))
row_num += 1 row_num += 1
# 设置行高 (默认字体大小10, 1.2倍行高 ≈ 15) # 设置行高 (默认字体大小10, 1.2倍行高 ≈ 15)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!