no message
This commit is contained in:
@@ -12,11 +12,7 @@ class APIGetStock(AbstractTask):
|
|||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
credential_provider = CredentialProvider(context=self.context)
|
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()
|
client_login, client_password = credential_provider.get_client_credentials()
|
||||||
self.client_provider = AbcpProvider(login=client_login, password=client_password)
|
self.client_provider = AbcpProvider(login=client_login, password=client_password)
|
||||||
@@ -28,11 +24,10 @@ class APIGetStock(AbstractTask):
|
|||||||
for position in order.positions:
|
for position in order.positions:
|
||||||
# Получаем остатки из-под учетной записи клиента
|
# Получаем остатки из-под учетной записи клиента
|
||||||
client_stock = self.client_provider.get_stock(position.sku, position.manufacturer)
|
client_stock = self.client_provider.get_stock(position.sku, position.manufacturer)
|
||||||
system_stock = self.system_provider.get_stock(position.sku, position.manufacturer)
|
|
||||||
|
|
||||||
# Используем StockSelector для фильтрации неподходящих поставщиков
|
# Используем StockSelector для фильтрации неподходящих поставщиков
|
||||||
selector = StockSelector(position, order.delivery_period)
|
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_stock(available_distributors)
|
||||||
position.set_order_item()
|
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.order_position import OrderPosition
|
||||||
from mail_order_bot.email_processor.handlers.abstract_task import AbstractTask
|
from mail_order_bot.email_processor.handlers.abstract_task import AbstractTask
|
||||||
|
|
||||||
from ...order.auto_part_position import AutoPartPosition
|
from mail_order_bot.email_processor.order.auto_part_position import AutoPartPosition
|
||||||
from ...order.auto_part_order import AutoPartOrder
|
from mail_order_bot.email_processor.order.auto_part_order import AutoPartOrder
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -27,24 +27,27 @@ class BasicExcelParser(AbstractTask):
|
|||||||
attachments = self.context.data.get("attachments", [])
|
attachments = self.context.data.get("attachments", [])
|
||||||
for attachment in attachments:
|
for attachment in attachments:
|
||||||
file_bytes = BytesIO(attachment['bytes']) # self.context.get("attachment") #
|
file_bytes = BytesIO(attachment['bytes']) # self.context.get("attachment") #
|
||||||
try:
|
delivery_period = attachment.get("delivery_period", 0)
|
||||||
df = self._make_dataframe(file_bytes)
|
#try:
|
||||||
mapping = self.config['mapping']
|
df = self._make_dataframe(file_bytes)
|
||||||
order = AutoPartOrder()
|
mapping = self.config['mapping']
|
||||||
|
order = AutoPartOrder()
|
||||||
|
attachment["order"] = order
|
||||||
|
|
||||||
# Парсим строки
|
# Парсим строки
|
||||||
positions = []
|
positions = []
|
||||||
for idx, row in df.iterrows():
|
for idx, row in df.iterrows():
|
||||||
position = self._parse_row(row, mapping)
|
position = self._parse_row(row, mapping)
|
||||||
if position:
|
if position:
|
||||||
order.add_position(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:
|
#except Exception as e:
|
||||||
logger.error(f"Ошибка при обработке файла: {e}")
|
# logger.error(f"Ошибка при обработке файла: {e}")
|
||||||
else:
|
#else:
|
||||||
attachment["order"] = order
|
attachment["order"] = order
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -67,7 +70,7 @@ class BasicExcelParser(AbstractTask):
|
|||||||
else:
|
else:
|
||||||
total = price * quantity
|
total = price * quantity
|
||||||
|
|
||||||
if mapping.get('name', "") in mapping.keys():
|
if "name" in mapping:
|
||||||
name = str(row[mapping.get('name', "")]).strip()
|
name = str(row[mapping.get('name', "")]).strip()
|
||||||
else:
|
else:
|
||||||
name = ""
|
name = ""
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
from .auto_part_position import AutoPartPosition, PositionStatus
|
from .auto_part_position import AutoPartPosition, PositionStatus
|
||||||
|
|
||||||
|
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
class OrderStatus(Enum):
|
class OrderStatus(Enum):
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ class AutoPartPosition:
|
|||||||
order_quantity: int = 0 # Количество для заказа
|
order_quantity: int = 0 # Количество для заказа
|
||||||
order_price: Decimal = Decimal('0.0') # Цена в заказе
|
order_price: Decimal = Decimal('0.0') # Цена в заказе
|
||||||
order_item: Dict[str, Any] = field(default_factory=dict)
|
order_item: Dict[str, Any] = field(default_factory=dict)
|
||||||
|
order_delivery_period = 0
|
||||||
|
|
||||||
stock: List[Dict[str, Any]] = None
|
stock: List[Dict[str, Any]] = None
|
||||||
additional_attrs: Dict[str, Any] = field(default_factory=dict)
|
additional_attrs: Dict[str, Any] = field(default_factory=dict)
|
||||||
@@ -71,7 +72,7 @@ class AutoPartPosition:
|
|||||||
available_distributors = self._filter_proper_price(available_distributors)
|
available_distributors = self._filter_proper_price(available_distributors)
|
||||||
|
|
||||||
# BR-3. Срок доставки не должен превышать ожидаемый
|
# 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. Без отрицательных остатков
|
# BR-4. Без отрицательных остатков
|
||||||
available_distributors = self._filter_proper_availability(available_distributors)
|
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]
|
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]]:
|
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)
|
email_from = EmailUtils.extract_first_sender(email_body)
|
||||||
self.context.data["email_from"] = email_from
|
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
|
self.context.data["email_subj"] = email_subj
|
||||||
|
|
||||||
client = EmailUtils.extract_domain(email_from)
|
client = EmailUtils.extract_domain(email_from)
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ async def main():
|
|||||||
#await app.stop()
|
#await app.stop()
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
print(os.getcwd())
|
||||||
if os.environ.get("APP_ENV") != "PRODUCTION":
|
if os.environ.get("APP_ENV") != "PRODUCTION":
|
||||||
logger.warning("Non production environment")
|
logger.warning("Non production environment")
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|||||||
Reference in New Issue
Block a user