no message
This commit is contained in:
@@ -13,10 +13,6 @@ class APIGetStock(AbstractTask):
|
||||
super().__init__(*args, **kwargs)
|
||||
credential_provider = CredentialProvider(context=self.context)
|
||||
|
||||
# Создаем провайдер для системной учетной записи
|
||||
system_login, system_password = credential_provider.get_system_credentials()
|
||||
self.system_provider = AbcpProvider(login=system_login, password=system_password)
|
||||
|
||||
# Создаем провайдер для учетной записи клиента
|
||||
client_login, client_password = credential_provider.get_client_credentials()
|
||||
self.client_provider = AbcpProvider(login=client_login, password=client_password)
|
||||
@@ -28,11 +24,10 @@ class APIGetStock(AbstractTask):
|
||||
for position in order.positions:
|
||||
# Получаем остатки из-под учетной записи клиента
|
||||
client_stock = self.client_provider.get_stock(position.sku, position.manufacturer)
|
||||
system_stock = self.system_provider.get_stock(position.sku, position.manufacturer)
|
||||
|
||||
# Используем StockSelector для фильтрации неподходящих поставщиков
|
||||
selector = StockSelector(position, order.delivery_period)
|
||||
available_distributors = selector.filter_stock(client_stock, system_stock)
|
||||
available_distributors = selector.filter_stock(client_stock)
|
||||
|
||||
position.set_stock(available_distributors)
|
||||
position.set_order_item()
|
||||
|
||||
@@ -6,8 +6,8 @@ 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 ...order.auto_part_position import AutoPartPosition
|
||||
from ...order.auto_part_order import AutoPartOrder
|
||||
from mail_order_bot.email_processor.order.auto_part_position import AutoPartPosition
|
||||
from mail_order_bot.email_processor.order.auto_part_order import AutoPartOrder
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -27,24 +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:
|
||||
df = self._make_dataframe(file_bytes)
|
||||
mapping = self.config['mapping']
|
||||
order = AutoPartOrder()
|
||||
delivery_period = attachment.get("delivery_period", 0)
|
||||
#try:
|
||||
df = self._make_dataframe(file_bytes)
|
||||
mapping = self.config['mapping']
|
||||
order = AutoPartOrder()
|
||||
attachment["order"] = order
|
||||
|
||||
# Парсим строки
|
||||
positions = []
|
||||
for idx, row in df.iterrows():
|
||||
position = self._parse_row(row, mapping)
|
||||
if position:
|
||||
order.add_position(position)
|
||||
# Парсим строки
|
||||
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)} строк")
|
||||
logger.info(f"Успешно обработано {len(order)} позиций из {len(df)} строк")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при обработке файла: {e}")
|
||||
else:
|
||||
attachment["order"] = order
|
||||
#except Exception as e:
|
||||
# logger.error(f"Ошибка при обработке файла: {e}")
|
||||
#else:
|
||||
attachment["order"] = order
|
||||
|
||||
|
||||
|
||||
@@ -67,7 +70,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 = ""
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from typing import List, Optional
|
||||
from .auto_part_position import AutoPartPosition, PositionStatus
|
||||
|
||||
|
||||
from enum import Enum
|
||||
|
||||
class OrderStatus(Enum):
|
||||
|
||||
@@ -34,6 +34,7 @@ class AutoPartPosition:
|
||||
order_quantity: int = 0 # Количество для заказа
|
||||
order_price: Decimal = Decimal('0.0') # Цена в заказе
|
||||
order_item: Dict[str, Any] = field(default_factory=dict)
|
||||
order_delivery_period = 0
|
||||
|
||||
stock: List[Dict[str, Any]] = None
|
||||
additional_attrs: Dict[str, Any] = field(default_factory=dict)
|
||||
@@ -71,7 +72,7 @@ class AutoPartPosition:
|
||||
available_distributors = self._filter_proper_price(available_distributors)
|
||||
|
||||
# BR-3. Срок доставки не должен превышать ожидаемый
|
||||
available_distributors = self._filter_proper_delivery_time(available_distributors, self.delivery_period)
|
||||
available_distributors = self._filter_proper_delivery_time(available_distributors)
|
||||
|
||||
# BR-4. Без отрицательных остатков
|
||||
available_distributors = self._filter_proper_availability(available_distributors)
|
||||
@@ -100,9 +101,9 @@ class AutoPartPosition:
|
||||
"""Фильтрует только локальные склады"""
|
||||
return [item for item in distributors if str(item["distributorId"]) == self.DISTRIBUTOR_ID]
|
||||
|
||||
def _filter_proper_delivery_time(self, distributors: List[Dict[str, Any]], delivery_period: int) -> List[Dict[str, Any]]:
|
||||
def _filter_proper_delivery_time(self, distributors: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""Фильтрует склады по сроку доставки"""
|
||||
return [item for item in distributors if item["deliveryPeriod"] <= delivery_period]
|
||||
return [item for item in distributors if item["deliveryPeriod"] <= self.order_delivery_period]
|
||||
|
||||
def _filter_proper_price(self, distributors: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""Фильтрует склады по цене (убирает дорогие)"""
|
||||
|
||||
@@ -45,7 +45,7 @@ class EmailProcessor:
|
||||
email_from = EmailUtils.extract_first_sender(email_body)
|
||||
self.context.data["email_from"] = email_from
|
||||
|
||||
email_subj = EmailUtils.extract_header(email_body, "Subject")
|
||||
email_subj = EmailUtils.extract_header(email, "subj")
|
||||
self.context.data["email_subj"] = email_subj
|
||||
|
||||
client = EmailUtils.extract_domain(email_from)
|
||||
|
||||
@@ -64,6 +64,7 @@ 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()
|
||||
|
||||
Reference in New Issue
Block a user