Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
lib-py-b2b / order_change / expedite.py
Size: Mime:
import abc

from botocore.exceptions import ClientError

from lib_b2b.order_status import OrderStatus
from lib_b2b.policy import Policy
from lib_b2b.errors import OrderStatusChangeError, VersionConflictError
from lib_b2b.change import ChangeRecord, ChangeDataProvider
from lib_b2b.order_change import OrderChangeRequest, SimpleOrderPredicate, OrderStatusChangeDataProvider
from lib_b2b.order import Order
from datetime import datetime
import logging

logger = logging.getLogger(__name__)


class OrderExpediteChangeDataProvider(ChangeDataProvider, metaclass=abc.ABCMeta):
    @property
    @abc.abstractmethod
    def expedite(self) -> bool:
        raise NotImplementedError


class OrderExpediteChangeRequest(OrderChangeRequest):
    """
    *** This should be an admin only change request and not part of the integration ***
    """
    # TODO: - Move these policies to be data driven
    _policy = Policy(
        name='expedite_change_policy',
        subject=Policy.SUBJECT_ALL,
        predicates=[
            SimpleOrderPredicate(
                lambda o: o.status < OrderStatus.SHIPPED,
                'The order can only be expedited until the order has shipped.')
        ]
    )

    def __init__(self, on_behalf_of: str, change_data_provider: OrderExpediteChangeDataProvider):
        super().__init__(on_behalf_of, OrderExpediteChangeRequest._policy)
        self.change_data_provider = change_data_provider

    def will_change(self, order: Order) -> bool:
        return order.expedite != self.change_data_provider.expedite

    def apply(self, order: Order):
        try:
            self.changeable_object = order
            if super().permitted(order):
                if self.will_change(order):
                    _before = order.expedite
                    order.expedite = self.change_data_provider.expedite
                    order.record(
                        ChangeRecord(before=_before,
                                     after=self.change_data_provider.expedite,
                                     description=f"Expedite was set to {self.change_data_provider.expedite}.",
                                     when=datetime.now().astimezone(UTC),
                                     who=self.on_behalf_of)
                    )
                    from lib_b2b.notification import Notifier, NotificationType, NotificationData
                    if self.change_data_provider.expedite:
                        Notifier.notify(
                            notification_type=NotificationType.OPERATIONS,
                            customer=order.customer_edi_id,
                            subject=f"Expedited handling requested for {order.order_id}",
                            data=NotificationData(order_id=order.order_id,
                                                  message=f"Expedited handling requested for "
                                                          f"{order.order_id} by {self.on_behalf_of}.")
                        )
                    else:
                        Notifier.notify(
                            notification_type=NotificationType.OPERATIONS,
                            customer=order.customer_edi_id,
                            subject=f"Expedited handling request cancelled for {order.order_id}",
                            data=NotificationData(order_id=order.order_id,
                                                  message=f"Expedited handling request cancelled for "
                                                          f"{order.order_id} by {self.on_behalf_of}.")
                        )
        except ValueError as ve:
            raise VersionConflictError(str(ve))
        except ClientError as ce:
            # order.error(ErrorRecord(code="ORDER-11",
            #                         msg=f"Order accept failed due to client error. [{str(ce)}]"))
            logger.error(f"Unable to expedite order due to client error. [{str(ce)}]")
            raise OrderStatusChangeError("Unable to expedite order") from ce