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

33 lines
2.3 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, multiply_price=1, sheet_name=''):
df = df[['Ваш SKU', 'Количество, шт.', 'Сумма транзакции, ₽']].copy().dropna() #выбираем нужные колонки, делаем копию, чтобы можно было удалить None inline модом
df = df[(df != 0).all(axis=1)] #drop all 0 values
df['Сумма транзакции, ₽'] *= multiply_price #умножаем на -1 для возвратов
df.rename(columns={'Ваш SKU': 'arti', 'Количество, шт.': 'counts', 'Сумма транзакции, ₽': 'price'}, inplace=True) #переименовываем для pydantic
df['arti'] = df['arti'].astype(str).str.extract(f'({PATTERN})', flags=re.IGNORECASE) #regex implemented
df['price'] = df['price'].astype(float) #To float, if exists
df['counts'] = df['counts'].astype(int) #To float, if exists
df = df.groupby('arti', as_index=False).agg({'counts': 'sum', 'price': 'sum'}) #groupping
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 {sheet_name}, check it ", errors)
return validated_rows
def evaluating(dfs):
validated_rows_1 = process_sheet(dfs["Получено от потребителей"], sheet_name="Получено от потребителей")
validated_rows_2 = process_sheet(dfs["Возвращено потребителям"], multiply_price=-1, sheet_name="Возвращено потребителям")
return validated_rows_1, validated_rows_2