Esempio n. 1
0
    def cart_remove_product():
        cart_app_service = CartAppService()

        try:
            request_data = blueprint.current_request.json_body
            simple_sku = str(request_data.get('simple_sku', '')).strip()
            simple_sku = simple_sku if len(simple_sku) > 0 else None
            if not simple_sku:
                raise HttpIncorrectInputDataException()

            cart_id = __get_cart_id()
            cart_app_service.remove_cart_product(cart_id, simple_sku)
            return __response_cart(cart_id)
        except BaseException as e:
            return http_response_exception_or_throw(e)
Esempio n. 2
0
def on_login():
    session_id = magento_blueprint.current_request.current_user.session_id
    user_id = magento_blueprint.current_request.current_user.id

    cart_app_service = CartAppService()
    cart_app_service.transfer_cart(session_id, user_id)
Esempio n. 3
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)
Esempio n. 4
0
    def credit_cards_checkout():
        cards_storage = CreditCardsStorageImplementation()
        checkout_storage = CheckoutStorageImplementation()
        order_app_service = OrderAppService()
        cart_service = CartAppService()
        checkout_service = CheckoutAppService()
        logger = Logger()

        try:
            user = __get_user()

            card_response_id = (blueprint.current_request.json_body
                                or {}).get('card_id') or None
            if not card_response_id:
                raise BadRequestError('Incorrect Input Data!')

            card = None
            for _card in cards_storage.get_all_by_customer(user.id):
                if __get_card_response(_card)['id'] == card_response_id:
                    card = _card
                    break

            if not card:
                raise NotFoundError('Card does not exist!')
            elif not card.is_verified:
                raise ApplicationLogicException(
                    'Unable to checkout with Not Verified Card!')

            checkout = checkout_storage.load(Id(user.id))
            if not checkout:
                raise HttpNotFoundException('Checkout does not exist!')
            elif checkout.total_due.value == 0:
                raise ApplicationLogicException(
                    'Unable to checkout 0 amount with Credit Cards!')

            order = order_app_service.get_waiting_for_payment_by_checkout_or_checkout_new(
                user.id)

            def __log_flow(text: str) -> None:
                logger.log_simple('Credit Cards : Checkout : {} : {}'.format(
                    order.number.value, text))

            __log_flow('Start')

            # init
            try:
                __log_flow('Payment Request...')
                response = requests.post(
                    url=settings.PEACH_PAYMENT_BASE_URL +
                    'registrations/{}/payments'.format(card.token),
                    data={
                        'entityId':
                        settings.PEACH_PAYMENT_ENTITY_ID,
                        'amount':
                        '%.2f' % order.total_current_cost_ordered.value,
                        'paymentType':
                        'DB',
                        'currency':
                        'ZAR',
                        'shopperResultUrl':
                        requests.utils.requote_uri(settings.FRONTEND_BASE_URL +
                                                   '/order/confirmation/{}'.
                                                   format(order.number.value)),
                        'customParameters[order_number]':
                        order.number.value,
                    },
                    headers={
                        'Authorization':
                        'Bearer {}'.format(settings.PEACH_PAYMENT_ACCESS_TOKEN)
                    })
                if response.status_code != 200:
                    raise Exception(
                        'Peach Payment Request has been Failed: {} - {} - {}'.
                        format(response.status_code, response.reason,
                               response.text))

                response_data = response.json()
                if response_data['result']['code'] not in (
                        '000.200.000',  # transaction pending
                ):
                    raise Exception(
                        'Credit Card Initial request response is not good: {} - {}'
                        .format(response_data['result']['code'],
                                response_data['result']['description']))

                __log_flow('Payment Request is Done!')
            except BaseException as e:
                logger.log_exception(e)
                __log_flow(
                    'Payment Request is Not done because of Error: {}'.format(
                        str(e)))
                raise UnprocessableEntityError(
                    'Credit Card Payment is unavailable now!')

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

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

            result = {
                'order_number':
                order.number.value,
                'url':
                response_data['redirect']['url'],
                'method':
                'POST',
                'parameters': [{
                    'name': param['name'],
                    'value': param['value'],
                } for param in response_data['redirect']['parameters']]
            }

            __log_flow('End')

            return result
        except BaseException as e:
            logger.log_exception(e)
            return http_response_exception_or_throw(e)
    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
        }
Esempio n. 6
0
    def mobicred_checkout():
        order_app_service = OrderAppService()
        cart_service = CartAppService()
        checkout_storage = CheckoutStorageImplementation()
        checkout_service = CheckoutAppService()
        logger = Logger()

        try:
            user = blueprint.current_request.current_user
            if user.is_anyonimous:
                raise HttpAuthenticationRequiredException()

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

            # check input data
            form = MobicredCredentialsForm()
            form.load(blueprint.current_request.json_body or {})
            form_errors = form.validate()
            if form_errors:
                return {'status': False, 'form_errors': form_errors}

            order = order_app_service.get_waiting_for_payment_by_checkout_or_checkout_new(
                user.id)

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

            __log_flow('Start')

            # init mobicred
            try:
                __log_flow('Payment Initializing...')
                response = requests.post(
                    url=settings.PEACH_PAYMENT_BASE_URL + 'payments​',
                    data={
                        'entityId':
                        settings.PEACH_PAYMENT_ENTITY_ID,
                        'paymentBrand':
                        'MOBICRED',
                        'paymentType':
                        'DB',
                        'virtualAccount[accountId]':
                        form.username,
                        'virtualAccount[password]':
                        form.password,
                        'amount':
                        '%.2f' % order.total_current_cost_ordered.value,
                        'currency':
                        'ZAR',
                        'customParameters[order_number]':
                        order.number.value,
                        'shopperResultUrl':
                        requests.utils.requote_uri(settings.FRONTEND_BASE_URL +
                                                   '/order/confirmation/{}'.
                                                   format(order.number.value)),
                    },
                    headers={
                        'Authorization':
                        'Bearer {}'.format(settings.PEACH_PAYMENT_ACCESS_TOKEN)
                    })
                if response.status_code != 200:
                    raise Exception(
                        'Mobicred Initial request has been failed: {} - {} - {}!'
                        .format(response.status_code, response.reason,
                                response.text))

                response_data = response.json()
                if response_data['result']['code'] not in (
                        '000.000.000',  # Transaction successfully processed in LIVE system
                        '000.100.110',  # Transaction successfully processed in TEST system
                ):
                    raise Exception(
                        'Mobicred Initial request response is not good: {} - {}'
                        .format(response_data['result']['code'],
                                response_data['result']['description']))
            except BaseException as e:
                logger.log_exception(e)
                __log_flow(
                    'Payment Not Initialized because of Error: {}'.format(
                        str(e)))
                raise HttpNotFoundException(
                    'Mobicred Payment is unavailable now!')

            __log_flow('Payment Initialized!')

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

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

            __log_flow('End')

            result = {
                'order_number': order.number.value,
                'url': response_data['redirect']['url'],
                'method': 'POST',
                'parameters': response_data['redirect']['parameters'],
            }

            return result
        except BaseException as e:
            return http_response_exception_or_throw(e)