Files
Excel-project/server/backend/handlers/wb_handler.py
2025-11-08 22:09:10 +03:00

42 lines
2.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from pydantic import ValidationError
from server.backend.pydantic import ExcelInfo
import re
from dotenv import load_dotenv #Работа с env
import os
load_dotenv()
PATTERN = os.getenv("PATTERN")
def process_sheet(df, document_type:str):
df = df[['Артикул поставщика', 'Тип документа', 'Кол-во', 'Вайлдберриз реализовал Товар (Пр)']].copy().dropna() #copy and drop all NA values
df = df[(df != 0).all(axis=1)] #drop all 0 values
df = df[df['Тип документа'] == document_type] #фильтруем по типу документа
df = df[['Артикул поставщика', 'Кол-во', 'Вайлдберриз реализовал Товар (Пр)']].copy()
df.rename(columns={'Артикул поставщика': 'arti', 'Кол-во': 'counts', 'Вайлдберриз реализовал Товар (Пр)': 'price'}, inplace=True) #переименовываем для pydantic
df['arti'] = df['arti'].astype(str).str.extract(f'({PATTERN})', flags=re.IGNORECASE) #arti под regex
df['price'] = df['price'].astype(float) #Float to Int, if exists
df['counts'] = df['counts'].astype(int) #Float to Int, if exists
df = df.groupby('arti', as_index=False).agg({'counts': 'sum', 'price': 'sum'})
validated_rows, errors = [], []
for i, row in df.iterrows(): #проходит построчно по df, где i - индекс строки, row - данные строки
try:
validated_rows.append(ExcelInfo(**row.to_dict())) #добавляем в список проверенные данные полученные от pydantic, которые туда передаются в виде dict
except ValidationError as e:
errors.append((i, e.errors())) #выводит ошибку и пишет номер строки
if errors:
raise Exception(f"There are some errors with validation in Sheet1, check it ", errors)
return validated_rows
def evaluating(dfs):
validated_rows_1 = process_sheet(dfs["Sheet1"], document_type='Продажа')
validated_rows_2 = process_sheet(dfs["Sheet1"], document_type='Возврат')
# sum_1 = sum(row.price for row in validated_rows_1)
# sum_2 = sum(row.price for row in validated_rows_2)
# print("Sum for 'Продажа':", sum_1)
# print("Sum for 'Возврат':", sum_2)
return validated_rows_1, validated_rows_2