Пример #1
0
    def test_create_existing_block_transaction_with_txn_id(self):
        user = mommy.make_recipe('flex_bookings.user', username="******")
        events = mommy.make_recipe('flex_bookings.future_EV', _quantity=5)
        block = mommy.make_recipe(
            'flex_bookings.block', name="test block"
        )
        for event in events:
            block.events.add(event)
        block_txn = helpers.create_block_paypal_transaction(user, block)
        block_txn.transaction_id = "test transaction id"
        block_txn.save()
        self.assertEqual(block_txn.block, block)
        self.assertEqual(
            block_txn.invoice_id,
            'testuser-tb-inv#001'
        )
        self.assertEqual(PaypalBlockTransaction.objects.count(), 1)

        second_block_txn = helpers.create_block_paypal_transaction(user, block)
        self.assertEqual(PaypalBlockTransaction.objects.count(), 2)
        self.assertNotEqual(block_txn, second_block_txn)
        self.assertEqual(
            second_block_txn.invoice_id,
            'testuser-tb-inv#002'
        )
Пример #2
0
    def test_create_block_transaction_with_duplicate_invoice_number(self):
        user = mommy.make_recipe('booking.user', username="******")
        block = mommy.make_recipe(
            'booking.block', user=user,
            block_type__event_type__subtype="Pole Level Class",
            block_type__size=10
        )
        block1 = mommy.make_recipe(
            'booking.block', user=user,
            block_type__event_type__subtype="Pole Level Class1",
            block_type__size=10,
            start_date=block.start_date
        )
        block_txn = helpers.create_block_paypal_transaction(user, block)
        self.assertEqual(block_txn.block, block)
        self.assertEqual(
            block_txn.invoice_id,
            'testuser-PLC-10-{}-inv#001'.format(
                block.start_date.strftime("%d%m%y%H%M")
            )
        )
        self.assertEqual(PaypalBlockTransaction.objects.count(), 1)

        second_block_txn = helpers.create_block_paypal_transaction(user, block1)
        self.assertEqual(PaypalBlockTransaction.objects.count(), 2)
        self.assertNotEqual(block_txn, second_block_txn)
        # to avoid duplication, the counter is set to 6 digits, the first 3
        # random between 100 and 999
        self.assertEqual(len(second_block_txn.invoice_id.split('#')[-1]), 6)
Пример #3
0
    def test_create_block_transaction_with_duplicate_invoice_number(self):
        user = mommy.make_recipe('flex_bookings.user', username="******")
        events = mommy.make_recipe('flex_bookings.future_EV', _quantity=5)
        block = mommy.make_recipe(
            'flex_bookings.block', name="test block"
        )
        for event in events:
            block.events.add(event)

        events1 = mommy.make_recipe('flex_bookings.future_EV', _quantity=5)
        block1 = mommy.make_recipe(
            'flex_bookings.block', name="test block"
        )
        for event in events1:
            block1.events.add(event)

        block_txn = helpers.create_block_paypal_transaction(user, block)
        self.assertEqual(block_txn.block, block)
        self.assertEqual(
            block_txn.invoice_id,
            'testuser-tb-inv#001'
        )
        self.assertEqual(PaypalBlockTransaction.objects.count(), 1)

        second_block_txn = helpers.create_block_paypal_transaction(user, block1)
        self.assertEqual(PaypalBlockTransaction.objects.count(), 2)
        self.assertNotEqual(block_txn, second_block_txn)
        # to avoid duplication, the counter is set to 6 digits, the first 3
        # random between 100 and 999
        self.assertEqual(len(second_block_txn.invoice_id.split('#')[-1]), 6)
Пример #4
0
    def test_create_existing_block_transaction_with_txn_id(self):
        user = mommy.make_recipe('booking.user', username="******")
        block = mommy.make_recipe(
            'booking.block', user=user,
            block_type__event_type__subtype="Pole Level Class",
            block_type__size=10
        )
        block_txn = helpers.create_block_paypal_transaction(user, block)
        block_txn.transaction_id = "test transaction id"
        block_txn.save()
        self.assertEqual(block_txn.block, block)
        self.assertEqual(
            block_txn.invoice_id,
            'testuser-PLC-10-{}-inv#001'.format(
                block.start_date.strftime("%d%m%y%H%M")
            )
        )
        self.assertEqual(PaypalBlockTransaction.objects.count(), 1)

        second_block_txn = helpers.create_block_paypal_transaction(user, block)
        self.assertEqual(PaypalBlockTransaction.objects.count(), 2)
        self.assertNotEqual(block_txn, second_block_txn)
        self.assertEqual(
            second_block_txn.invoice_id,
            'testuser-PLC-10-{}-inv#002'.format(
                block.start_date.strftime("%d%m%y%H%M")
            )
        )
Пример #5
0
    def test_create_block_transaction_with_duplicate_invoice_number(self):
        user = mommy.make_recipe('booking.user', username="******")
        block = mommy.make_recipe(
            'booking.block',
            user=user,
            block_type__event_type__subtype="Pole Level Class",
            block_type__size=10)
        block1 = mommy.make_recipe(
            'booking.block',
            user=user,
            block_type__event_type__subtype="Pole Level Class1",
            block_type__size=10,
            start_date=block.start_date)
        block_txn = helpers.create_block_paypal_transaction(user, block)
        self.assertEqual(block_txn.block, block)
        self.assertEqual(
            block_txn.invoice_id, 'testuser-PLC-10-{}-inv#001'.format(
                block.start_date.strftime("%d%m%y%H%M")))
        self.assertEqual(PaypalBlockTransaction.objects.count(), 1)

        second_block_txn = helpers.create_block_paypal_transaction(
            user, block1)
        self.assertEqual(PaypalBlockTransaction.objects.count(), 2)
        self.assertNotEqual(block_txn, second_block_txn)
        # to avoid duplication, the counter is set to 6 digits, the first 3
        # random between 100 and 999
        self.assertEqual(len(second_block_txn.invoice_id.split('#')[-1]), 6)
Пример #6
0
    def test_paypal_notify_url_with_block(self, mock_postback):
        mock_postback.return_value = b"VERIFIED"
        user = mommy.make_recipe('flex_bookings.user')
        events = mommy.make_recipe('flex_bookings.future_EV', _quantity=5)
        block = mommy.make_recipe('flex_bookings.block')
        for event in events:
            block.events.add(event)
            booking = mommy.make_recipe(
                'flex_bookings.booking', user=user, event=event
            )
            block.bookings.add(booking)
        invoice_id = helpers.create_block_paypal_transaction(
            user, block
        ).invoice_id

        self.assertFalse(PayPalIPN.objects.exists())
        params = dict(IPN_POST_PARAMS)
        params.update(
            {
                'custom': b('block {}'.format(block.id)),
                'invoice': b(invoice_id)
            }
        )
        resp = self.paypal_post(params)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(PayPalIPN.objects.count(), 1)
        ppipn = PayPalIPN.objects.first()
        self.assertFalse(ppipn.flag)
        self.assertEqual(ppipn.flag_info, '')

        block.refresh_from_db()
        # 2 emails sent, to user and studio
        self.assertEqual(len(mail.outbox), 2)
Пример #7
0
    def test_paypal_block_admin_display(self):
        user = mommy.make_recipe(
            'flex_bookings.user', first_name='Test', last_name='User'
        )
        events = mommy.make_recipe('flex_bookings.future_EV', _quantity=5)
        block = mommy.make_recipe('flex_bookings.block')
        for event in events:
            block.events.add(event)
            booking = mommy.make_recipe(
                'flex_bookings.booking', user=user, event=event
            )
            block.bookings.add(booking)
        pptrans = helpers.create_block_paypal_transaction(
            user, block
        )

        ppblock_admin = PaypalBlockTransactionAdmin(
            PaypalBlockTransaction, AdminSite()
        )
        ppblock_query = ppblock_admin.get_queryset(None)[0]

        self.assertEqual(
            ppblock_admin.get_block_id(ppblock_query), block.id
        )
        self.assertEqual(
            ppblock_admin.get_user(ppblock_query), 'Test User'
        )
        self.assertEqual(
            ppblock_admin.cost(ppblock_query),
            u"\u00A3{:.2f}".format(
                block.item_cost * block.bookings.count()
            )
        )
Пример #8
0
    def test_paypal_block_admin_display(self):
        user = mommy.make_recipe(
            'booking.user', first_name='Test', last_name='User')
        block = mommy.make_recipe('booking.block_5', user=user)
        pptrans = helpers.create_block_paypal_transaction(
            block.user, block
        )

        ppblock_admin = admin.PaypalBlockTransactionAdmin(
            PaypalBlockTransaction, AdminSite()
        )
        ppblock_query = ppblock_admin.get_queryset(None)[0]

        self.assertEqual(
            ppblock_admin.get_block_id(ppblock_query), block.id
        )
        self.assertEqual(
            ppblock_admin.get_user(ppblock_query), 'Test User'
        )
        self.assertEqual(
            ppblock_admin.get_blocktype(ppblock_query), block.block_type
        )
        self.assertEqual(
            ppblock_admin.cost(ppblock_query),
            u"\u00A3{:.2f}".format(block.block_type.cost)
        )
        self.assertEqual(
            ppblock_admin.block_start(ppblock_query),
            block.start_date.strftime('%d %b %Y, %H:%M')
        )
        self.assertEqual(
            ppblock_admin.block_expiry(ppblock_query),
            block.expiry_date.strftime('%d %b %Y, %H:%M')
        )
Пример #9
0
    def test_create_existing_block_transaction(self):
        user = mommy.make_recipe('booking.user', username="******")
        block = mommy.make_recipe(
            'booking.block',
            user=user,
            block_type__event_type__subtype="Pole Level Class",
            block_type__size=10)
        block_txn = helpers.create_block_paypal_transaction(user, block)
        self.assertEqual(block_txn.block, block)
        self.assertEqual(
            block_txn.invoice_id, 'testuser-PLC-10-{}-inv#001'.format(
                block.start_date.strftime("%d%m%y%H%M")))
        self.assertEqual(PaypalBlockTransaction.objects.count(), 1)

        dp_block_txn = helpers.create_block_paypal_transaction(user, block)
        self.assertEqual(PaypalBlockTransaction.objects.count(), 1)
        self.assertEqual(block_txn, dp_block_txn)
Пример #10
0
    def test_paypal_notify_url_with_more_than_one_block_trans_object(
            self, mock_postback
    ):
        """
        The PayPalBooking/Block/TicketBookingTransaction object is created and
        retrieved using the username and event name/date.  If the user changes
        their username between booking and paying, a second Transaction object
        will be created.  In this case, we use the Transaction object that has
        the invoice number that matches the paypal ipn; if the paypal ipn has
        no invoice associated, we use the latest one.
        """
        mock_postback.return_value = b"VERIFIED"
        user = mommy.make_recipe('flex_bookings.user')
        events = mommy.make_recipe('flex_bookings.future_EV', _quantity=5)
        block = mommy.make_recipe('flex_bookings.block')
        for event in events:
            block.events.add(event)
            booking = mommy.make_recipe(
                'flex_bookings.booking', user=user, event=event
            )
            block.bookings.add(booking)
        self.assertFalse(PayPalIPN.objects.exists())
        self.assertFalse(PaypalBlockTransaction.objects.exists())

        pptn = helpers.create_block_paypal_transaction(user, block)
        pptn.invoice_id = 'invoice_1'
        pptn.save()
        pptn1 = helpers.create_block_paypal_transaction(user, block)
        pptn1.invoice_id = 'invoice_2'
        pptn1.save()

        params = dict(IPN_POST_PARAMS)
        params.update(
            {
                'custom': b('block {}'.format(block.id)),
                'invoice': b'invoice_1'
            }
        )
        self.paypal_post(params)
        pptn.refresh_from_db()
        self.assertEqual(b(pptn.transaction_id), IPN_POST_PARAMS['txn_id'])

        block.refresh_from_db()
        # 2 emails sent, to user and studio
        self.assertEqual(len(mail.outbox), 2)
Пример #11
0
 def test_create_block_transaction(self):
     user = mommy.make_recipe('flex_bookings.user', username="******")
     events = mommy.make_recipe('flex_bookings.future_EV', _quantity=5)
     block = mommy.make_recipe(
         'flex_bookings.block', name="test block"
     )
     for event in events:
         block.events.add(event)
     block_txn = helpers.create_block_paypal_transaction(user, block)
     self.assertEqual(block_txn.block, block)
     self.assertEqual(block_txn.invoice_id, 'testuser-tb-inv#001')
     # str returns invoice id
     self.assertEqual(str(block_txn), block_txn.invoice_id)
Пример #12
0
    def test_paypal_notify_url_with_more_than_one_block_trans_object_no_invoice(
            self, mock_postback
    ):
        mock_postback.return_value = b"VERIFIED"
        user = mommy.make_recipe('flex_bookings.user')
        events = mommy.make_recipe('flex_bookings.future_EV', _quantity=5)
        block = mommy.make_recipe('flex_bookings.block')
        for event in events:
            block.events.add(event)
            booking = mommy.make_recipe(
                'flex_bookings.booking', user=user, event=event
            )
            block.bookings.add(booking)
        self.assertFalse(PayPalIPN.objects.exists())
        self.assertFalse(PaypalBlockTransaction.objects.exists())

        pptn = helpers.create_block_paypal_transaction(user, block)
        pptn.invoice_id = 'invoice_1'
        pptn.save()
        pptn1 = helpers.create_block_paypal_transaction(user, block)
        pptn1.invoice_id = 'invoice_2'
        pptn1.save()

        # if paypal ipn doesn't contain invoice number
        params = dict(IPN_POST_PARAMS)
        params.update(
            {
                'custom': b('block {}'.format(block.id)),
                'invoice': b''
            }
        )
        self.paypal_post(params)
        pptn1.refresh_from_db()
        self.assertEqual(b(pptn1.transaction_id), IPN_POST_PARAMS['txn_id'])

        block.refresh_from_db()
        # 3 emails sent, to user and studio, and support b/c no invoice id
        self.assertEqual(len(mail.outbox), 3)
Пример #13
0
 def test_create_block_transaction(self):
     user = mommy.make_recipe('booking.user', username="******")
     block = mommy.make_recipe(
         'booking.block',
         user=user,
         block_type__event_type__subtype="Pole Level Class",
         block_type__size=10)
     block_txn = helpers.create_block_paypal_transaction(user, block)
     self.assertEqual(block_txn.block, block)
     self.assertEqual(
         block_txn.invoice_id, 'testuser-PLC-10-{}-inv#001'.format(
             block.start_date.strftime("%d%m%y%H%M")))
     # str returns invoice id
     self.assertEqual(str(block_txn), block_txn.invoice_id)
Пример #14
0
 def test_create_block_transaction(self):
     user = mommy.make_recipe('booking.user', username="******")
     block = mommy.make_recipe(
         'booking.block', user=user,
         block_type__event_type__subtype="Pole Level Class",
         block_type__size=10
     )
     block_txn = helpers.create_block_paypal_transaction(user, block)
     self.assertEqual(block_txn.block, block)
     self.assertEqual(
         block_txn.invoice_id,
         'testuser-PLC-10-{}-inv#001'.format(
             block.start_date.strftime("%d%m%y%H%M")
         )
     )
     # str returns invoice id
     self.assertEqual(str(block_txn), block_txn.invoice_id)
Пример #15
0
    def test_paypal_block_admin_display(self):
        user = mommy.make_recipe('booking.user',
                                 first_name='Test',
                                 last_name='User')
        block = mommy.make_recipe('booking.block_5', user=user)
        pptrans = helpers.create_block_paypal_transaction(block.user, block)

        ppblock_admin = admin.PaypalBlockTransactionAdmin(
            PaypalBlockTransaction, AdminSite())
        ppblock_query = ppblock_admin.get_queryset(None)[0]

        self.assertEqual(ppblock_admin.get_block_id(ppblock_query), block.id)
        self.assertEqual(ppblock_admin.get_user(ppblock_query), 'Test User')
        self.assertEqual(ppblock_admin.get_blocktype(ppblock_query),
                         block.block_type)
        self.assertEqual(ppblock_admin.cost(ppblock_query),
                         u"\u00A3{:.2f}".format(block.block_type.cost))
        self.assertEqual(ppblock_admin.block_start(ppblock_query),
                         block.start_date.strftime('%d %b %Y, %H:%M'))
        self.assertEqual(ppblock_admin.block_expiry(ppblock_query),
                         block.expiry_date.strftime('%d %b %Y, %H:%M'))
Пример #16
0
def payments_pending(request):
    unpaid_bookings = Booking.objects.filter(
        user=request.user, status='OPEN', paid=False
    )
    unpaid_booked_events = [booking.event for booking in unpaid_bookings]

    blocks = []
    unpaid_single_bookings = []

    for booking in unpaid_bookings:
        if booking.event in unpaid_booked_events and booking.block:
            blocks.append(booking.block)
        else:
            invoice_id = create_booking_paypal_transaction(
            request.user, booking).invoice_id
            host = 'http://{}'.format(request.META.get('HTTP_HOST'))
            paypal_form = PayPalPaymentsListForm(
                initial=context_helpers.get_paypal_dict(
                    host,
                    booking.cost,
                    booking.event,
                    invoice_id,
                    'userid {} {} {}'.format(
                        request.user.id, 'booking', booking.id
                    )
                )
            )
            unpaid_booking = {
                'booking': booking,
                'paypalform': paypal_form
                }
            unpaid_single_bookings.append(unpaid_booking)

    unpaid_blocks = []
    for block in set(blocks):
        invoice_id = create_block_paypal_transaction(
            request.user, block).invoice_id
        host = 'http://{}'.format(request.META.get('HTTP_HOST'))
        paypal_form = PayPalPaymentsListForm(
            initial=context_helpers.get_paypal_dict(
                host,
                block.item_cost * block.events.count(),
                block.name,
                invoice_id,
                'userid {} {} {}'.format(request.user.id, 'block', block.id)
            )
        )
        unpaid_block = {
            'block': block,
            'paypalform': paypal_form
            }
        unpaid_blocks.append(unpaid_block)


    context = {
        'unpaid_blocks': unpaid_blocks,
        'unpaid_bookings': unpaid_single_bookings
    }

    return TemplateResponse(
        request, 'flex_bookings/payments_pending.html', context
    )
Пример #17
0
    def get_extra_context(self, **kwargs):
        context = {}
        try:
            self.request.user.online_disclaimer
            context['disclaimer'] = True
        except ObjectDoesNotExist:
            pass

        try:
            self.request.user.print_disclaimer
            context['disclaimer'] = True
        except ObjectDoesNotExist:
            pass

        types_available_to_book = context_helpers.\
            get_blocktypes_available_to_book(self.request.user)
        if types_available_to_book:
            context['can_book_block'] = True

        voucher = kwargs.get('voucher', None)
        voucher_error = kwargs.get('voucher_error', None)
        code = kwargs.get('code', None)
        context['voucher_form'] = VoucherForm(initial={'code': code})
        if voucher:
            context['voucher'] = voucher
        if voucher_error:
            context['voucher_error'] = voucher_error
        valid_voucher = False
        if voucher:
            valid_voucher = not bool(voucher_error)
            context['valid_voucher'] = valid_voucher

        blockformlist = []
        for block in self.get_queryset():
            expired = block.expiry_date < timezone.now()
            paypal_cost = None
            voucher_applied = False

            if not block.paid and not expired:
                context['has_unpaid_block'] = True
                paypal_cost = block.block_type.cost
                if valid_voucher and voucher.check_block_type(block.block_type):
                    paypal_cost = Decimal(
                        float(paypal_cost) * ((100 - voucher.discount) / 100)
                    ).quantize(Decimal('.05'))
                    voucher_applied = True

                invoice_id = create_block_paypal_transaction(
                    self.request.user, block).invoice_id
                host = 'http://{}'.format(self.request.META.get('HTTP_HOST'))
                paypal_form = PayPalPaymentsListForm(
                    initial=context_helpers.get_paypal_dict(
                        host,
                        paypal_cost,
                        block.block_type,
                        invoice_id,
                        '{} {}{}'.format(
                            'block', block.id, ' {}'.format(code)
                            if valid_voucher else ''
                        ),
                        paypal_email=block.block_type.paypal_email
                    )
                )
            else:
                paypal_form = None
            full = Booking.objects.filter(
                block__id=block.id).count() >= block.block_type.size
            blockform = {
                'block': block,
                'voucher_applied': voucher_applied,
                'block_cost': paypal_cost,
                'paypalform': paypal_form,
                'expired': expired or full}
            blockformlist.append(blockform)

        context['blockformlist'] = blockformlist

        return context
Пример #18
0
def get_obj(ipn_obj):
    from payments import helpers

    try:
        custom = ipn_obj.custom.split()
        obj_type = custom[0]
        obj_id = int(custom[-1])
    except IndexError:  # in case custom not included in paypal response
        raise PayPalTransactionError('Unknown object type for payment')

    if obj_type == 'booking':
        try:
            obj = Booking.objects.get(id=obj_id)
        except Booking.DoesNotExist:
            raise PayPalTransactionError(
                'Booking with id {} does not exist'.format(obj_id)
            )

        paypal_trans = PaypalBookingTransaction.objects.filter(booking=obj)
        if not paypal_trans:
            paypal_trans = helpers.create_booking_paypal_transaction(
                user=obj.user, booking=obj
            )
        elif paypal_trans.count() > 1:
            # we may have two ppb transactions created if user changed their
            # username between booking and paying (invoice_id is created and
            # retrieved using username)
            if ipn_obj.invoice:
                paypal_trans = PaypalBookingTransaction.objects.get(
                    booking=obj, invoice_id=ipn_obj.invoice
                )
            else:
                paypal_trans = paypal_trans.latest('id')
        else:  # we got one paypaltrans, as we should have
            paypal_trans = paypal_trans[0]

    elif obj_type == 'block':
        try:
            obj = Block.objects.get(id=obj_id)
        except Block.DoesNotExist:
            raise PayPalTransactionError(
                'Block with id {} does not exist'.format(obj_id)
            )
        paypal_trans = PaypalBlockTransaction.objects.filter(block=obj)
        if not paypal_trans:
            paypal_trans = helpers.create_block_paypal_transaction(
                user=obj.bookings.first().user, block=obj
            )
        elif paypal_trans.count() > 1:
            # we may have two ppb transactions created if user changed their
            # username between booking block and paying (invoice_id is created and
            # retrieved using username)
            if ipn_obj.invoice:
                paypal_trans = PaypalBlockTransaction.objects.get(
                    block=obj, invoice_id=ipn_obj.invoice
                )
            else:
                paypal_trans = paypal_trans.latest('id')
        else:  # we got one paypaltrans, as we should have
            paypal_trans = paypal_trans[0]

    else:
        raise PayPalTransactionError('Unknown object type for payment')

    return {
        'obj_type': obj_type,
        'obj': obj,
        'paypal_trans': paypal_trans
    }
Пример #19
0
def get_obj(ipn_obj):
    from payments import helpers
    additional_data = {}
    try:
        custom = ipn_obj.custom.split()
        obj_type = custom[0]
        obj_id = int(custom[1])
        voucher_code = custom[2] if len(custom) == 3 and \
            obj_type != 'test' else None
    except IndexError:  # in case custom not included in paypal response
        raise PayPalTransactionError('Unknown object type for payment')

    if obj_type == 'paypal_test':
        # a test payment for paypal email
        # custom in a test payment is in form
        # 'test 0 <invoice_id> <paypal email being tested> <user's email>'
        obj = None
        paypal_trans = None
        additional_data['test_invoice'] = custom[2]
        additional_data['test_paypal_email'] = custom[3]
        additional_data['user_email'] = custom[4]

    elif obj_type == 'booking':
        try:
            obj = Booking.objects.get(id=obj_id)
        except Booking.DoesNotExist:
            raise PayPalTransactionError(
                'Booking with id {} does not exist'.format(obj_id))

        paypal_trans = PaypalBookingTransaction.objects.filter(booking=obj)
        if not paypal_trans:
            paypal_trans = helpers.create_booking_paypal_transaction(
                user=obj.user, booking=obj)
        elif paypal_trans.count() > 1:
            # we may have two ppb transactions created if user changed their
            # username between booking and paying (invoice_id is created and
            # retrieved using username)
            if ipn_obj.invoice:
                paypal_trans = PaypalBookingTransaction.objects.get(
                    booking=obj, invoice_id=ipn_obj.invoice)
            else:
                paypal_trans = paypal_trans.latest('id')
        else:  # we got one paypaltrans, as we should have
            paypal_trans = paypal_trans[0]

    elif obj_type == 'block':
        try:
            obj = Block.objects.get(id=obj_id)
        except Block.DoesNotExist:
            raise PayPalTransactionError(
                'Block with id {} does not exist'.format(obj_id))

        paypal_trans = PaypalBlockTransaction.objects.filter(block=obj)
        if not paypal_trans:
            paypal_trans = helpers.create_block_paypal_transaction(
                user=obj.user, block=obj)
        elif paypal_trans.count() > 1:
            # we may have two ppb transactions created if user changed their
            # username between booking block and paying (invoice_id is created and
            # retrieved using username)
            if ipn_obj.invoice:
                paypal_trans = PaypalBlockTransaction.objects.get(
                    block=obj, invoice_id=ipn_obj.invoice)
            else:
                paypal_trans = paypal_trans.latest('id')
        else:  # we got one paypaltrans, as we should have
            paypal_trans = paypal_trans[0]

    elif obj_type == 'ticket_booking':
        try:
            obj = TicketBooking.objects.get(id=obj_id)
        except TicketBooking.DoesNotExist:
            raise PayPalTransactionError(
                'Ticket Booking with id {} does not exist'.format(obj_id))

        paypal_trans = PaypalTicketBookingTransaction.objects.filter(
            ticket_booking=obj)
        if not paypal_trans:
            paypal_trans = helpers.create_ticket_booking_paypal_transaction(
                user=obj.user, ticket_booking=obj)
        elif paypal_trans.count() > 1:
            # we may have two ppb transactions created if user changed their
            # username between booking and paying (invoice_id is created and
            # retrieved using username)
            if ipn_obj.invoice:
                paypal_trans = PaypalTicketBookingTransaction.objects.get(
                    ticket_booking=obj, invoice_id=ipn_obj.invoice)
            else:
                paypal_trans = paypal_trans.latest('id')
        else:  # we got one paypaltrans, as we should have
            paypal_trans = paypal_trans[0]

    else:
        raise PayPalTransactionError('Unknown object type for payment')

    return {
        'obj_type': obj_type,
        'obj': obj,
        'paypal_trans': paypal_trans,
        'voucher_code': voucher_code,
        'additional_data': additional_data
    }
Пример #20
0
def get_obj(ipn_obj):
    from payments import helpers
    additional_data = {}
    try:
        custom = ipn_obj.custom.split()
        obj_type = custom[0]
        obj_id = int(custom[1])
        voucher_code = custom[2] if len(custom) == 3 and \
            obj_type != 'test' else None
    except IndexError:  # in case custom not included in paypal response
        raise PayPalTransactionError('Unknown object type for payment')

    if obj_type == 'paypal_test':
        # a test payment for paypal email
        # custom in a test payment is in form
        # 'test 0 <invoice_id> <paypal email being tested> <user's email>'
        obj = None
        paypal_trans = None
        additional_data['test_invoice'] = custom[2]
        additional_data['test_paypal_email'] = custom[3]
        additional_data['user_email'] = custom[4]

    elif obj_type == 'booking':
        try:
            obj = Booking.objects.get(id=obj_id)
        except Booking.DoesNotExist:
            raise PayPalTransactionError(
                'Booking with id {} does not exist'.format(obj_id)
            )

        paypal_trans = PaypalBookingTransaction.objects.filter(booking=obj)
        if not paypal_trans:
            paypal_trans = helpers.create_booking_paypal_transaction(
                user=obj.user, booking=obj
            )
        elif paypal_trans.count() > 1:
            # we may have two ppb transactions created if user changed their
            # username between booking and paying (invoice_id is created and
            # retrieved using username)
            if ipn_obj.invoice:
                paypal_trans = PaypalBookingTransaction.objects.get(
                    booking=obj, invoice_id=ipn_obj.invoice
                )
            else:
                paypal_trans = paypal_trans.latest('id')
        else:  # we got one paypaltrans, as we should have
            paypal_trans = paypal_trans[0]

    elif obj_type == 'block':
        try:
            obj = Block.objects.get(id=obj_id)
        except Block.DoesNotExist:
            raise PayPalTransactionError(
                'Block with id {} does not exist'.format(obj_id)
            )

        paypal_trans = PaypalBlockTransaction.objects.filter(block=obj)
        if not paypal_trans:
            paypal_trans = helpers.create_block_paypal_transaction(
                user=obj.user, block=obj
            )
        elif paypal_trans.count() > 1:
            # we may have two ppb transactions created if user changed their
            # username between booking block and paying (invoice_id is created and
            # retrieved using username)
            if ipn_obj.invoice:
                paypal_trans = PaypalBlockTransaction.objects.get(
                    block=obj, invoice_id=ipn_obj.invoice
                )
            else:
                paypal_trans = paypal_trans.latest('id')
        else:  # we got one paypaltrans, as we should have
            paypal_trans = paypal_trans[0]


    elif obj_type == 'ticket_booking':
        try:
            obj = TicketBooking.objects.get(id=obj_id)
        except TicketBooking.DoesNotExist:
            raise PayPalTransactionError(
                'Ticket Booking with id {} does not exist'.format(obj_id)
            )

        paypal_trans = PaypalTicketBookingTransaction.objects.filter(
            ticket_booking=obj
        )
        if not paypal_trans:
            paypal_trans = helpers.create_ticket_booking_paypal_transaction(
                user=obj.user, ticket_booking=obj
            )
        elif paypal_trans.count() > 1:
            # we may have two ppb transactions created if user changed their
            # username between booking and paying (invoice_id is created and
            # retrieved using username)
            if ipn_obj.invoice:
                paypal_trans = PaypalTicketBookingTransaction.objects.get(
                    ticket_booking=obj, invoice_id=ipn_obj.invoice
                )
            else:
                paypal_trans = paypal_trans.latest('id')
        else:  # we got one paypaltrans, as we should have
            paypal_trans = paypal_trans[0]

    else:
        raise PayPalTransactionError('Unknown object type for payment')

    return {
        'obj_type': obj_type,
        'obj': obj,
        'paypal_trans': paypal_trans,
        'voucher_code': voucher_code,
        'additional_data': additional_data
    }