wb_real_handler 1.0 + yandex_real_handler 1.1
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import pandas as pd
|
||||
import server.backend.handlers.yandex_handler as yandex_handler
|
||||
import server.backend.handlers.wb_handler as wb_handler
|
||||
# def read_excel(base_dir):
|
||||
# try:
|
||||
# dfs = pd.read_excel(base_dir, sheet_name=None)
|
||||
@@ -37,7 +38,8 @@ class WBHandler(BaseHandler):
|
||||
dfs = pd.read_excel(self.file_path, sheet_name=None)
|
||||
if "Sheet1" not in dfs :
|
||||
raise Exception(f"В файле {self.file_path.name} отсутствуют необходимые листы")
|
||||
print("Реализация WB")
|
||||
validated_data = wb_handler.evaluating(dfs)
|
||||
print("Реализация WB завершена, валидированных строк:", len(validated_data[0]), "Реализация", len(validated_data[1]), "Возвраты")
|
||||
|
||||
class OZONHandler(BaseHandler):
|
||||
def process(self):
|
||||
|
||||
35
server/backend/handlers/wb_handler.py
Normal file
35
server/backend/handlers/wb_handler.py
Normal file
@@ -0,0 +1,35 @@
|
||||
from pydantic import ValidationError
|
||||
from server.backend.pydantic import ExcelInfo
|
||||
import re
|
||||
def process_sheet(df, document_type= ''):
|
||||
pattern = r'[A-ZА-Я]{0,1}\d{4}[A-ZА-Я]{1,2}\d{1}' #regex
|
||||
df = df[['Артикул поставщика', 'Тип документа', 'Кол-во', 'Вайлдберриз реализовал Товар (Пр)']].copy().dropna() #copy and drop all NA values
|
||||
df = df[(df != 0).all(axis=1)] #drop all 0 values
|
||||
df_validate = df[['Артикул поставщика', 'Кол-во', 'Вайлдберриз реализовал Товар (Пр)']].copy()
|
||||
df_validate.rename(columns={'Артикул поставщика': 'arti', 'Кол-во': 'counts', 'Вайлдберриз реализовал Товар (Пр)': 'price'}, inplace=True) #переименовываем для pydantic
|
||||
df_validate['arti'] = df_validate['arti'].astype(str).str.extract(f'({pattern})', flags=re.IGNORECASE) #arti под regex
|
||||
|
||||
df_validate['price'] = df_validate['price'].astype(float) #Float to Int, if exists
|
||||
df_validate['counts'] = df_validate['counts'].astype(int) #Float to Int, if exists
|
||||
|
||||
validated_rows, errors = [], []
|
||||
for i, row in df_validate.iterrows(): #проходит построчно по df, где i - индекс строки, row - данные строки
|
||||
try:
|
||||
if df.loc[i, 'Тип документа'] == document_type:
|
||||
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
|
||||
|
||||
@@ -6,9 +6,13 @@ def process_sheet(df, multiply_price=1, sheet_name=''):
|
||||
pattern = r'[A-ZА-Я]{0,1}\d{4}[A-ZА-Я]{1,2}\d{1}'
|
||||
|
||||
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) #
|
||||
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
|
||||
|
||||
validated_rows, errors = [], []
|
||||
for i, row in df.iterrows(): #проходит построчно по df, где i - индекс строки, row - данные строки
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
class ExcelInfo(BaseModel):
|
||||
arti:str = Field(..., min_length=6, max_length=12, description="arti of the clothes")
|
||||
counts:int = Field(..., ge=0, description="the quantity of the clothes")
|
||||
price:int = Field(..., ge=0, description="the price of the clothes")
|
||||
counts:int = Field(..., gt=0, description="the quantity of the clothes")
|
||||
price:float = Field(..., gt=0, description="the price of the clothes")
|
||||
class ExcelRealization(BaseModel):
|
||||
pass
|
||||
class ExcelReturning(BaseModel):
|
||||
|
||||
Reference in New Issue
Block a user