def test_unicode_csv(self):
        event = EventFactory(collect_housing_data=True, currency='GBP')
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        AttendeeFactory(
            order=order,
            bought_items=order.bought_items.all(),
            housing_status=Attendee.HOME,
        )

        view = AttendeeFilterView()
        view.event = event
        view.request = self.factory.get('/?format=csv')
        view.request.user = AnonymousUser()

        table = view.get_table(Attendee.objects.all())
        response = view.render_to_response({'table': table})
        self.assertEqual(response['content-disposition'],
                         'attachment; filename="export.csv"')
        content = list(response)
        self.assertIn('£200.00', content[1])
Exemple #2
0
class OrderAlertMailerWithUnconfirmedCheckPayments(TestCase):
    def setUp(self):
        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        transaction = TransactionFactory(event=event,
                                         order=self.order,
                                         amount=130,
                                         method=Transaction.CHECK,
                                         is_confirmed=False)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30,
                                   discount_type='percent',
                                   event=event,
                                   item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderAlertMailer(transaction,
                                       site='dancerfly.com',
                                       secure=True)
        self.event_name = event.name

    def test_body_plaintext(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn("keep an eye on your mail", body)
Exemple #3
0
    def test_summary_data__discount_deleted(self):
        """
        Test that get_summary_data returns correct values for savings and
        total cost even if a discount was deleted.

        """
        event = EventFactory()
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)
        discount = DiscountFactory(amount=20,
                                   event=event,
                                   item_options=[item_option])

        order.add_to_cart(item_option)
        order.add_discount(discount)
        order.mark_cart_paid(transaction)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], -20)
        self.assertEqual(summary_data['net_cost'], 80)

        discount.delete()

        # Make sure that the value isn't cached.
        order = Order.objects.get(pk=order.pk)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], -20)
        self.assertEqual(summary_data['net_cost'], 80)
Exemple #4
0
    def test_summary_data__itemoption_changed(self):
        """
        Test that get_summary_data returns correct values for savings and
        total cost even if an itemoption was changed.

        """
        event = EventFactory()
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], 0)
        self.assertEqual(summary_data['net_cost'], 100)

        item_option.price = 200
        item_option.save()

        # Make sure that the value isn't cached.
        order = Order.objects.get(pk=order.pk)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], 0)
        self.assertEqual(summary_data['net_cost'], 100)
Exemple #5
0
    def test_order_by_purchase_date(self):
        """
        If ordering by purchase date is selected, we should get that
        ordering even if the field isn't selected.

        """
        order2 = OrderFactory(event=self.event)
        transaction = TransactionFactory(
            event=self.event,
            order=order2,
            timestamp=timezone.now() - datetime.timedelta(days=50)
        )
        order2.add_to_cart(self.item_option)
        order2.mark_cart_paid(transaction)
        attendee2 = AttendeeFactory(
            order=order2,
            bought_items=order2.bought_items.all(),
            housing_status='have',
            email='*****@*****.**',
            other_needs='99 mattresses',
            person_avoid='Darth Vader',
            person_prefer='Han Solo',
        )

        table = AttendeeTable(
            event=self.event,
            data={
                'o': '-purchase_date',
                TABLE_COLUMN_FIELD: ['pk', 'get_full_name'],
            },
        )
        rows = list(table)
        self.assertEqual(rows[0]['pk'].value, self.attendee.pk)
        self.assertEqual(rows[1]['pk'].value, attendee2.pk)
Exemple #6
0
    def test_summary_data__base(self):
        """
        Test that get_summary_data returns correct values for savings and
        total cost.

        """
        event = EventFactory()
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)
        discount = DiscountFactory(amount=20,
                                   event=event,
                                   item_options=[item_option])

        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], 0)
        self.assertEqual(summary_data['net_cost'], 100)

        # Discounts don't get added to BOUGHT items.
        order.add_discount(discount)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], 0)
        self.assertEqual(summary_data['net_cost'], 100)
class OrderAlertMailerWithUnconfirmedCheckPayments(TestCase):

    def setUp(self):
        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        transaction = TransactionFactory(event=event, order=self.order,
                                         amount=130, method=Transaction.CHECK,
                                         is_confirmed=False)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30, discount_type='percent',
                                   event=event, item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderAlertMailer(transaction, site='dancerfly.com',
                                       secure=True)
        self.event_name = event.name

    def test_body_plaintext(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn("keep an eye on your mail", body)
    def test_attendee_count__home_housing(self):
        """Attendee count should be present & accurate; housing data should."""
        event = EventFactory(collect_housing_data=True)
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        AttendeeFactory(
            order=order,
            bought_items=order.bought_items.all(),
            housing_status=Attendee.HOME,
        )

        view = EventSummaryView()
        view.request = self.factory.get('/')
        view.request.user = AnonymousUser()
        view.event = event
        context_data = view.get_context_data()

        self.assertEqual(context_data['attendee_count'], 1)
        self.assertEqual(context_data['attendee_requesting_count'], 0)
        self.assertEqual(context_data['attendee_arranged_count'], 0)
        self.assertEqual(context_data['attendee_home_count'], 1)
    def test_summary_data__base(self):
        """
        Test that get_summary_data returns correct values for savings and
        total cost.

        """
        event = EventFactory()
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)
        discount = DiscountFactory(amount=20, event=event, item_options=[item_option])

        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], 0)
        self.assertEqual(summary_data['net_cost'], 100)

        # Discounts don't get added to BOUGHT items.
        order.add_discount(discount)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], 0)
        self.assertEqual(summary_data['net_cost'], 100)
    def test_attendee_count__home_housing(self):
        """Attendee count should be present & accurate; housing data should."""
        event = EventFactory(collect_housing_data=True)
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        AttendeeFactory(
            order=order,
            bought_items=order.bought_items.all(),
            housing_status=Attendee.HOME,
        )

        view = EventSummaryView()
        view.request = self.factory.get('/')
        view.request.user = AnonymousUser()
        view.event = event
        context_data = view.get_context_data()

        self.assertEqual(context_data['attendee_count'], 1)
        self.assertEqual(context_data['attendee_requesting_count'], 0)
        self.assertEqual(context_data['attendee_arranged_count'], 0)
        self.assertEqual(context_data['attendee_home_count'], 1)
    def test_summary_data__discount_deleted(self):
        """
        Test that get_summary_data returns correct values for savings and
        total cost even if a discount was deleted.

        """
        event = EventFactory()
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)
        discount = DiscountFactory(amount=20, event=event, item_options=[item_option])

        order.add_to_cart(item_option)
        order.add_discount(discount)
        order.mark_cart_paid(transaction)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], -20)
        self.assertEqual(summary_data['net_cost'], 80)

        discount.delete()

        # Make sure that the value isn't cached.
        order = Order.objects.get(pk=order.pk)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], -20)
        self.assertEqual(summary_data['net_cost'], 80)
    def test_unicode_csv(self):
        event = EventFactory(collect_housing_data=True, currency='GBP')
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        AttendeeFactory(
            order=order,
            bought_items=order.bought_items.all(),
            housing_status=Attendee.HOME,
        )

        view = AttendeeFilterView()
        view.event = event
        view.request = self.factory.get('/?format=csv')
        view.request.user = AnonymousUser()

        table = view.get_table(Attendee.objects.all())
        response = view.render_to_response({'table': table})
        self.assertEqual(response['content-disposition'], 'attachment; filename="export.csv"')
        content = list(response)
        self.assertIn('£200.00', content[1])
    def test_summary_data__itemoption_changed(self):
        """
        Test that get_summary_data returns correct values for savings and
        total cost even if an itemoption was changed.

        """
        event = EventFactory()
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], 0)
        self.assertEqual(summary_data['net_cost'], 100)

        item_option.price = 200
        item_option.save()

        # Make sure that the value isn't cached.
        order = Order.objects.get(pk=order.pk)

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], 0)
        self.assertEqual(summary_data['net_cost'], 100)
Exemple #14
0
class OrderAlertMailerForNonUserOrderTestCase(TestCase):
    def setUp(self):
        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        transaction = TransactionFactory(event=event,
                                         order=self.order,
                                         amount=130)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30,
                                   discount_type='percent',
                                   event=event,
                                   item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderAlertMailer(transaction,
                                       site='dancerfly.com',
                                       secure=True)
        self.event_name = event.name

    def test_subject(self):
        subject = self.mailer.render_subject(self.mailer.get_context_data())
        expected_subject = (
            '[{event_name}] New purchase by {order_email}'.format(
                event_name=self.event_name, order_email=self.order.email))
        self.assertEqual(subject, expected_subject)
class OrderReceiptMailerForNonUserTestCase(TestCase):
    def setUp(self):
        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        transaction = TransactionFactory(event=event,
                                         order=self.order,
                                         amount=130)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30,
                                   discount_type='percent',
                                   event=event,
                                   item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderReceiptMailer(transaction,
                                         site='dancerfly.com',
                                         secure=True)

    def test_recipients(self):
        self.assertEqual(self.mailer.get_recipients(), [self.order.email])
class OrderAlertMailerForNonUserOrderTestCase(TestCase):

    def setUp(self):
        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        transaction = TransactionFactory(event=event, order=self.order,
                                         amount=130)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30, discount_type='percent',
                                   event=event, item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderAlertMailer(transaction, site='dancerfly.com',
                                       secure=True)
        self.event_name = event.name

    def test_subject(self):
        subject = self.mailer.render_subject(self.mailer.get_context_data())
        expected_subject = ('[{event_name}] New purchase by {order_email}'
                            .format(event_name=self.event_name,
                                    order_email=self.order.email))
        self.assertEqual(subject, expected_subject)
class OrderDetailViewTest(TestCase):
    def setUp(self):
        self.owner = Person.objects.create_user(email="*****@*****.**", password="******")
        self.non_owner = Person.objects.create_user(email="*****@*****.**", password="******")
        self.event = EventFactory(collect_housing_data=False)
        OrganizationMember.objects.create(
            person=self.owner,
            organization=self.event.organization,
            role=OrganizationMember.OWNER,
        )
        self.order = OrderFactory(event=self.event, code='aaaaaaaa')
        self.transaction = TransactionFactory(event=self.event, order=self.order)
        item = ItemFactory(event=self.event)
        item_option = ItemOptionFactory(price=100, item=item)

        self.order.add_to_cart(item_option)
        self.order.add_to_cart(item_option)
        self.order.mark_cart_paid(self.transaction)

        self.attendee = AttendeeFactory(order=self.order, bought_items=self.order.bought_items.all())
        self.url = reverse('brambling_event_order_detail', kwargs={
            'event_slug': self.event.slug,
            'organization_slug': self.event.organization.slug,
            'code': self.order.code,
        })

    def test_post__order_notes(self):
        self.client.login(username=self.owner.email, password='******')
        response = self.client.post(
            self.url,
            {
                'is_notes_form': '1',
                'notes': 'Hello',
            },
        )

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], self.url)
        self.order.refresh_from_db()
        self.assertEqual(self.order.notes, 'Hello')

    def test_post__attendee_notes(self):
        self.client.login(username=self.owner.email, password='******')
        response = self.client.post(
            self.url,
            {
                'is_attendee_form': '1',
                'attendee_id': str(self.attendee.pk),
                'notes': 'Hello',
            },
        )

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], self.url)
        self.attendee.refresh_from_db()
        self.assertEqual(self.attendee.notes, 'Hello')
class ItemOptionViewSetTestCase(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        self.transaction = TransactionFactory(
            event=event, order=self.order, amount=130,
            method=Transaction.CHECK, is_confirmed=False)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30, discount_type='percent',
                                   event=event, item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(self.transaction)

        order2 = OrderFactory(event=event, email='*****@*****.**')
        order2.add_to_cart(item_option2)
        transaction2 = TransactionFactory(event=event, order=self.order,
                                          amount=130, method=Transaction.CHECK,
                                          is_confirmed=True)
        order2.mark_cart_paid(transaction2)

        self.order3 = OrderFactory(event=event, email='*****@*****.**')
        self.order3.add_to_cart(item_option1)
        transaction3 = TransactionFactory(event=event, order=self.order3,
                                          amount=130, method=Transaction.CHECK,
                                          is_confirmed=True)
        self.order3.mark_cart_paid(transaction3)

        self.viewset = ItemOptionViewSet()
        self.viewset.request = self.factory.get('/')
        self.viewset.request.user = self.order.person

    def test_taken_counts(self):
        qs = self.viewset.get_queryset()
        self.assertEqual([2, 2], [int(p.taken) for p in qs])

    def test_exclude_refunded(self):
        """should exclude refunded items from the taken count"""
        self.transaction.refund()
        qs = self.viewset.get_queryset()
        self.assertEqual([1, 1], [int(p.taken) for p in qs])

    def test_exclude_transferred(self):
        """should exclude transferred items from the taken count"""
        for item in self.order3.bought_items.all():
            item.status = BoughtItem.TRANSFERRED
            item.save()
        qs = self.viewset.get_queryset()
        self.assertEqual([1, 2], [int(p.taken) for p in qs])
Exemple #19
0
class ItemOptionViewSetTestCase(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        self.transaction = TransactionFactory(
            event=event, order=self.order, amount=130,
            method=Transaction.CHECK, is_confirmed=False)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30, discount_type='percent',
                                   event=event, item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(self.transaction)

        order2 = OrderFactory(event=event, email='*****@*****.**')
        order2.add_to_cart(item_option2)
        transaction2 = TransactionFactory(event=event, order=self.order,
                                          amount=130, method=Transaction.CHECK,
                                          is_confirmed=True)
        order2.mark_cart_paid(transaction2)

        self.order3 = OrderFactory(event=event, email='*****@*****.**')
        self.order3.add_to_cart(item_option1)
        transaction3 = TransactionFactory(event=event, order=self.order3,
                                          amount=130, method=Transaction.CHECK,
                                          is_confirmed=True)
        self.order3.mark_cart_paid(transaction3)

        self.viewset = ItemOptionViewSet()
        self.viewset.request = self.factory.get('/')
        self.viewset.request.user = self.order.person

    def test_taken_counts(self):
        qs = self.viewset.get_queryset()
        self.assertEqual([2, 2], [int(p.taken) for p in qs])

    def test_exclude_refunded(self):
        """should exclude refunded items from the taken count"""
        self.transaction.refund()
        qs = self.viewset.get_queryset()
        self.assertEqual([1, 1], [int(p.taken) for p in qs])

    def test_exclude_transferred(self):
        """should exclude transferred items from the taken count"""
        for item in self.order3.bought_items.all():
            item.status = BoughtItem.TRANSFERRED
            item.save()
        qs = self.viewset.get_queryset()
        self.assertEqual([1, 2], [int(p.taken) for p in qs])
Exemple #20
0
    def setUp(self):
        event = EventFactory(collect_housing_data=True)
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        self.attendee = AttendeeFactory(
            order=order,
            bought_items=order.bought_items.all(),
            housing_status='have',
            email='*****@*****.**',
            other_needs='99 mattresses',
            person_avoid='Darth Vader',
            person_prefer='Lando Calrissian',
        )
        self.attendee.ef_cause = [
            EnvironmentalFactorFactory(name='Laughter'),
            EnvironmentalFactorFactory(name='Confusion'),
        ]
        self.attendee.housing_prefer = [
            HousingCategoryFactory(name='Yurt'),
        ]
        self.attendee.ef_avoid = [
            EnvironmentalFactorFactory(name='Ontology'),
            EnvironmentalFactorFactory(name='Gnosticism'),
        ]
        self.attendee.nights.add(
            HousingRequestNightFactory(date=event.start_date))

        attendee_form = CustomFormFactory(event=event, form_type='attendee')
        f1 = CustomFormFieldFactory(form=attendee_form, name='favorite color')
        self.custom_key1 = f1.key
        entry1 = CustomFormEntry.objects.create(
            related_ct=ContentType.objects.get(model='attendee'),
            related_id=self.attendee.id,
            form_field=f1)
        entry1.set_value('ochre')
        entry1.save()

        housing_form = CustomFormFactory(event=event, form_type='housing')
        f2 = CustomFormFieldFactory(form=housing_form, name='floor or bed')
        self.custom_key2 = f2.key
        entry2 = CustomFormEntry.objects.create(
            related_ct=ContentType.objects.get(model='attendee'),
            related_id=self.attendee.pk,
            form_field=f2)
        entry2.set_value('bed')
        entry2.save()

        self.event = event
    def test_needs_housing(self):
        event = EventFactory(collect_housing_data=False)
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        a1 = AttendeeFactory(order=order, bought_items=order.bought_items.all(),
                             housing_status=Attendee.NEED)
        a2 = AttendeeFactory(order=order, bought_items=order.bought_items.all())
        self.assertTrue(a1.needs_housing())
        self.assertFalse(a2.needs_housing())
    def set_up_view(self, orderer=None, is_confirmed=False):
        organization = OrganizationFactory(check_payment_allowed=True)
        OrganizationMember.objects.create(
            person=PersonFactory(),
            organization=organization,
            role=OrganizationMember.OWNER,
        )
        event = EventFactory(
            collect_housing_data=False,
            organization=organization,
            check_postmark_cutoff=timezone.now().date() + timedelta(1),
        )
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        receiver = PersonFactory()
        order_kwargs = dict(event=event)
        if orderer:
            order_kwargs['person'] = orderer
        order = OrderFactory(**order_kwargs)
        order.add_to_cart(item_option)
        transaction = TransactionFactory(event=event,
                                         order=order,
                                         is_confirmed=is_confirmed)
        order.mark_cart_paid(transaction)

        # The BoughtItem should be in the correct state if we've set up this
        # test Order correctly.
        self.assertEqual(order.bought_items.first().status, BoughtItem.BOUGHT)

        view = TransferView()
        view.kwargs = dict(
            event_slug=event.slug,
            organization_slug=organization.slug,
        )
        view.request = self.factory.post(
            '/',
            dict(
                bought_item=order.bought_items.first().pk,
                email=receiver.email,
            ))
        view.request.user = orderer if orderer else AnonymousUser()
        view.event = event
        view.order = order
        view.workflow = RegistrationWorkflow(order=order, event=event)
        view.current_step = view.workflow.steps.get(view.current_step_slug)
        return view
class OrderReceiptMailerWithUnconfirmedCheckPayments(TestCase):
    def setUp(self):
        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        transaction = TransactionFactory(event=event,
                                         order=self.order,
                                         amount=130,
                                         method=Transaction.CHECK,
                                         is_confirmed=False)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30,
                                   discount_type='percent',
                                   event=event,
                                   item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderReceiptMailer(transaction,
                                         site='dancerfly.com',
                                         secure=True)
        self.event = event

    def test_still_time_to_mail_check(self):
        self.event.check_postmark_cutoff = date.today() + timedelta(days=5)
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn("Checks must be postmarked no later than", body)

    def test_past_postmark_cutoff(self):
        self.event.check_postmark_cutoff = date.today() - timedelta(days=5)
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn("Payment was due to be postmarked", body)

    def test_postmark_cutoff_today(self):
        self.event.check_postmark_cutoff = date.today()
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn("postmarked no later than today", body)
Exemple #24
0
    def test_needs_housing(self):
        event = EventFactory(collect_housing_data=False)
        order = OrderFactory(event=event)
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        a1 = AttendeeFactory(order=order,
                             bought_items=order.bought_items.all(),
                             housing_status=Attendee.NEED)
        a2 = AttendeeFactory(order=order,
                             bought_items=order.bought_items.all())
        self.assertTrue(a1.needs_housing())
        self.assertFalse(a2.needs_housing())
    def set_up_view(self, orderer=None, is_confirmed=False):
        organization = OrganizationFactory(check_payment_allowed=True)
        OrganizationMember.objects.create(
            person=PersonFactory(),
            organization=organization,
            role=OrganizationMember.OWNER,
        )
        event = EventFactory(
            collect_housing_data=False,
            organization=organization,
            check_postmark_cutoff=timezone.now().date() + timedelta(1),
        )
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        receiver = PersonFactory()
        order_kwargs = dict(event=event)
        if orderer:
            order_kwargs['person'] = orderer
        order = OrderFactory(**order_kwargs)
        order.add_to_cart(item_option)
        transaction = TransactionFactory(event=event, order=order, is_confirmed=is_confirmed)
        order.mark_cart_paid(transaction)

        # The BoughtItem should be in the correct state if we've set up this
        # test Order correctly.
        self.assertEqual(order.bought_items.first().status, BoughtItem.BOUGHT)

        view = TransferView()
        view.kwargs = dict(
            event_slug=event.slug,
            organization_slug=organization.slug,
        )
        view.request = self.factory.post('/', dict(
            bought_item=order.bought_items.first().pk,
            email=receiver.email,
        ))
        view.request.user = orderer if orderer else AnonymousUser()
        view.event = event
        view.order = order
        view.workflow = RegistrationWorkflow(order=order, event=event)
        view.current_step = view.workflow.steps.get(view.current_step_slug)
        return view
    def setUp(self):
        self.factory = RequestFactory()
        self.owner = Person.objects.create_user(email="*****@*****.**", password="******")
        self.non_owner = Person.objects.create_user(email="*****@*****.**", password="******")
        self.event = EventFactory(collect_housing_data=False)
        OrganizationMember.objects.create(
            person=self.owner,
            organization=self.event.organization,
            role=OrganizationMember.OWNER,
        )
        order = OrderFactory(event=self.event, code='aaaaaaaa')
        self.transaction = TransactionFactory(event=self.event, order=order)
        item = ItemFactory(event=self.event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.add_to_cart(item_option)
        order.mark_cart_paid(self.transaction)

        AttendeeFactory(order=order, bought_items=order.bought_items.all())
class OrderReceiptMailerWithUnconfirmedCheckPayments(TestCase):

    def setUp(self):
        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        transaction = TransactionFactory(event=event, order=self.order,
                                         amount=130, method=Transaction.CHECK,
                                         is_confirmed=False)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30, discount_type='percent',
                                   event=event, item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderReceiptMailer(transaction, site='dancerfly.com',
                                         secure=True)
        self.event = event

    def test_still_time_to_mail_check(self):
        self.event.check_postmark_cutoff = date.today() + timedelta(days=5)
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn("Checks must be postmarked no later than", body)

    def test_past_postmark_cutoff(self):
        self.event.check_postmark_cutoff = date.today() - timedelta(days=5)
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn("Payment was due to be postmarked", body)

    def test_postmark_cutoff_today(self):
        self.event.check_postmark_cutoff = date.today()
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn("postmarked no later than today", body)
class AttendeeFilterViewTest(TestCase):
    def setUp(self):
        self.event = EventFactory()
        self.order = OrderFactory(event=self.event)
        self.transaction = TransactionFactory(
            event=self.event,
            order=self.order,
        )
        self.item = ItemFactory(event=self.event)
        self.item_option = ItemOptionFactory(price=100, item=self.item)

        self.order.add_to_cart(self.item_option)
        self.order.mark_cart_paid(self.transaction)

        self.attendee = AttendeeFactory(
            order=self.order,
            bought_items=self.order.bought_items.all(),
        )

        self.view = AttendeeFilterView()
        self.view.event = self.event

    def test_get_queryset__includes_bought(self):
        self.assertEqual(
            list(self.view.get_queryset()),
            [self.attendee],
        )

    def test_get_queryset__excludes_transferred(self):
        """
        Received transferred items use status: BOUGHT. Sent transferred
        items use status: TRANSFERRED. These attendees shouldn't _exist_
        but also shouldn't be displayed if they do.
        """
        self.order.bought_items.update(status=BoughtItem.TRANSFERRED)
        self.assertEqual(
            list(self.view.get_queryset()),
            [],
        )
Exemple #29
0
class AttendeeFilterViewTest(TestCase):
    def setUp(self):
        self.event = EventFactory()
        self.order = OrderFactory(event=self.event)
        self.transaction = TransactionFactory(
            event=self.event,
            order=self.order,
        )
        self.item = ItemFactory(event=self.event)
        self.item_option = ItemOptionFactory(price=100, item=self.item)

        self.order.add_to_cart(self.item_option)
        self.order.mark_cart_paid(self.transaction)

        self.attendee = AttendeeFactory(
            order=self.order,
            bought_items=self.order.bought_items.all(),
        )

        self.view = AttendeeFilterView()
        self.view.event = self.event

    def test_get_queryset__includes_bought(self):
        self.assertEqual(
            list(self.view.get_queryset()),
            [self.attendee],
        )

    def test_get_queryset__excludes_transferred(self):
        """
        Received transferred items use status: BOUGHT. Sent transferred
        items use status: TRANSFERRED. These attendees shouldn't _exist_
        but also shouldn't be displayed if they do.
        """
        self.order.bought_items.update(status=BoughtItem.TRANSFERRED)
        self.assertEqual(
            list(self.view.get_queryset()),
            [],
        )
    def setUp(self):
        self.factory = RequestFactory()
        self.owner = Person.objects.create_user(email="*****@*****.**",
                                                password="******")
        self.non_owner = Person.objects.create_user(
            email="*****@*****.**", password="******")
        self.event = EventFactory(collect_housing_data=False)
        OrganizationMember.objects.create(
            person=self.owner,
            organization=self.event.organization,
            role=OrganizationMember.OWNER,
        )
        order = OrderFactory(event=self.event, code='aaaaaaaa')
        self.transaction = TransactionFactory(event=self.event, order=order)
        item = ItemFactory(event=self.event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.add_to_cart(item_option)
        order.mark_cart_paid(self.transaction)

        AttendeeFactory(order=order, bought_items=order.bought_items.all())
    def setUp(self):
        self.factory = RequestFactory()
        owner = PersonFactory()
        self.event = EventFactory(collect_housing_data=False)
        OrganizationMember.objects.create(
            person=owner,
            organization=self.event.organization,
            role=OrganizationMember.OWNER,
        )
        order = OrderFactory(event=self.event, code='aaaaaaaa')
        self.transaction = TransactionFactory(event=self.event, order=order)
        item = ItemFactory(event=self.event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.add_to_cart(item_option)
        order.mark_cart_paid(self.transaction)

        AttendeeFactory(order=order, bought_items=order.bought_items.all())

        self.view = SendReceiptView()
        self.view.request = self.factory.get('/')
        self.view.request.user = owner
    def setUp(self):
        self.factory = RequestFactory()
        owner = PersonFactory()
        self.event = EventFactory(collect_housing_data=False)
        OrganizationMember.objects.create(
            person=owner,
            organization=self.event.organization,
            role=OrganizationMember.OWNER,
        )
        order = OrderFactory(event=self.event, code='aaaaaaaa')
        self.transaction = TransactionFactory(event=self.event, order=order)
        item = ItemFactory(event=self.event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.add_to_cart(item_option)
        order.mark_cart_paid(self.transaction)

        AttendeeFactory(order=order, bought_items=order.bought_items.all())

        self.view = SendReceiptView()
        self.view.request = self.factory.get('/')
        self.view.request.user = owner
Exemple #33
0
    def setUp(self):
        self.factory = RequestFactory()

        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        self.transaction = TransactionFactory(
            event=event, order=self.order, amount=130,
            method=Transaction.CHECK, is_confirmed=False)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30, discount_type='percent',
                                   event=event, item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(self.transaction)

        order2 = OrderFactory(event=event, email='*****@*****.**')
        order2.add_to_cart(item_option2)
        transaction2 = TransactionFactory(event=event, order=self.order,
                                          amount=130, method=Transaction.CHECK,
                                          is_confirmed=True)
        order2.mark_cart_paid(transaction2)

        self.order3 = OrderFactory(event=event, email='*****@*****.**')
        self.order3.add_to_cart(item_option1)
        transaction3 = TransactionFactory(event=event, order=self.order3,
                                          amount=130, method=Transaction.CHECK,
                                          is_confirmed=True)
        self.order3.mark_cart_paid(transaction3)

        self.viewset = ItemOptionViewSet()
        self.viewset.request = self.factory.get('/')
        self.viewset.request.user = self.order.person
    def setUp(self):
        self.factory = RequestFactory()

        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        self.transaction = TransactionFactory(
            event=event, order=self.order, amount=130,
            method=Transaction.CHECK, is_confirmed=False)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30, discount_type='percent',
                                   event=event, item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(self.transaction)

        order2 = OrderFactory(event=event, email='*****@*****.**')
        order2.add_to_cart(item_option2)
        transaction2 = TransactionFactory(event=event, order=self.order,
                                          amount=130, method=Transaction.CHECK,
                                          is_confirmed=True)
        order2.mark_cart_paid(transaction2)

        self.order3 = OrderFactory(event=event, email='*****@*****.**')
        self.order3.add_to_cart(item_option1)
        transaction3 = TransactionFactory(event=event, order=self.order3,
                                          amount=130, method=Transaction.CHECK,
                                          is_confirmed=True)
        self.order3.mark_cart_paid(transaction3)

        self.viewset = ItemOptionViewSet()
        self.viewset.request = self.factory.get('/')
        self.viewset.request.user = self.order.person
class OrderReceiptMailerForNonUserTestCase(TestCase):

    def setUp(self):
        event = EventFactory()
        self.order = OrderFactory(event=event, email='*****@*****.**')
        transaction = TransactionFactory(event=event, order=self.order,
                                         amount=130)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30, discount_type='percent',
                                   event=event, item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderReceiptMailer(transaction, site='dancerfly.com',
                                         secure=True)

    def test_recipients(self):
        self.assertEqual(self.mailer.get_recipients(), [self.order.email])
Exemple #36
0
class OrderReceiptMailerTestCase(TestCase):
    def setUp(self):
        self.person = PersonFactory()
        event = EventFactory()
        owner = PersonFactory()
        OrganizationMember.objects.create(
            person=owner,
            organization=event.organization,
            role=OrganizationMember.OWNER,
        )
        self.order = OrderFactory(event=event, person=self.person)
        transaction = TransactionFactory(event=event,
                                         order=self.order,
                                         amount=130)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30,
                                   discount_type='percent',
                                   event=event,
                                   item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderAlertMailer(transaction,
                                       site='dancerfly.com',
                                       secure=True)
        self.event_name = event.name
        self.discount_amount = format_money(discount.amount, event.currency)
        self.total_amount = format_money(transaction.amount, event.currency)
        self.option1 = '{0} ({1})'.format(item.name, item_option1.name)
        self.option2 = '{0} ({1})'.format(item.name, item_option1.name)
        self.item_price = format_money(item_option1.price, event.currency)

    def test_render_plaintext(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn(self.total_amount, body)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)
        self.assertNotIn("outstanding check payments", body)

    def test_render_inlined(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       inlined=True)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)
        self.assertIn(self.total_amount, body)

    def test_recipients(self):
        self.assertSequenceEqual(
            self.mailer.get_recipients(),
            [self.order.event.organization.members.get().email])

    def test_recipients__notify_never(self):
        person = self.order.event.organization.members.get()
        person.notify_new_purchases = 'never'
        person.save()
        self.assertSequenceEqual(self.mailer.get_recipients(), [])

    def test_recipients__notify_daily(self):
        person = self.order.event.organization.members.get()
        person.notify_new_purchases = 'daily'
        person.save()
        self.assertSequenceEqual(self.mailer.get_recipients(), [])

    def test_subject(self):
        subject = self.mailer.render_subject(self.mailer.get_context_data())
        expected_subject = (
            '[{event_name}] New purchase by {person_name}'.format(
                event_name=self.event_name,
                person_name=self.person.get_full_name()))
        self.assertEqual(subject, expected_subject)

    def test_body_non_inlined_non_plaintext(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       inlined=False,
                                       plaintext=False)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)
        self.assertIn(self.total_amount, body)

    def test_subject_apostrophe(self):
        event = EventFactory(name="Han & Leia's Wedding!")
        self.person = PersonFactory(first_name="Ma'ayan", last_name="Plaut")
        self.event_name = event.name
        self.order = OrderFactory(event=event, person=self.person)
        transaction = TransactionFactory(event=event,
                                         order=self.order,
                                         amount=130)
        self.mailer = OrderAlertMailer(transaction,
                                       site='dancerfly.com',
                                       secure=True)
        subject = self.mailer.render_subject(self.mailer.get_context_data())
        expected_subject = (
            '[{event_name}] New purchase by {person_name}'.format(
                event_name=self.event_name,
                person_name=self.person.get_full_name()))
        self.assertEqual(subject, expected_subject)
Exemple #37
0
    def test_summary_data__transfer(self):
        """Items sent or received in a transfer shouldn't count towards net cost and savings"""
        event = EventFactory()
        order = OrderFactory(
            event=event,
            person=PersonFactory(),
        )
        person2 = PersonFactory()
        transaction = TransactionFactory(
            event=event,
            order=order,
            is_confirmed=True,
            transaction_type=Transaction.PURCHASE,
            amount=80,
        )
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)
        discount = DiscountFactory(amount=20,
                                   event=event,
                                   item_options=[item_option])

        order.add_to_cart(item_option)
        order.add_discount(discount)
        order.mark_cart_paid(transaction)

        bought_item = transaction.bought_items.get()
        invite = TransferInvite.get_or_create(
            request=Mock(user=person2, session={}),
            email=person2.email,
            content=bought_item,
        )[0]
        invite.accept()

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], -20)
        self.assertEqual(summary_data['total_refunds'], 0)
        self.assertEqual(summary_data['total_payments'], 80)
        self.assertEqual(summary_data['net_cost'], 80)
        self.assertEqual(summary_data['net_balance'], 0)
        self.assertEqual(summary_data['unconfirmed_check_payments'], False)
        transactions = summary_data['transactions']
        self.assertEqual(len(transactions), 2)
        transfer_txn, transfer_txn_dict = transactions.items()[0]
        self.assertEqual(transfer_txn.transaction_type, Transaction.TRANSFER)
        self.assertEqual(transfer_txn_dict['items'], [bought_item])
        self.assertEqual(transfer_txn_dict['gross_cost'], 0)
        self.assertEqual(transfer_txn_dict['discounts'], [])
        self.assertEqual(transfer_txn_dict['total_savings'], 0)
        self.assertEqual(transfer_txn_dict['net_cost'], 0)
        purchase_txn, purchase_txn_dict = transactions.items()[1]
        self.assertEqual(purchase_txn.transaction_type, Transaction.PURCHASE)
        self.assertEqual(purchase_txn_dict['items'], [bought_item])
        self.assertEqual(purchase_txn_dict['gross_cost'], 100)
        self.assertEqual(purchase_txn_dict['discounts'],
                         [bought_item.discounts.first()])
        self.assertEqual(purchase_txn_dict['total_savings'], -20)
        self.assertEqual(purchase_txn_dict['net_cost'], 80)

        order2 = Order.objects.get(event=event, person=person2)
        summary_data2 = order2.get_summary_data()
        self.assertEqual(summary_data2['gross_cost'], 0)
        self.assertEqual(summary_data2['total_savings'], 0)
        self.assertEqual(summary_data2['total_refunds'], 0)
        self.assertEqual(summary_data2['total_payments'], 0)
        self.assertEqual(summary_data2['net_cost'], 0)
        self.assertEqual(summary_data2['net_balance'], 0)
        self.assertEqual(summary_data2['unconfirmed_check_payments'], False)
        transactions2 = summary_data2['transactions']
        self.assertEqual(len(transactions2), 1)
        transfer_txn2, transfer_txn2_dict = transactions.items()[0]
        self.assertEqual(transfer_txn2.transaction_type, Transaction.TRANSFER)
        self.assertEqual(transfer_txn2_dict['items'], [bought_item])
        self.assertEqual(transfer_txn2_dict['gross_cost'], 0)
        self.assertEqual(transfer_txn2_dict['discounts'], [])
        self.assertEqual(transfer_txn2_dict['total_savings'], 0)
        self.assertEqual(transfer_txn2_dict['net_cost'], 0)
    def setUp(self):
        event = EventFactory(collect_housing_data=True,
                             start_date=now().date() + timedelta(days=2),
                             end_date=now().date() + timedelta(days=2))
        order = OrderFactory(event=event, providing_housing=False)
        housing = EventHousingFactory(event=event,
                                      order=order,
                                      contact_name='Zardoz',
                                      contact_email='*****@*****.**',
                                      contact_phone='111-111-1111',
                                      public_transit_access=True,
                                      person_prefer='Han Solo',
                                      person_avoid='Greedo')
        HousingSlotFactory(eventhousing=housing,
                           date=event.start_date,
                           spaces=1,
                           spaces_max=1)
        HousingSlotFactory(eventhousing=housing,
                           date=event.start_date - timedelta(days=1),
                           spaces=1,
                           spaces_max=1)
        housing.ef_present.add(EnvironmentalFactorFactory(name='Carbonite'))
        housing.ef_present.add(EnvironmentalFactorFactory(name='Sandbarges'))
        housing.ef_avoid.add(EnvironmentalFactorFactory(name='Jedi'))
        housing.ef_avoid.add(EnvironmentalFactorFactory(name='Droids'))
        housing.housing_categories.add(HousingCategoryFactory(name='Palace'))
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        self.attendee = AttendeeFactory(
            order=order,
            bought_items=order.bought_items.all(),
            housing_status='have',
            email='*****@*****.**',
            other_needs='99 mattresses',
            person_avoid='Darth Vader',
            person_prefer='Lando Calrissian',
        )
        self.attendee.ef_cause = [
            EnvironmentalFactorFactory(name='Laughter'),
            EnvironmentalFactorFactory(name='Confusion'),
        ]
        self.attendee.housing_prefer = [
            HousingCategoryFactory(name='Yurt'),
        ]
        self.attendee.ef_avoid = [
            EnvironmentalFactorFactory(name='Ontology'),
            EnvironmentalFactorFactory(name='Gnosticism'),
        ]
        self.attendee.nights.add(
            HousingRequestNightFactory(date=event.start_date))

        housing_form = CustomFormFactory(event=event, form_type='hosting')
        field = CustomFormFieldFactory(form=housing_form, name='bed condition')
        self.custom_key = field.key
        entry2 = CustomFormEntry.objects.create(
            related_ct=ContentType.objects.get(model='eventhousing'),
            related_id=housing.pk,
            form_field=field)
        entry2.set_value('unmade')
        entry2.save()

        self.event = event
        self.order = order
Exemple #39
0
class OrderDetailViewTest(TestCase):
    def setUp(self):
        self.owner = Person.objects.create_user(email="*****@*****.**",
                                                password="******")
        self.non_owner = Person.objects.create_user(
            email="*****@*****.**", password="******")
        self.event = EventFactory(collect_housing_data=False)
        OrganizationMember.objects.create(
            person=self.owner,
            organization=self.event.organization,
            role=OrganizationMember.OWNER,
        )
        self.order = OrderFactory(event=self.event, code='aaaaaaaa')
        self.transaction = TransactionFactory(event=self.event,
                                              order=self.order)
        item = ItemFactory(event=self.event)
        item_option = ItemOptionFactory(price=100, item=item)

        self.order.add_to_cart(item_option)
        self.order.add_to_cart(item_option)
        self.order.mark_cart_paid(self.transaction)

        self.attendee = AttendeeFactory(
            order=self.order, bought_items=self.order.bought_items.all())
        self.url = reverse('brambling_event_order_detail',
                           kwargs={
                               'event_slug': self.event.slug,
                               'organization_slug':
                               self.event.organization.slug,
                               'code': self.order.code,
                           })

    def test_post__order_notes(self):
        self.client.login(username=self.owner.email, password='******')
        response = self.client.post(
            self.url,
            {
                'is_notes_form': '1',
                'notes': 'Hello',
            },
        )

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], self.url)
        self.order.refresh_from_db()
        self.assertEqual(self.order.notes, 'Hello')

    def test_post__attendee_notes(self):
        self.client.login(username=self.owner.email, password='******')
        response = self.client.post(
            self.url,
            {
                'is_attendee_form': '1',
                'attendee_id': str(self.attendee.pk),
                'notes': 'Hello',
            },
        )

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], self.url)
        self.attendee.refresh_from_db()
        self.assertEqual(self.attendee.notes, 'Hello')
class MergeUnclaimableOrderTest(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        self.view = MergeOrderView()

        event = EventFactory(collect_housing_data=True)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        self.person = PersonFactory()
        self.order1 = OrderFactory(event=event, person=self.person)
        self.order2 = OrderFactory(event=event, person=None,
                                   email=self.person.email)

        self.tr1 = TransactionFactory(event=event, order=self.order1)
        self.tr2 = TransactionFactory(event=event, order=self.order2)

        self.order1.add_to_cart(item_option)
        self.order1.mark_cart_paid(self.tr1)

        self.order2.add_to_cart(item_option)
        self.order2.add_to_cart(item_option)
        self.order2.mark_cart_paid(self.tr2)

        self.att1 = AttendeeFactory(
            order=self.order1, bought_items=self.order1.bought_items.all(),
            email='*****@*****.**')
        self.att2 = AttendeeFactory(
            order=self.order2, bought_items=self.order2.bought_items.all(),
            email='*****@*****.**')

        self.housing2 = EventHousingFactory(
            event=event, order=self.order2, contact_name='Picard',
            contact_email='*****@*****.**', contact_phone='111-111-1111',
            public_transit_access=True, person_prefer='Dr. Crusher',
            person_avoid='Wesley Crusher')

        self.attendee1 = AttendeeFactory(order=self.order1)
        self.attendee2 = AttendeeFactory(order=self.order2)

        self.view.request = self.factory.post('/', {'pk': self.order2.pk})
        self.view.request.user = self.person

        setattr(self.view.request, 'session', 'session')
        messages = FallbackStorage(self.view.request)
        setattr(self.view.request, '_messages', messages)

    def test_should_redirect(self):
        response = self.view.post(self.view.request)

        self.assertEqual(response.status_code, 302)

    def test_should_transfer_transactions_to_new_order(self):
        self.view.post(self.view.request)

        self.tr2 = Transaction.objects.get(pk=self.tr2.pk)
        self.assertEqual(self.tr2.order, self.order1)

    def test_should_transfer_bought_items_to_new_order(self):
        self.view.post(self.view.request)

        self.assertEqual(self.order1.bought_items.count(), 3)
        for item in self.tr2.bought_items.all():
            self.assertEqual(item.order, self.order1)

    def test_should_transfer_attendees_to_new_order(self):
        self.view.post(self.view.request)

        self.att2 = Attendee.objects.get(pk=self.att2.pk)
        self.assertEqual(self.att2.order, self.order1)

    def test_should_delete_old_order(self):
        self.view.post(self.view.request)

        with self.assertRaises(Order.DoesNotExist):
            Order.objects.get(pk=self.order2.pk)

    def test_should_transfer_eventhousing_if_none_present(self):
        self.view.post(self.view.request)

        self.order1 = Order.objects.get(pk=self.order1.pk)

        self.assertEqual(self.order1.get_eventhousing(), self.housing2)

    def test_should_not_transfer_eventhousing_if_present(self):
        housing1 = EventHousingFactory(
            event=self.order1.event, order=self.order1, contact_name='Riker',
            contact_email='*****@*****.**', contact_phone='111-111-1111',
            public_transit_access=True, person_prefer='Troi',
            person_avoid='Worf')
        self.view.post(self.view.request)

        self.order1 = Order.objects.get(pk=self.order1.pk)
        self.assertEqual(self.order1.get_eventhousing(), housing1)
    def test_summary_data__transfer(self):
        """Items sent or received in a transfer shouldn't count towards net cost and savings"""
        event = EventFactory()
        order = OrderFactory(
            event=event,
            person=PersonFactory(),
        )
        person2 = PersonFactory()
        transaction = TransactionFactory(
            event=event,
            order=order,
            is_confirmed=True,
            transaction_type=Transaction.PURCHASE,
            amount=80,
        )
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)
        discount = DiscountFactory(amount=20, event=event, item_options=[item_option])

        order.add_to_cart(item_option)
        order.add_discount(discount)
        order.mark_cart_paid(transaction)

        bought_item = transaction.bought_items.get()
        invite = TransferInvite.get_or_create(
            request=Mock(user=person2, session={}),
            email=person2.email,
            content=bought_item,
        )[0]
        invite.accept()

        summary_data = order.get_summary_data()
        self.assertEqual(summary_data['gross_cost'], 100)
        self.assertEqual(summary_data['total_savings'], -20)
        self.assertEqual(summary_data['total_refunds'], 0)
        self.assertEqual(summary_data['total_payments'], 80)
        self.assertEqual(summary_data['net_cost'], 80)
        self.assertEqual(summary_data['net_balance'], 0)
        self.assertEqual(summary_data['unconfirmed_check_payments'], False)
        transactions = summary_data['transactions']
        self.assertEqual(len(transactions), 2)
        transfer_txn, transfer_txn_dict = transactions.items()[0]
        self.assertEqual(transfer_txn.transaction_type, Transaction.TRANSFER)
        self.assertEqual(transfer_txn_dict['items'], [bought_item])
        self.assertEqual(transfer_txn_dict['gross_cost'], 0)
        self.assertEqual(transfer_txn_dict['discounts'], [])
        self.assertEqual(transfer_txn_dict['total_savings'], 0)
        self.assertEqual(transfer_txn_dict['net_cost'], 0)
        purchase_txn, purchase_txn_dict = transactions.items()[1]
        self.assertEqual(purchase_txn.transaction_type, Transaction.PURCHASE)
        self.assertEqual(purchase_txn_dict['items'], [bought_item])
        self.assertEqual(purchase_txn_dict['gross_cost'], 100)
        self.assertEqual(purchase_txn_dict['discounts'], [bought_item.discounts.first()])
        self.assertEqual(purchase_txn_dict['total_savings'], -20)
        self.assertEqual(purchase_txn_dict['net_cost'], 80)

        order2 = Order.objects.get(event=event, person=person2)
        summary_data2 = order2.get_summary_data()
        self.assertEqual(summary_data2['gross_cost'], 0)
        self.assertEqual(summary_data2['total_savings'], 0)
        self.assertEqual(summary_data2['total_refunds'], 0)
        self.assertEqual(summary_data2['total_payments'], 0)
        self.assertEqual(summary_data2['net_cost'], 0)
        self.assertEqual(summary_data2['net_balance'], 0)
        self.assertEqual(summary_data2['unconfirmed_check_payments'], False)
        transactions2 = summary_data2['transactions']
        self.assertEqual(len(transactions2), 1)
        transfer_txn2, transfer_txn2_dict = transactions.items()[0]
        self.assertEqual(transfer_txn2.transaction_type, Transaction.TRANSFER)
        self.assertEqual(transfer_txn2_dict['items'], [bought_item])
        self.assertEqual(transfer_txn2_dict['gross_cost'], 0)
        self.assertEqual(transfer_txn2_dict['discounts'], [])
        self.assertEqual(transfer_txn2_dict['total_savings'], 0)
        self.assertEqual(transfer_txn2_dict['net_cost'], 0)
class OrderReceiptMailerTestCase(TestCase):
    def setUp(self):
        self.person = PersonFactory()
        event = EventFactory()
        self.order = OrderFactory(event=event, person=self.person)
        transaction = TransactionFactory(event=event,
                                         order=self.order,
                                         amount=130)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30,
                                   discount_type='percent',
                                   event=event,
                                   item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderReceiptMailer(transaction,
                                         site='dancerfly.com',
                                         secure=True)
        self.event_name = event.name
        self.discount_amount = format_money(discount.amount, event.currency)
        self.total_amount = format_money(transaction.amount, event.currency)
        self.option1 = '{0} ({1})'.format(item.name, item_option1.name)
        self.option2 = '{0} ({1})'.format(item.name, item_option1.name)
        self.item_price = format_money(item_option1.price, event.currency)

    def test_render_plaintext(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn(self.total_amount, body)
        self.assertIn(self.discount_amount, body)
        self.assertIn(self.item_price, body)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)

    def test_render_inlined(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       inlined=True)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)
        self.assertIn(self.item_price, body)
        self.assertIn(self.discount_amount, body)
        self.assertIn(self.total_amount, body)

    def test_recipients(self):
        self.assertEqual(self.mailer.get_recipients(), [self.person.email])

    def test_subject(self):
        subject = self.mailer.render_subject(self.mailer.get_context_data())
        expected_subject = (
            '[{event_name}] Receipt for order {order_code}'.format(
                event_name=self.event_name, order_code=self.order.code))
        self.assertEqual(subject, expected_subject)

    def test_body_non_inlined_non_plaintext(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       inlined=False,
                                       plaintext=False)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)
        self.assertIn(self.item_price, body)
        self.assertIn(self.discount_amount, body)
        self.assertIn(self.total_amount, body)

    def test_subject_apostrophe(self):
        event = EventFactory(name="Han & Leia's Wedding")
        self.event_name = event.name
        self.order = OrderFactory(event=event, person=self.person)
        transaction = TransactionFactory(event=event,
                                         order=self.order,
                                         amount=130)
        self.mailer = OrderReceiptMailer(transaction,
                                         site='dancerfly.com',
                                         secure=True)
        subject = self.mailer.render_subject(self.mailer.get_context_data())
        expected_subject = (
            '[{event_name}] Receipt for order {order_code}'.format(
                event_name=self.event_name, order_code=self.order.code))
        self.assertEqual(subject, expected_subject)
class SuccessfulRefundWebhookTestCase(TestCase):
    @vcr.use_cassette(os.path.join(VCR_DIR, 'stripe_webhook_refund_success.yaml'))
    def setUp(self):
        stripe_prep(TEST)

        self.event = EventFactory()
        self.order = OrderFactory(event=self.event)

        self.factory = RequestFactory()
        self.view = StripeWebhookView.as_view()
        self.stripe_event = {'id': 'evt_123_event_id'}
        self.data = json.dumps(self.stripe_event)

        self.request = self.factory.post(path='/',
                                         content_type='application/json',
                                         data=self.data)

        item = ItemFactory(event=self.event)
        item_option = ItemOptionFactory(price=60, item=item)
        self.order.add_to_cart(item_option)

        token = stripe.Token.create(
            card={
                'number': '4242424242424242',
                'exp_month': 12,
                'exp_year': 2017,
                'cvc': '123'
            },
        )

        charge = stripe_charge(token, 100, self.order, self.event)

        self.txn = Transaction.from_stripe_charge(
            charge,
            event=self.event,
            order=self.order,
            api_type=self.event.api_type,
        )

        self.refund = stripe_refund(self.order, self.event, charge.id, 100)

        data = mock.Mock(object=mock.Mock(name='charge', id=charge.id))
        self.mock_event = mock.Mock(
            data=data,
            type='charge.refunded',
            livemode=False,
        )
        self.order.mark_cart_paid(self.txn)

    @skipUnless(os.environ.get('STRIPE_TEST_APPLICATION_ID'), 'stripe test settings required')
    @mock.patch('stripe.Event.retrieve')
    def test_transaction_refunded_successfully(self, event_retrieve):
        event_retrieve.return_value = self.mock_event
        response = self.view(self.request)

        refund = Transaction.objects.get(
            related_transaction=self.txn,
            transaction_type=Transaction.REFUND,
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(refund.amount, -100)
        self.assertEqual(refund.application_fee, -2.5)
        self.assertEqual(refund.method, Transaction.STRIPE)
        self.assertEqual(refund.order, self.order)
        self.assertEqual(refund.event, self.event)

    @skipUnless(os.environ.get('STRIPE_TEST_APPLICATION_ID'), 'stripe test settings required')
    @mock.patch('stripe.Event.retrieve')
    def test_events_should_be_processed_exactly_once(self, event_retrieve):
        event_retrieve.return_value = self.mock_event
        response1 = self.view(self.request)
        response2 = self.view(self.request)

        self.assertEqual(response1.status_code, 200)
        self.assertEqual(response2.status_code, 200)
        Transaction.objects.get(related_transaction=self.txn,
                                transaction_type=Transaction.REFUND)

    @skipUnless(os.environ.get('STRIPE_TEST_APPLICATION_ID'), 'stripe test settings required')
    @mock.patch('stripe.Event.retrieve')
    def test_events_should_be_processed_exactly_once_in_livemode(self, event_retrieve):
        self.mock_event.livemode = True
        self.txn.api_type = Transaction.LIVE
        self.txn.save()
        event_retrieve.return_value = self.mock_event

        response1 = self.view(self.request)
        response2 = self.view(self.request)

        self.assertEqual(response1.status_code, 200)
        self.assertEqual(response2.status_code, 200)
        Transaction.objects.get(related_transaction=self.txn,
                                transaction_type=Transaction.REFUND)

    @skipUnless(os.environ.get('STRIPE_TEST_APPLICATION_ID'), 'stripe test settings required')
    @mock.patch('stripe.Event.retrieve')
    def test_events_should_be_logged_in_test_mode(self, event_retrieve):
        event_retrieve.return_value = self.mock_event
        self.view(self.request)
        ProcessedStripeEvent.objects.get(
            api_type=ProcessedStripeEvent.TEST,
            stripe_event_id=self.stripe_event['id'],
        )

    @mock.patch('stripe.Event.retrieve')
    def test_events_should_be_logged_in_live_mode(self, event_retrieve):
        self.mock_event.livemode = True
        event_retrieve.return_value = self.mock_event
        self.view(self.request)
        ProcessedStripeEvent.objects.get(
            api_type=ProcessedStripeEvent.LIVE,
            stripe_event_id=self.stripe_event['id'],
        )
Exemple #44
0
class AttendeeTableTestCase(TestCase):

    def setUp(self):
        self.event = EventFactory(collect_housing_data=True)
        self.item = ItemFactory(event=self.event)
        self.item_option = ItemOptionFactory(price=100, item=self.item)

        self.order = OrderFactory(event=self.event)
        self.transaction = TransactionFactory(
            event=self.event,
            order=self.order,
        )
        self.order.add_to_cart(self.item_option)
        self.order.mark_cart_paid(self.transaction)

        self.attendee = AttendeeFactory(
            order=self.order,
            bought_items=self.order.bought_items.all(),
            housing_status='have',
            email='*****@*****.**',
            other_needs='99 mattresses',
            person_avoid='Darth Vader',
            person_prefer='Lando Calrissian',
        )
        self.attendee.ef_cause = [
            EnvironmentalFactorFactory(name='Laughter'),
            EnvironmentalFactorFactory(name='Confusion'),
        ]
        self.attendee.housing_prefer = [
            HousingCategoryFactory(name='Yurt'),
        ]
        self.attendee.ef_avoid = [
            EnvironmentalFactorFactory(name='Ontology'),
            EnvironmentalFactorFactory(name='Gnosticism'),
        ]
        self.attendee.nights.add(HousingRequestNightFactory(date=self.event.start_date))

        attendee_form = CustomFormFactory(event=self.event, form_type='attendee')
        f1 = CustomFormFieldFactory(form=attendee_form, name='favorite color')
        self.custom_key1 = f1.key
        entry1 = CustomFormEntry.objects.create(
            related_ct=ContentType.objects.get(model='attendee'),
            related_id=self.attendee.id,
            form_field=f1)
        entry1.set_value('ochre')
        entry1.save()

        housing_form = CustomFormFactory(event=self.event, form_type='housing')
        f2 = CustomFormFieldFactory(form=housing_form, name='floor or bed')
        self.custom_key2 = f2.key
        entry2 = CustomFormEntry.objects.create(
            related_ct=ContentType.objects.get(model='attendee'),
            related_id=self.attendee.pk,
            form_field=f2)
        entry2.set_value('bed')
        entry2.save()

    def test_blank_housing_fields_if_attendee_does_not_need_housing(self):
        table = AttendeeTable(self.event)

        for row in table:
            self.assertEqual(row['other_needs_if_needed'].value, '')
            self.assertEqual(row['housing_nights'].value, '')
            self.assertEqual(row['housing_preferences'].value, '')
            self.assertEqual(row['environment_avoid'].value, '')
            self.assertEqual(row['environment_cause'].value, '')
            self.assertEqual(row['person_prefer_if_needed'].value, '')
            self.assertEqual(row['person_avoid_if_needed'].value, '')
            self.assertEqual(row[self.custom_key2].value, '')

    def test__show_non_housing_form_data_if_attendee_needs_housing(self):
        table = AttendeeTable(self.event)
        for row in table:
            self.assertEqual(row[self.custom_key1].value, 'ochre')

    def test_show_non_housing_form_data_if_attendee_does_not_need_housing(self):
        self.attendee.housing_status = 'need'
        self.attendee.save()
        table = AttendeeTable(self.event)
        for row in table:
            self.assertEqual(row[self.custom_key1].value, 'ochre')

    def test_filled_housing_fields_if_attendee_needs_housing(self):
        self.attendee.housing_status = 'need'
        self.attendee.save()
        table = AttendeeTable(self.event)

        for row in table:
            self.assertNotEqual(row['other_needs_if_needed'].value, '')
            self.assertNotEqual(row['housing_nights'].value, '')
            self.assertNotEqual(row['housing_preferences'].value, '')
            self.assertNotEqual(row['environment_avoid'].value, '')
            self.assertNotEqual(row['environment_cause'].value, '')
            self.assertNotEqual(row['person_prefer_if_needed'].value, '')
            self.assertNotEqual(row['person_avoid_if_needed'].value, '')
            self.assertNotEqual(row[self.custom_key2].value, '')

    def test_purchase_date_field(self):
        table = AttendeeTable(
            event=self.event,
            data={
                TABLE_COLUMN_FIELD: ['pk', 'purchase_date'],
            },
        )
        row = list(table)[0]
        self.assertEqual(
            row['purchase_date'].value,
            format_as_localtime(
                self.transaction.timestamp,
                '%Y-%m-%d %H:%M',
                self.event.timezone,
            ),
        )

    def test_order_by_purchase_date(self):
        """
        If ordering by purchase date is selected, we should get that
        ordering even if the field isn't selected.

        """
        order2 = OrderFactory(event=self.event)
        transaction = TransactionFactory(
            event=self.event,
            order=order2,
            timestamp=timezone.now() - datetime.timedelta(days=50)
        )
        order2.add_to_cart(self.item_option)
        order2.mark_cart_paid(transaction)
        attendee2 = AttendeeFactory(
            order=order2,
            bought_items=order2.bought_items.all(),
            housing_status='have',
            email='*****@*****.**',
            other_needs='99 mattresses',
            person_avoid='Darth Vader',
            person_prefer='Han Solo',
        )

        table = AttendeeTable(
            event=self.event,
            data={
                'o': '-purchase_date',
                TABLE_COLUMN_FIELD: ['pk', 'get_full_name'],
            },
        )
        rows = list(table)
        self.assertEqual(rows[0]['pk'].value, self.attendee.pk)
        self.assertEqual(rows[1]['pk'].value, attendee2.pk)
class OrderReceiptMailerTestCase(TestCase):

    def setUp(self):
        self.person = PersonFactory()
        event = EventFactory()
        owner = PersonFactory()
        OrganizationMember.objects.create(
            person=owner,
            organization=event.organization,
            role=OrganizationMember.OWNER,
        )
        self.order = OrderFactory(event=event, person=self.person)
        transaction = TransactionFactory(event=event, order=self.order,
                                         amount=130)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30, discount_type='percent',
                                   event=event, item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderAlertMailer(transaction, site='dancerfly.com',
                                       secure=True)
        self.event_name = event.name
        self.discount_amount = format_money(discount.amount, event.currency)
        self.total_amount = format_money(transaction.amount, event.currency)
        self.option1 = '{0} ({1})'.format(item.name, item_option1.name)
        self.option2 = '{0} ({1})'.format(item.name, item_option1.name)
        self.item_price = format_money(item_option1.price, event.currency)

    def test_render_plaintext(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn(self.total_amount, body)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)
        self.assertNotIn("outstanding check payments", body)

    def test_render_inlined(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       inlined=True)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)
        self.assertIn(self.total_amount, body)

    def test_recipients(self):
        self.assertSequenceEqual(self.mailer.get_recipients(),
                                 [self.order.event.organization.members.get().email])

    def test_recipients__notify_never(self):
        person = self.order.event.organization.members.get()
        person.notify_new_purchases = 'never'
        person.save()
        self.assertSequenceEqual(self.mailer.get_recipients(),
                                 [])

    def test_recipients__notify_daily(self):
        person = self.order.event.organization.members.get()
        person.notify_new_purchases = 'daily'
        person.save()
        self.assertSequenceEqual(self.mailer.get_recipients(),
                                 [])

    def test_subject(self):
        subject = self.mailer.render_subject(self.mailer.get_context_data())
        expected_subject = ('[{event_name}] New purchase by {person_name}'
                            .format(event_name=self.event_name,
                                    person_name=self.person.get_full_name()))
        self.assertEqual(subject, expected_subject)

    def test_body_non_inlined_non_plaintext(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       inlined=False, plaintext=False)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)
        self.assertIn(self.total_amount, body)

    def test_subject_apostrophe(self):
        event = EventFactory(name="Han & Leia's Wedding!")
        self.person = PersonFactory(first_name="Ma'ayan", last_name="Plaut")
        self.event_name = event.name
        self.order = OrderFactory(event=event, person=self.person)
        transaction = TransactionFactory(event=event, order=self.order, amount=130)
        self.mailer = OrderAlertMailer(transaction, site='dancerfly.com',
                                       secure=True)
        subject = self.mailer.render_subject(self.mailer.get_context_data())
        expected_subject = ('[{event_name}] New purchase by {person_name}'
                            .format(event_name=self.event_name,
                                    person_name=self.person.get_full_name()))
        self.assertEqual(subject, expected_subject)
class SuccessfulRefundWebhookTestCase(TestCase):
    @vcr.use_cassette(
        os.path.join(VCR_DIR, 'stripe_webhook_refund_success.yaml'))
    def setUp(self):
        stripe_prep(TEST)

        self.event = EventFactory()
        self.order = OrderFactory(event=self.event)

        self.factory = RequestFactory()
        self.view = StripeWebhookView.as_view()
        self.stripe_event = {'id': 'evt_123_event_id'}
        self.data = json.dumps(self.stripe_event)

        self.request = self.factory.post(path='/',
                                         content_type='application/json',
                                         data=self.data)

        item = ItemFactory(event=self.event)
        item_option = ItemOptionFactory(price=60, item=item)
        self.order.add_to_cart(item_option)

        token = stripe.Token.create(card={
            'number': '4242424242424242',
            'exp_month': 12,
            'exp_year': 2017,
            'cvc': '123'
        }, )

        charge = stripe_charge(token, 100, self.order, self.event)

        self.txn = Transaction.from_stripe_charge(
            charge,
            event=self.event,
            order=self.order,
            api_type=self.event.api_type,
        )

        self.refund = stripe_refund(self.order, self.event, charge.id, 100)

        data = mock.Mock(object=mock.Mock(name='charge', id=charge.id))
        self.mock_event = mock.Mock(
            data=data,
            type='charge.refunded',
            livemode=False,
        )
        self.order.mark_cart_paid(self.txn)

    @skipUnless(os.environ.get('STRIPE_TEST_APPLICATION_ID'),
                'stripe test settings required')
    @mock.patch('stripe.Event.retrieve')
    def test_transaction_refunded_successfully(self, event_retrieve):
        event_retrieve.return_value = self.mock_event
        response = self.view(self.request)

        refund = Transaction.objects.get(
            related_transaction=self.txn,
            transaction_type=Transaction.REFUND,
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(refund.amount, -100)
        self.assertEqual(refund.application_fee, -2.5)
        self.assertEqual(refund.method, Transaction.STRIPE)
        self.assertEqual(refund.order, self.order)
        self.assertEqual(refund.event, self.event)

    @skipUnless(os.environ.get('STRIPE_TEST_APPLICATION_ID'),
                'stripe test settings required')
    @mock.patch('stripe.Event.retrieve')
    def test_events_should_be_processed_exactly_once(self, event_retrieve):
        event_retrieve.return_value = self.mock_event
        response1 = self.view(self.request)
        response2 = self.view(self.request)

        self.assertEqual(response1.status_code, 200)
        self.assertEqual(response2.status_code, 200)
        Transaction.objects.get(related_transaction=self.txn,
                                transaction_type=Transaction.REFUND)

    @skipUnless(os.environ.get('STRIPE_TEST_APPLICATION_ID'),
                'stripe test settings required')
    @mock.patch('stripe.Event.retrieve')
    def test_events_should_be_processed_exactly_once_in_livemode(
            self, event_retrieve):
        self.mock_event.livemode = True
        self.txn.api_type = Transaction.LIVE
        self.txn.save()
        event_retrieve.return_value = self.mock_event

        response1 = self.view(self.request)
        response2 = self.view(self.request)

        self.assertEqual(response1.status_code, 200)
        self.assertEqual(response2.status_code, 200)
        Transaction.objects.get(related_transaction=self.txn,
                                transaction_type=Transaction.REFUND)

    @skipUnless(os.environ.get('STRIPE_TEST_APPLICATION_ID'),
                'stripe test settings required')
    @mock.patch('stripe.Event.retrieve')
    def test_events_should_be_logged_in_test_mode(self, event_retrieve):
        event_retrieve.return_value = self.mock_event
        self.view(self.request)
        ProcessedStripeEvent.objects.get(
            api_type=ProcessedStripeEvent.TEST,
            stripe_event_id=self.stripe_event['id'],
        )

    @mock.patch('stripe.Event.retrieve')
    def test_events_should_be_logged_in_live_mode(self, event_retrieve):
        self.mock_event.livemode = True
        event_retrieve.return_value = self.mock_event
        self.view(self.request)
        ProcessedStripeEvent.objects.get(
            api_type=ProcessedStripeEvent.LIVE,
            stripe_event_id=self.stripe_event['id'],
        )
Exemple #47
0
class MergeUnclaimableOrderTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.view = MergeOrderView()

        event = EventFactory(collect_housing_data=True)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        self.person = PersonFactory()
        self.order1 = OrderFactory(event=event, person=self.person)
        self.order2 = OrderFactory(event=event,
                                   person=None,
                                   email=self.person.email)

        self.tr1 = TransactionFactory(event=event, order=self.order1)
        self.tr2 = TransactionFactory(event=event, order=self.order2)

        self.order1.add_to_cart(item_option)
        self.order1.mark_cart_paid(self.tr1)

        self.order2.add_to_cart(item_option)
        self.order2.add_to_cart(item_option)
        self.order2.mark_cart_paid(self.tr2)

        self.att1 = AttendeeFactory(
            order=self.order1,
            bought_items=self.order1.bought_items.all(),
            email='*****@*****.**')
        self.att2 = AttendeeFactory(
            order=self.order2,
            bought_items=self.order2.bought_items.all(),
            email='*****@*****.**')

        self.housing2 = EventHousingFactory(
            event=event,
            order=self.order2,
            contact_name='Picard',
            contact_email='*****@*****.**',
            contact_phone='111-111-1111',
            public_transit_access=True,
            person_prefer='Dr. Crusher',
            person_avoid='Wesley Crusher')

        self.attendee1 = AttendeeFactory(order=self.order1)
        self.attendee2 = AttendeeFactory(order=self.order2)

        self.view.request = self.factory.post('/', {'pk': self.order2.pk})
        self.view.request.user = self.person

        setattr(self.view.request, 'session', 'session')
        messages = FallbackStorage(self.view.request)
        setattr(self.view.request, '_messages', messages)

    def test_should_redirect(self):
        response = self.view.post(self.view.request)

        self.assertEqual(response.status_code, 302)

    def test_should_transfer_transactions_to_new_order(self):
        self.view.post(self.view.request)

        self.tr2 = Transaction.objects.get(pk=self.tr2.pk)
        self.assertEqual(self.tr2.order, self.order1)

    def test_should_transfer_bought_items_to_new_order(self):
        self.view.post(self.view.request)

        self.assertEqual(self.order1.bought_items.count(), 3)
        for item in self.tr2.bought_items.all():
            self.assertEqual(item.order, self.order1)

    def test_should_transfer_attendees_to_new_order(self):
        self.view.post(self.view.request)

        self.att2 = Attendee.objects.get(pk=self.att2.pk)
        self.assertEqual(self.att2.order, self.order1)

    def test_should_delete_old_order(self):
        self.view.post(self.view.request)

        with self.assertRaises(Order.DoesNotExist):
            Order.objects.get(pk=self.order2.pk)

    def test_should_transfer_eventhousing_if_none_present(self):
        self.view.post(self.view.request)

        self.order1 = Order.objects.get(pk=self.order1.pk)

        self.assertEqual(self.order1.get_eventhousing(), self.housing2)

    def test_should_not_transfer_eventhousing_if_present(self):
        housing1 = EventHousingFactory(event=self.order1.event,
                                       order=self.order1,
                                       contact_name='Riker',
                                       contact_email='*****@*****.**',
                                       contact_phone='111-111-1111',
                                       public_transit_access=True,
                                       person_prefer='Troi',
                                       person_avoid='Worf')
        self.view.post(self.view.request)

        self.order1 = Order.objects.get(pk=self.order1.pk)
        self.assertEqual(self.order1.get_eventhousing(), housing1)
class OrderReceiptMailerTestCase(TestCase):

    def setUp(self):
        self.person = PersonFactory()
        event = EventFactory()
        self.order = OrderFactory(event=event, person=self.person)
        transaction = TransactionFactory(event=event, order=self.order,
                                         amount=130)
        item = ItemFactory(event=event, name='Multipass')
        item_option1 = ItemOptionFactory(price=100, item=item, name='Gold')
        item_option2 = ItemOptionFactory(price=60, item=item, name='Silver')

        discount = DiscountFactory(amount=30, discount_type='percent',
                                   event=event, item_options=[item_option1])

        self.order.add_to_cart(item_option1)
        self.order.add_to_cart(item_option2)
        self.order.add_discount(discount)
        self.order.mark_cart_paid(transaction)

        self.mailer = OrderReceiptMailer(transaction, site='dancerfly.com',
                                         secure=True)
        self.event_name = event.name
        self.discount_amount = format_money(discount.amount, event.currency)
        self.total_amount = format_money(transaction.amount, event.currency)
        self.option1 = '{0} ({1})'.format(item.name, item_option1.name)
        self.option2 = '{0} ({1})'.format(item.name, item_option1.name)
        self.item_price = format_money(item_option1.price, event.currency)

    def test_render_plaintext(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       plaintext=True)
        self.assertIn(self.total_amount, body)
        self.assertIn(self.discount_amount, body)
        self.assertIn(self.item_price, body)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)

    def test_render_inlined(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       inlined=True)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)
        self.assertIn(self.item_price, body)
        self.assertIn(self.discount_amount, body)
        self.assertIn(self.total_amount, body)

    def test_recipients(self):
        self.assertEqual(self.mailer.get_recipients(), [self.person.email])

    def test_subject(self):
        subject = self.mailer.render_subject(self.mailer.get_context_data())
        expected_subject = ('[{event_name}] Receipt for order {order_code}'
                            .format(event_name=self.event_name,
                                    order_code=self.order.code))
        self.assertEqual(subject, expected_subject)

    def test_body_non_inlined_non_plaintext(self):
        body = self.mailer.render_body(self.mailer.get_context_data(),
                                       inlined=False, plaintext=False)
        self.assertIn(self.option1, body)
        self.assertIn(self.option2, body)
        self.assertIn(self.item_price, body)
        self.assertIn(self.discount_amount, body)
        self.assertIn(self.total_amount, body)

    def test_subject_apostrophe(self):
        event = EventFactory(name="Han & Leia's Wedding")
        self.event_name = event.name
        self.order = OrderFactory(event=event, person=self.person)
        transaction = TransactionFactory(event=event, order=self.order,
                                         amount=130)
        self.mailer = OrderReceiptMailer(transaction, site='dancerfly.com',
                                         secure=True)
        subject = self.mailer.render_subject(self.mailer.get_context_data())
        expected_subject = ('[{event_name}] Receipt for order {order_code}'
                            .format(event_name=self.event_name,
                                    order_code=self.order.code))
        self.assertEqual(subject, expected_subject)
    def setUp(self):
        event = EventFactory(
            collect_housing_data=True,
            start_date=now().date() + timedelta(days=2),
            end_date=now().date() + timedelta(days=2)
        )
        order = OrderFactory(event=event, providing_housing=False)
        housing = EventHousingFactory(
            event=event, order=order, contact_name='Zardoz',
            contact_email='*****@*****.**', contact_phone='111-111-1111',
            public_transit_access=True, person_prefer='Han Solo',
            person_avoid='Greedo')
        HousingSlotFactory(eventhousing=housing, date=event.start_date,
                           spaces=1, spaces_max=1)
        HousingSlotFactory(eventhousing=housing,
                           date=event.start_date - timedelta(days=1),
                           spaces=1, spaces_max=1)
        housing.ef_present.add(EnvironmentalFactorFactory(name='Carbonite'))
        housing.ef_present.add(EnvironmentalFactorFactory(name='Sandbarges'))
        housing.ef_avoid.add(EnvironmentalFactorFactory(name='Jedi'))
        housing.ef_avoid.add(EnvironmentalFactorFactory(name='Droids'))
        housing.housing_categories.add(HousingCategoryFactory(name='Palace'))
        transaction = TransactionFactory(event=event, order=order)
        item = ItemFactory(event=event)
        item_option = ItemOptionFactory(price=100, item=item)

        order.add_to_cart(item_option)
        order.mark_cart_paid(transaction)

        self.attendee = AttendeeFactory(
            order=order,
            bought_items=order.bought_items.all(),
            housing_status='have',
            email='*****@*****.**',
            other_needs='99 mattresses',
            person_avoid='Darth Vader',
            person_prefer='Lando Calrissian',
        )
        self.attendee.ef_cause = [
            EnvironmentalFactorFactory(name='Laughter'),
            EnvironmentalFactorFactory(name='Confusion'),
        ]
        self.attendee.housing_prefer = [
            HousingCategoryFactory(name='Yurt'),
        ]
        self.attendee.ef_avoid = [
            EnvironmentalFactorFactory(name='Ontology'),
            EnvironmentalFactorFactory(name='Gnosticism'),
        ]
        self.attendee.nights.add(HousingRequestNightFactory(date=event.start_date))

        housing_form = CustomFormFactory(event=event, form_type='hosting')
        field = CustomFormFieldFactory(form=housing_form, name='bed condition')
        self.custom_key = field.key
        entry2 = CustomFormEntry.objects.create(
            related_ct=ContentType.objects.get(model='eventhousing'),
            related_id=housing.pk,
            form_field=field)
        entry2.set_value('unmade')
        entry2.save()

        self.event = event
        self.order = order