feat: Excel导入增强——支持多行+跳过明细+状态改为verified
This commit is contained in:
Binary file not shown.
+26
-12
@@ -23,33 +23,47 @@ async def import_excel(file: UploadFile = File(...), db: Session = Depends(get_d
|
|||||||
if not all(c in df.columns for c in required):
|
if not all(c in df.columns for c in required):
|
||||||
raise HTTPException(400, f"Excel必须包含列: {required}")
|
raise HTTPException(400, f"Excel必须包含列: {required}")
|
||||||
|
|
||||||
|
if len(df) == 0:
|
||||||
|
raise HTTPException(400, "Excel文件为空,没有数据行")
|
||||||
|
|
||||||
|
from app.models import KPIDefinition
|
||||||
|
kpi_map = {k.kpi_code: k.id for k in db.query(KPIDefinition).all()}
|
||||||
|
|
||||||
batch = hashlib.md5(str(datetime.now().timestamp()).encode()).hexdigest()[:12]
|
batch = hashlib.md5(str(datetime.now().timestamp()).encode()).hexdigest()[:12]
|
||||||
count = 0
|
count = 0
|
||||||
for _, row in df.iterrows():
|
skipped = []
|
||||||
kpi_code = str(row.get("kpi_code", ""))
|
for idx, row in df.iterrows():
|
||||||
period = str(row.get("period", ""))
|
kpi_code = str(row.get("kpi_code", "")).strip()
|
||||||
|
period = str(row.get("period", "")).strip()
|
||||||
value = row.get("actual_value")
|
value = row.get("actual_value")
|
||||||
|
|
||||||
if not kpi_code or not period or pd.isna(value):
|
if not kpi_code or not period or pd.isna(value):
|
||||||
|
skipped.append(f"第{idx+2}行: 缺少必填字段")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
from app.models import KPIDefinition
|
kid = kpi_map.get(kpi_code)
|
||||||
kpi = db.query(KPIDefinition).filter(KPIDefinition.kpi_code == kpi_code).first()
|
if not kid:
|
||||||
if not kpi:
|
skipped.append(f"第{idx+2}行: KPI编码「{kpi_code}」不存在")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
kv = KPIValue(
|
db.add(KPIValue(
|
||||||
kpi_id=kpi.id,
|
kpi_id=kid,
|
||||||
period=period,
|
period=period,
|
||||||
actual_value=float(value),
|
actual_value=float(value),
|
||||||
source_type="excel",
|
source_type="excel",
|
||||||
source_batch=batch,
|
source_batch=batch,
|
||||||
data_status="pending",
|
data_status="verified",
|
||||||
)
|
))
|
||||||
db.add(kv)
|
|
||||||
count += 1
|
count += 1
|
||||||
|
|
||||||
db.commit()
|
db.commit()
|
||||||
return {"message": f"导入成功 {count} 条数据", "batch": batch}
|
|
||||||
|
msg = f"✅ 导入成功 {count} 条数据"
|
||||||
|
if skipped:
|
||||||
|
msg += f",{len(skipped)}条跳过:\n" + "\n".join(skipped[:10])
|
||||||
|
if len(skipped) > 10:
|
||||||
|
msg += f"\n...还有{len(skipped)-10}条"
|
||||||
|
return {"message": msg, "batch": batch, "total": count, "skipped": len(skipped)}
|
||||||
|
|
||||||
@router.get("/sources")
|
@router.get("/sources")
|
||||||
def list_sources(db: Session = Depends(get_db)):
|
def list_sources(db: Session = Depends(get_db)):
|
||||||
|
|||||||
Reference in New Issue
Block a user