Exemplo n.º 1
0
 def __init__(self):
     self.__requests_elastic = Elastic(
         settings.AWS_ELASTICSEARCH_PURCHASE_RETURN_REQUESTS,
         settings.AWS_ELASTICSEARCH_PURCHASE_RETURN_REQUESTS)
     self.__customer_requests_map_elastic = Elastic(
         settings.AWS_ELASTICSEARCH_PURCHASE_RETURN_REQUESTS_CUSTOMER_MAP,
         settings.AWS_ELASTICSEARCH_PURCHASE_RETURN_REQUESTS_CUSTOMER_MAP)
     self.__reflector = Reflector()
Exemplo n.º 2
0
 def __init__(self):
     self.__requests_elastic = Elastic(
         settings.AWS_ELASTICSEARCH_PURCHASE_CANCEL_REQUESTS,
         settings.AWS_ELASTICSEARCH_PURCHASE_CANCEL_REQUESTS)
     self.__order_requests_map_elastic = Elastic(
         settings.AWS_ELASTICSEARCH_PURCHASE_CANCEL_REQUESTS_ORDERS_MAP,
         settings.AWS_ELASTICSEARCH_PURCHASE_CANCEL_REQUESTS_ORDERS_MAP)
     self.__reflector = Reflector()
Exemplo n.º 3
0
 def __init__(self):
     self.__orders_elastic = Elastic(
         settings.AWS_ELASTICSEARCH_PURCHASE_ORDERS,
         settings.AWS_ELASTICSEARCH_PURCHASE_ORDERS)
     self.__customer_orders_map_elastic = Elastic(
         settings.AWS_ELASTICSEARCH_PURCHASE_ORDERS_CUSTOMER_ORDERS_MAP,
         settings.AWS_ELASTICSEARCH_PURCHASE_ORDERS_CUSTOMER_ORDERS_MAP)
     self.__reflector = Reflector()
     self.__current_vat_value = PurchaseSettings().vat
Exemplo n.º 4
0
    def customer_credit_info():
        try:
            user = __get_user()
            """"""
            # @TODO : REFACTORING !!!
            from chalicelib.libs.purchase.customer.sqs import FbucksChargeSqsHandler
            see = FbucksChargeSqsHandler
            """"""

            # fbucks amount
            __fbucks_customer_amount_elastic = Elastic(
                settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
                settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
            )
            fbucks_amount_row = __fbucks_customer_amount_elastic.get_data(
                user.id)
            fbucks_amount = fbucks_amount_row[
                'amount'] or 0 if fbucks_amount_row else 0

            # fbucks history
            __fbucks_customer_amount_changes_elastic = Elastic(
                settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT_CHANGES,
                settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT_CHANGES,
            )
            fbucks_changes = __fbucks_customer_amount_changes_elastic.post_search(
                {
                    "query": {
                        "term": {
                            "customer_id": user.id
                        }
                    }
                }).get('hits', {}).get('hits', []) or []
            fbucks_changes = [
                fbucks_change['_source'] for fbucks_change in fbucks_changes
            ]

            fbucks_changes = [{
                'amount': fbucks_change['amount'],
                'changed_at': fbucks_change['changed_at'],
                'order_number': fbucks_change['order_number'],
            } for fbucks_change in fbucks_changes]

            # cash out balance
            credit = CreditStorageImplementation().load(user.email)
            cash_out_balance = credit.paid if credit else 0

            return {
                'fbucks_amount': fbucks_amount,
                'fbucks_changes': fbucks_changes,
                'cache_out_balance': cash_out_balance,
            }

        except BaseException as e:
            return http_response_exception_or_throw(e)
Exemplo n.º 5
0
 def __init__(self) -> None:
     """
         curl -X DELETE http://localhost:9200/personalization_orders
         curl -X PUT http://localhost:9200/personalization_orders -H "Content-Type: application/json" -d'{
             "mappings": {
                 "personalization_orders": {
                     "properties": {
                         "order_number": {"type": "keyword"},
                         "email": {"type": "keyword"},
                         "ordered_at": {"type": "date", "format": "yyyy-MM-dd HH:mm:ss"},
                         "rs_sku": {"type": "keyword"},
                         "rs_simple_sku": {"type": "keyword"},
                         "product_name": {"type": "keyword"},
                         "manufacturer": {"type": "keyword"},
                         "gender": {"type": "keyword"},
                         "product_size_attribute": {"type": "keyword"},
                         "rs_colour": {"type": "keyword"},
                         "size": {"type": "keyword"}
                     }
                 }
              }
         }'
     """
     self.__elastic = Elastic(
         settings.AWS_ELASTICSEARCH_PERSONALIZATION_ORDERS,
         settings.AWS_ELASTICSEARCH_PERSONALIZATION_ORDERS)
Exemplo n.º 6
0
    def __init__(self, customer: CustomerInterface,
                 checkout_items: Tuple['Checkout.Item'], delivery_cost: Cost,
                 vat_percent: Percentage):
        if not isinstance(customer, CustomerInterface):
            raise ArgumentTypeException(self.__init__, 'customer', customer)

        if sum([
                not isinstance(checkout_item, Checkout.Item)
                for checkout_item in checkout_items
        ]) > 0:
            raise TypeError(
                '{0} expects array of {1} in {2}, but {3} is given!'.format(
                    self.__init__.__qualname__, Checkout.Item.__qualname__,
                    'checkout_items', str(checkout_items)))

        if not isinstance(delivery_cost, Cost):
            raise ArgumentTypeException(self.__init__, 'delivery_cost',
                                        delivery_cost)

        if not isinstance(vat_percent, Percentage):
            raise ArgumentTypeException(self.__init__, 'vat_percent',
                                        vat_percent)

        self.__customer = customer
        self.__checkout_items = [
            checkout_item for checkout_item in checkout_items
        ]
        self.__delivery_address = None
        self.__delivery_cost = delivery_cost
        self.__vat_percent = vat_percent

        # Available credits amount must be set on checkout initialization, because
        # amount can be changed by other process during current checkout (other browser, cash-out, etc.).
        # Currently this is unavailable, because we always have only one checkout process for user (used user.id)
        # and we don't use other credits, expect f-bucks, which can be only increased in other process,
        # but we can't trust this, because we should not know about these things on this layer.
        # We should reserve credit amounts at the start of checkout process.
        # This will protect us from multiple usage of the same credit amounts.
        # Another way is to load fresh credits amount every time, but in this case
        # user can see different amounts before and after payment operation. And looks like other strange things
        # can happen in this case. So the best way is reservation.
        # @todo : implement reservation of credit amounts ???

        # @todo : raw data usage. should be used customer.credits or so ???
        from chalicelib.settings import settings
        from chalicelib.libs.core.elastic import Elastic
        available_credits_amount = Cost((Elastic(
            settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
            settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT).get_data(
                customer.customer_id.value) or {
                    'amount': 0
                }).get('amount') or 0)

        self.__available_credits_amount = available_credits_amount
        self.__is_credits_in_use = False
Exemplo n.º 7
0
 def __init__(self):
     """
     curl -X DELETE localhost:9200/purchase_customer_credit_cards
     curl -X PUT localhost:9200/purchase_customer_credit_cards -H "Content-Type: application/json" -d'{
         "mappings": {
             "purchase_customer_credit_cards": {
                 "properties": {
                     "token": {"type": "keyword"},
                     "customer_id": {"type": "keyword"},
                     "brand": {"type": "keyword"},
                     "number_hidden": {"type": "keyword"},
                     "expires": {"type": "keyword"}, //2005 -> 2020/05
                     "holder_name": {"type": "keyword"},
                     "is_verified": {"type": "boolean"},
                     "created_at": {"type": "date", "format": "yyyy-MM-dd HH:mm:ss"}
                 }
             }
         }
     }'
     curl -X DELETE localhost:9200/purchase_customer_credit_cards_customer_map
     curl -X PUT localhost:9200/purchase_customer_credit_cards_customer_map -H "Content-Type: application/json" -d'{
         "mappings": {
             "purchase_customer_credit_cards_customer_map": {
                 "properties": {
                     "tokens_json": {"type": "keyword"}
                 }
             }
         }
     }'
     """
     self.__elastic_cards = Elastic(
         settings.AWS_ELASTICSEARCH_PURCHASE_CUSTOMER_CREDIT_CARDS,
         settings.AWS_ELASTICSEARCH_PURCHASE_CUSTOMER_CREDIT_CARDS)
     self.__elastic_customer_cards_map = Elastic(
         settings.
         AWS_ELASTICSEARCH_PURCHASE_CUSTOMER_CREDIT_CARDS_CUSTOMER_MAP,
         settings.
         AWS_ELASTICSEARCH_PURCHASE_CUSTOMER_CREDIT_CARDS_CUSTOMER_MAP)
     self.__reflector = Reflector()
Exemplo n.º 8
0
 def __init__(self):
     self.__tiers_storage = CustomerTierStorageImplementation()
     self.__messages = MessageStorageImplementation()
     self.__logger = Logger()
     """"""
     # @todo : refactoring
     from chalicelib.libs.purchase.core import CustomerInterface
     from chalicelib.libs.purchase.customer.storage import CustomerStorageImplementation
     see = CustomerInterface.tier
     see = CustomerStorageImplementation.save
     """"""
     self.__elastic = Elastic(
         settings.AWS_ELASTICSEARCH_CUSTOMER_TIERS_CUSTOMER_TIERS,
         settings.AWS_ELASTICSEARCH_CUSTOMER_TIERS_CUSTOMER_TIERS)
Exemplo n.º 9
0
 def __init__(self):
     """
     curl -X DELETE localhost:9200/customer_tiers_tiers
     curl -X PUT localhost:9200/customer_tiers_tiers -H "Content-Type: application/json" -d'{
         "mappings": {
             "customer_tiers_tiers": {
                 "properties": {
                     "id": {"type": "integer"},
                     "name": {"type": "keyword"},
                     "credit_back_percent": {"type": "integer"},
                     "spent_amount_min": {"type": "integer"},
                     "spent_amount_max": {"type": "integer"},
                     "is_deleted": {"type": "boolean"}
                 }
             }
         }
     }'
     """
     self.__elastic = Elastic(
         settings.AWS_ELASTICSEARCH_CUSTOMER_TIERS_TIERS,
         settings.AWS_ELASTICSEARCH_CUSTOMER_TIERS_TIERS
     )
     self.__reflector = Reflector()
Exemplo n.º 10
0
    def customer_credits_checkout():
        checkout_storage = CheckoutStorageImplementation()
        order_storage = OrderStorageImplementation()
        order_app_service = OrderAppService()
        cart_service = CartAppService()
        checkout_service = CheckoutAppService()
        sqs_sender = SqsSenderImplementation()
        logger = Logger()

        try:
            user = __get_user()

            # @todo : refactoring
            checkout = checkout_storage.load(Id(user.id))
            if not checkout:
                raise ApplicationLogicException('Checkout does not exist!')
            elif checkout.total_due.value != 0:
                raise ApplicationLogicException('Unable to checkout not 0 amount with Customer Credits!')

            order = order_app_service.get_waiting_for_payment_by_checkout_or_checkout_new(user.id)

            def __log_flow(text: str) -> None:
                logger.log_simple('Customer Credits Payment Log for Order #{} : {}'.format(
                    order.number.value,
                    text
                ))

            __log_flow('Start')

            try:
                __log_flow('Credits Spending...')
                # Attention!
                # Currently we use f-bucks only! Other credits are not available for now!
                # @todo : other credit types
                # @todo : copy-paste code
                # @todo : when reservation of credits amount will be done, perhaps, use sqs to spend credits
                """"""
                from chalicelib.libs.purchase.core import Checkout
                see = Checkout.__init__
                """"""
                # @TODO : refactoring : raw data usage
                import uuid
                import datetime
                from chalicelib.settings import settings
                from chalicelib.libs.core.elastic import Elastic
                fbucks_customer_amount_elastic = Elastic(
                    settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
                    settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
                )
                fbucks_customer_amount_changes_elastic = Elastic(
                    settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT_CHANGES,
                    settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT_CHANGES,
                )
                fbucks_customer_amount_elastic.update_data(order.customer_id.value, {
                    'script': 'ctx._source.amount -= ' + str(order.credit_spent_amount.value)
                })
                fbucks_customer_amount_changes_elastic.create(str(uuid.uuid4()) + str(order.customer_id.value), {
                    "customer_id": order.customer_id.value,
                    "amount": -order.credit_spent_amount.value,
                    "changed_at": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "order_number": order.number.value,
                })
                __log_flow('Credits Spent!')

                __log_flow('Order Updating...')
                order.payment_method = CustomerCreditsOrderPaymentMethod()
                order.status = Order.Status(Order.Status.PAYMENT_SENT)
                order.status = Order.Status(Order.Status.PAYMENT_RECEIVED)
                order_storage.save(order)
                __log_flow('Order Updated!')
            except BaseException as e:
                __log_flow('Not done because of Error : {}'.format(str(e)))
                raise e

            # send order update to sqs
            try:
                __log_flow('Order Change SQS Sending...')
                sqs_sender.send(OrderChangeSqsSenderEvent(order))
                __log_flow('Order Change SQS Sent!')
            except BaseException as e:
                __log_flow('Order Change SQS NOT Sent because of Error: {}!'.format(str(e)))
                logger.log_exception(e)

            # flush cart
            try:
                __log_flow('Cart Flushing...')
                cart_service.clear_cart(user.session_id)
                __log_flow('Cart Flushed!')
            except BaseException as e:
                __log_flow('Cart NOT Flushed because of Error: {}'.format(str(e)))
                logger.log_exception(e)

            # flush checkout
            try:
                __log_flow('Checkout Flushing...')
                checkout_service.remove(user.id)
                __log_flow('Checkout Flushed!')
            except BaseException as e:
                __log_flow('Checkout NOT Flushed because of Error: {}'.format(str(e)))
                logger.log_exception(e)

            result = {
                'order_number': order.number.value
            }

            __log_flow('End')

            return result
        except BaseException as e:
            logger.log_exception(e)
            return http_response_exception_or_throw(e)
Exemplo n.º 11
0
 def __init__(self):
     self.__elastic = Elastic(settings.AWS_ELASTICSEARCH_SCORED_PRODUCTS,
                              settings.AWS_ELASTICSEARCH_SCORED_PRODUCTS)
Exemplo n.º 12
0
    def regular_eft_checkout():
        checkout_storage = CheckoutStorageImplementation()
        order_storage = OrderStorageImplementation()
        order_app_service = OrderAppService()
        logger = Logger()
        mailer = MailerImplementation()

        # 1. Get or create order. Critical!
        # ------------------------------------------------------

        try:
            user = __get_user()

            # @todo : refactoring
            checkout = checkout_storage.load(Id(user.id))
            if not checkout:
                raise ApplicationLogicException('Checkout does not exist!')
            elif checkout.total_due.value == 0:
                raise ApplicationLogicException('Unable to checkout 0 amount with Regular Eft!')

            order = order_app_service.get_waiting_for_payment_by_checkout_or_checkout_new(user.id)

            def __log_order_flow(text: str) -> None:
                logger.log_simple('Regular EFT : Checkout : {} : {}'.format(order.number.value, text))

            __log_order_flow('Start')

            # Attention!
            # Currently we use f-bucks only! Other credits are not available for now!
            # @todo : other credit types
            # @todo : copy-paste code
            # @todo : when reservation of credits amount will be done, perhaps, use sqs to spend credits
            if order.credit_spent_amount.value > 0:
                __log_order_flow('Spending Credits...')
                """"""
                from chalicelib.libs.purchase.core import Checkout
                see = Checkout.__init__
                """"""
                # @TODO : refactoring : raw data usage
                import uuid
                import datetime
                from chalicelib.settings import settings
                from chalicelib.libs.core.elastic import Elastic
                fbucks_customer_amount_elastic = Elastic(
                    settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
                    settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
                )
                fbucks_customer_amount_changes_elastic = Elastic(
                    settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT_CHANGES,
                    settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT_CHANGES,
                )
                fbucks_customer_amount_elastic.update_data(order.customer_id.value, {
                    'script': 'ctx._source.amount -= ' + str(order.credit_spent_amount.value),
                })
                fbucks_customer_amount_changes_elastic.create(str(uuid.uuid4()) + str(order.customer_id.value), {
                    "customer_id": order.customer_id.value,
                    "amount": -order.credit_spent_amount.value,
                    "changed_at": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "order_number": order.number.value,
                })
                __log_order_flow('Spending Credits: Done!')

            __log_order_flow('Order Updating...')
            order.payment_method = RegularEftOrderPaymentMethod()
            order_storage.save(order)
            __log_order_flow('Order Updated!')
        except BaseException as e:
            logger.log_exception(e)
            return http_response_exception_or_throw(e)

        # 2. Send eft email. Not critical.
        # Theoretically can be redone or downloaded manually.
        # ------------------------------------------------------

        try:
            __log_order_flow('EFT Email Sending...')
            message = RegularEftBankDetailsMailMessage(order)
            mailer.send(message)
            __log_order_flow('EFT Email Sent!')
        except BaseException as e:
            logger.log_exception(e)
            __log_order_flow('EFT Email Not Sent because of Error: {}'.format(str(e)))

        # 3. Flush cart, checkout. Not critical.
        # ------------------------------------------------------

        # flush cart
        try:
            __log_order_flow('Cart Flushing...')
            from chalicelib.libs.purchase.cart.service import CartAppService
            cart_service = CartAppService()
            cart_service.clear_cart(user.session_id)
            __log_order_flow('Cart Flushed!')
        except BaseException as e:
            logger.log_exception(e)
            __log_order_flow('Cart Not Flushed because of Error: {}'.format(str(e)))

        # flush checkout
        try:
            __log_order_flow('Checkout Flushing...')
            from chalicelib.libs.purchase.checkout.service import CheckoutAppService
            checkout_service = CheckoutAppService()
            checkout_service.remove(user.id)
            __log_order_flow('Checkout Flushed!')
        except BaseException as e:
            logger.log_exception(e)
            __log_order_flow('Checkout Not Flushed because of Error: {}'.format(str(e)))

        return {
            'order_number': order.number.value
        }
Exemplo n.º 13
0
        def __return(cart_items: Tuple[Cart.Item], original_subtotal: float,
                     current_subtotal: float,
                     current_subtotal_vat_amount: float):
            tier = blueprint.current_request.current_user.profile.tier

            # fbucks available to spend
            available_fbucks_amount = None
            if not tier[
                    'is_neutral'] and not blueprint.current_request.current_user.is_anyonimous:
                """"""
                # @TODO : REFACTORING !!!
                from chalicelib.libs.purchase.customer.sqs import FbucksChargeSqsHandler
                see = FbucksChargeSqsHandler
                """"""
                from chalicelib.settings import settings
                from chalicelib.libs.core.elastic import Elastic
                __fbucks_customer_amount_elastic = Elastic(
                    settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
                    settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
                )
                fbucks_amount_row = __fbucks_customer_amount_elastic.get_data(
                    blueprint.current_request.current_user.id)
                available_fbucks_amount = fbucks_amount_row[
                    'amount'] or 0 if fbucks_amount_row else 0

            products = MpcProduct()
            items_data = []
            for cart_item in cart_items:
                product = products.getRawDataBySimpleSku(
                    cart_item.simple_sku.value)
                product_sizes = product.get('sizes', []) if product else ()
                size = tuple(
                    filter(
                        lambda s: s.get('simple_sku') == cart_item.simple_sku.
                        value, product_sizes))[0]
                dtd = dtd_calculator.calculate(cart_item.simple_sku,
                                               cart_item.qty)

                item_fbucks = None
                if not tier[
                        'is_neutral'] and not blueprint.current_request.current_user.is_anyonimous:
                    item_fbucks = math.ceil(cart_item.current_cost.value *
                                            tier['discount_rate'] / 100)

                items_data.append({
                    'sku':
                    product['sku'],
                    'simple_sku':
                    cart_item.simple_sku.value,
                    'name':
                    product.get('title'),
                    'brand_name':
                    product.get('brand'),
                    'size_name':
                    size.get('size'),
                    'image_url':
                    product.get('image', {}).get('src', None),
                    'qty_available':
                    int(size.get('qty')),
                    'qty_added':
                    cart_item.qty.value,
                    'is_added_over_limit':
                    cart_item.is_added_over_limit,
                    'product_original_price':
                    cart_item.product_original_price.value,
                    'product_current_price':
                    cart_item.product_current_price.value,
                    'original_cost':
                    cart_item.original_cost.value,
                    'current_cost':
                    cart_item.current_cost.value,
                    'dtd': {
                        'occasion': {
                            'name': dtd.occasion.name.value,
                            'description': dtd.occasion.description.value,
                        } if dtd.occasion else None,
                        'date_from': dtd.date_from.strftime('%Y-%m-%d'),
                        'date_to': dtd.date_to.strftime('%Y-%m-%d'),
                        'working_days_from': dtd.working_days_from,
                        'working_days_to': dtd.working_days_to,
                    },
                    'fbucks':
                    item_fbucks,
                })

            return {
                'items': items_data,
                'original_subtotal': original_subtotal,
                'current_subtotal': current_subtotal,
                'current_subtotal_vat_amount': current_subtotal_vat_amount,
                'available_fbucks_amount': available_fbucks_amount,
            }
Exemplo n.º 14
0
    def handle(self, sqs_message: SqsMessage) -> None:
        """
        crutch
        customer_info_request_answer
        [
            'customer_email' => $customer->getEmail(),
            'name' => [
                'first' => $customer->getFirstName() ?: null,
                'last' => $customer->getLastName() ?: null,
            ],
            'gender' => 'F' / 'M',
            'addresses' => [
                [
                    'nickname' => $address->getAddressNickname() ?: null,
                    'phone' => $address->getTelephone() ?: $address->getContactNumber() ?: null,
                    'street' => $address->getStreet() ?: null,
                    'suburb' => $address->getSuburb() ?: null,
                    'post_code' => $address->getPostCode() ?: null,
                    'city' => $address->getCity() ?: null,
                    'province' => $address->getProvince() ?: null,
                    'country_code' => $address->getCountryCode() ?: null,
                    'is_default_billing' => $address->getId() == $customer->getDefaultBillingAddressId(),
                    'is_default_shipping' => $address->getId() == $customer->getDefaultShippingAddressId(),
                ],
                ...
            ],
            'tier' => [
                'id' => $customerTier->getId(),
                'name' => $customerTier->getName(),
                'credit_back_percent' => $customerTier->getCreditBackPercent(),
                'spent_amount_min' => $customerTier->getSpendAmountMin(),
                'spent_amount_max' => $customerTier->getSpendAmountMax(),
            ]
        ]
        """

        # @todo : perhaps, update other data - needs to be able to get customer by email

        # 'tier' here is the same tier as in 'customer_tiers_set' sqs-message.
        # Theoretically this message can be handled earlier than 'customer_tiers_set' message,
        # so we need to be sure, that all new tiers exist.
        tier_data = sqs_message.message_data['tier']
        tier = self.__tiers_storage.get_by_id(Id(str(tier_data['id'])))
        if not tier:
            tier = CustomerTier(
                Id(str(tier_data['id'])), Name(tier_data['name']),
                Percentage(int(tier_data['credit_back_percent'])),
                int(tier_data['spent_amount_min']),
                int(tier_data['spent_amount_max']))
            self.__tiers_storage.save(tier)

        # assign user to tier
        """"""
        # @todo : refactoring
        from chalicelib.libs.purchase.core import CustomerInterface
        from chalicelib.libs.purchase.customer.storage import CustomerStorageImplementation
        see = CustomerInterface.tier
        see = CustomerStorageImplementation.save
        """"""
        customer_email = sqs_message.message_data['customer_email']
        elastic = Elastic(
            settings.AWS_ELASTICSEARCH_CUSTOMER_TIERS_CUSTOMER_TIERS,
            settings.AWS_ELASTICSEARCH_CUSTOMER_TIERS_CUSTOMER_TIERS)
        if elastic.get_data(customer_email):
            elastic.update_data(customer_email,
                                {'doc': {
                                    'tier_id': tier.id.value
                                }})
        else:
            elastic.create(customer_email, {'tier_id': tier.id.value})
Exemplo n.º 15
0
    def __init__(self):
        self.__orders_storage = OrderStorageImplementation()
        self.__logger = Logger()

        # """
        # curl -X DELETE localhost:9200/fbucks_handled_orders
        # curl -X PUT localhost:9200/fbucks_handled_orders -H "Content-Type: application/json" -d'{
        #     "mappings": {
        #         "fbucks_handled_orders": {
        #             "properties": {
        #                 "handled_at": {"type": "date", "format": "yyyy-MM-dd HH:mm:ss"}
        #             }
        #         }
        #     }
        # }'
        # """
        # self.__fbucks_handled_orders_elastic = Elastic(
        #     settings.AWS_ELASTICSEARCH_FBUCKS_HANDLED_ORDERS,
        #     settings.AWS_ELASTICSEARCH_FBUCKS_HANDLED_ORDERS,
        # )
        self.__fbucks_handled_orders_dynamo_db = DynamoModel(
            settings.AWS_DYNAMODB_CMS_TABLE_NAME)
        self.__fbucks_handled_orders_dynamo_db.PARTITION_KEY = 'PURCHASE_FBUCKS_REWARD_HANDLED_ORDERS'

        # Attention!
        # We can get current customer's amount as a sum of all changes by customer_id
        # But theoretically elastic can not be in time with index update (1 second) between requests.
        # So there is another index to store amount value.
        """
        curl -X DELETE localhost:9200/fbucks_customer_amount
        curl -X PUT localhost:9200/fbucks_customer_amount -H "Content-Type: application/json" -d'{
            "mappings": {
                "fbucks_customer_amount": {
                    "properties": {
                        "amount": {"type": "integer"}
                    }
                }
            }
        }'
        curl -X DELETE localhost:9200/fbucks_customer_amount_changes
        curl -X PUT localhost:9200/fbucks_customer_amount_changes -H "Content-Type: application/json" -d'{
            "mappings": {
                "fbucks_customer_amount_changes": {
                    "properties": {
                        "customer_id": {"type": "keyword"},
                        "amount": {"type": "integer"},
                        "changed_at": {"type": "date", "format": "yyyy-MM-dd HH:mm:ss"},
                        "order_number": {"type": "keyword"}
                    }
                }
            }
        }'
        """
        self.__fbucks_customer_amount_elastic = Elastic(
            settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
            settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT,
        )
        self.__fbucks_customer_amount_changes_elastic = Elastic(
            settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT_CHANGES,
            settings.AWS_ELASTICSEARCH_FBUCKS_CUSTOMER_AMOUNT_CHANGES,
        )

        self.__customer_storage = CustomerStorageImplementation()
        self.__messages_storage = MessageStorageImplementation()