Compare commits
3 Commits
0db1509f0f
...
1239db4e23
| Author | SHA1 | Date | |
|---|---|---|---|
| 1239db4e23 | |||
| ee439c6bf6 | |||
| 6abceda30e |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -4,4 +4,7 @@ __pycache__
|
||||
.env
|
||||
.cursorignore
|
||||
logs/
|
||||
files/
|
||||
files/
|
||||
Настроено/
|
||||
Не настроено/
|
||||
проблемные/
|
||||
28
src/mail_order_bot/config2.yml
Normal file
28
src/mail_order_bot/config2.yml
Normal file
@@ -0,0 +1,28 @@
|
||||
clients:
|
||||
"todx.ru":
|
||||
- handler: "OrderParser",
|
||||
config:
|
||||
sheet_name: "Лист1"
|
||||
key_value: "Артикул"
|
||||
mapping:
|
||||
name: "Наименование"
|
||||
manufacturer: "Производитель"
|
||||
price: "Цена\nдетали"
|
||||
quantity: "Кол-\nво"
|
||||
total: "Сумма"
|
||||
- handler: "OrderCreator"
|
||||
- handler: "ExcelWriter"
|
||||
config: "output.xlsx"
|
||||
- handler: "EmailSender"
|
||||
config:
|
||||
to: "todx@yandex.ru"
|
||||
- Notifier:
|
||||
- channel: "email"
|
||||
to : "status@zapchastiya.ru"
|
||||
- channel: "telegram"
|
||||
to: "123454323"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
17
src/mail_order_bot/configs/todx.ru.yml
Normal file
17
src/mail_order_bot/configs/todx.ru.yml
Normal file
@@ -0,0 +1,17 @@
|
||||
pipeline:
|
||||
- handler: "ConfigurableExcelParser"
|
||||
result_section: "positions"
|
||||
config:
|
||||
sheet_name: 0
|
||||
key_field: "Код детали"
|
||||
mapping:
|
||||
article: "Код детали"
|
||||
manufacturer: "Производитель"
|
||||
name: "Наименование"
|
||||
price: "Цена\nдетали"
|
||||
quantity: "Кол-\nво"
|
||||
total: "Сумма"
|
||||
|
||||
|
||||
|
||||
|
||||
1
src/mail_order_bot/task_handler/__init__.py
Normal file
1
src/mail_order_bot/task_handler/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from .processor import TaskProcessor
|
||||
21
src/mail_order_bot/task_handler/abcp_client/OrderCreator.py
Normal file
21
src/mail_order_bot/task_handler/abcp_client/OrderCreator.py
Normal file
@@ -0,0 +1,21 @@
|
||||
import logging
|
||||
import requests
|
||||
from ..abstract_task import AbstractTask
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class InstantOrderTest(AbstractTask):
|
||||
URL = "https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}"
|
||||
|
||||
def do(self) -> None:
|
||||
|
||||
positions = self.context["positions"]
|
||||
|
||||
message = f"Запрос на создание заказа от {self.context['client']}:\n"
|
||||
message += "\n".join(f"{pos.article}: {pos.name} ({pos.quantity} x {pos.price} = {pos.total})" for pos in positions)
|
||||
|
||||
api_key = self.config["api_key"]
|
||||
chat_id = self.config["chat_id"]
|
||||
url = self.URL.format(api_key, chat_id, message)
|
||||
resp = requests.get(url).json()
|
||||
logger.info(resp)
|
||||
22
src/mail_order_bot/task_handler/abstract_task.py
Normal file
22
src/mail_order_bot/task_handler/abstract_task.py
Normal file
@@ -0,0 +1,22 @@
|
||||
import logging
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Dict, Any
|
||||
|
||||
|
||||
class AbstractTask(ABC):
|
||||
"""
|
||||
Абстрактный базовый класс для всех хэндлеров.
|
||||
"""
|
||||
def __init__(self, config: Dict[str, Any], context: Dict[str, Any],*args, **kwargs) -> None:
|
||||
self.config = config
|
||||
self.context = context
|
||||
|
||||
@abstractmethod
|
||||
def do(self) -> None:
|
||||
"""
|
||||
Выполняет работу над заданием
|
||||
Входные и выходные данные - в self.context
|
||||
Конфиг задается при инициализации
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import logging
|
||||
import pandas as pd
|
||||
from typing import Dict, Any, Optional, List
|
||||
from decimal import Decimal
|
||||
from io import BytesIO
|
||||
from .order_position import OrderPosition
|
||||
from ..abstract_task import AbstractTask
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BasicExcelParser(AbstractTask):
|
||||
RESULT_SECTION = "positions"
|
||||
"""
|
||||
Универсальный парсер, настраиваемый через конфигурацию.
|
||||
Подходит для большинства стандартных случаев.
|
||||
"""
|
||||
|
||||
def do(self) -> None:
|
||||
|
||||
# todo сделать проверку на наличие файла и его тип
|
||||
file_bytes = BytesIO(self.context.get("attachment")) # self.context.get("attachment") #
|
||||
try:
|
||||
df = self._make_dataframe(file_bytes)
|
||||
# Получаем маппинг колонок из конфигурации
|
||||
mapping = self.config['mapping']
|
||||
|
||||
# Парсим строки
|
||||
positions = []
|
||||
for idx, row in df.iterrows():
|
||||
try:
|
||||
position = self._parse_row(row, mapping)
|
||||
if position:
|
||||
positions.append(position)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка парсинга строки {idx}: {e}, {row}")
|
||||
continue
|
||||
|
||||
logger.info(f"Успешно обработано {len(positions)} позиций из {len(df)} строк")
|
||||
|
||||
self.context[self.RESULT_SECTION] = positions
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при обработке файла: {e}")
|
||||
raise Exception from e
|
||||
|
||||
def _parse_row(self, row: pd.Series, mapping: Dict[str, str]) -> Optional[OrderPosition]:
|
||||
"""Парсит одну строку Excel в OrderPosition"""
|
||||
|
||||
# Проверяем обязательные поля
|
||||
required_fields = ['article', 'price', 'quantity']
|
||||
|
||||
for field in required_fields:
|
||||
if pd.isna(row.get(mapping[field])):
|
||||
logger.warning(f"Позиция не создана - не заполнено поле {mapping[field]}")
|
||||
return None
|
||||
|
||||
price = Decimal(str(row[mapping['price']]).replace(",", ".").strip())
|
||||
quantity = int(row[mapping['quantity']])
|
||||
|
||||
if "total" in mapping.keys():
|
||||
total = Decimal(str(row[mapping['total']]).replace(",", ".").strip())
|
||||
else:
|
||||
total = price * quantity
|
||||
|
||||
if mapping.get('name', "") in mapping.keys():
|
||||
name = str(row[mapping.get('name', "")]).strip()
|
||||
else:
|
||||
name = ""
|
||||
|
||||
# Создаем объект позиции
|
||||
position = OrderPosition(
|
||||
article=str(row[mapping['article']]).strip(),
|
||||
manufacturer=str(row[mapping.get('manufacturer', "")]).strip(),
|
||||
name=name,
|
||||
price=price,
|
||||
quantity=quantity,
|
||||
total=total,
|
||||
additional_attrs=self._extract_additional_attrs(row, mapping)
|
||||
)
|
||||
return position
|
||||
|
||||
def _extract_additional_attrs(self, row: pd.Series, mapping: Dict[str, str]) -> Dict[str, Any]:
|
||||
"""Извлекает дополнительные атрибуты, не входящие в основную модель"""
|
||||
additional = {}
|
||||
mapped_columns = set(mapping.values())
|
||||
|
||||
for col in row.index:
|
||||
if col not in mapped_columns and not pd.isna(row[col]):
|
||||
additional[col] = row[col]
|
||||
|
||||
return additional
|
||||
|
||||
def _make_dataframe(self, bio) -> pd.DataFrame:
|
||||
# Получаем все данные из файла
|
||||
sheet_name = self.config.get("sheet_name", 0)
|
||||
df_full = pd.read_excel(bio, sheet_name=sheet_name, header=None)
|
||||
|
||||
# Находим индекс строки с заголовком
|
||||
key_field = self.config.get("key_field")
|
||||
header_row_idx = df_full[
|
||||
df_full.apply(lambda row: row.astype(str).str.contains(key_field, case=False, na=False).any(),
|
||||
axis=1)].index[0]
|
||||
|
||||
# Считываем таблицу с правильным заголовком
|
||||
df = pd.read_excel(bio, header=header_row_idx, sheet_name=sheet_name, engine='calamine') # openpyxl calamine
|
||||
|
||||
# Находим индекс первой строки с пустым 'Артикул'
|
||||
first_empty_index = df[df[key_field].isna()].index.min()
|
||||
|
||||
# Обрезаем DataFrame до первой пустой строки (не включая её)
|
||||
df_trimmed = df.loc[:first_empty_index - 1]
|
||||
|
||||
return df_trimmed
|
||||
@@ -0,0 +1,25 @@
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, Any
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
@dataclass
|
||||
class OrderPosition:
|
||||
"""
|
||||
Унифицированная модель позиции для заказа.
|
||||
Все контрагенты приводятся к этой структуре.
|
||||
"""
|
||||
article: str # Артикул товара
|
||||
manufacturer: str # Производитель
|
||||
name: str # Наименование
|
||||
price: Decimal # Цена за единицу
|
||||
quantity: int # Количество
|
||||
total: Decimal # Общая сумма
|
||||
additional_attrs: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self):
|
||||
"""Валидация после инициализации"""
|
||||
if self.quantity < 0:
|
||||
raise ValueError(f"Количество не может быть отрицательным: {self.quantity}")
|
||||
if self.price < 0:
|
||||
raise ValueError(f"Цена не может быть отрицательной: {self.price}")
|
||||
18
src/mail_order_bot/task_handler/notifiers/test_notifier.py
Normal file
18
src/mail_order_bot/task_handler/notifiers/test_notifier.py
Normal file
@@ -0,0 +1,18 @@
|
||||
import logging
|
||||
import pandas as pd
|
||||
from typing import Dict, Any, Optional, List
|
||||
from decimal import Decimal
|
||||
|
||||
from ..abstract_task import AbstractTask
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class TestNotifier(AbstractTask):
|
||||
def do(self) -> None:
|
||||
|
||||
positions = self.context["positions"]
|
||||
|
||||
print(f"\nПолучено {len(positions)} позиций от {self.context["client"]}:")
|
||||
for pos in positions: # Первые 5
|
||||
print(f" - {pos.article}: {pos.name} "
|
||||
f"({pos.quantity} x {pos.price} = {pos.total})")
|
||||
15
src/mail_order_bot/task_handler/order.py
Normal file
15
src/mail_order_bot/task_handler/order.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from enum import Enum
|
||||
|
||||
class OrderStatus(Enum):
|
||||
NEW = 1
|
||||
IN_PROGRESS = 2
|
||||
COMPLETED = 3
|
||||
FAILED = 4
|
||||
OPERATOR_HANDLING = 5
|
||||
INVALID = 6
|
||||
|
||||
|
||||
class Order:
|
||||
def __init__(self, context: dict):
|
||||
attachment = context["attachment"]
|
||||
self.context = context
|
||||
41
src/mail_order_bot/task_handler/processor.py
Normal file
41
src/mail_order_bot/task_handler/processor.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
import yaml
|
||||
import logging
|
||||
from typing import Dict, Any
|
||||
from pathlib import Path
|
||||
|
||||
from ..task_handler.excel_parsers.basic_excel_parcer import BasicExcelParser
|
||||
from ..task_handler.notifiers.test_notifier import TestNotifier
|
||||
from ..task_handler.abcp_client.OrderCreator import InstantOrderTest
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class TaskProcessor:
|
||||
def __init__(self, config_path: Path):
|
||||
self.config_path = config_path
|
||||
self.context = dict()
|
||||
|
||||
def process(self, client, attachment):
|
||||
config = self._load_config(client)
|
||||
self.context = dict()
|
||||
self.context["client"] = client
|
||||
self.context["attachment"] = attachment.content
|
||||
|
||||
self.context["status"] = client
|
||||
|
||||
for stage in config["pipeline"]:
|
||||
handler_name = stage["handler"]
|
||||
logger.info(f"Processing handler: {handler_name}")
|
||||
task = globals()[handler_name](stage.get("config", None), self.context)
|
||||
task.do()
|
||||
|
||||
return self.context
|
||||
|
||||
|
||||
pass
|
||||
def _load_config(self, client) -> Dict[str, Any]:
|
||||
"""Загружает конфигурацию из YAML или JSON"""
|
||||
path = os.path.join(self.config_path, client + '.yml')
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
return yaml.safe_load(f)
|
||||
27
tests/excel_processor/configs/todx.ru.yml
Normal file
27
tests/excel_processor/configs/todx.ru.yml
Normal file
@@ -0,0 +1,27 @@
|
||||
# Конфигурационный файл для контрагента todx.ru
|
||||
|
||||
pipeline:
|
||||
# Обработчик вложений
|
||||
- handler: "BasicExcelParser"
|
||||
config:
|
||||
sheet_name: 0
|
||||
key_field: "Код детали"
|
||||
mapping:
|
||||
article: "Код детали"
|
||||
manufacturer: "Производитель"
|
||||
name: "Наименование"
|
||||
price: "Цена\nдетали"
|
||||
quantity: "Кол-\nво"
|
||||
total: "Сумма"
|
||||
|
||||
- handler: InstantOrderTest
|
||||
config:
|
||||
api_key: "8056899069:AAFEfw9QRMvmEwQyH0CI4e_v_sZuOSdNWcE"
|
||||
chat_id: 211945135
|
||||
|
||||
- handler: "TestNotifier"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
59
tests/excel_processor/hanler_test.py
Normal file
59
tests/excel_processor/hanler_test.py
Normal file
@@ -0,0 +1,59 @@
|
||||
import os
|
||||
import chardet # pip install chardet
|
||||
import traceback
|
||||
from mail_order_bot.task_handler import TaskProcessor
|
||||
import datetime
|
||||
# установим рабочую директорию
|
||||
import os
|
||||
|
||||
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
||||
from io import BytesIO
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.WARNING, format='%(module)s - %(message)s') # %(asctime)s -
|
||||
BASE_PATH = './files'
|
||||
|
||||
|
||||
from mail_order_bot.email_client import EmailMessage, EmailAttachment
|
||||
|
||||
processor = TaskProcessor("./configs")
|
||||
|
||||
for provider_name in os.listdir(BASE_PATH):
|
||||
provider_folder = os.path.join(BASE_PATH, provider_name)
|
||||
if os.path.isdir(provider_folder):
|
||||
for file_name in os.listdir(provider_folder):
|
||||
file_path = os.path.join(provider_folder, file_name)
|
||||
if os.path.isfile(file_path):
|
||||
with open(file_path, 'rb') as file: # бинарный режим
|
||||
raw_data = file.read()
|
||||
|
||||
# Создаем объект EmailAttachment
|
||||
att = EmailAttachment(file_name, raw_data)
|
||||
email = EmailMessage(
|
||||
from_addr=provider_name,
|
||||
from_email='test@gmail.com',
|
||||
subj='order request',
|
||||
dt=datetime.datetime.now(),
|
||||
body= 'body text',
|
||||
attachments=[att],
|
||||
first_sender='test@gmail.com'
|
||||
)
|
||||
|
||||
|
||||
|
||||
#bio = BytesIO(raw_data)
|
||||
print("========================================================")
|
||||
print(f'Обработка: {provider_name} - {file_name}')
|
||||
try:
|
||||
|
||||
positions_a = processor.process(provider_name, att)
|
||||
|
||||
|
||||
|
||||
|
||||
except Exception as e:
|
||||
print(f"Ошибка обработки: {e}", traceback.format_exc())
|
||||
|
||||
|
||||
Reference in New Issue
Block a user