Compare commits
9 Commits
816da1eb16
...
features/f
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b5bba2a17 | |||
| f96b0a076b | |||
| 4cb8c9c88e | |||
| 55ba627f6b | |||
| b26485c5cc | |||
| 0022141684 | |||
| 7043743373 | |||
| 0c39af460f | |||
| 1222488aec |
9
business_rules/br.md
Normal file
9
business_rules/br.md
Normal file
@@ -0,0 +1,9 @@
|
||||
Создание заказа через API ABCP
|
||||
1. Логинимся под учеткой заказчика
|
||||
2. Получаем остатки
|
||||
3. Отсекаем не подходящие по сроку (дольше) и цене
|
||||
4. Подбираем позицию максимально близкую к цене из заказа
|
||||
- Приоритет отдаем складу, где есть все заказы
|
||||
- Приоритет отдаем позициям из наличия, потом с доставкой с других складов
|
||||
- По цене выбираем наиболее близкую к цене заказа (меньше или равно)
|
||||
- При невозможности заказать в одном месте разбиваем заказ из нескольких складов
|
||||
@@ -10,3 +10,7 @@ IMAP_PORT=993
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
SMTP_PORT=587
|
||||
|
||||
# Telegram Bot settings
|
||||
TELEGRAM_BOT_TOKEN=your_bot_token_here
|
||||
TELEGRAM_CHAT_ID=your_chat_id_here
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
from .main import MailOrderBotException
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
Классы для работы с API платформы ABCP
|
||||
"""
|
||||
|
||||
from .abcp_provider import AbcpProvider
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import os
|
||||
import hashlib
|
||||
import requests
|
||||
import logging
|
||||
@@ -13,19 +12,28 @@ class AbcpProvider:
|
||||
"Content-Type": "application/x-www-form-urlencoded"
|
||||
}
|
||||
|
||||
def __init__(self, account="SYSTEM"):
|
||||
self.base_url = self.HOST
|
||||
def __init__(self, login: str, password: str):
|
||||
"""
|
||||
Инициализация AbcpProvider.
|
||||
|
||||
def get_stock(self, sku, manufacturer, partner="SYSTEM"):
|
||||
Args:
|
||||
login: Логин для доступа к API
|
||||
password: Пароль для доступа к API
|
||||
"""
|
||||
self.base_url = self.HOST
|
||||
self.login = login
|
||||
self.password = password
|
||||
|
||||
def get_stock(self, sku, manufacturer):
|
||||
method = "GET"
|
||||
path = "/search/articles"
|
||||
|
||||
params = {"number": sku, "brand": manufacturer, "withOutAnalogs": "1"}
|
||||
return self._execute(partner, path, method, params)
|
||||
return self._execute(path, method, params)
|
||||
|
||||
def _execute(self, partner, path, method="GET", params={}, data=None, ):
|
||||
params["userlogin"] = os.getenv(f"ABCP_LOGIN_{partner}")
|
||||
params["userpsw"] = hashlib.md5(os.getenv(f"ABCP_PASSWORD_{partner}").encode("utf-8")).hexdigest()
|
||||
def _execute(self, path, method="GET", params={}, data=None):
|
||||
params["userlogin"] = self.login
|
||||
params["userpsw"] = hashlib.md5(self.password.encode("utf-8")).hexdigest()
|
||||
|
||||
response = requests.request(method, self.HOST+path, data=data, headers=self.HEADERS, params=params)
|
||||
payload = response.json()
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
"""
|
||||
Пакет содержит реализацию для создания заказов из вложений.
|
||||
|
||||
На входе файл из вложения
|
||||
Его обработка производится хендлерами, коотрые настраиваются в конфиге
|
||||
На выходе - экземпляр класса, который в себе содержит
|
||||
- прочитанный файл в виде pandas DataFrame
|
||||
- распарсенный файл заказа с позициями
|
||||
- полученные остатки
|
||||
- результат проверки возможности создания заказа
|
||||
|
||||
Так же класс содержит методы
|
||||
- для создания заказа
|
||||
- для получения отредактированного файла
|
||||
|
||||
"""
|
||||
|
||||
from .processor import TaskProcessor
|
||||
@@ -1,9 +0,0 @@
|
||||
from .abcp_clients.check_stock import GetStock
|
||||
from .abcp_clients.create_order import InstantOrderTest
|
||||
|
||||
from .excel_parcers.basic_excel_parcer import BasicExcelParser
|
||||
|
||||
from .notifications.test_notifier import TestNotifier
|
||||
|
||||
|
||||
from .validators.price_quantity_ckecker import CheckOrder
|
||||
@@ -1,26 +0,0 @@
|
||||
import random
|
||||
import logging
|
||||
from mail_order_bot.attachment_handler.handlers.abstract_task import AbstractTask
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_stock(brand, part_number):
|
||||
return random.randint(0, 10)
|
||||
|
||||
class GetStock(AbstractTask):
|
||||
|
||||
def do(self) -> None:
|
||||
positions = self.order.positions
|
||||
for position in positions:
|
||||
self._update_stock(position)
|
||||
|
||||
def _update_stock(self, position):
|
||||
# Эмулируем получение данных
|
||||
max_stock = self.config.get('max_stock',10)
|
||||
stock = random.randint(0, max_stock)
|
||||
price = position.requested_price
|
||||
|
||||
position.stock_price = price
|
||||
position.stock_quantity = stock
|
||||
@@ -1,37 +0,0 @@
|
||||
import logging
|
||||
import requests
|
||||
from mail_order_bot.attachment_handler.handlers.abstract_task import AbstractTask
|
||||
from mail_order_bot.attachment_handler.order.auto_part_order import OrderStatus
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class InstantOrderTest(AbstractTask):
|
||||
URL = "https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}"
|
||||
|
||||
def do(self) -> None:
|
||||
api_key = self.config["api_key"]
|
||||
chat_id = self.config["chat_id"]
|
||||
|
||||
if self.order.status == OrderStatus.IN_PROGRESS:
|
||||
positions = self.order.positions
|
||||
|
||||
message = f"Запрос на создание заказа от {self.context['client']}:\n"
|
||||
message += "\n".join(f"{pos.sku}: {pos.name} ({pos.order_quantity} x {pos.order_price} = {pos.total})" for pos in positions)
|
||||
|
||||
elif self.order.status == OrderStatus.OPERATOR_REQUIRED:
|
||||
message = f"Запрос на создание заказа от {self.context['client']} отклонен - необходима ручная обработка.\n"
|
||||
message += f"Причина: {self.order.reason}"
|
||||
|
||||
else:
|
||||
message = f"Запрос на создание заказа от {self.context['client']} отклонен.\n"
|
||||
message += f" Статус заказа: {self.order.status}"
|
||||
|
||||
#url = self.URL.format(api_key, chat_id, message)
|
||||
#resp = requests.get(url).json()
|
||||
print(message)
|
||||
#logger.info(resp)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import logging
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Dict, Any
|
||||
from ..order.auto_part_order import AutoPartOrder
|
||||
|
||||
class AbstractTask(ABC):
|
||||
RESULT_SECTION = "section"
|
||||
"""
|
||||
Абстрактный базовый класс для всех хэндлеров.
|
||||
"""
|
||||
def __init__(self, config: Dict[str, Any], context: Dict[str, Any], order: AutoPartOrder, *args, **kwargs) -> None:
|
||||
self.config = config
|
||||
self.context = context
|
||||
self.order = order
|
||||
|
||||
@abstractmethod
|
||||
def do(self) -> None:
|
||||
"""
|
||||
Выполняет работу над заданием
|
||||
Входные и выходные данные - в self.context
|
||||
Конфиг задается при инициализации
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
|
||||
import smtplib
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.base import MIMEBase
|
||||
from email.utils import formatdate
|
||||
from email import encoders
|
||||
from abc import ABC, abstractmethod
|
||||
import os
|
||||
|
||||
|
||||
class AbstractTask(ABC):
|
||||
"""Базовый класс для задач"""
|
||||
|
||||
def __init__(self, context, config):
|
||||
self.context = context
|
||||
self.config = config
|
||||
|
||||
@abstractmethod
|
||||
def do(self):
|
||||
"""Метод для реализации в подклассах"""
|
||||
pass
|
||||
|
||||
|
||||
class EmailReplyTask(AbstractTask):
|
||||
"""Класс для ответа на электронные письма"""
|
||||
|
||||
def do(self):
|
||||
"""
|
||||
Отправляет ответ на входящее письмо
|
||||
|
||||
Ожидает в self.context:
|
||||
- message: email.message.Message объект входящего письма
|
||||
- attachment: путь к файлу для вложения
|
||||
|
||||
Ожидает в self.config:
|
||||
- reply_to: адрес электронной почты для копии
|
||||
- smtp_host: хост SMTP сервера
|
||||
- smtp_port: порт SMTP сервера
|
||||
- smtp_user: пользователь SMTP
|
||||
- smtp_password: пароль SMTP
|
||||
- from_email: адрес отправителя
|
||||
"""
|
||||
|
||||
incoming_message = self.context.get("message")
|
||||
attachment_path = self.context.get("attacnment")
|
||||
|
||||
if not incoming_message:
|
||||
raise ValueError("В context не найдено письмо (message)")
|
||||
|
||||
# Получаем адрес отправителя входящего письма
|
||||
from_addr = incoming_message.get("From")
|
||||
if not from_addr:
|
||||
raise ValueError("Входящее письмо не содержит адреса отправителя")
|
||||
|
||||
# Создаем ответное письмо
|
||||
reply_message = MIMEMultipart()
|
||||
|
||||
# Заголовки ответного письма
|
||||
reply_message["From"] = self.config.get("from_email", "noreply@example.com")
|
||||
reply_message["To"] = from_addr
|
||||
reply_message["Cc"] = self.config.get("reply_to", "")
|
||||
reply_message["Subject"] = f"Re: {incoming_message.get('Subject', '')}"
|
||||
reply_message["Date"] = formatdate(localtime=True)
|
||||
|
||||
# Тело письма
|
||||
body = "Ваш заказ создан"
|
||||
reply_message.attach(MIMEText(body, "plain", "utf-8"))
|
||||
|
||||
# Добавляем вложение если указан путь к файлу
|
||||
if attachment_path and os.path.isfile(attachment_path):
|
||||
self._attach_file(reply_message, attachment_path)
|
||||
|
||||
# Отправляем письмо
|
||||
self._send_email(reply_message, from_addr)
|
||||
|
||||
def _attach_file(self, message, file_path):
|
||||
"""
|
||||
Добавляет файл в качестве вложения к письму
|
||||
|
||||
Args:
|
||||
message: MIMEMultipart объект
|
||||
file_path: путь к файлу для вложения
|
||||
"""
|
||||
try:
|
||||
with open(file_path, "rb") as attachment:
|
||||
part = MIMEBase("application", "octet-stream")
|
||||
part.set_payload(attachment.read())
|
||||
|
||||
encoders.encode_base64(part)
|
||||
|
||||
file_name = os.path.basename(file_path)
|
||||
part.add_header(
|
||||
"Content-Disposition",
|
||||
f"attachment; filename= {file_name}"
|
||||
)
|
||||
|
||||
message.attach(part)
|
||||
except FileNotFoundError:
|
||||
raise FileNotFoundError(f"Файл не найден: {file_path}")
|
||||
except Exception as e:
|
||||
raise Exception(f"Ошибка при добавлении вложения: {str(e)}")
|
||||
|
||||
def _send_email(self, message, recipient):
|
||||
"""
|
||||
Отправляет письмо через SMTP
|
||||
|
||||
Args:
|
||||
message: MIMEMultipart объект письма
|
||||
recipient: адрес получателя
|
||||
"""
|
||||
try:
|
||||
smtp_host = self.config.get("smtp_host")
|
||||
smtp_port = self.config.get("smtp_port", 587)
|
||||
smtp_user = self.config.get("smtp_user")
|
||||
smtp_password = self.config.get("smtp_password")
|
||||
|
||||
if not all([smtp_host, smtp_user, smtp_password]):
|
||||
raise ValueError("Не указаны параметры SMTP в config")
|
||||
|
||||
with smtplib.SMTP(smtp_host, smtp_port) as server:
|
||||
server.starttls()
|
||||
server.login(smtp_user, smtp_password)
|
||||
|
||||
# Получаем адреса получателей (основной + копия)
|
||||
recipients = [recipient]
|
||||
reply_to = self.config.get("reply_to")
|
||||
if reply_to:
|
||||
recipients.append(reply_to)
|
||||
|
||||
server.sendmail(
|
||||
self.config.get("from_email"),
|
||||
recipients,
|
||||
message.as_string()
|
||||
)
|
||||
except smtplib.SMTPException as e:
|
||||
raise Exception(f"Ошибка SMTP: {str(e)}")
|
||||
except Exception as e:
|
||||
raise Exception(f"Ошибка при отправке письма: {str(e)}")
|
||||
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
import logging
|
||||
import pandas as pd
|
||||
from typing import Dict, Any, Optional
|
||||
from decimal import Decimal
|
||||
from io import BytesIO
|
||||
#from mail_order_bot.attachment_handler.handlers.order_position import OrderPosition
|
||||
from mail_order_bot.attachment_handler.handlers.abstract_task import AbstractTask
|
||||
|
||||
from ...order.auto_part_position import AutoPartPosition
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BasicExcelParser(AbstractTask):
|
||||
RESULT_SECTION = "positions"
|
||||
"""
|
||||
Универсальный парсер, настраиваемый через конфигурацию.
|
||||
Подходит для большинства стандартных случаев.
|
||||
"""
|
||||
|
||||
def do(self) -> None:
|
||||
|
||||
# todo сделать проверку на наличие файла и его тип
|
||||
file_bytes = BytesIO(self.context.get("attachment").content) # 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)
|
||||
self.order.add_position(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[AutoPartPosition]:
|
||||
"""Парсит одну строку 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 = AutoPartPosition(
|
||||
sku=str(row[mapping['article']]).strip(),
|
||||
manufacturer=str(row[mapping.get('manufacturer', "")]).strip(),
|
||||
name=name,
|
||||
requested_price=price,
|
||||
requested_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
|
||||
@@ -1,15 +0,0 @@
|
||||
import logging
|
||||
|
||||
from mail_order_bot.attachment_handler.handlers.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.sku}: {pos.name} "
|
||||
f"({pos.requested_quantity} x {pos.requested_price} = {pos.total})")
|
||||
@@ -1,50 +0,0 @@
|
||||
import random
|
||||
import logging
|
||||
from mail_order_bot.attachment_handler.handlers.abstract_task import AbstractTask
|
||||
from mail_order_bot.attachment_handler.order.auto_part_order import OrderStatus
|
||||
from decimal import Decimal
|
||||
import random
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CheckOrder(AbstractTask):
|
||||
|
||||
def do(self) -> None:
|
||||
refused = 0
|
||||
positions = self.order.positions
|
||||
for position in positions:
|
||||
self._set_order_price(position)
|
||||
self._set_order_quantity(position)
|
||||
|
||||
if position.order_price == 0 or position.order_quantity == 0:
|
||||
refused += 1
|
||||
|
||||
self._check_refusal_threshold(refused)
|
||||
|
||||
|
||||
def _set_order_price(self, position):
|
||||
# Эмулируем получение данных
|
||||
acceptable_price_reduction = self.config.get("acceptable_price_reduction")
|
||||
acceptable_price = position.stock_price* Decimal(str((1-acceptable_price_reduction/100)))
|
||||
|
||||
if position.requested_price < acceptable_price:
|
||||
position.order_price = 0
|
||||
else:
|
||||
position.order_price = position.requested_price
|
||||
|
||||
def _set_order_quantity(self, position):
|
||||
max_stock = self.config.get("max_stock", 100)
|
||||
min_stock = self.config.get("min_stock", 0)
|
||||
|
||||
stock_quantity = random.randint(min_stock, max_stock)
|
||||
|
||||
position.order_quantity = max(0, min(position.stock_quantity, stock_quantity))
|
||||
|
||||
def _check_refusal_threshold(self, refused):
|
||||
refusal_threshold_limit = self.config.get("refusal_threshold", 1)
|
||||
refusal_level = refused/len(self.order.positions)
|
||||
|
||||
if refusal_level > refusal_threshold_limit:
|
||||
self.order.status = OrderStatus.OPERATOR_REQUIRED
|
||||
self.order.reason = "Превышен порог отказов"
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
from typing import List, Optional
|
||||
from .auto_part_position import AutoPartPosition
|
||||
from enum import Enum
|
||||
|
||||
class OrderStatus(Enum):
|
||||
NEW = "new"
|
||||
IN_PROGRESS = "in progress"
|
||||
FAILED = "failed"
|
||||
COMPLETED = "completed"
|
||||
OPERATOR_REQUIRED = "operator required"
|
||||
INVALID = "invalid"
|
||||
|
||||
|
||||
class AutoPartOrder:
|
||||
def __init__(self):
|
||||
self.positions: List[AutoPartPosition] = []
|
||||
self.status = OrderStatus.NEW
|
||||
self.reason = ""
|
||||
|
||||
def add_position(self, position: AutoPartPosition) -> None:
|
||||
self.positions.append(position)
|
||||
if self.status == OrderStatus.NEW:
|
||||
self.status = OrderStatus.IN_PROGRESS
|
||||
|
||||
def find_positions(self, brand: Optional[str] = None, sku: Optional[str] = None) -> List[AutoPartPosition]:
|
||||
results = self.positions
|
||||
if brand is not None:
|
||||
results = [p for p in results if p.manufacturer == brand]
|
||||
if sku is not None:
|
||||
results = [p for p in results if p.sku == sku]
|
||||
return results
|
||||
|
||||
def __len__(self):
|
||||
return len(self.positions)
|
||||
@@ -1,77 +0,0 @@
|
||||
from typing import List, Optional
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, Any
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
@dataclass
|
||||
class AutoPartPosition:
|
||||
"""
|
||||
Унифицированная модель позиции для заказа.
|
||||
Все контрагенты приводятся к этой структуре.
|
||||
"""
|
||||
sku: str # Артикул товара
|
||||
manufacturer: str # Производитель
|
||||
name: str # Наименование
|
||||
requested_price: Decimal # Цена за единицу
|
||||
requested_quantity: int # Количество
|
||||
total: Decimal # Общая сумма
|
||||
stock_quantity: int = 0 # Остаток на складе
|
||||
stock_price: Decimal = Decimal('0.0') # Цена на складе
|
||||
order_quantity: int = 0 # Количество для заказа
|
||||
order_price: Decimal = Decimal('0.0') # Цена в заказе
|
||||
additional_attrs: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self):
|
||||
"""Валидация после инициализации"""
|
||||
if self.requested_quantity < 0:
|
||||
raise ValueError(f"Количество не может быть отрицательным: {self.requested_quantity}")
|
||||
if self.requested_price < 0:
|
||||
raise ValueError(f"Цена не может быть отрицательной: {self.requested_price}")
|
||||
|
||||
|
||||
|
||||
class AutoPartPosition2:
|
||||
brand: str
|
||||
sku: str
|
||||
name: str
|
||||
customer_price: float
|
||||
customer_quantity: int
|
||||
supplier_price: float
|
||||
stock_remaining: int
|
||||
|
||||
def __init__(self, brand: str, sku: str, name: str,
|
||||
customer_price: float, customer_quantity: int,
|
||||
supplier_price: float, stock_remaining: int):
|
||||
self.brand = brand
|
||||
self.sku = sku
|
||||
self.name = name
|
||||
self.customer_price = customer_price
|
||||
self.customer_quantity = customer_quantity
|
||||
self.supplier_price = supplier_price
|
||||
self.stock_remaining = stock_remaining
|
||||
|
||||
def customer_cost(self) -> float:
|
||||
return self.customer_price * self.customer_quantity
|
||||
|
||||
def supplier_cost(self) -> float:
|
||||
return self.supplier_price * self.customer_quantity
|
||||
|
||||
def is_available(self) -> bool:
|
||||
return self.stock_remaining >= self.customer_quantity
|
||||
|
||||
def restock(self, amount: int) -> None:
|
||||
if amount < 0:
|
||||
raise ValueError("Restock amount must be non-negative")
|
||||
self.stock_remaining += amount
|
||||
|
||||
def __post_init__(self):
|
||||
if self.customer_price < 0:
|
||||
raise ValueError("Customer price cannot be negative")
|
||||
if self.customer_quantity < 0:
|
||||
raise ValueError("Customer quantity cannot be negative")
|
||||
if self.supplier_price < 0:
|
||||
raise ValueError("Supplier price cannot be negative")
|
||||
if self.stock_remaining < 0:
|
||||
raise ValueError("Stock remaining cannot be negative")
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
from mail_order_bot.attachment_handler.order.auto_part_order import AutoPartOrder
|
||||
|
||||
class Position:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
class AutoPartOrder
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
class OrderRequest:
|
||||
def __init__(self, attachment):
|
||||
self.attachment = attachment
|
||||
self.parsed = None
|
||||
self.positions = []
|
||||
self.status=None
|
||||
|
||||
def add_position(self, position):
|
||||
pass
|
||||
|
||||
def find_positions(self):
|
||||
pass
|
||||
|
||||
def __process(self):
|
||||
pass
|
||||
|
||||
def get_file(self):
|
||||
pass
|
||||
|
||||
def get_attachment(self):
|
||||
pass
|
||||
@@ -1,42 +0,0 @@
|
||||
import os
|
||||
import yaml
|
||||
import logging
|
||||
from typing import Dict, Any
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
from .order.auto_part_order import AutoPartOrder
|
||||
from .handlers import *
|
||||
|
||||
class TaskProcessor:
|
||||
def __init__(self, config_path: Path):
|
||||
self.config_path = config_path
|
||||
self.context = dict()
|
||||
self.order = None
|
||||
|
||||
def process(self, client, attachment):
|
||||
config = self._load_config(client)
|
||||
self.context = dict()
|
||||
self.order = AutoPartOrder()
|
||||
|
||||
self.context["client"] = client
|
||||
self.context["attachment"] = attachment
|
||||
|
||||
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, self.order)
|
||||
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)
|
||||
@@ -1,10 +1,46 @@
|
||||
# Настройки обработки =================================================================
|
||||
folder: "spareparts"
|
||||
|
||||
clients:
|
||||
lesha.spb@gmail.com:
|
||||
enabled: true
|
||||
client_id: 6148154 # Сейчас стоит айдишник Димы для тестовых заказов
|
||||
|
||||
pipeline:
|
||||
- ExcelExtractor
|
||||
- DeliveryPeriodFromConfig
|
||||
- OrderExtractor
|
||||
- StockSelector
|
||||
- UpdateExcelFile
|
||||
- SaveOrderToTelegram
|
||||
- EmailReplyTask
|
||||
|
||||
excel:
|
||||
sheet_name: 0
|
||||
key_field: "Номер"
|
||||
mapping:
|
||||
article: "Номер"
|
||||
manufacturer: "Фирма"
|
||||
name: "Наименование"
|
||||
price: "Цена"
|
||||
quantity: "Кол-во"
|
||||
total: "Сумма"
|
||||
updatable_fields:
|
||||
ordered_quantity: "Кол-во Поставщика"
|
||||
ordered_price: "Цена Поставщика"
|
||||
|
||||
# Значение для хендлера DeliveryPeriodFromConfig
|
||||
delivery_period: 100 # в часах
|
||||
|
||||
amtel.ru:
|
||||
enabled: false
|
||||
|
||||
|
||||
|
||||
# Раздел с общими конфигурационными параметрами ===============================
|
||||
update_interval: 1
|
||||
work_interval: 60
|
||||
email_dir: "spareparts"
|
||||
|
||||
# Логирование =================================================================
|
||||
log:
|
||||
version: 1
|
||||
@@ -36,10 +72,9 @@ log:
|
||||
level: CRITICAL
|
||||
formatter: telegram
|
||||
class: logging_telegram_handler.TelegramHandler
|
||||
chat_id: 211945135
|
||||
chat_id: -1002960678041 #-1002960678041 #211945135
|
||||
alias: "Mail order bot"
|
||||
|
||||
|
||||
# Логгеры
|
||||
loggers:
|
||||
'':
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
pipeline:
|
||||
# Настраиваем парсинг экселя
|
||||
- handler: BasicExcelParser
|
||||
config:
|
||||
#=========================================
|
||||
client: amtel.club
|
||||
enabled: true
|
||||
client_id: 6148154 # Сейчас стоит айдишник Димы, фактический id у amtel.club - 156799563
|
||||
|
||||
delivery_period: 100 # в часах
|
||||
excel:
|
||||
sheet_name: 0
|
||||
key_field: "Номер"
|
||||
mapping:
|
||||
@@ -12,12 +15,18 @@ pipeline:
|
||||
quantity: "Кол-во"
|
||||
total: "Сумма"
|
||||
|
||||
# Определяем логику обработки заказа (в данном случае все с локального склада)
|
||||
- handler: DeliveryPeriodLocalStore
|
||||
|
||||
# Запрос остатков со склада
|
||||
- handler: GetStock
|
||||
updatable_fields:
|
||||
ordered_quantity: "Кол-во Поставщика"
|
||||
ordered_price: "Цена Поставщика"
|
||||
|
||||
#=========================================
|
||||
pipeline:
|
||||
- ExcelExtractor
|
||||
- OrderExtractor
|
||||
- DeliveryPeriodFromConfig
|
||||
- StockSelector
|
||||
- UpdateExcelFile
|
||||
- SaveOrderToTelegram
|
||||
|
||||
|
||||
|
||||
|
||||
39
src/mail_order_bot/configs/gmail.com.yml
Normal file
39
src/mail_order_bot/configs/gmail.com.yml
Normal file
@@ -0,0 +1,39 @@
|
||||
#=========================================
|
||||
client: gmail.com
|
||||
enabled: true
|
||||
client_id: 6148154 # Сейчас стоит айдишник Димы, фактический id у amtel.club - 156799563
|
||||
|
||||
delivery_period: 100 # в часах
|
||||
excel:
|
||||
sheet_name: 0
|
||||
key_field: "Номер"
|
||||
mapping:
|
||||
article: "Номер"
|
||||
manufacturer: "Фирма"
|
||||
name: "Наименование"
|
||||
price: "Цена"
|
||||
quantity: "Кол-во"
|
||||
total: "Сумма"
|
||||
|
||||
updatable_fields:
|
||||
ordered_quantity: "Кол-во Поставщика"
|
||||
ordered_price: "Цена Поставщика"
|
||||
|
||||
#=========================================
|
||||
pipeline:
|
||||
- ExcelExtractor
|
||||
- OrderExtractor
|
||||
- DeliveryPeriodFromConfig
|
||||
- StockSelector
|
||||
- UpdateExcelFile
|
||||
- SaveOrderToTelegram
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,27 @@
|
||||
"""
|
||||
Структура контекста
|
||||
|
||||
email : Электронное письмо в формате EmailObject
|
||||
config : Конфиг для текущего клиента
|
||||
attachments : [ Список вложений
|
||||
{
|
||||
name : Имя файла
|
||||
isOrder : Признак что файл является валидным файлом заказа
|
||||
bytes : содержимое файла в формате BytesIO
|
||||
deliveryPeriod: Int
|
||||
sheet : Распарсенный лист в формате ExcelFileParcer
|
||||
order : Файл заказа в формате AutopartOrder
|
||||
log : Лог сообщений по обработке файла в формате LogMessage
|
||||
}
|
||||
]
|
||||
status:
|
||||
|
||||
|
||||
|
||||
"""
|
||||
|
||||
|
||||
|
||||
import threading
|
||||
from typing import Any, Dict
|
||||
import logging
|
||||
|
||||
108
src/mail_order_bot/credential_provider.py
Normal file
108
src/mail_order_bot/credential_provider.py
Normal file
@@ -0,0 +1,108 @@
|
||||
import os
|
||||
import logging
|
||||
from typing import Optional, Tuple
|
||||
from mail_order_bot.context import Context
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CredentialProvider:
|
||||
"""
|
||||
Класс для получения учетных данных (логин и пароль) для доступа к API.
|
||||
|
||||
Учетные данные берутся из переменных окружения в формате:
|
||||
- {PREFIX}_LOGIN_{CLIENT_NAME} - логин для клиента
|
||||
- {PREFIX}_PASSWORD_{CLIENT_NAME} - пароль для клиента
|
||||
- {PREFIX}_LOGIN_SYSTEM - логин для системной учетной записи
|
||||
- {PREFIX}_PASSWORD_SYSTEM - пароль для системной учетной записи
|
||||
"""
|
||||
|
||||
SYSTEM_ACCOUNT = "SYSTEM"
|
||||
|
||||
def __init__(self, prefix: str = "ABCP", context: Optional[Context] = None):
|
||||
"""
|
||||
Инициализация CredentialProvider.
|
||||
|
||||
Args:
|
||||
prefix: Префикс для переменных окружения (по умолчанию "ABCP")
|
||||
context: Контекст приложения. Если не передан, будет получен через Context()
|
||||
"""
|
||||
self.prefix = prefix.upper()
|
||||
self.context = context if context is not None else Context()
|
||||
|
||||
def get_client_credentials(self, client_name: Optional[str] = None) -> Tuple[str, str]:
|
||||
"""
|
||||
Получает учетные данные для клиента.
|
||||
|
||||
Если client_name не указан, берется из контекста (context.data.get("client")).
|
||||
|
||||
Args:
|
||||
client_name: Имя клиента. Если None, берется из контекста.
|
||||
|
||||
Returns:
|
||||
Tuple[str, str]: Кортеж (логин, пароль)
|
||||
|
||||
Raises:
|
||||
ValueError: Если не удалось получить имя клиента или учетные данные не найдены
|
||||
"""
|
||||
if client_name is None:
|
||||
client_name = self.context.data.get("client")
|
||||
if client_name is None:
|
||||
raise ValueError("Имя клиента не указано и не найдено в контексте")
|
||||
|
||||
login_key = f"{self.prefix}_LOGIN_{client_name}"
|
||||
password_key = f"{self.prefix}_PASSWORD_{client_name}"
|
||||
|
||||
login = os.getenv(login_key)
|
||||
password = os.getenv(password_key)
|
||||
|
||||
if login is None or password is None:
|
||||
raise ValueError(
|
||||
f"Учетные данные для клиента '{client_name}' не найдены. "
|
||||
f"Проверьте переменные окружения: {login_key} и {password_key}"
|
||||
)
|
||||
|
||||
logger.debug(f"Получены учетные данные для клиента '{client_name}'")
|
||||
return login, password
|
||||
|
||||
def get_system_credentials(self) -> Tuple[str, str]:
|
||||
"""
|
||||
Получает учетные данные для системной учетной записи.
|
||||
|
||||
Returns:
|
||||
Tuple[str, str]: Кортеж (логин, пароль)
|
||||
|
||||
Raises:
|
||||
ValueError: Если учетные данные системной учетной записи не найдены
|
||||
"""
|
||||
login_key = f"{self.prefix}_LOGIN"
|
||||
password_key = f"{self.prefix}_PASSWORD"
|
||||
|
||||
login = os.getenv(login_key)
|
||||
password = os.getenv(password_key)
|
||||
|
||||
if login is None or password is None:
|
||||
raise ValueError(
|
||||
f"Учетные данные для системной учетной записи не найдены. "
|
||||
f"Проверьте переменные окружения: {login_key} и {password_key}"
|
||||
)
|
||||
|
||||
logger.debug("Получены учетные данные для системной учетной записи")
|
||||
return login, password
|
||||
|
||||
def get_credentials(self, use_system: bool = False, client_name: Optional[str] = None) -> Tuple[str, str]:
|
||||
"""
|
||||
Универсальный метод для получения учетных данных.
|
||||
|
||||
Args:
|
||||
use_system: Если True, возвращает учетные данные системной учетной записи.
|
||||
Если False, возвращает учетные данные клиента.
|
||||
client_name: Имя клиента. Если None и use_system=False, берется из контекста.
|
||||
|
||||
Returns:
|
||||
Tuple[str, str]: Кортеж (логин, пароль)
|
||||
"""
|
||||
if use_system:
|
||||
return self.get_system_credentials()
|
||||
else:
|
||||
return self.get_client_credentials(client_name)
|
||||
@@ -1,2 +1,3 @@
|
||||
from .client import EmailClient
|
||||
from .objects import EmailMessage, EmailAttachment
|
||||
from .utils import EmailUtils
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from typing import List, Optional, Union
|
||||
from dataclasses import dataclass
|
||||
import email
|
||||
from email import encoders
|
||||
@@ -8,12 +8,23 @@ from email.mime.text import MIMEText
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.base import MIMEBase
|
||||
from email.header import decode_header
|
||||
from email.message import Message
|
||||
import imaplib
|
||||
import smtplib
|
||||
|
||||
import logging
|
||||
|
||||
from mail_order_bot import MailOrderBotException
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# from .objects import EmailMessage, EmailAttachment
|
||||
|
||||
class EmailClientException(MailOrderBotException):
|
||||
pass
|
||||
|
||||
|
||||
class EmailClient:
|
||||
def __init__(self, imap_host: str, smtp_host: str, email: str, password: str,
|
||||
@@ -27,7 +38,7 @@ class EmailClient:
|
||||
self.imap_conn = None
|
||||
|
||||
def connect(self):
|
||||
"""Установkение IMAP соединения"""
|
||||
"""Установление IMAP соединения"""
|
||||
if self.imap_conn is None:
|
||||
self.imap_conn = imaplib.IMAP4_SSL(self.imap_host, self.imap_port)
|
||||
self.imap_conn.login(self.email, self.password)
|
||||
@@ -53,6 +64,7 @@ class EmailClient:
|
||||
|
||||
def get_emails_id(self, folder: str = "INBOX", only_unseen: bool = True) -> List[int]:
|
||||
"""Получить список новых электронных писем."""
|
||||
try:
|
||||
self.connect()
|
||||
self.imap_conn.select(folder, readonly=False)
|
||||
# Ищем письма
|
||||
@@ -64,8 +76,16 @@ class EmailClient:
|
||||
return []
|
||||
|
||||
email_ids = messages[0].split()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
raise
|
||||
else:
|
||||
return email_ids
|
||||
|
||||
|
||||
|
||||
|
||||
def get_email(self, email_id, mark_as_read: bool = True):
|
||||
"""Получить список новых электронных писем."""
|
||||
self.connect()
|
||||
@@ -102,3 +122,61 @@ class EmailClient:
|
||||
decoded_parts.append(str(part))
|
||||
|
||||
return ''.join(decoded_parts)
|
||||
|
||||
def send_email(self, message: Union[MIMEMultipart, MIMEText, Message]):
|
||||
"""
|
||||
Отправить подготовленное письмо через SMTP.
|
||||
|
||||
Args:
|
||||
message: Подготовленное письмо (MIMEMultipart, MIMEText или email.message.Message)
|
||||
Должно содержать заголовки From, To и Subject
|
||||
"""
|
||||
try:
|
||||
# Извлекаем получателей из письма
|
||||
recipients = []
|
||||
|
||||
# Основной получатель
|
||||
to_header = message.get("To", "")
|
||||
if to_header:
|
||||
# Обрабатываем несколько адресов, разделенных запятыми
|
||||
to_addresses = [addr.strip() for addr in to_header.split(",")]
|
||||
recipients.extend(to_addresses)
|
||||
|
||||
# Копия
|
||||
cc_header = message.get("Cc", "")
|
||||
if cc_header:
|
||||
cc_addresses = [addr.strip() for addr in cc_header.split(",")]
|
||||
recipients.extend(cc_addresses)
|
||||
|
||||
# Скрытая копия
|
||||
bcc_header = message.get("Bcc", "")
|
||||
if bcc_header:
|
||||
bcc_addresses = [addr.strip() for addr in bcc_header.split(",")]
|
||||
recipients.extend(bcc_addresses)
|
||||
|
||||
if not recipients:
|
||||
raise ValueError("Не указаны получатели письма (To, Cc или Bcc)")
|
||||
|
||||
# Извлекаем отправителя из письма или используем email из настроек
|
||||
from_email = message.get("From", self.email)
|
||||
|
||||
# Подключаемся к SMTP серверу
|
||||
with smtplib.SMTP(self.smtp_host, self.smtp_port) as server:
|
||||
server.starttls()
|
||||
server.login(self.email, self.password)
|
||||
|
||||
# Отправляем письмо
|
||||
server.sendmail(
|
||||
from_email,
|
||||
recipients,
|
||||
message.as_string()
|
||||
)
|
||||
|
||||
logger.info(f"Письмо успешно отправлено получателям: {', '.join(recipients)}")
|
||||
|
||||
except smtplib.SMTPException as e:
|
||||
logger.error(f"Ошибка SMTP при отправке письма: {str(e)}")
|
||||
raise Exception(f"Ошибка SMTP: {str(e)}")
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при отправке письма: {str(e)}")
|
||||
raise Exception(f"Ошибка при отправке письма: {str(e)}")
|
||||
@@ -1,16 +1,11 @@
|
||||
from email.header import decode_header, make_header
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from dataclasses import dataclass
|
||||
from typing import List
|
||||
import email
|
||||
from email import encoders
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.base import MIMEBase
|
||||
from email.header import decode_header
|
||||
import imaplib
|
||||
import smtplib
|
||||
from email.header import make_header, decode_header
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
from .objects import EmailMessage, EmailAttachment
|
||||
|
||||
@@ -99,8 +94,3 @@ class EmailUtils:
|
||||
return None
|
||||
# убираем пробелы по краям и берём часть после '@'
|
||||
return email_message.strip().split("@", 1)[1]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
from .processor import EmailProcessor
|
||||
@@ -1,16 +0,0 @@
|
||||
from .attachment_handler.attachment_handler import AttachmentHandler
|
||||
from .excel_parcers.order_parcer_basic import BasicExcelParser
|
||||
from .destination_time.local_store import DeliveryPeriodLocalStore
|
||||
|
||||
|
||||
|
||||
from .abcp.api_get_stock import GetStock
|
||||
from .abcp.api_create_order import InstantOrderTest
|
||||
|
||||
|
||||
|
||||
from .notifications.test_notifier import TestNotifier
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import logging
|
||||
import requests
|
||||
from mail_order_bot.email_processor.handlers.abstract_task import AbstractTask
|
||||
from mail_order_bot.email_processor.order.auto_part_order import OrderStatus
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class InstantOrderTest(AbstractTask):
|
||||
URL = "https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}"
|
||||
|
||||
def do(self) -> None:
|
||||
api_key = self.config["api_key"]
|
||||
chat_id = self.config["chat_id"]
|
||||
|
||||
if self.order.status == OrderStatus.IN_PROGRESS:
|
||||
positions = self.order.positions
|
||||
|
||||
message = f"Запрос на создание заказа от {self.context['client']}:\n"
|
||||
message += "\n".join(f"{pos.sku}: {pos.name} ({pos.order_quantity} x {pos.order_price} = {pos.total})" for pos in positions)
|
||||
|
||||
elif self.order.status == OrderStatus.OPERATOR_REQUIRED:
|
||||
message = f"Запрос на создание заказа от {self.context['client']} отклонен - необходима ручная обработка.\n"
|
||||
message += f"Причина: {self.order.reason}"
|
||||
|
||||
else:
|
||||
message = f"Запрос на создание заказа от {self.context['client']} отклонен.\n"
|
||||
message += f" Статус заказа: {self.order.status}"
|
||||
|
||||
#url = self.URL.format(api_key, chat_id, message)
|
||||
#resp = requests.get(url).json()
|
||||
print(message)
|
||||
#logger.info(resp)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import random
|
||||
import logging
|
||||
|
||||
from mail_order_bot.email_processor.handlers.abstract_task import AbstractTask
|
||||
from mail_order_bot.abcp_api.abcp_provider import AbcpProvider
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class APIGetStock(AbstractTask):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.abcp_provider = AbcpProvider()
|
||||
|
||||
def do(self) -> None:
|
||||
attachments = self.context.data.get("attachments", [])
|
||||
for attachment in attachments:
|
||||
order = attachment["order"]
|
||||
for position in order.positions:
|
||||
stock = self.get_stock(position.sku, position.manufacturer)
|
||||
position.update_stock(stock, order.delivery_period)
|
||||
position.fill_from_stock()
|
||||
logger.info(f"Получены позиции со склада для файла {attachment.get('name', "no name")}")
|
||||
|
||||
def get_stock(self, sku: str, manufacturer: str) -> int:
|
||||
return self.abcp_provider.get_stock(sku, manufacturer)
|
||||
@@ -1,21 +0,0 @@
|
||||
from mail_order_bot.email_processor.handlers.abstract_task import AbstractTask
|
||||
from mail_order_bot.email_client.utils import EmailUtils
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class AttachmentHandler(AbstractTask):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def do(self) -> None:
|
||||
email = self.context.data["email"]
|
||||
attachments = EmailUtils.extract_attachments(email)
|
||||
self.context.data["attachments"] = attachments
|
||||
logger.debug(f"AttachmentHandler отработал, извлек вложений: {len(attachments)} ")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
from mail_order_bot.email_processor.handlers.abstract_task import AbstractTask
|
||||
from mail_order_bot.email_client.utils import EmailUtils
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class DeliveryPeriodLocalStore(AbstractTask):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def do(self) -> None:
|
||||
attachments = self.context.data["attachments"]
|
||||
for attachment in attachments:
|
||||
order = attachment["order"]
|
||||
order.set_delivery_period(0)
|
||||
logger.info(f"Доставка только с локального склада, срок 1 день.")
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
|
||||
import smtplib
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.base import MIMEBase
|
||||
from email.utils import formatdate
|
||||
from email import encoders
|
||||
from abc import ABC, abstractmethod
|
||||
import os
|
||||
|
||||
|
||||
class AbstractTask(ABC):
|
||||
"""Базовый класс для задач"""
|
||||
|
||||
def __init__(self, context, config):
|
||||
self.context = context
|
||||
self.config = config
|
||||
|
||||
@abstractmethod
|
||||
def do(self):
|
||||
"""Метод для реализации в подклассах"""
|
||||
pass
|
||||
|
||||
|
||||
class EmailReplyTask(AbstractTask):
|
||||
"""Класс для ответа на электронные письма"""
|
||||
|
||||
def do(self):
|
||||
"""
|
||||
Отправляет ответ на входящее письмо
|
||||
|
||||
Ожидает в self.context:
|
||||
- message: email.message.Message объект входящего письма
|
||||
- attachment: путь к файлу для вложения
|
||||
|
||||
Ожидает в self.config:
|
||||
- reply_to: адрес электронной почты для копии
|
||||
- smtp_host: хост SMTP сервера
|
||||
- smtp_port: порт SMTP сервера
|
||||
- smtp_user: пользователь SMTP
|
||||
- smtp_password: пароль SMTP
|
||||
- from_email: адрес отправителя
|
||||
"""
|
||||
|
||||
incoming_message = self.context.get("message")
|
||||
attachment_path = self.context.get("attacnment")
|
||||
|
||||
if not incoming_message:
|
||||
raise ValueError("В context не найдено письмо (message)")
|
||||
|
||||
# Получаем адрес отправителя входящего письма
|
||||
from_addr = incoming_message.get("From")
|
||||
if not from_addr:
|
||||
raise ValueError("Входящее письмо не содержит адреса отправителя")
|
||||
|
||||
# Создаем ответное письмо
|
||||
reply_message = MIMEMultipart()
|
||||
|
||||
# Заголовки ответного письма
|
||||
reply_message["From"] = self.config.get("from_email", "noreply@example.com")
|
||||
reply_message["To"] = from_addr
|
||||
reply_message["Cc"] = self.config.get("reply_to", "")
|
||||
reply_message["Subject"] = f"Re: {incoming_message.get('Subject', '')}"
|
||||
reply_message["Date"] = formatdate(localtime=True)
|
||||
|
||||
# Тело письма
|
||||
body = "Ваш заказ создан"
|
||||
reply_message.attach(MIMEText(body, "plain", "utf-8"))
|
||||
|
||||
# Добавляем вложение если указан путь к файлу
|
||||
if attachment_path and os.path.isfile(attachment_path):
|
||||
self._attach_file(reply_message, attachment_path)
|
||||
|
||||
# Отправляем письмо
|
||||
self._send_email(reply_message, from_addr)
|
||||
|
||||
def _attach_file(self, message, file_path):
|
||||
"""
|
||||
Добавляет файл в качестве вложения к письму
|
||||
|
||||
Args:
|
||||
message: MIMEMultipart объект
|
||||
file_path: путь к файлу для вложения
|
||||
"""
|
||||
try:
|
||||
with open(file_path, "rb") as attachment:
|
||||
part = MIMEBase("application", "octet-stream")
|
||||
part.set_payload(attachment.read())
|
||||
|
||||
encoders.encode_base64(part)
|
||||
|
||||
file_name = os.path.basename(file_path)
|
||||
part.add_header(
|
||||
"Content-Disposition",
|
||||
f"attachment; filename= {file_name}"
|
||||
)
|
||||
|
||||
message.attach(part)
|
||||
except FileNotFoundError:
|
||||
raise FileNotFoundError(f"Файл не найден: {file_path}")
|
||||
except Exception as e:
|
||||
raise Exception(f"Ошибка при добавлении вложения: {str(e)}")
|
||||
|
||||
def _send_email(self, message, recipient):
|
||||
"""
|
||||
Отправляет письмо через SMTP
|
||||
|
||||
Args:
|
||||
message: MIMEMultipart объект письма
|
||||
recipient: адрес получателя
|
||||
"""
|
||||
try:
|
||||
smtp_host = self.config.get("smtp_host")
|
||||
smtp_port = self.config.get("smtp_port", 587)
|
||||
smtp_user = self.config.get("smtp_user")
|
||||
smtp_password = self.config.get("smtp_password")
|
||||
|
||||
if not all([smtp_host, smtp_user, smtp_password]):
|
||||
raise ValueError("Не указаны параметры SMTP в config")
|
||||
|
||||
with smtplib.SMTP(smtp_host, smtp_port) as server:
|
||||
server.starttls()
|
||||
server.login(smtp_user, smtp_password)
|
||||
|
||||
# Получаем адреса получателей (основной + копия)
|
||||
recipients = [recipient]
|
||||
reply_to = self.config.get("reply_to")
|
||||
if reply_to:
|
||||
recipients.append(reply_to)
|
||||
|
||||
server.sendmail(
|
||||
self.config.get("from_email"),
|
||||
recipients,
|
||||
message.as_string()
|
||||
)
|
||||
except smtplib.SMTPException as e:
|
||||
raise Exception(f"Ошибка SMTP: {str(e)}")
|
||||
except Exception as e:
|
||||
raise Exception(f"Ошибка при отправке письма: {str(e)}")
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import random
|
||||
import logging
|
||||
from mail_order_bot.email_processor.handlers.abstract_task import AbstractTask
|
||||
from mail_order_bot.email_processor.order.auto_part_order import OrderStatus
|
||||
from mail_order_bot.email_processor.order.auto_part_position import AutoPartPosition, PositionStatus
|
||||
from decimal import Decimal
|
||||
import random
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LocalStoreOrder(AbstractTask):
|
||||
"""Сейчас логика такая
|
||||
- ищем на складе наш сапплиер код, берем самую дешевую позицию и делаем заказ из нее
|
||||
|
||||
Другие чуть более дорогие не рассматриваем
|
||||
|
||||
"""
|
||||
# это код нашего склада
|
||||
|
||||
def do(self) -> None:
|
||||
attachments = self.context.data["attachments"]
|
||||
for attachment in attachments:
|
||||
order = attachment["order"]
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
from typing import List, Optional
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, Any
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
|
||||
class PositionStatus(Enum):
|
||||
NEW = "new" # Новая позиция
|
||||
STOCK_RECIEVED = "stock_received" # Получен остаток
|
||||
STOCK_FAILED = "stock_failed" # Остаток не получен
|
||||
NO_AVAILABLE_STOCK = "no_available_stock" #Нет доступных складов
|
||||
READY = "ready"
|
||||
READY_PARTIAL = "ready_partial"
|
||||
ORDERED = "ordered" # Заказано
|
||||
REFUSED = "refused" # Отказано
|
||||
|
||||
|
||||
@dataclass
|
||||
class AutoPartPosition:
|
||||
DISTRIBUTOR_ID = "1577730"
|
||||
"""
|
||||
Унифицированная модель позиции для заказа.
|
||||
Все контрагенты приводятся к этой структуре.
|
||||
"""
|
||||
sku: str # Артикул товара
|
||||
manufacturer: str # Производитель
|
||||
|
||||
requested_price: Decimal # Цена за единицу
|
||||
requested_quantity: int # Количество
|
||||
|
||||
total: Decimal = 0 # Общая сумма
|
||||
name: str = "" # Наименование
|
||||
|
||||
order_quantity: int = 0 # Количество для заказа
|
||||
order_price: Decimal = Decimal('0.0') # Цена в заказе
|
||||
order_item: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
stock: List[Dict[str, Any]] = None
|
||||
additional_attrs: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
status: PositionStatus = PositionStatus.NEW
|
||||
desc: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
"""Валидация после инициализации"""
|
||||
if self.requested_quantity < 0:
|
||||
raise ValueError(f"Количество не может быть отрицательным: {self.requested_quantity}")
|
||||
if self.requested_price < 0:
|
||||
raise ValueError(f"Цена не может быть отрицательной: {self.requested_price}")
|
||||
|
||||
def update_stock(self, stock: Dict[str, Any], delivery_period: int = 0) -> None:
|
||||
if stock["success"]:
|
||||
available_distributors = stock["data"]
|
||||
|
||||
# Для доставки только с локального склада сперва убираем все остальные склады
|
||||
if delivery_period == 0:
|
||||
available_distributors = self._filter_only_local_storage(available_distributors)
|
||||
|
||||
#Отбираем склады по сроку доставки
|
||||
available_distributors = self._filter_proper_delivery_time(available_distributors, delivery_period)
|
||||
|
||||
# Убираем дорогие склады с ценой выше запрошенной
|
||||
available_distributors = self._filter_proper_price(available_distributors)
|
||||
|
||||
# Убираем отрицательные остатки
|
||||
available_distributors = self._filter_proper_availability(available_distributors)
|
||||
|
||||
# Сортируем по цене
|
||||
available_distributors.sort(key=lambda item: Decimal(item["price"]), reverse=False)
|
||||
|
||||
self.stock = available_distributors
|
||||
if len (self.stock):
|
||||
self.status = PositionStatus.STOCK_RECIEVED
|
||||
else:
|
||||
self.status = PositionStatus.NO_AVAILABLE_STOCK
|
||||
else:
|
||||
self.status = PositionStatus.STOCK_FAILED
|
||||
|
||||
|
||||
def fill_from_stock(self):
|
||||
if self.status == PositionStatus.STOCK_RECIEVED:
|
||||
|
||||
for distributor in self.stock:
|
||||
distributor["profit"] = int(distributor["availability"]) * self.requested_price - int(distributor["availability"]) * Decimal(distributor["price"])
|
||||
|
||||
self.stock.sort(key=lambda item: item["profit"], reverse=True)
|
||||
|
||||
self.order_quantity = self.stock[0]["availability"]
|
||||
self.order_price = self.requested_price
|
||||
self.order_item = self.stock[0]
|
||||
|
||||
self.status = PositionStatus.READY
|
||||
|
||||
|
||||
def _filter_only_local_storage(self, distributors):
|
||||
return [item for item in distributors if str(item["distributorId"]) == self.DISTRIBUTOR_ID]
|
||||
|
||||
def _filter_proper_delivery_time(self, distributors, delivery_period):
|
||||
return [item for item in distributors if item["deliveryPeriod"] <= delivery_period]
|
||||
|
||||
def _filter_proper_price(self, distributors):
|
||||
return [item for item in distributors if Decimal(item["price"]) <= self.requested_price]
|
||||
|
||||
def _filter_proper_availability(self, distributors):
|
||||
return [item for item in distributors if Decimal(item["availability"]) > 0]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import os
|
||||
import yaml
|
||||
import logging
|
||||
from typing import Dict, Any
|
||||
from pathlib import Path
|
||||
import threading
|
||||
from mail_order_bot.context import Context
|
||||
from mail_order_bot.email_client.utils import EmailUtils
|
||||
from enum import Enum
|
||||
|
||||
from mail_order_bot.email_processor.handlers import *
|
||||
|
||||
from mail_order_bot.email_processor.handlers import AttachmentHandler
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RequestStatus(Enum):
|
||||
NEW = "new"
|
||||
IN_PROGRESS = "in progress"
|
||||
FAILED = "failed"
|
||||
EXECUTED = "executed"
|
||||
OPERATOR_REQUIRED = "operator required"
|
||||
INVALID = "invalid"
|
||||
|
||||
|
||||
class EmailProcessor:
|
||||
def __init__(self, configs_path: str):
|
||||
super().__init__()
|
||||
self.context = Context()
|
||||
self.configs_path = configs_path
|
||||
self.status = RequestStatus.NEW
|
||||
|
||||
def process_email(self, email):
|
||||
# Очистить контекст
|
||||
self.context.clear()
|
||||
|
||||
# Сохранить письмо в контекст
|
||||
self.context.data["email"] = email
|
||||
|
||||
# Определить клиента
|
||||
email_body = EmailUtils.extract_body(email)
|
||||
email_from = EmailUtils.extract_first_sender(email_body)
|
||||
client = EmailUtils.extract_domain(email_from)
|
||||
|
||||
try:
|
||||
# Определить конфиг для пайплайна
|
||||
config = self._load_config(client)
|
||||
self.context.data["config"] = config
|
||||
|
||||
# Обработка вложений
|
||||
attachments_handler_task = AttachmentHandler()
|
||||
attachments_handler_task.do()
|
||||
|
||||
# Запустить обработку пайплайна
|
||||
for stage in config["pipeline"]:
|
||||
handler_name = stage["handler"]
|
||||
logger.info(f"Processing handler: {handler_name}")
|
||||
task = globals()[handler_name](stage.get("config", None))
|
||||
task.do()
|
||||
|
||||
|
||||
except FileNotFoundError:
|
||||
logger.error(f"Конфиг для клиента {client} не найден")
|
||||
|
||||
for attachment in self.context.data["attachments"]:
|
||||
print(attachment["order"].__dict__)
|
||||
#except Exception as e:
|
||||
# logger.error(f"Произошла другая ошибка: {e}")
|
||||
|
||||
|
||||
def _load_config(self, client) -> Dict[str, Any]:
|
||||
"""Загружает конфигурацию из YAML или JSON"""
|
||||
|
||||
path = os.path.join(self.configs_path, client + '.yml')
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
return yaml.safe_load(f)
|
||||
@@ -7,13 +7,16 @@ import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from email_client import EmailClient
|
||||
from email_processor import EmailProcessor
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
from task_processor import TaskProcessor
|
||||
|
||||
from mail_order_bot.context import Context
|
||||
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
class MailOrderBotException(Exception):
|
||||
pass
|
||||
|
||||
class MailOrderBot(ConfigManager):
|
||||
def __init__(self, *agrs, **kwargs):
|
||||
@@ -34,29 +37,44 @@ class MailOrderBot(ConfigManager):
|
||||
self.context.email_client = self.email_client
|
||||
|
||||
# Обработчик писем
|
||||
self.email_processor = EmailProcessor("./configs")
|
||||
#self.email_processor = TaskProcessor("./configs")
|
||||
|
||||
config = self.config.get("clients")
|
||||
self.email_processor = TaskProcessor(config)
|
||||
logger.warning("MailOrderBot инициализирован")
|
||||
|
||||
|
||||
def execute(self):
|
||||
# Получить список айдишников письма
|
||||
unread_email_ids = self.email_client.get_emails_id(folder="spareparts")
|
||||
|
||||
folder = self.config.get("folder")
|
||||
try:
|
||||
unread_email_ids = self.email_client.get_emails_id(folder=folder)
|
||||
logger.info(f"Новых писем - {len(unread_email_ids)}")
|
||||
|
||||
# Обработать каждое письмо по идентификатору
|
||||
for email_id in unread_email_ids:
|
||||
logger.debug(f"==================================================")
|
||||
logger.debug(f"Обработка письма с идентификатором {email_id}")
|
||||
try:
|
||||
logger.info(f"Обработка письма с идентификатором {email_id}")
|
||||
# Получить письмо по идентификатору и запустить его обработку
|
||||
email = self.email_client.get_email(email_id)
|
||||
email = self.email_client.get_email(email_id, mark_as_read=False)
|
||||
self.email_processor.process_email(email)
|
||||
pass
|
||||
|
||||
except MailOrderBotException as e:
|
||||
logger.error(f"Произошла ошибка {e}")
|
||||
|
||||
except MailOrderBotException as e:
|
||||
logger.error(f"Произошла ошибка {e}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Произошла непредвиденная ошибка {e}")
|
||||
|
||||
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
async def main():
|
||||
logger.critical("Запуск приложения")
|
||||
app = MailOrderBot("config.yml")
|
||||
await app.start()
|
||||
|
||||
@@ -64,9 +82,13 @@ async def main():
|
||||
#await app.stop()
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(os.getcwd())
|
||||
|
||||
if os.environ.get("APP_ENV") != "PRODUCTION":
|
||||
logger.warning("Non production environment")
|
||||
load_dotenv()
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
"""Классы для работы с сущностью заказа и позиции"""
|
||||
from .auto_part_order import AutoPartOrder, OrderStatus
|
||||
from .auto_part_position import AutoPartPosition, PositionStatus
|
||||
@@ -3,6 +3,7 @@ from .auto_part_position import AutoPartPosition, PositionStatus
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class OrderStatus(Enum):
|
||||
NEW = "new"
|
||||
IN_PROGRESS = "in progress"
|
||||
@@ -13,7 +14,8 @@ class OrderStatus(Enum):
|
||||
|
||||
|
||||
class AutoPartOrder:
|
||||
def __init__(self):
|
||||
def __init__(self, client_id):
|
||||
self.client_id = client_id
|
||||
self.positions: List[AutoPartPosition] = []
|
||||
self.status = OrderStatus.NEW
|
||||
self.delivery_period = 0
|
||||
@@ -34,13 +36,6 @@ class AutoPartOrder:
|
||||
def set_delivery_period(self, delivery_period: int) -> None:
|
||||
self.delivery_period = delivery_period
|
||||
|
||||
def fill_from_local_supplier(self) -> None:
|
||||
for position in self.positions:
|
||||
errors = position.fill_from_stock()
|
||||
self.errors += errors
|
||||
|
||||
|
||||
|
||||
def check_order(self, config) -> None:
|
||||
""" Проверяет заказ на возможность исполнения"""
|
||||
# 1. Проверка общего количества отказов
|
||||
@@ -54,6 +49,5 @@ class AutoPartOrder:
|
||||
f"({refusal_positions_count} из {len(self.positions)})")
|
||||
self.status = OrderStatus.OPERATOR_REQUIRED
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return len(self.positions)
|
||||
73
src/mail_order_bot/order/auto_part_position.py
Normal file
73
src/mail_order_bot/order/auto_part_position.py
Normal file
@@ -0,0 +1,73 @@
|
||||
from typing import List, Optional
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, Any
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class PositionStatus(Enum):
|
||||
NEW = "new" # Новая позиция
|
||||
STOCK_RECIEVED = "stock_received" # Получен остаток
|
||||
STOCK_FAILED = "stock_failed" # Остаток не получен
|
||||
NO_AVAILABLE_STOCK = "no_available_stock" # Нет доступных складов
|
||||
READY = "ready"
|
||||
ORDERED = "ordered" # Заказано
|
||||
REFUSED = "refused" # Отказано
|
||||
|
||||
|
||||
@dataclass
|
||||
class AutoPartPosition:
|
||||
"""
|
||||
Унифицированная модель позиции для заказа.
|
||||
Все контрагенты приводятся к этой структуре.
|
||||
"""
|
||||
sku: str # Артикул товара
|
||||
manufacturer: str # Производитель
|
||||
|
||||
asking_price: Decimal # Цена за единицу
|
||||
asking_quantity: int # Количество
|
||||
|
||||
total: Decimal = 0 # Общая сумма
|
||||
name: str = "" # Наименование
|
||||
|
||||
order_item: Dict[str, Any] = field(default_factory=dict)
|
||||
order_price: Decimal = Decimal('0.0') # Цена в заказе
|
||||
order_quantity: int = 0 # Количество для заказа
|
||||
order_delivery_period: int = 0
|
||||
|
||||
profit: Decimal = Decimal('0.0')
|
||||
|
||||
additional_attrs: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
status: PositionStatus = PositionStatus.NEW
|
||||
desc: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
"""Валидация после инициализации"""
|
||||
if self.asking_quantity < 0:
|
||||
raise ValueError(f"Количество не может быть отрицательным: {self.asking_quantity}")
|
||||
if self.asking_price < 0:
|
||||
raise ValueError(f"Цена не может быть отрицательной: {self.asking_price}")
|
||||
|
||||
def set_order_item(self, order_item):
|
||||
# Запоминаем всю позицию
|
||||
self.order_item = order_item
|
||||
|
||||
# ---===Устанавливаем конкретные значения по параметрам заказа===---
|
||||
# Берем максимально доступное значение со склада, но не больше чем в заказе.
|
||||
self.order_quantity = min(self.order_item.get("availability"), self.asking_quantity)
|
||||
|
||||
# Продаем по цене, которая была заказана
|
||||
self.order_price = self.asking_price
|
||||
|
||||
# Устанавливаем актуальный срок доставки
|
||||
self.order_delivery_period = self.order_item.get("deliveryPeriod")
|
||||
|
||||
# ФИксируем профит. Для инфо/отчетности
|
||||
self.profit = (self.asking_price - Decimal(self.order_item.get("price"))) * self.order_quantity
|
||||
|
||||
# Устанавливаем статус
|
||||
self.status = PositionStatus.READY
|
||||
|
||||
|
||||
|
||||
4
src/mail_order_bot/parsers/__init__.py
Normal file
4
src/mail_order_bot/parsers/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
"""Данный пакет содержит модули и классы дял парсинга объектов"""
|
||||
|
||||
from .excel_parcer import ExcelFileParcer
|
||||
from .order_parcer import OrderParser
|
||||
106
src/mail_order_bot/parsers/excel_parcer.py
Normal file
106
src/mail_order_bot/parsers/excel_parcer.py
Normal file
@@ -0,0 +1,106 @@
|
||||
import logging
|
||||
import pandas as pd
|
||||
from io import BytesIO
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ExcelFileParcer:
|
||||
def __init__(self, file_bytes, config):
|
||||
self.config = config
|
||||
self.bytes = file_bytes
|
||||
self.sheet_name = self.config.get("sheet_name", 0)
|
||||
self.df = self._parse_file(file_bytes)
|
||||
|
||||
def _parse_file(self, file_bytes):
|
||||
"""Парсит вложение в формате эл таблиц"""
|
||||
try:
|
||||
df = pd.read_excel(file_bytes, sheet_name=self.sheet_name, header=None)
|
||||
except Exception as e:
|
||||
df = None
|
||||
logger.warning("Не удалось распарсить значение файла")
|
||||
return df
|
||||
|
||||
def set_value(self, sku, manufacturer, column, value):
|
||||
"""Устанавливает значение в строке позиции в заданной колонке"""
|
||||
# Находим строку (ось Y)
|
||||
attr_row = self._get_attr_row(sku, manufacturer)
|
||||
|
||||
# Находим колонку (ось X)
|
||||
attr_col = self._get_attr_column(column)
|
||||
|
||||
self.df.iloc[attr_row, attr_col] = value
|
||||
logger.debug(
|
||||
f"Установлено значение {value} в колонке {column} для строки {attr_row} ( {sku} | {manufacturer} )")
|
||||
|
||||
def get_file_bytes(self):
|
||||
"Этот метод будет возвращать эксель из датафрейма в виде байтов"
|
||||
buf = BytesIO()
|
||||
|
||||
with pd.ExcelWriter(buf, engine="xlsxwriter") as writer:
|
||||
self.df.to_excel(writer, sheet_name="Sheet1", index=False, header=False)
|
||||
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
def get_order_rows(self):
|
||||
"Будет такой метод или какой-то другой который формирует файл с заказом"
|
||||
# Получаем все данные из файла
|
||||
|
||||
# Находим индекс строки с заголовком
|
||||
key_field = self.config.get("key_field")
|
||||
header_row_idx = self.df[
|
||||
self.df.apply(lambda row: row.astype(str).str.contains(key_field, case=False, na=False).any(),
|
||||
axis=1)].index[0]
|
||||
|
||||
# Считываем таблицу с правильным заголовком
|
||||
df = pd.read_excel(self.bytes, header=header_row_idx, sheet_name=self.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
|
||||
|
||||
def _get_header_row(self):
|
||||
"""Метод возвращает строку заголовка по наличию в ней ключевого слова. Поиск заголовка нужен при определении колонок с данными."""
|
||||
|
||||
key_column = self.config.get("key_field")
|
||||
header_row_idx = int(
|
||||
self.df.apply(lambda row: row.astype(str).str.contains(key_column, na=False).any(), axis=1).idxmax())
|
||||
# todo надо выкинуть ошибку если в файле не найдено ключевое поле
|
||||
# todo надо выкинуть ошибку если найдено несколько строк с CONFIG_KEY_COLUMN
|
||||
logger.debug(f"Индекс строки заголовка - {header_row_idx}")
|
||||
return header_row_idx
|
||||
|
||||
def _get_attr_column(self, col_name):
|
||||
"""Поиск по оси Х - метод возвращает индекс колонки по названию атрибута"""
|
||||
header_row_idx = self._get_header_row()
|
||||
|
||||
header_row = self.df.iloc[header_row_idx]
|
||||
|
||||
col_id = header_row[header_row == col_name].index[0]
|
||||
# todo добавить перехват ошибок и выброс понятного и сключения при отсутствии колонки
|
||||
logger.debug(f"Индекс колонки {col_name} - {col_id}")
|
||||
return int(col_id)
|
||||
|
||||
def _get_attr_row(self, sku, manufacturer):
|
||||
"""Поиск по оси Y - метод возвращает индекс строки по бренду и артикулу"""
|
||||
|
||||
sku_col_name = self.config["mapping"]["article"]
|
||||
sku_col_idx = self._get_attr_column(sku_col_name)
|
||||
|
||||
man_col_name = self.config["mapping"]["manufacturer"]
|
||||
man_col_idx = self._get_attr_column(man_col_name)
|
||||
|
||||
matching_rows = self.df[
|
||||
(self.df.iloc[:, sku_col_idx] == sku) & (self.df.iloc[:, man_col_idx] == manufacturer)].index
|
||||
|
||||
# todo сделать проверку на наличие дублей
|
||||
logger.info(f"Индекс строки позиции {sku}/{manufacturer} - {matching_rows}")
|
||||
|
||||
return matching_rows.values[0]
|
||||
|
||||
|
||||
86
src/mail_order_bot/parsers/order_parcer.py
Normal file
86
src/mail_order_bot/parsers/order_parcer.py
Normal file
@@ -0,0 +1,86 @@
|
||||
import logging
|
||||
import pandas as pd
|
||||
from typing import Dict, Any, Optional
|
||||
from decimal import Decimal
|
||||
from io import BytesIO
|
||||
|
||||
from mail_order_bot.order import AutoPartPosition
|
||||
from mail_order_bot.order import AutoPartOrder
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OrderParser:
|
||||
"""
|
||||
Универсальный парсер, настраиваемый через конфигурацию.
|
||||
Подходит для большинства стандартных случаев.
|
||||
"""
|
||||
|
||||
def __init__(self, mapping, delivery_period, client_id):
|
||||
self.mapping = mapping
|
||||
self.delivery_period = delivery_period
|
||||
self.client_id = client_id
|
||||
|
||||
def parse(self, df):
|
||||
order = AutoPartOrder(self.client_id)
|
||||
# Парсим строки
|
||||
positions = []
|
||||
for idx, row in df.iterrows():
|
||||
position = self._parse_row(row, self.mapping)
|
||||
if position:
|
||||
order.add_position(position)
|
||||
|
||||
logger.info(f"Успешно обработано {len(order)} позиций из {len(df)} строк")
|
||||
|
||||
# except Exception as e:
|
||||
# logger.error(f"Ошибка при обработке файла: {e}")
|
||||
# else:
|
||||
return order
|
||||
|
||||
def _parse_row(self, row: pd.Series, mapping: Dict[str, str]) -> Optional[AutoPartPosition]:
|
||||
"""Парсит одну строку 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 "name" in mapping:
|
||||
name = str(row[mapping.get('name', "")]).strip()
|
||||
else:
|
||||
name = ""
|
||||
|
||||
# Создаем объект позиции
|
||||
position = AutoPartPosition(
|
||||
sku=str(row[mapping['article']]).strip(),
|
||||
manufacturer=str(row[mapping.get('manufacturer', "")]).strip(),
|
||||
name=name,
|
||||
asking_price=price,
|
||||
asking_quantity=quantity,
|
||||
total=total,
|
||||
order_delivery_period=self.delivery_period,
|
||||
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
|
||||
2
src/mail_order_bot/task_processor/__init__.py
Normal file
2
src/mail_order_bot/task_processor/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
from .processor import TaskProcessor
|
||||
from .message import LogMessage, LogMessageLevel, LogMessageStorage
|
||||
@@ -9,9 +9,10 @@ class AbstractTask():
|
||||
"""
|
||||
Абстрактный базовый класс для всех хэндлеров.
|
||||
"""
|
||||
def __init__(self, config: Dict[str, Any]={}) -> None:
|
||||
def __init__(self) -> None:
|
||||
self.context = Context()
|
||||
self.config = config
|
||||
#self.config = config
|
||||
self.config = self.context.data.get("config", {})
|
||||
|
||||
@abstractmethod
|
||||
def do(self) -> None:
|
||||
@@ -22,3 +23,6 @@ class AbstractTask():
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_name(self) -> str:
|
||||
pass
|
||||
|
||||
18
src/mail_order_bot/task_processor/handlers/__init__.py
Normal file
18
src/mail_order_bot/task_processor/handlers/__init__.py
Normal file
@@ -0,0 +1,18 @@
|
||||
|
||||
|
||||
from .attachment_handler.attachment_handler import AttachmentHandler
|
||||
from .abcp.api_get_stock import APIGetStock
|
||||
from .delivery_time.local_store import DeliveryPeriodLocalStore
|
||||
from .delivery_time.from_config import DeliveryPeriodFromConfig
|
||||
from .notifications.test_notifier import TestNotifier
|
||||
from .excel_parcers.excel_extractor import ExcelExtractor
|
||||
from .excel_parcers.order_extractor import OrderExtractor
|
||||
from .abcp.api_save_order import SaveOrderToTelegram
|
||||
|
||||
from .stock_selectors.stock_selector import StockSelector
|
||||
|
||||
from .excel_parcers.update_excel_file import UpdateExcelFile
|
||||
|
||||
from .email.send_email import EmailReplyTask
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
Перебирает аттачменты
|
||||
Для каждого ордера в аттачменте перебирает позиции
|
||||
Для каждой позиции запрашивает остатки и запускает процедуру выбора оптмальной позиции со склада/
|
||||
Возможно логику выбора позиции надо вынести из позиции, но пока так
|
||||
"""
|
||||
import logging
|
||||
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
from mail_order_bot.abcp_api.abcp_provider import AbcpProvider
|
||||
from mail_order_bot.credential_provider import CredentialProvider
|
||||
from mail_order_bot.order.auto_part_order import OrderStatus
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class APIGetStock(AbstractTask):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
credential_provider = CredentialProvider(context=self.context)
|
||||
|
||||
# Создаем провайдер для учетной записи клиента
|
||||
client_login, client_password = credential_provider.get_client_credentials()
|
||||
self.client_provider = AbcpProvider(login=client_login, password=client_password)
|
||||
|
||||
def do(self) -> None:
|
||||
|
||||
attachments = self.context.data.get("attachments", [])
|
||||
for attachment in attachments:
|
||||
|
||||
order = attachment.get("order", None)
|
||||
for position in order.positions:
|
||||
# Получаем остатки из-под учетной записи клиента
|
||||
client_stock = self.client_provider.get_stock(position.sku, position.manufacturer)
|
||||
position.set_order_item(client_stock)
|
||||
#position.set_order_item()
|
||||
|
||||
logger.info(f"Получены позиции со склада для файла {attachment.get('name', "no name")}")
|
||||
|
||||
|
||||
def get_stock(self, sku: str, manufacturer: str) -> int:
|
||||
return self.client_provider.get_stock(sku, manufacturer)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
Перебирает аттачменты
|
||||
Для каждого ордера в аттачменте перебирает позиции
|
||||
Для каждой позиции запрашивает остатки и запускает процедуру выбора оптмальной позиции со склада/
|
||||
Возможно логику выбора позиции надо вынести из позиции, но пока так
|
||||
"""
|
||||
import logging
|
||||
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
from mail_order_bot.abcp_api.abcp_provider import AbcpProvider
|
||||
from mail_order_bot.credential_provider import CredentialProvider
|
||||
|
||||
from mail_order_bot.telegram.client import TelegramClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class SaveOrderToTelegram(AbstractTask):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def do(self) -> None:
|
||||
client = TelegramClient()
|
||||
|
||||
attachments = self.context.data.get("attachments", [])
|
||||
for attachment in attachments:
|
||||
order = attachment["order"]
|
||||
positions = order.positions
|
||||
message = "\nОбработка заказа {указать название контрагента}\n"
|
||||
message += f"\nПолучено {len(positions)} позиций от {order.client_id}\n"
|
||||
message += "===============================\n"
|
||||
for position in positions:
|
||||
message += f"{position.sku} - {position.manufacturer} - {position.name} \n"
|
||||
message += f"{position.asking_quantity} x {position.asking_price} = {position.total} \n"
|
||||
|
||||
rejected = position.asking_quantity - position.order_quantity
|
||||
if position.order_quantity == 0:
|
||||
message += f"Отказ\n"
|
||||
elif rejected:
|
||||
message += (f"Отказ: {rejected}, запрошено, {position.asking_quantity}, "
|
||||
f"отгружено {position.order_quantity}, профит {position.profit}\n")
|
||||
else:
|
||||
message += f"Позиция отгружена полностью, профит {position.profit}\n"
|
||||
message += "-------------------------------\n"
|
||||
|
||||
result = client.send_message(message)
|
||||
|
||||
# Отправка экселя в телеграм
|
||||
excel = attachment["excel"]
|
||||
file = excel.get_file_bytes()
|
||||
|
||||
client.send_document(
|
||||
document=file,
|
||||
filename="document.xlsx"
|
||||
)
|
||||
# logger.critical(message)
|
||||
|
||||
#===============================
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""
|
||||
Устанавливает хардкодом период доставки 0, что означает использование локального склада.
|
||||
Для заказчиков, которые должны всегда получать заказ только из наличия
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class DeliveryPeriodFromConfig(AbstractTask):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def do(self) -> None:
|
||||
attachments = self.context.data["attachments"]
|
||||
for attachment in attachments:
|
||||
delivery_period = self.config.get("delivery_period", 0)
|
||||
attachment["delivery_period"] = delivery_period
|
||||
logger.info(f"Срок доставки для файла {attachment["name"]} установлен из конфига - {delivery_period}")
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
Парсер срока доставки из темы письма
|
||||
"""
|
||||
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class DeliveryPeriodFromSubject(AbstractTask):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def do(self) -> None:
|
||||
"""
|
||||
Извлекает срок доставки из темы письма и сохраняет в каждый элемент attachments.
|
||||
|
||||
Правила парсинга:
|
||||
- Если есть слово "Наличие" - срок доставки = 0 дней
|
||||
- Если найдены оба варианта (диапазон и точное значение) - используется точное значение
|
||||
- Если есть только фраза "N-M дней/дня/день" (диапазон) - срок доставки = минимальное значение (N)
|
||||
- Если есть только фраза "N дней/дня/день" - срок доставки = N дней
|
||||
- Если ничего не указано - срок доставки = 0 дней
|
||||
- Срок переводится в часы (умножается на 24)
|
||||
"""
|
||||
# Получаем тему письма
|
||||
|
||||
try:
|
||||
email_subj = self.context.data.get("email_subj", "")
|
||||
if not email_subj:
|
||||
logger.warning("Тема письма не найдена в контексте")
|
||||
email_subj = ""
|
||||
|
||||
# Парсим срок доставки
|
||||
delivery_days = self._parse_delivery_period(email_subj)
|
||||
|
||||
# Переводим в часы
|
||||
delivery_time = delivery_days * 24
|
||||
|
||||
logger.info(f"Извлечен срок доставки из темы: {delivery_days} дней ({delivery_time} часов)")
|
||||
|
||||
# Сохраняем в каждый элемент attachments
|
||||
attachments = self.context.data.get("attachments", [])
|
||||
for attachment in attachments:
|
||||
attachment["delivery_time"] = delivery_time
|
||||
logger.debug(f"Срок доставки для файла {attachment["name"]} установлен как {delivery_time}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
|
||||
|
||||
def _parse_delivery_period(self, subject: str) -> int:
|
||||
"""
|
||||
Парсит срок доставки из темы письма.
|
||||
|
||||
Args:
|
||||
subject: Тема письма
|
||||
|
||||
Returns:
|
||||
Количество дней доставки (0 по умолчанию)
|
||||
"""
|
||||
if not subject:
|
||||
return 0
|
||||
|
||||
subject_lower = subject.lower()
|
||||
|
||||
# Проверяем наличие слова "Наличие"
|
||||
if "наличие" in subject_lower:
|
||||
return 0
|
||||
|
||||
# Ищем оба паттерна одновременно
|
||||
range_pattern = r'(\d+)-(\d+)\s+(?:дней|дня|день)'
|
||||
single_pattern = r'(\d+)\s+(?:дней|дня|день)'
|
||||
|
||||
range_match = re.search(range_pattern, subject_lower)
|
||||
single_match = re.search(single_pattern, subject_lower)
|
||||
|
||||
# Если найдены оба варианта - используем точное значение (одиночное число)
|
||||
if range_match and single_match:
|
||||
days = int(single_match.group(1))
|
||||
logger.debug(f"Найдены оба варианта (диапазон и точное значение), используется точное: {days} дней")
|
||||
return days
|
||||
|
||||
# Если найден только диапазон - используем минимальное значение
|
||||
if range_match:
|
||||
min_days = int(range_match.group(1))
|
||||
max_days = int(range_match.group(2))
|
||||
logger.debug(f"Найден диапазон: {min_days}-{max_days} дней, используется минимальное: {min_days} дней")
|
||||
return min(min_days, max_days)
|
||||
|
||||
# Если найдено только одиночное число - используем его
|
||||
if single_match:
|
||||
days = int(single_match.group(1))
|
||||
logger.debug(f"Найдено точное значение: {days} дней")
|
||||
return days
|
||||
|
||||
# Если ничего не найдено, возвращаем 0 (из наличия)
|
||||
return 0
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
Устанавливает хардкодом период доставки 0, что означает использование локального склада.
|
||||
Для заказчиков, которые должны всегда получать заказ только из наличия
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class DeliveryPeriodLocalStore(AbstractTask):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def do(self) -> None:
|
||||
attachments = self.context.data["attachments"]
|
||||
for attachment in attachments:
|
||||
attachment["delivery_period"] = 0
|
||||
logger.info(f"Срок доставки для файла {attachment["name"]} - только из наличия")
|
||||
@@ -0,0 +1,69 @@
|
||||
"""
|
||||
Обрабатывает письмо
|
||||
|
||||
"""
|
||||
import logging
|
||||
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
from mail_order_bot.email_client.utils import EmailUtils
|
||||
from mail_order_bot import MailOrderBotException
|
||||
from mail_order_bot.task_processor import LogMessage, LogMessageLevel
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class EmailParcerException(MailOrderBotException):
|
||||
pass
|
||||
|
||||
|
||||
class EmailParcer(AbstractTask):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def do(self) -> None:
|
||||
# Определить клиента
|
||||
try:
|
||||
email = self.context.data.get("email", None)
|
||||
if email is not None:
|
||||
email_body = EmailUtils.extract_body(email)
|
||||
self.context.data["email_body"] = email_body
|
||||
|
||||
# todo при переводе на основной ящик переделать на другую функцию
|
||||
header_from = EmailUtils.extract_header(email, "From")
|
||||
email_from = EmailUtils.extract_email(header_from)
|
||||
#email_from = EmailUtils.extract_first_sender(email_body)
|
||||
self.context.data["email_from"] = email_from
|
||||
|
||||
email_from_domain = EmailUtils.extract_domain(email_from)
|
||||
self.context.data["email_from_domain"] = email_from_domain
|
||||
|
||||
email_subj = EmailUtils.extract_header(email, "subj")
|
||||
self.context.data["email_subj"] = email_subj
|
||||
|
||||
client = EmailUtils.extract_domain(email_from)
|
||||
self.context.data["client"] = client
|
||||
|
||||
attachments = EmailUtils.extract_attachments(email)
|
||||
|
||||
self.context.data["attachments"] = attachments
|
||||
logger.info(f"Извлечено вложений: {len(attachments)} ")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
|
||||
self.context.data["error"].add(
|
||||
LogMessage(
|
||||
handler="EmailParcer",
|
||||
level=LogMessageLevel.ERROR,
|
||||
message="Возникла ошибка при парсинге письма",
|
||||
error_data=str(e)
|
||||
)
|
||||
)
|
||||
|
||||
#raise EmailParcerException(f"Ошибка при парсинге письма {e}") from e
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import logging
|
||||
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.base import MIMEBase
|
||||
from email.utils import formatdate
|
||||
from email import encoders
|
||||
|
||||
from mail_order_bot import MailOrderBotException
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class EmailReplyTaskException(MailOrderBotException):
|
||||
pass
|
||||
|
||||
|
||||
class EmailReplyTask(AbstractTask):
|
||||
"""Формирует ответ на входящее письмо с запросом на заказ°"""
|
||||
EMAIl = "zosimovaa@yandex.ru" #"noreply@zapchastiya.ru"
|
||||
|
||||
def do(self):
|
||||
|
||||
try:
|
||||
email = self.context.data.get("email")
|
||||
|
||||
if not email:
|
||||
raise ValueError("В контексте нет входящего сообщения")
|
||||
|
||||
email_from = self.context.data.get("email_from")
|
||||
if not email_from:
|
||||
raise ValueError("В контексте не определен адрес отправителя")
|
||||
|
||||
|
||||
reply_message = MIMEMultipart()
|
||||
|
||||
email_subj = self.context.data.get("email_subj")
|
||||
|
||||
reply_message["From"] = self.EMAIl
|
||||
reply_message["To"] = email_from
|
||||
#reply_message["Cc"] = self.config.get("reply_to", "")
|
||||
reply_message["Subject"] = f"Re: {email_subj}"
|
||||
reply_message["Date"] = formatdate(localtime=True)
|
||||
|
||||
body = "Автоматический ответ на создание заказа"
|
||||
reply_message.attach(MIMEText(body, "plain", "utf-8"))
|
||||
|
||||
attachments = self.context.data.get("attachments")
|
||||
for attachment in attachments:
|
||||
self._attach_file(reply_message, attachment)
|
||||
|
||||
self.context.email_client.send_email(reply_message)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
def _attach_file(self, reply_message, attachment):
|
||||
"""
|
||||
Args:
|
||||
message: MIMEMultipart
|
||||
file_path:
|
||||
"""
|
||||
try:
|
||||
|
||||
part = MIMEBase("application", "octet-stream")
|
||||
|
||||
excel_file = attachment["excel"]
|
||||
excel_file_bytes = excel_file.get_file_bytes()
|
||||
part.set_payload(excel_file_bytes.read())
|
||||
|
||||
encoders.encode_base64(part)
|
||||
|
||||
file_name = attachment["name"][0]
|
||||
part.add_header(
|
||||
"Content-Disposition",
|
||||
f"attachment; filename= {file_name}"
|
||||
)
|
||||
|
||||
reply_message.attach(part)
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"Ошибка при аттаче файла: {str(e)}")
|
||||
@@ -3,16 +3,16 @@ import pandas as pd
|
||||
from typing import Dict, Any, Optional
|
||||
from decimal import Decimal
|
||||
from io import BytesIO
|
||||
#from mail_order_bot.email_processor.handlers.order_position import OrderPosition
|
||||
from mail_order_bot.email_processor.handlers.abstract_task import AbstractTask
|
||||
#from mail_order_bot.task_processor.handlers.order_position import OrderPosition
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
|
||||
from ...order.auto_part_position import AutoPartPosition
|
||||
from ...order.auto_part_order import AutoPartOrder
|
||||
from mail_order_bot.task_processor.order.auto_part_position import AutoPartPosition
|
||||
from mail_order_bot.task_processor.order.auto_part_order import AutoPartOrder
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BasicExcelParser(AbstractTask):
|
||||
class OrderParser(AbstractTask):
|
||||
"""
|
||||
Универсальный парсер, настраиваемый через конфигурацию.
|
||||
Подходит для большинства стандартных случаев.
|
||||
@@ -27,23 +27,27 @@ class BasicExcelParser(AbstractTask):
|
||||
attachments = self.context.data.get("attachments", [])
|
||||
for attachment in attachments:
|
||||
file_bytes = BytesIO(attachment['bytes']) # self.context.get("attachment") #
|
||||
try:
|
||||
delivery_period = attachment.get("delivery_period", 0)
|
||||
#try:
|
||||
df = self._make_dataframe(file_bytes)
|
||||
mapping = self.config['mapping']
|
||||
mapping = self.config["mapping"]
|
||||
client_id = self.config["client_id"]
|
||||
order = AutoPartOrder()
|
||||
attachment["order"] = order
|
||||
|
||||
# Парсим строки
|
||||
positions = []
|
||||
for idx, row in df.iterrows():
|
||||
position = self._parse_row(row, mapping)
|
||||
if position:
|
||||
position.order_delivery_period = delivery_period
|
||||
order.add_position(position)
|
||||
|
||||
logger.info(f"Успешно обработано {len(order)} позиций из {len(df)} строк")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при обработке файла: {e}")
|
||||
else:
|
||||
#except Exception as e:
|
||||
# logger.error(f"Ошибка при обработке файла: {e}")
|
||||
#else:
|
||||
attachment["order"] = order
|
||||
|
||||
|
||||
@@ -67,7 +71,7 @@ class BasicExcelParser(AbstractTask):
|
||||
else:
|
||||
total = price * quantity
|
||||
|
||||
if mapping.get('name', "") in mapping.keys():
|
||||
if "name" in mapping:
|
||||
name = str(row[mapping.get('name', "")]).strip()
|
||||
else:
|
||||
name = ""
|
||||
@@ -3,7 +3,7 @@ import pandas as pd
|
||||
from typing import Dict, Any, Optional
|
||||
from decimal import Decimal
|
||||
from io import BytesIO
|
||||
#from mail_order_bot.email_processor.handlers.order_position import OrderPosition
|
||||
#from mail_order_bot.task_processor.handlers.order_position import OrderPosition
|
||||
from mail_order_bot.email_processor.handlers.abstract_task import AbstractTask
|
||||
|
||||
from ...order.auto_part_position import AutoPartPosition
|
||||
@@ -0,0 +1,43 @@
|
||||
import logging
|
||||
import pandas as pd
|
||||
from io import BytesIO
|
||||
|
||||
from mail_order_bot.email_client import EmailUtils
|
||||
#from mail_order_bot.task_processor.handlers.order_position import OrderPosition
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
|
||||
from mail_order_bot.parsers.excel_parcer import ExcelFileParcer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ExcelExtractor(AbstractTask):
|
||||
"""
|
||||
Хендлер для каждого вложения считывает эксель файл и сохраняет его контекст
|
||||
"""
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.excel_config = self.config.get("excel", {})
|
||||
|
||||
def do(self) -> None:
|
||||
|
||||
# todo сделать проверку на наличие файла и его тип
|
||||
|
||||
attachments = self.context.data.get("attachments", [])
|
||||
|
||||
for attachment in attachments:
|
||||
try:
|
||||
file_bytes = BytesIO(attachment['bytes'])
|
||||
excel_file = ExcelFileParcer(file_bytes, self.excel_config)
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Не удалось прочитать файл {attachment['name']}: {e}")
|
||||
attachment["excel"] = None
|
||||
|
||||
else:
|
||||
attachment["excel"] = excel_file
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import logging
|
||||
import pandas as pd
|
||||
from io import BytesIO
|
||||
from mail_order_bot.parsers.order_parcer import OrderParser
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
|
||||
from mail_order_bot.parsers.excel_parcer import ExcelFileParcer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OrderExtractor(AbstractTask):
|
||||
"""
|
||||
Хендлер для каждого вложения считывает эксель файл и сохраняет его контекст
|
||||
"""
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.excel_config = self.config.get("excel", {})
|
||||
|
||||
|
||||
def do(self) -> None:
|
||||
|
||||
# todo сделать проверку на наличие файла и его тип
|
||||
|
||||
attachments = self.context.data.get("attachments", [])
|
||||
for attachment in attachments:
|
||||
|
||||
delivery_period = attachment.get("delivery_period", 0)
|
||||
mapping = self.excel_config.get("mapping")
|
||||
|
||||
excel_file = attachment.get("excel")
|
||||
client_id = self.config.get("client_id")
|
||||
order_parcer = OrderParser(mapping, delivery_period, client_id)
|
||||
|
||||
order_dataframe = excel_file.get_order_rows()
|
||||
|
||||
order = order_parcer.parse(order_dataframe)
|
||||
attachment["order"] = order
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import logging
|
||||
import pandas as pd
|
||||
from io import BytesIO
|
||||
# from mail_order_bot.task_processor.handlers.order_position import OrderPosition
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
|
||||
|
||||
from mail_order_bot.order.auto_part_position import PositionStatus
|
||||
from mail_order_bot.parsers.excel_parcer import ExcelFileParcer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class UpdateExcelFile(AbstractTask):
|
||||
"""
|
||||
Хендлер для каждого вложения считывает эксель файл и сохраняет его контекст
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.excel_config = self.config.get("excel", {})
|
||||
|
||||
def do(self) -> None:
|
||||
# todo сделать проверку на наличие файла и его тип
|
||||
|
||||
attachments = self.context.data.get("attachments", [])
|
||||
for attachment in attachments:
|
||||
excel_file = attachment.get("excel")
|
||||
order = attachment.get("order")
|
||||
config = self.context.data.get("config", {})
|
||||
excel_config = config.get("excel", {})
|
||||
updatable_fields = excel_config.get("updatable_fields", {})
|
||||
|
||||
for position in order.positions:
|
||||
|
||||
sku = position.sku
|
||||
manufacturer = position.manufacturer
|
||||
|
||||
for key, value in updatable_fields.items():
|
||||
|
||||
if key == "ordered_quantity":
|
||||
column = value
|
||||
value = position.order_quantity
|
||||
excel_file.set_value(sku, manufacturer, column, value)
|
||||
|
||||
if key == "ordered_price":
|
||||
column = value
|
||||
value = position.order_price
|
||||
excel_file.set_value(sku, manufacturer, column, value)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
|
||||
from mail_order_bot.email_processor.handlers.abstract_task import AbstractTask
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -12,4 +12,4 @@ class TestNotifier(AbstractTask):
|
||||
print(f"\nПолучено {len(positions)} позиций от {self.context["client"]}:")
|
||||
for pos in positions: # Первые 5
|
||||
print(f" - {pos.sku}: {pos.name} "
|
||||
f"({pos.requested_quantity} x {pos.requested_price} = {pos.total})")
|
||||
f"({pos.asking_quantity} x {pos.asking_price} = {pos.total})")
|
||||
@@ -0,0 +1,121 @@
|
||||
import logging
|
||||
import pandas as pd
|
||||
from io import BytesIO
|
||||
|
||||
from dotenv.parser import Position
|
||||
|
||||
from mail_order_bot.parsers.order_parcer import OrderParser
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
from mail_order_bot.order.auto_part_position import AutoPartPosition, PositionStatus
|
||||
from mail_order_bot.parsers.excel_parcer import ExcelFileParcer
|
||||
from decimal import Decimal
|
||||
|
||||
from mail_order_bot.task_processor.abstract_task import AbstractTask
|
||||
from mail_order_bot.abcp_api.abcp_provider import AbcpProvider
|
||||
from mail_order_bot.credential_provider import CredentialProvider
|
||||
from mail_order_bot.order.auto_part_order import OrderStatus
|
||||
|
||||
|
||||
from typing import Dict, Any
|
||||
from typing import List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class StockSelector(AbstractTask):
|
||||
DISTRIBUTOR_ID = 1577730 # ID локального склада
|
||||
"""
|
||||
Выбирает подходящие позиции со склада
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
credential_provider = CredentialProvider(context=self.context)
|
||||
# Создаем провайдер для учетной записи клиента
|
||||
client_login, client_password = credential_provider.get_system_credentials()
|
||||
self.client_provider = AbcpProvider(login=client_login, password=client_password)
|
||||
|
||||
def do(self) -> None:
|
||||
# todo сделать проверку на наличие файла и его тип
|
||||
attachments = self.context.data.get("attachments", [])
|
||||
for attachment in attachments:
|
||||
order = attachment.get("order", None)
|
||||
delivery_period = attachment.get("delivery_period")
|
||||
for position in order.positions:
|
||||
|
||||
#1. Получаем остатки со складов
|
||||
stock_data = self.client_provider.get_stock(position.sku, position.manufacturer)
|
||||
|
||||
#2. Из данных остатков выбираем оптимальное значение по стратегии
|
||||
if stock_data["success"]:
|
||||
stock_list = stock_data.get("data", [])
|
||||
asking_price = position.asking_price
|
||||
asking_quantity = position.asking_quantity
|
||||
|
||||
|
||||
optimal_stock_positions = self.get_optimal_stock(stock_list, asking_price, asking_quantity, delivery_period)
|
||||
|
||||
# 3. Устанавливаем выбранное значение в позицию
|
||||
if len(optimal_stock_positions):
|
||||
position.set_order_item(optimal_stock_positions[0])
|
||||
else:
|
||||
position.status = PositionStatus.NO_AVAILABLE_STOCK
|
||||
# Мне не очень нравится управление статусами в этом месте, кажется что лучше это делать внутри AutoPartPosition
|
||||
else:
|
||||
position.status = PositionStatus.STOCK_FAILED
|
||||
|
||||
|
||||
|
||||
def get_optimal_stock(self, stock_list, asking_price, asking_quantity, delivery_period):
|
||||
"""Выбирает позицию для заказа"""
|
||||
|
||||
# BR-1. Отсекаем склады для заказов из наличия (только локальный склад)
|
||||
stock_list = self._br1_only_local_stock(stock_list)
|
||||
|
||||
# BR-2. Цена не должна превышать цену из заказа
|
||||
#stock_list = self._br2_price_below_asked_price(stock_list, asking_price)
|
||||
|
||||
# BR-3. Срок доставки не должен превышать ожидаемый
|
||||
stock_list = self._br3_delivery_time_shorted_asked_time(stock_list, delivery_period)
|
||||
|
||||
# BR-4. Без отрицательных остатков
|
||||
stock_list = self._br4_only_positive_stock(stock_list)
|
||||
|
||||
# BR-5 Выбираем склад с максимальным профитом
|
||||
stock_list = self._br5_max_profit(stock_list, asking_price, asking_quantity)
|
||||
|
||||
# пока не реализовано
|
||||
# BR-7 Приоритет на склады с полным стоком
|
||||
# BR-8. Сначала оборачиваем локальный склад, потом удаленные
|
||||
# BR-9. Даем немного уйти в минус при заказе из наличия
|
||||
|
||||
return stock_list
|
||||
|
||||
def _br1_only_local_stock(self, stocks):
|
||||
return [item for item in stocks if item["distributorId"] == self.DISTRIBUTOR_ID]
|
||||
|
||||
def _br2_price_below_asked_price(self, distributors: List[Dict[str, Any]], asking_price) -> List[Dict[str, Any]]:
|
||||
"""Фильтрует склады по цене (убирает дорогие)"""
|
||||
return [item for item in distributors if Decimal(item["price"]) <= asking_price]
|
||||
|
||||
def _br3_delivery_time_shorted_asked_time(self, distributors: List[Dict[str, Any]], delivery_period) -> List[Dict[str, Any]]:
|
||||
"""Фильтрует склады по сроку доставки"""
|
||||
# Вопрос - надо ли ориентироваться на deliveryPeriodMax
|
||||
return [item for item in distributors if item["deliveryPeriod"] <= delivery_period]
|
||||
|
||||
def _br4_only_positive_stock(self, distributors: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""Фильтрует склады с положительным остатком"""
|
||||
return [item for item in distributors if Decimal(item["availability"]) > 0]
|
||||
|
||||
def _br5_max_profit(self, distributors: List[Dict[str, Any]], asking_price, asking_quantity) -> List[Dict[str, Any]]:
|
||||
"""Фильтрует склады с положительным остатком"""
|
||||
for item in distributors:
|
||||
item["profit"] = (asking_price - Decimal(item["price"])) * min(asking_quantity, item["availability"])
|
||||
|
||||
distributors.sort(key=lambda item: Decimal(item["profit"]), reverse=False)
|
||||
|
||||
return distributors
|
||||
|
||||
|
||||
|
||||
|
||||
44
src/mail_order_bot/task_processor/message.py
Normal file
44
src/mail_order_bot/task_processor/message.py
Normal file
@@ -0,0 +1,44 @@
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class LogMessageLevel(Enum):
|
||||
SUCCESS = "SUCCESS"
|
||||
WARNING = "WARNING"
|
||||
ERROR = "ERROR"
|
||||
|
||||
class LogMessage:
|
||||
def __init__(self, handler=None, level=None, message=None, error_data=None):
|
||||
self.handler = handler
|
||||
self.level = level
|
||||
self.message = message
|
||||
self.error_data = error_data
|
||||
|
||||
def __str__(self):
|
||||
return self.message
|
||||
|
||||
class LogMessageStorage:
|
||||
def __init__(self, filename=None):
|
||||
self.filename = filename
|
||||
self.messages = []
|
||||
|
||||
def append(self, message):
|
||||
self.messages.append(message)
|
||||
|
||||
def check_errors(self) -> bool:
|
||||
fatal_statuses = [message.level == LogMessageLevel.ERROR for message in self.messages]
|
||||
return bool(sum(fatal_statuses))
|
||||
|
||||
def get_messages_log(self) -> str:
|
||||
response = ""
|
||||
|
||||
if self.filename is not None:
|
||||
response += f" Лог обработки файла: {self.filename}"
|
||||
|
||||
for message in self.messages:
|
||||
if len(response):
|
||||
response += "\n"
|
||||
response += f"{message.handler} [{message.level}]: {message.message}"
|
||||
if message.error_data is not None:
|
||||
response += f"\n{message.error_data}"
|
||||
|
||||
105
src/mail_order_bot/task_processor/processor.py
Normal file
105
src/mail_order_bot/task_processor/processor.py
Normal file
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
Общая логика обработки писем следующая
|
||||
|
||||
1. Общая часть
|
||||
- скачиваем письмо
|
||||
- складываем в контекст
|
||||
- обработчик и парсим данные - тело, тема, отправитель
|
||||
|
||||
2. Запускаем паплайн
|
||||
- прогоняем обработчик для каждого вложения
|
||||
- каждый обработчик для вложения докидывает результат своей работы
|
||||
- каждый обработчик анализирует общий лог на наличие фатальных ошибок. Если есть - пропускаем шаг.
|
||||
Последний обработчик направляет лог ошибок на администратора
|
||||
|
||||
Ограничения:
|
||||
- каждое вложение воспринимается как "отдельное письмо", т.е. если клиент в одном письме направит несколько вложений,
|
||||
то они будут обрабатываться как отдельные письма, и на каждое будет дан ответ (если он требуется).
|
||||
|
||||
|
||||
Исключительные ситуации:
|
||||
- При невозможности создать заказ - пересылаем письмо на администратора с логом обработки вложения
|
||||
- Вложения, которые не являются файлами заказа игнорируем.
|
||||
|
||||
|
||||
todo
|
||||
[ ] Нужен класс, который будет хранить сообщения от обработчиков
|
||||
- метод для добавления сообщения
|
||||
- метод для проверки фатальных ошибок
|
||||
- метод для извлечения лога
|
||||
|
||||
"""
|
||||
|
||||
import os
|
||||
import yaml
|
||||
import logging
|
||||
from typing import Dict, Any, List
|
||||
from pathlib import Path
|
||||
import threading
|
||||
from mail_order_bot.context import Context
|
||||
from mail_order_bot.email_client.utils import EmailUtils
|
||||
from enum import Enum
|
||||
|
||||
from mail_order_bot.task_processor.handlers import *
|
||||
from mail_order_bot.task_processor.handlers.email.email_parcer import EmailParcer
|
||||
|
||||
from mail_order_bot import MailOrderBotException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RequestStatus(Enum):
|
||||
NEW = "new"
|
||||
IN_PROGRESS = "in progress"
|
||||
FAILED = "failed"
|
||||
EXECUTED = "executed"
|
||||
OPERATOR_REQUIRED = "operator required"
|
||||
INVALID = "invalid"
|
||||
|
||||
|
||||
class TaskProcessor:
|
||||
#def __init__(self, configs_path: str):
|
||||
def __init__(self, config: Dict[str, Any]):
|
||||
super().__init__()
|
||||
self.context = Context()
|
||||
#self.configs_path = configs_path
|
||||
self.config = config
|
||||
self.status = RequestStatus.NEW
|
||||
|
||||
def process_email(self, email):
|
||||
# Очистить контекст и запушить туда письмо
|
||||
self.context.clear()
|
||||
self.context.data["email"] = email
|
||||
|
||||
try:
|
||||
# Парсинг письма
|
||||
email_parcer = EmailParcer()
|
||||
email_parcer.do()
|
||||
|
||||
email_sender = self.context.data.get("email_from")
|
||||
|
||||
# Определить конфиг для пайплайна
|
||||
config = self._load_config(email_sender)
|
||||
self.context.data["config"] = config
|
||||
|
||||
# Запустить обработку пайплайна
|
||||
pipeline = config["pipeline"]
|
||||
for handler_name in pipeline:
|
||||
logger.info(f"Processing handler: {handler_name}")
|
||||
task = globals()[handler_name]()
|
||||
task.do()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Произошла ошибка: {e}")
|
||||
|
||||
|
||||
def _load_config(self, email_from) -> Dict[str, Any]:
|
||||
if email_from in self.config:
|
||||
return self.config[email_from]
|
||||
|
||||
email_from_domain = EmailUtils.extract_domain(email_from)
|
||||
|
||||
if email_from_domain in self.config:
|
||||
return self.config[email_from_domain]
|
||||
|
||||
raise FileNotFoundError
|
||||
4
src/mail_order_bot/telegram/__init__.py
Normal file
4
src/mail_order_bot/telegram/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from mail_order_bot.telegram.client import TelegramClient
|
||||
|
||||
__all__ = ['TelegramClient']
|
||||
|
||||
176
src/mail_order_bot/telegram/client.py
Normal file
176
src/mail_order_bot/telegram/client.py
Normal file
@@ -0,0 +1,176 @@
|
||||
import os
|
||||
import logging
|
||||
import requests
|
||||
from typing import Optional
|
||||
from io import BytesIO
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TelegramClient:
|
||||
"""
|
||||
Класс для отправки сообщений через Telegram Bot API.
|
||||
|
||||
Поддерживает отправку:
|
||||
- Текстовых сообщений
|
||||
- Сообщений с вложением (Excel файл в формате BytesIO)
|
||||
"""
|
||||
|
||||
BASE_URL = "https://api.telegram.org/bot"
|
||||
|
||||
def __init__(self, bot_token: Optional[str] = None, chat_id: Optional[str] = None):
|
||||
"""
|
||||
Инициализация TelegramClient.
|
||||
|
||||
Args:
|
||||
bot_token: Токен бота Telegram. Если не указан, берется из TELEGRAM_BOT_TOKEN
|
||||
chat_id: ID чата для отправки сообщений. Если не указан, берется из TELEGRAM_CHAT_ID
|
||||
"""
|
||||
self.bot_token = bot_token or os.getenv('TELEGRAM_BOT_TOKEN')
|
||||
self.chat_id = chat_id or os.getenv('TELEGRAM_CHAT_ID')
|
||||
|
||||
if not self.bot_token:
|
||||
raise ValueError("Telegram bot token is required. Set TELEGRAM_BOT_TOKEN environment variable or pass bot_token parameter.")
|
||||
|
||||
if not self.chat_id:
|
||||
raise ValueError("Telegram chat ID is required. Set TELEGRAM_CHAT_ID environment variable or pass chat_id parameter.")
|
||||
|
||||
self.api_url = f"{self.BASE_URL}{self.bot_token}"
|
||||
|
||||
def send_message(self, text: str, parse_mode: Optional[str] = None) -> dict:
|
||||
"""
|
||||
Отправляет текстовое сообщение в Telegram.
|
||||
|
||||
Args:
|
||||
text: Текст сообщения для отправки
|
||||
parse_mode: Режим парсинга (HTML, Markdown, MarkdownV2). По умолчанию None
|
||||
|
||||
Returns:
|
||||
dict: Результат запроса с полями success (bool) и data/error
|
||||
"""
|
||||
url = f"{self.api_url}/sendMessage"
|
||||
|
||||
payload = {
|
||||
"chat_id": self.chat_id,
|
||||
"text": text
|
||||
}
|
||||
|
||||
if parse_mode:
|
||||
payload["parse_mode"] = parse_mode
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=payload)
|
||||
response.raise_for_status()
|
||||
|
||||
result = response.json()
|
||||
if result.get("ok"):
|
||||
logger.debug(f"Сообщение успешно отправлено в Telegram")
|
||||
return {
|
||||
"success": True,
|
||||
"data": result.get("result")
|
||||
}
|
||||
else:
|
||||
error_description = result.get("description", "Unknown error")
|
||||
logger.warning(f"Ошибка отправки сообщения в Telegram: {error_description}")
|
||||
return {
|
||||
"success": False,
|
||||
"error": error_description
|
||||
}
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error(f"Ошибка при отправке сообщения в Telegram: {e}")
|
||||
return {
|
||||
"success": False,
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
def send_document(
|
||||
self,
|
||||
document: BytesIO,
|
||||
filename: str = "document.xlsx",
|
||||
caption: Optional[str] = None,
|
||||
parse_mode: Optional[str] = None
|
||||
) -> dict:
|
||||
"""
|
||||
Отправляет документ (Excel файл) в Telegram.
|
||||
|
||||
Args:
|
||||
document: BytesIO объект с содержимым файла
|
||||
filename: Имя файла для отправки (по умолчанию "document.xlsx")
|
||||
caption: Подпись к документу (опционально)
|
||||
parse_mode: Режим парсинга для подписи (HTML, Markdown, MarkdownV2). По умолчанию None
|
||||
|
||||
Returns:
|
||||
dict: Результат запроса с полями success (bool) и data/error
|
||||
"""
|
||||
url = f"{self.api_url}/sendDocument"
|
||||
|
||||
# Убедимся, что указатель файла находится в начале
|
||||
document.seek(0)
|
||||
|
||||
files = {
|
||||
"document": (filename, document, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
}
|
||||
|
||||
data = {
|
||||
"chat_id": self.chat_id
|
||||
}
|
||||
|
||||
if caption:
|
||||
data["caption"] = caption
|
||||
|
||||
if parse_mode:
|
||||
data["parse_mode"] = parse_mode
|
||||
|
||||
try:
|
||||
response = requests.post(url, files=files, data=data)
|
||||
response.raise_for_status()
|
||||
|
||||
result = response.json()
|
||||
if result.get("ok"):
|
||||
logger.debug(f"Документ успешно отправлен в Telegram")
|
||||
return {
|
||||
"success": True,
|
||||
"data": result.get("result")
|
||||
}
|
||||
else:
|
||||
error_description = result.get("description", "Unknown error")
|
||||
logger.warning(f"Ошибка отправки документа в Telegram: {error_description}")
|
||||
return {
|
||||
"success": False,
|
||||
"error": error_description
|
||||
}
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error(f"Ошибка при отправке документа в Telegram: {e}")
|
||||
return {
|
||||
"success": False,
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
def send_message_with_document(
|
||||
self,
|
||||
text: str,
|
||||
document: BytesIO,
|
||||
filename: str = "document.xlsx",
|
||||
parse_mode: Optional[str] = None
|
||||
) -> dict:
|
||||
"""
|
||||
Отправляет сообщение с документом. Текст используется как подпись к документу.
|
||||
|
||||
Args:
|
||||
text: Текст сообщения (будет использован как подпись к документу)
|
||||
document: BytesIO объект с содержимым файла
|
||||
filename: Имя файла для отправки (по умолчанию "document.xlsx")
|
||||
parse_mode: Режим парсинга для подписи (HTML, Markdown, MarkdownV2). По умолчанию None
|
||||
|
||||
Returns:
|
||||
dict: Результат запроса с полями success (bool) и data/error
|
||||
"""
|
||||
return self.send_document(
|
||||
document=document,
|
||||
filename=filename,
|
||||
caption=text,
|
||||
parse_mode=parse_mode
|
||||
)
|
||||
|
||||
@@ -13,10 +13,12 @@ if __name__ == "__main__":
|
||||
position = AutoPartPosition(sku="560300054", manufacturer="VST", requested_quantity=1)
|
||||
order.add_position(position)
|
||||
|
||||
provider = AbcpProvider()
|
||||
login = os.getenv('ABCP_LOGIN_SYSTEM')
|
||||
password = os.getenv('ABCP_PASSWORD_SYSTEM')
|
||||
provider = AbcpProvider(login=login, password=password)
|
||||
|
||||
provider.get_stock(order)
|
||||
result = provider.get_stock(position.sku, position.manufacturer)
|
||||
|
||||
print(order.positions[0].stock)
|
||||
|
||||
print(os.getenv('ABCP_LOGIN'))
|
||||
print(os.getenv('ABCP_LOGIN_SYSTEM'))
|
||||
2
tests/parsers/__init__.py
Normal file
2
tests/parsers/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
# Tests for parsers module
|
||||
|
||||
320
tests/parsers/test_excel_parcer.py
Normal file
320
tests/parsers/test_excel_parcer.py
Normal file
@@ -0,0 +1,320 @@
|
||||
import pytest
|
||||
import pandas as pd
|
||||
from io import BytesIO
|
||||
from unittest.mock import patch
|
||||
|
||||
from mail_order_bot.parsers.excel_parcer import ExcelFileParcer
|
||||
|
||||
|
||||
class TestExcelFileParcer:
|
||||
"""Тесты для класса ExcelFileParcer"""
|
||||
|
||||
@pytest.fixture
|
||||
def sample_config(self):
|
||||
"""Базовая конфигурация для тестов"""
|
||||
return {
|
||||
"sheet_name": 0,
|
||||
"key_field": "Артикул",
|
||||
"mapping": {
|
||||
"article": "Артикул",
|
||||
"manufacturer": "Производитель",
|
||||
"name": "Наименование",
|
||||
"price": "Цена",
|
||||
"quantity": "Количество"
|
||||
}
|
||||
}
|
||||
|
||||
@pytest.fixture
|
||||
def sample_excel_bytes(self):
|
||||
"""Создает тестовый Excel файл в виде байтов"""
|
||||
df = pd.DataFrame({
|
||||
'Артикул': ['ART001', 'ART002', 'ART003'],
|
||||
'Производитель': ['MAN001', 'MAN002', 'MAN003'],
|
||||
'Наименование': ['Товар 1', 'Товар 2', 'Товар 3'],
|
||||
'Цена': [100.0, 200.0, 300.0],
|
||||
'Количество': [1, 2, 3]
|
||||
})
|
||||
buf = BytesIO()
|
||||
with pd.ExcelWriter(buf, engine='xlsxwriter') as writer:
|
||||
df.to_excel(writer, sheet_name='Sheet1', index=False)
|
||||
buf.seek(0)
|
||||
return buf.getvalue()
|
||||
|
||||
@pytest.fixture
|
||||
def excel_with_header_row(self):
|
||||
"""Создает Excel файл с заголовком не в первой строке"""
|
||||
df = pd.DataFrame([
|
||||
['Заголовок документа', None, None, None, None],
|
||||
['Артикул', 'Производитель', 'Наименование', 'Цена', 'Количество'],
|
||||
['ART001', 'MAN001', 'Товар 1', 100.0, 1],
|
||||
['ART002', 'MAN002', 'Товар 2', 200.0, 2],
|
||||
['ART003', 'MAN003', 'Товар 3', 300.0, 3],
|
||||
[None, None, None, None, None] # Пустая строка для обрезки
|
||||
])
|
||||
buf = BytesIO()
|
||||
with pd.ExcelWriter(buf, engine='xlsxwriter') as writer:
|
||||
df.to_excel(writer, sheet_name='Sheet1', index=False, header=False)
|
||||
buf.seek(0)
|
||||
return buf.getvalue()
|
||||
|
||||
def test_init_with_valid_file(self, sample_excel_bytes, sample_config):
|
||||
"""Тест инициализации с валидным файлом"""
|
||||
parser = ExcelFileParcer(sample_excel_bytes, sample_config)
|
||||
|
||||
assert parser.config == sample_config
|
||||
assert parser.bytes == sample_excel_bytes
|
||||
assert parser.sheet_name == 0
|
||||
assert parser.df is not None
|
||||
assert isinstance(parser.df, pd.DataFrame)
|
||||
|
||||
def test_init_with_custom_sheet_name(self, sample_excel_bytes):
|
||||
"""Тест инициализации с кастомным именем листа"""
|
||||
config = {
|
||||
"sheet_name": "Sheet2",
|
||||
"key_field": "Артикул",
|
||||
"mapping": {
|
||||
"article": "Артикул",
|
||||
"manufacturer": "Производитель"
|
||||
}
|
||||
}
|
||||
parser = ExcelFileParcer(sample_excel_bytes, config)
|
||||
assert parser.sheet_name == "Sheet2"
|
||||
|
||||
def test_init_with_default_sheet_name(self, sample_excel_bytes):
|
||||
"""Тест инициализации с дефолтным именем листа"""
|
||||
config = {
|
||||
"key_field": "Артикул",
|
||||
"mapping": {
|
||||
"article": "Артикул",
|
||||
"manufacturer": "Производитель"
|
||||
}
|
||||
}
|
||||
parser = ExcelFileParcer(sample_excel_bytes, config)
|
||||
assert parser.sheet_name == 0
|
||||
|
||||
@patch('mail_order_bot.parsers.excel_parcer.pd.read_excel')
|
||||
def test_init_with_invalid_file(self, mock_read_excel, sample_config):
|
||||
"""Тест инициализации с невалидным файлом"""
|
||||
mock_read_excel.side_effect = Exception("Ошибка парсинга")
|
||||
invalid_bytes = b"invalid excel content"
|
||||
|
||||
parser = ExcelFileParcer(invalid_bytes, sample_config)
|
||||
|
||||
assert parser.df is None
|
||||
|
||||
def test_parse_file_success(self, sample_excel_bytes, sample_config):
|
||||
"""Тест успешного парсинга файла"""
|
||||
parser = ExcelFileParcer(sample_excel_bytes, sample_config)
|
||||
assert parser.df is not None
|
||||
assert len(parser.df) > 0
|
||||
|
||||
@patch('mail_order_bot.parsers.excel_parcer.pd.read_excel')
|
||||
def test_parse_file_failure(self, mock_read_excel, sample_config):
|
||||
"""Тест обработки ошибки при парсинге файла"""
|
||||
mock_read_excel.side_effect = Exception("Ошибка чтения")
|
||||
invalid_bytes = b"invalid"
|
||||
|
||||
parser = ExcelFileParcer(invalid_bytes, sample_config)
|
||||
assert parser.df is None
|
||||
|
||||
def test_get_header_row(self, excel_with_header_row, sample_config):
|
||||
"""Тест поиска строки заголовка"""
|
||||
parser = ExcelFileParcer(excel_with_header_row, sample_config)
|
||||
header_row = parser._get_header_row()
|
||||
|
||||
assert header_row == 1 # Заголовок во второй строке (индекс 1)
|
||||
|
||||
def test_get_attr_column(self, excel_with_header_row, sample_config):
|
||||
"""Тест поиска индекса колонки по имени"""
|
||||
parser = ExcelFileParcer(excel_with_header_row, sample_config)
|
||||
col_idx = parser._get_attr_column("Артикул")
|
||||
|
||||
assert isinstance(col_idx, int)
|
||||
assert col_idx >= 0
|
||||
|
||||
def test_get_attr_column_nonexistent(self, excel_with_header_row, sample_config):
|
||||
"""Тест поиска несуществующей колонки"""
|
||||
parser = ExcelFileParcer(excel_with_header_row, sample_config)
|
||||
|
||||
with pytest.raises((IndexError, KeyError)):
|
||||
parser._get_attr_column("Несуществующая колонка")
|
||||
|
||||
def test_get_attr_row(self, excel_with_header_row, sample_config):
|
||||
"""Тест поиска строки по артикулу и производителю"""
|
||||
parser = ExcelFileParcer(excel_with_header_row, sample_config)
|
||||
row_idx = parser._get_attr_row("ART001", "MAN001")
|
||||
|
||||
assert isinstance(row_idx, (int, pd.core.indexes.numeric.Int64Index))
|
||||
# Проверяем, что индекс найден
|
||||
assert row_idx is not None
|
||||
|
||||
def test_get_attr_row_nonexistent(self, excel_with_header_row, sample_config):
|
||||
"""Тест поиска несуществующей строки"""
|
||||
parser = ExcelFileParcer(excel_with_header_row, sample_config)
|
||||
|
||||
with pytest.raises((IndexError, KeyError)):
|
||||
parser._get_attr_row("NONEXISTENT", "NONEXISTENT")
|
||||
|
||||
def test_set_value(self, excel_with_header_row, sample_config):
|
||||
"""Тест установки значения в ячейку"""
|
||||
parser = ExcelFileParcer(excel_with_header_row, sample_config)
|
||||
|
||||
# Получаем исходное значение
|
||||
original_value = parser.df.iloc[2, 3] # Строка с ART001, колонка "Цена"
|
||||
|
||||
# Устанавливаем новое значение
|
||||
parser.set_value("ART001", "MAN001", "Цена", 999.0)
|
||||
|
||||
# Проверяем, что значение изменилось
|
||||
new_value = parser.df.iloc[2, 3]
|
||||
assert new_value == 999.0
|
||||
assert new_value != original_value
|
||||
|
||||
def test_get_file_bytes(self, sample_excel_bytes, sample_config):
|
||||
"""Тест получения файла в виде байтов"""
|
||||
parser = ExcelFileParcer(sample_excel_bytes, sample_config)
|
||||
result_bytes = parser.get_file_bytes()
|
||||
|
||||
assert result_bytes is not None
|
||||
assert hasattr(result_bytes, 'read')
|
||||
assert hasattr(result_bytes, 'seek')
|
||||
|
||||
# Проверяем, что можно прочитать байты
|
||||
result_bytes.seek(0)
|
||||
content = result_bytes.read()
|
||||
assert len(content) > 0
|
||||
|
||||
def test_get_file_bytes_creates_valid_excel(self, sample_excel_bytes, sample_config):
|
||||
"""Тест что get_file_bytes создает валидный Excel файл"""
|
||||
parser = ExcelFileParcer(sample_excel_bytes, sample_config)
|
||||
result_bytes = parser.get_file_bytes()
|
||||
|
||||
# Пытаемся прочитать созданный файл
|
||||
result_bytes.seek(0)
|
||||
df = pd.read_excel(result_bytes, sheet_name=0, header=None)
|
||||
|
||||
assert df is not None
|
||||
assert len(df) > 0
|
||||
|
||||
def test_get_order_rows(self, excel_with_header_row, sample_config):
|
||||
"""Тест получения строк заказа"""
|
||||
parser = ExcelFileParcer(excel_with_header_row, sample_config)
|
||||
order_rows = parser.get_order_rows()
|
||||
|
||||
assert order_rows is not None
|
||||
assert isinstance(order_rows, pd.DataFrame)
|
||||
assert len(order_rows) > 0
|
||||
# Проверяем, что пустая строка обрезана
|
||||
assert len(order_rows) == 3 # Только строки с данными
|
||||
|
||||
def test_get_order_rows_with_empty_file(self, sample_config):
|
||||
"""Тест получения строк заказа из пустого файла"""
|
||||
# Создаем пустой DataFrame
|
||||
df = pd.DataFrame([['Артикул', 'Производитель'], [None, None]])
|
||||
buf = BytesIO()
|
||||
with pd.ExcelWriter(buf, engine='xlsxwriter') as writer:
|
||||
df.to_excel(writer, sheet_name='Sheet1', index=False, header=False)
|
||||
buf.seek(0)
|
||||
empty_bytes = buf.getvalue()
|
||||
|
||||
parser = ExcelFileParcer(empty_bytes, sample_config)
|
||||
|
||||
# Должен вернуть пустой DataFrame или вызвать ошибку
|
||||
try:
|
||||
order_rows = parser.get_order_rows()
|
||||
assert len(order_rows) == 0
|
||||
except (IndexError, KeyError):
|
||||
# Ожидаемое поведение при отсутствии данных
|
||||
pass
|
||||
|
||||
def test_set_value_updates_dataframe(self, excel_with_header_row, sample_config):
|
||||
"""Тест что set_value обновляет DataFrame"""
|
||||
parser = ExcelFileParcer(excel_with_header_row, sample_config)
|
||||
|
||||
# Находим строку с ART002
|
||||
row_idx = parser._get_attr_row("ART002", "MAN002")
|
||||
price_col_idx = parser._get_attr_column("Цена")
|
||||
|
||||
original_price = parser.df.iloc[row_idx, price_col_idx]
|
||||
|
||||
# Устанавливаем новое значение
|
||||
parser.set_value("ART002", "MAN002", "Цена", 555.0)
|
||||
|
||||
# Проверяем обновление
|
||||
updated_price = parser.df.iloc[row_idx, price_col_idx]
|
||||
assert updated_price == 555.0
|
||||
assert updated_price != original_price
|
||||
|
||||
def test_multiple_set_value_operations(self, excel_with_header_row, sample_config):
|
||||
"""Тест множественных операций set_value"""
|
||||
parser = ExcelFileParcer(excel_with_header_row, sample_config)
|
||||
|
||||
# Устанавливаем несколько значений
|
||||
parser.set_value("ART001", "MAN001", "Цена", 111.0)
|
||||
parser.set_value("ART002", "MAN002", "Цена", 222.0)
|
||||
parser.set_value("ART003", "MAN003", "Цена", 333.0)
|
||||
|
||||
# Проверяем все значения
|
||||
price_col_idx = parser._get_attr_column("Цена")
|
||||
row1_idx = parser._get_attr_row("ART001", "MAN001")
|
||||
row2_idx = parser._get_attr_row("ART002", "MAN002")
|
||||
row3_idx = parser._get_attr_row("ART003", "MAN003")
|
||||
|
||||
assert parser.df.iloc[row1_idx, price_col_idx] == 111.0
|
||||
assert parser.df.iloc[row2_idx, price_col_idx] == 222.0
|
||||
assert parser.df.iloc[row3_idx, price_col_idx] == 333.0
|
||||
|
||||
def test_get_order_rows_trimmed_correctly(self, sample_config):
|
||||
"""Тест что get_order_rows правильно обрезает пустые строки"""
|
||||
# Создаем файл с пустой строкой в середине
|
||||
df = pd.DataFrame([
|
||||
['Артикул', 'Производитель', 'Наименование'],
|
||||
['ART001', 'MAN001', 'Товар 1'],
|
||||
['ART002', 'MAN002', 'Товар 2'],
|
||||
[None, None, None], # Пустая строка
|
||||
['ART003', 'MAN003', 'Товар 3'],
|
||||
[None, None, None] # Еще одна пустая строка
|
||||
])
|
||||
buf = BytesIO()
|
||||
with pd.ExcelWriter(buf, engine='xlsxwriter') as writer:
|
||||
df.to_excel(writer, sheet_name='Sheet1', index=False, header=False)
|
||||
buf.seek(0)
|
||||
excel_bytes = buf.getvalue()
|
||||
|
||||
parser = ExcelFileParcer(excel_bytes, sample_config)
|
||||
order_rows = parser.get_order_rows()
|
||||
|
||||
# Должны остаться только строки до первой пустой
|
||||
assert len(order_rows) == 2 # ART001 и ART002
|
||||
|
||||
@patch('mail_order_bot.parsers.excel_parcer.pd.read_excel')
|
||||
def test_get_order_rows_with_calamine_engine(self, mock_read_excel, sample_config):
|
||||
"""Тест что get_order_rows использует calamine engine"""
|
||||
# Создаем мок DataFrame
|
||||
mock_df = pd.DataFrame({
|
||||
'Артикул': ['ART001', 'ART002', None],
|
||||
'Производитель': ['MAN001', 'MAN002', None]
|
||||
})
|
||||
mock_read_excel.return_value = mock_df
|
||||
|
||||
# Создаем парсер с моком для первого чтения
|
||||
df_init = pd.DataFrame([
|
||||
['Артикул', 'Производитель'],
|
||||
['ART001', 'MAN001'],
|
||||
['ART002', 'MAN002'],
|
||||
[None, None]
|
||||
])
|
||||
with patch('mail_order_bot.parsers.excel_parcer.pd.read_excel') as mock_init:
|
||||
mock_init.return_value = df_init
|
||||
parser = ExcelFileParcer(b"test", sample_config)
|
||||
|
||||
# Тестируем get_order_rows
|
||||
with patch('mail_order_bot.parsers.excel_parcer.pd.read_excel') as mock_get:
|
||||
mock_get.return_value = mock_df
|
||||
result = parser.get_order_rows()
|
||||
|
||||
# Проверяем, что был вызван read_excel с engine='calamine'
|
||||
mock_get.assert_called_once()
|
||||
call_kwargs = mock_get.call_args[1]
|
||||
assert call_kwargs.get('engine') == 'calamine'
|
||||
|
||||
Reference in New Issue
Block a user