103 lines
3.6 KiB
Python
103 lines
3.6 KiB
Python
# app/routes/upload.py
|
||
"""
|
||
Маршруты API для загрузки и импорта данных
|
||
Соответствует требованиям ТЗ по импорту данных
|
||
"""
|
||
import pandas as pd
|
||
from fastapi import APIRouter, UploadFile, File, HTTPException
|
||
from app.database import db
|
||
from app.models import UploadResponse
|
||
|
||
router = APIRouter()
|
||
|
||
@router.post("/partners")
|
||
async def upload_partners(file: UploadFile = File(...)):
|
||
"""
|
||
Загрузка партнеров из файла
|
||
Подготовка данных для импорта согласно ТЗ
|
||
"""
|
||
try:
|
||
if file.filename.endswith('.xlsx'):
|
||
df = pd.read_excel(file.file)
|
||
elif file.filename.endswith('.csv'):
|
||
df = pd.read_csv(file.file)
|
||
else:
|
||
raise HTTPException(status_code=400, detail="Unsupported file format")
|
||
|
||
processed = 0
|
||
errors = []
|
||
|
||
for index, row in df.iterrows():
|
||
try:
|
||
# Валидация и преобразование данных
|
||
rating = row.get('rating', 0)
|
||
if pd.isna(rating):
|
||
rating = 0
|
||
|
||
db.execute_query("""
|
||
INSERT INTO partners
|
||
(partner_type, company_name, legal_address, inn, director_name,
|
||
phone, email, rating, sales_locations)
|
||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||
""", (
|
||
row.get('partner_type'),
|
||
row.get('company_name'),
|
||
row.get('legal_address'),
|
||
row.get('inn'),
|
||
row.get('director_name'),
|
||
row.get('phone'),
|
||
row.get('email'),
|
||
int(rating), # Конвертация в целое число
|
||
row.get('sales_locations')
|
||
))
|
||
processed += 1
|
||
except Exception as e:
|
||
errors.append(f"Row {index}: {str(e)}")
|
||
|
||
return UploadResponse(
|
||
message="File processed successfully",
|
||
processed_rows=processed,
|
||
errors=errors
|
||
)
|
||
|
||
except Exception as e:
|
||
raise HTTPException(status_code=500, detail=str(e))
|
||
|
||
@router.post("/sales")
|
||
async def upload_sales(file: UploadFile = File(...)):
|
||
"""Загрузка продаж из файла"""
|
||
try:
|
||
if file.filename.endswith('.xlsx'):
|
||
df = pd.read_excel(file.file)
|
||
elif file.filename.endswith('.csv'):
|
||
df = pd.read_csv(file.file)
|
||
else:
|
||
raise HTTPException(status_code=400, detail="Unsupported file format")
|
||
|
||
processed = 0
|
||
errors = []
|
||
|
||
for index, row in df.iterrows():
|
||
try:
|
||
db.execute_query("""
|
||
INSERT INTO sales
|
||
(partner_id, product_name, quantity, sale_date)
|
||
VALUES (%s, %s, %s, %s)
|
||
""", (
|
||
int(row.get('partner_id')),
|
||
row.get('product_name'),
|
||
row.get('quantity'),
|
||
row.get('sale_date')
|
||
))
|
||
processed += 1
|
||
except Exception as e:
|
||
errors.append(f"Row {index}: {str(e)}")
|
||
|
||
return UploadResponse(
|
||
message="File processed successfully",
|
||
processed_rows=processed,
|
||
errors=errors
|
||
)
|
||
|
||
except Exception as e:
|
||
raise HTTPException(status_code=500, detail=str(e))
|