def test_add_with_default_mode(self): """ Tests add_to_cart where the mode specified in the argument is NOT in the database and NOT the default "honor". In this case it just adds the user in the CourseMode.DEFAULT_MODE, 0 price """ reg1 = PaidCourseRegistration.add_to_order(self.cart, self.course_key, mode_slug="DNE") self.assertEqual(reg1.unit_cost, 0) self.assertEqual(reg1.line_cost, 0) self.assertEqual(reg1.mode, "honor") self.assertEqual(reg1.user, self.user) self.assertEqual(reg1.status, "cart") self.assertEqual(self.cart.total_cost, 0) self.assertTrue( PaidCourseRegistration.contained_in_order(self.cart, self.course_key)) course_reg_code_item = CourseRegCodeItem.add_to_order(self.cart, self.course_key, 2, mode_slug="DNE") self.assertEqual(course_reg_code_item.unit_cost, 0) self.assertEqual(course_reg_code_item.line_cost, 0) self.assertEqual(course_reg_code_item.mode, "honor") self.assertEqual(course_reg_code_item.user, self.user) self.assertEqual(course_reg_code_item.status, "cart") self.assertEqual(self.cart.total_cost, 0) self.assertTrue( CourseRegCodeItem.contained_in_order(self.cart, self.course_key))
def test_reg_code_with_multiple_courses_and_checkout_scenario(self): self.add_reg_code(self.course_key) # Two courses in user shopping cart self.login_user() PaidCourseRegistration.add_to_order(self.cart, self.course_key) PaidCourseRegistration.add_to_order(self.cart, self.testing_course.id) self.assertEquals(self.cart.orderitem_set.count(), 2) resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.reg_code}) self.assertEqual(resp.status_code, 200) resp = self.client.get(reverse('shoppingcart.views.show_cart', args=[])) self.assertIn('Check Out', resp.content) self.cart.purchase(first='FirstNameTesting123', street1='StreetTesting123') resp = self.client.get(reverse('shoppingcart.views.show_receipt', args=[self.cart.id])) self.assertEqual(resp.status_code, 200) ((template, context), _) = render_mock.call_args # pylint: disable=W0621 self.assertEqual(template, 'shoppingcart/receipt.html') self.assertEqual(context['order'], self.cart) self.assertEqual(context['order'].total_cost, self.testing_cost) course_enrollment = CourseEnrollment.objects.filter(user=self.user) self.assertEqual(course_enrollment.count(), 2)
def test_user_has_finance_admin_rights_in_e_commerce_tab(self): response = self.client.get(self.url) self.assertTrue(self.e_commerce_link in response.content) # Total amount html should render in e-commerce page, total amount will be 0 total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item( self.course.id) self.assertTrue('<span>Total Amount: <span>$' + str(total_amount) + '</span></span>' in response.content) self.assertTrue('Download All e-Commerce Purchase' in response.content) # removing the course finance_admin role of login user CourseFinanceAdminRole(self.course.id).remove_users(self.instructor) # total amount should not be visible in e-commerce page if the user is not finance admin url = reverse( 'instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url) total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item( self.course.id) self.assertFalse( 'Download All e-Commerce Purchase' in response.content) self.assertFalse('<span>Total Amount: <span>$' + str(total_amount) + '</span></span>' in response.content)
def test_user_cart_has_paid_course_registration_items(self): cart = Order.get_cart_for_user(self.user) item = PaidCourseRegistration(order=cart, user=self.user) item.save() self.assertTrue( Order.user_cart_has_items(self.user, PaidCourseRegistration)) self.assertFalse(Order.user_cart_has_items(self.user, CertificateItem))
def test_clear_cart(self): self.login_user() PaidCourseRegistration.add_to_order(self.cart, self.course_key) CertificateItem.add_to_order(self.cart, self.verified_course_key, self.cost, 'honor') self.assertEquals(self.cart.orderitem_set.count(), 2) resp = self.client.post(reverse('shoppingcart.views.clear_cart', args=[])) self.assertEqual(resp.status_code, 200) self.assertEquals(self.cart.orderitem_set.count(), 0)
def add_to_cart(self): """ Adds content to self.user's cart """ course = CourseFactory.create(org='MITx', number='999', display_name='Robot Super Course') CourseModeFactory.create(course_id=course.id) cart = Order.get_cart_for_user(self.user) PaidCourseRegistration.add_to_order(cart, course.id)
def add_to_cart(self): """ Adds content to self.user's cart """ course = CourseFactory.create(org='MITx', number='999', display_name='Robot Super Course') CourseModeFactory(course_id=course.id) cart = Order.get_cart_for_user(self.user) PaidCourseRegistration.add_to_order(cart, course.id)
def test_user_cart_has_both_items(self): """ This test exists b/c having both CertificateItem and PaidCourseRegistration in an order used to break PaidCourseRegistration.contained_in_order """ cart = Order.get_cart_for_user(self.user) CertificateItem.add_to_order(cart, self.course_key, self.cost, 'honor') PaidCourseRegistration.add_to_order(self.cart, self.course_key) self.assertTrue(PaidCourseRegistration.contained_in_order(cart, self.course_key))
def test_add_course_to_cart_already_in_cart(self): PaidCourseRegistration.add_to_order(self.cart, self.course_key) self.login_user() resp = self.client.post( reverse("shoppingcart.views.add_course_to_cart", args=[self.course_key.to_deprecated_string()]) ) self.assertEqual(resp.status_code, 400) self.assertIn( "The course {0} is already in your cart.".format(self.course_key.to_deprecated_string()), resp.content )
def test_add_course_to_cart_already_in_cart(self): PaidCourseRegistration.add_to_order(self.cart, self.course_id) self.login_user() resp = self.client.post( reverse('shoppingcart.views.add_course_to_cart', args=[self.course_id])) self.assertEqual(resp.status_code, 400) self.assertIn( _('The course {0} is already in your cart.'.format( self.course_id)), resp.content)
def test_report_csv(self): PaidCourseRegistration.add_to_order(self.cart, self.course_id) self.cart.purchase() self.login_user() self.add_to_download_group(self.user) response = self.client.post(reverse('payment_csv_report'), {'start_date': '1970-01-01', 'end_date': '2100-01-01'}) self.assertEqual(response['Content-Type'], 'text/csv') self.assertIn(",".join(OrderItem.csv_report_header_row()), response.content) self.assertIn(self.CORRECT_CSV_NO_DATE, response.content)
def change_enrollment(strategy, user=None, *args, **kwargs): """Enroll a user in a course. If a user entered the authentication flow when trying to enroll in a course, then attempt to enroll the user. We will try to do this if the pipeline was started with the querystring param `enroll_course_id`. In the following cases, we can't enroll the user: * The course does not have an honor mode. * The course has an honor mode with a minimum price. * The course is not yet open for enrollment. * The course does not exist. If we can't enroll the user now, then skip this step. For paid courses, users will be redirected to the payment flow upon completion of the authentication pipeline (configured using the ?next parameter to the third party auth login url). """ enroll_course_id = strategy.session_get('enroll_course_id') if enroll_course_id: course_id = CourseKey.from_string(enroll_course_id) modes = CourseMode.modes_for_course_dict(course_id) # If the email opt in parameter is found, set the preference. email_opt_in = strategy.session_get(AUTH_EMAIL_OPT_IN_KEY) if email_opt_in: opt_in = email_opt_in.lower() == 'true' profile.update_email_opt_in(user.username, course_id.org, opt_in) if CourseMode.can_auto_enroll(course_id, modes_dict=modes): try: CourseEnrollment.enroll(user, course_id, check_access=True) except CourseEnrollmentException: pass except Exception as ex: logger.exception(ex) # Handle white-label courses as a special case # If a course is white-label, we should add it to the shopping cart. elif CourseMode.is_white_label(course_id, modes_dict=modes): try: cart = Order.get_cart_for_user(user) PaidCourseRegistration.add_to_order(cart, course_id) except ( CourseDoesNotExistException, ItemAlreadyInCartException, AlreadyEnrolledInCourseException ): pass # It's more important to complete login than to # ensure that the course was added to the shopping cart. # Log errors, but don't stop the authentication pipeline. except Exception as ex: logger.exception(ex)
def test_add_to_order(self): reg1 = PaidCourseRegistration.add_to_order(self.cart, self.course_id) self.assertEqual(reg1.unit_cost, self.cost) self.assertEqual(reg1.line_cost, self.cost) self.assertEqual(reg1.unit_cost, self.course_mode.min_price) self.assertEqual(reg1.mode, "honor") self.assertEqual(reg1.user, self.user) self.assertEqual(reg1.status, "cart") self.assertTrue(PaidCourseRegistration.part_of_order(self.cart, self.course_id)) self.assertFalse(PaidCourseRegistration.part_of_order(self.cart, self.course_id + "abcd")) self.assertEqual(self.cart.total_cost, self.cost)
def test_add_to_order(self): reg1 = PaidCourseRegistration.add_to_order(self.cart, self.course_id) self.assertEqual(reg1.unit_cost, self.cost) self.assertEqual(reg1.line_cost, self.cost) self.assertEqual(reg1.unit_cost, self.course_mode.min_price) self.assertEqual(reg1.mode, "honor") self.assertEqual(reg1.user, self.user) self.assertEqual(reg1.status, "cart") self.assertTrue(PaidCourseRegistration.contained_in_order(self.cart, self.course_id)) self.assertFalse(PaidCourseRegistration.contained_in_order(self.cart, self.course_id + "abcd")) self.assertEqual(self.cart.total_cost, self.cost)
def test_add_to_order(self): reg1 = PaidCourseRegistration.add_to_order(self.cart, self.course_key) self.assertEqual(reg1.unit_cost, self.cost) self.assertEqual(reg1.line_cost, self.cost) self.assertEqual(reg1.unit_cost, self.course_mode.min_price) self.assertEqual(reg1.mode, "honor") self.assertEqual(reg1.user, self.user) self.assertEqual(reg1.status, "cart") self.assertTrue(PaidCourseRegistration.contained_in_order(self.cart, self.course_key)) self.assertFalse(PaidCourseRegistration.contained_in_order(self.cart, SlashSeparatedCourseKey("MITx", "999", "Robot_Super_Course_abcd"))) self.assertEqual(self.cart.total_cost, self.cost)
def test_report_csv_too_long(self): PaidCourseRegistration.add_to_order(self.cart, self.course_id) self.cart.purchase() self.login_user() self.add_to_download_group(self.user) response = self.client.post(reverse('payment_csv_report'), {'start_date': '1970-01-01', 'end_date': '2100-01-01'}) ((template, context), unused_kwargs) = render_mock.call_args self.assertEqual(template, 'shoppingcart/download_report.html') self.assertTrue(context['total_count_error']) self.assertFalse(context['date_fmt_error']) self.assertIn(_("There are too many results in your report.") + " (>0)", response.content)
def test_report_csv(self): PaidCourseRegistration.add_to_order(self.cart, self.course_id) self.cart.purchase() self.login_user() self.add_to_download_group(self.user) response = self.client.post(reverse('payment_csv_report'), { 'start_date': '1970-01-01', 'end_date': '2100-01-01' }) self.assertEqual(response['Content-Type'], 'text/csv') self.assertIn(",".join(OrderItem.csv_report_header_row()), response.content) self.assertIn(self.CORRECT_CSV_NO_DATE, response.content)
def change_enrollment(strategy, user=None, *args, **kwargs): """Enroll a user in a course. If a user entered the authentication flow when trying to enroll in a course, then attempt to enroll the user. We will try to do this if the pipeline was started with the querystring param `enroll_course_id`. In the following cases, we can't enroll the user: * The course does not have an honor mode. * The course has an honor mode with a minimum price. * The course is not yet open for enrollment. * The course does not exist. If we can't enroll the user now, then skip this step. For paid courses, users will be redirected to the payment flow upon completion of the authentication pipeline (configured using the ?next parameter to the third party auth login url). """ enroll_course_id = strategy.session_get('enroll_course_id') if enroll_course_id: course_id = CourseKey.from_string(enroll_course_id) modes = CourseMode.modes_for_course_dict(course_id) # If the email opt in parameter is found, set the preference. email_opt_in = strategy.session_get(AUTH_EMAIL_OPT_IN_KEY) if email_opt_in: opt_in = email_opt_in.lower() == 'true' profile.update_email_opt_in(user.username, course_id.org, opt_in) if CourseMode.can_auto_enroll(course_id, modes_dict=modes): try: CourseEnrollment.enroll(user, course_id, check_access=True) except CourseEnrollmentException: pass except Exception as ex: logger.exception(ex) # Handle white-label courses as a special case # If a course is white-label, we should add it to the shopping cart. elif CourseMode.is_white_label(course_id, modes_dict=modes): try: cart = Order.get_cart_for_user(user) PaidCourseRegistration.add_to_order(cart, course_id) except (CourseDoesNotExistException, ItemAlreadyInCartException, AlreadyEnrolledInCourseException): pass # It's more important to complete login than to # ensure that the course was added to the shopping cart. # Log errors, but don't stop the authentication pipeline. except Exception as ex: logger.exception(ex)
def test_already_in_cart(self): """ This makes sure if a user has this course in the cart, that the expected message appears """ self.setup_user() cart = Order.get_cart_for_user(self.user) PaidCourseRegistration.add_to_order(cart, self.course.id) url = reverse('about_course', args=[text_type(self.course.id)]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("This course is in your", resp.content) self.assertNotIn("Add buyme to Cart <span>($10 USD)</span>", resp.content)
def test_already_in_cart(self): """ This makes sure if a user has this course in the cart, that the expected message appears """ self.setup_user() cart = Order.get_cart_for_user(self.user) PaidCourseRegistration.add_to_order(cart, self.course.id) url = reverse('about_course', args=[self.course.id.to_deprecated_string()]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("This course is in your", resp.content) self.assertNotIn("Add buyme to Cart ($10)", resp.content)
def test_add_with_default_mode(self): """ Tests add_to_cart where the mode specified in the argument is NOT in the database and NOT the default "honor". In this case it just adds the user in the CourseMode.DEFAULT_MODE, 0 price """ reg1 = PaidCourseRegistration.add_to_order(self.cart, self.course_id, mode_slug="DNE") self.assertEqual(reg1.unit_cost, 0) self.assertEqual(reg1.line_cost, 0) self.assertEqual(reg1.mode, "honor") self.assertEqual(reg1.user, self.user) self.assertEqual(reg1.status, "cart") self.assertEqual(self.cart.total_cost, 0) self.assertTrue(PaidCourseRegistration.part_of_order(self.cart, self.course_id))
def test_report_csv_itemized(self): report_type = 'itemized_purchase_report' start_date = '1970-01-01' end_date = '2100-01-01' PaidCourseRegistration.add_to_order(self.cart, self.course_key) self.cart.purchase() self.login_user() self.add_to_download_group(self.user) response = self.client.post(reverse('payment_csv_report'), {'start_date': start_date, 'end_date': end_date, 'requested_report': report_type}) self.assertEqual(response['Content-Type'], 'text/csv') report = initialize_report(report_type, start_date, end_date) self.assertIn(",".join(report.header()), response.content) self.assertIn(self.CORRECT_CSV_NO_DATE_ITEMIZED_PURCHASE, response.content)
def setUp(self): self.user = UserFactory.create() self.course_id = "MITx/999/Robot_Super_Course" self.cost = 40 self.course = CourseFactory.create(org='MITx', number='999', display_name=u'Robot Super Course') course_mode = CourseMode(course_id=self.course_id, mode_slug="honor", mode_display_name="honor cert", min_price=self.cost) course_mode.save() course_mode2 = CourseMode(course_id=self.course_id, mode_slug="verified", mode_display_name="verified cert", min_price=self.cost) course_mode2.save() self.annotation = PaidCourseRegistrationAnnotation( course_id=self.course_id, annotation=self.TEST_ANNOTATION) self.annotation.save() self.cart = Order.get_cart_for_user(self.user) self.reg = PaidCourseRegistration.add_to_order(self.cart, self.course_id) self.cert_item = CertificateItem.add_to_order(self.cart, self.course_id, self.cost, 'verified') self.cart.purchase() self.now = datetime.datetime.now(pytz.UTC)
def test_report_csv_itemized(self): report_type = "itemized_purchase_report" start_date = "1970-01-01" end_date = "2100-01-01" PaidCourseRegistration.add_to_order(self.cart, self.course_id) self.cart.purchase() self.login_user() self.add_to_download_group(self.user) response = self.client.post( reverse("payment_csv_report"), {"start_date": start_date, "end_date": end_date, "requested_report": report_type}, ) self.assertEqual(response["Content-Type"], "text/csv") report = initialize_report(report_type, start_date, end_date) self.assertIn(",".join(report.header()), response.content) self.assertIn(self.CORRECT_CSV_NO_DATE_ITEMIZED_PURCHASE, response.content)
def test_show_receipt_404s(self): PaidCourseRegistration.add_to_order(self.cart, self.course_key) CertificateItem.add_to_order(self.cart, self.verified_course_key, self.cost, 'honor') self.cart.purchase() user2 = UserFactory.create() cart2 = Order.get_cart_for_user(user2) PaidCourseRegistration.add_to_order(cart2, self.course_key) cart2.purchase() self.login_user() resp = self.client.get(reverse('shoppingcart.views.show_receipt', args=[cart2.id])) self.assertEqual(resp.status_code, 404) resp2 = self.client.get(reverse('shoppingcart.views.show_receipt', args=[1000])) self.assertEqual(resp2.status_code, 404)
def test_purchased_callback_exception(self): reg1 = PaidCourseRegistration.add_to_order(self.cart, self.course_key) reg1.course_id = CourseLocator(org="changed", course="forsome", run="reason") reg1.save() with self.assertRaises(PurchasedCallbackException): reg1.purchased_callback() self.assertFalse( CourseEnrollment.is_enrolled(self.user, self.course_key)) reg1.course_id = CourseLocator(org="abc", course="efg", run="hij") reg1.save() with self.assertRaises(PurchasedCallbackException): reg1.purchased_callback() self.assertFalse( CourseEnrollment.is_enrolled(self.user, self.course_key)) course_reg_code_item = CourseRegCodeItem.add_to_order( self.cart, self.course_key, 2) course_reg_code_item.course_id = CourseLocator(org="changed1", course="forsome1", run="reason1") course_reg_code_item.save() with self.assertRaises(PurchasedCallbackException): course_reg_code_item.purchased_callback()
def test_remove_item(self, exception_log): self.login_user() reg_item = PaidCourseRegistration.add_to_order(self.cart, self.course_id) cert_item = CertificateItem.add_to_order(self.cart, self.verified_course_id, self.cost, 'honor') self.assertEquals(self.cart.orderitem_set.count(), 2) resp = self.client.post( reverse('shoppingcart.views.remove_item', args=[]), {'id': reg_item.id}) self.assertEqual(resp.status_code, 200) self.assertEquals(self.cart.orderitem_set.count(), 1) self.assertNotIn(reg_item, self.cart.orderitem_set.all().select_subclasses()) self.cart.purchase() resp2 = self.client.post( reverse('shoppingcart.views.remove_item', args=[]), {'id': cert_item.id}) self.assertEqual(resp2.status_code, 200) exception_log.assert_called_with( 'Cannot remove cart OrderItem id={0}. DoesNotExist or item is already purchased' .format(cert_item.id)) resp3 = self.client.post( reverse('shoppingcart.views.remove_item', args=[]), {'id': -1}) self.assertEqual(resp3.status_code, 200) exception_log.assert_called_with( 'Cannot remove cart OrderItem id={0}. DoesNotExist or item is already purchased' .format(-1))
def add_course_to_user_cart(self, course_key): """ adding course to user cart """ self.login_user() reg_item = PaidCourseRegistration.add_to_order(self.cart, course_key) return reg_item
def add_course_to_user_cart(self): """ adding course to user cart """ self.login_user() reg_item = PaidCourseRegistration.add_to_order(self.cart, self.course_key) return reg_item
def test_user_has_finance_admin_rights_in_e_commerce_tab(self): response = self.client.get(self.url) self.assertTrue(self.e_commerce_link in response.content) # Total amount html should render in e-commerce page, total amount will be 0 total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course.id) self.assertTrue('<span>Total Amount: <span>$' + str(total_amount) + '</span></span>' in response.content) # removing the course finance_admin role of login user CourseFinanceAdminRole(self.course.id).remove_users(self.instructor) # total amount should not be visible in e-commerce page if the user is not finance admin url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url) total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course.id) self.assertFalse('<span>Total Amount: <span>$' + str(total_amount) + '</span></span>' in response.content)
def _section_e_commerce(course_key, access): """ Provide data for the corresponding dashboard section """ coupons = Coupon.objects.filter(course_id=course_key).order_by('-is_active') total_amount = None course_price = None course_honor_mode = CourseMode.mode_for_course(course_key, 'honor') if course_honor_mode and course_honor_mode.min_price > 0: course_price = course_honor_mode.min_price if access['finance_admin']: total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(course_key) section_data = { 'section_key': 'e-commerce', 'section_display_name': _('E-Commerce'), 'access': access, 'course_id': course_key.to_deprecated_string(), 'ajax_remove_coupon_url': reverse('remove_coupon', kwargs={'course_id': course_key.to_deprecated_string()}), 'ajax_get_coupon_info': reverse('get_coupon_info', kwargs={'course_id': course_key.to_deprecated_string()}), 'ajax_update_coupon': reverse('update_coupon', kwargs={'course_id': course_key.to_deprecated_string()}), 'ajax_add_coupon': reverse('add_coupon', kwargs={'course_id': course_key.to_deprecated_string()}), 'get_purchase_transaction_url': reverse('get_purchase_transaction', kwargs={'course_id': course_key.to_deprecated_string()}), 'instructor_url': reverse('instructor_dashboard', kwargs={'course_id': course_key.to_deprecated_string()}), 'get_registration_code_csv_url': reverse('get_registration_codes', kwargs={'course_id': course_key.to_deprecated_string()}), 'generate_registration_code_csv_url': reverse('generate_registration_codes', kwargs={'course_id': course_key.to_deprecated_string()}), 'active_registration_code_csv_url': reverse('active_registration_codes', kwargs={'course_id': course_key.to_deprecated_string()}), 'spent_registration_code_csv_url': reverse('spent_registration_codes', kwargs={'course_id': course_key.to_deprecated_string()}), 'set_course_mode_url': reverse('set_course_mode_price', kwargs={'course_id': course_key.to_deprecated_string()}), 'coupons': coupons, 'total_amount': total_amount, 'course_price': course_price } return section_data
def test_student_paid_course_enrollment_report(self): """ test to check the paid user enrollment csv report status and enrollment source. """ student = UserFactory() student_cart = Order.get_cart_for_user(student) PaidCourseRegistration.add_to_order(student_cart, self.course.id) student_cart.purchase() task_input = {'features': []} with patch('instructor_task.tasks_helper._get_current_task'): result = upload_enrollment_report(None, None, self.course.id, task_input, 'generating_enrollment_report') self.assertDictContainsSubset({'attempted': 1, 'succeeded': 1, 'failed': 0}, result) self._verify_cell_data_in_csv(student.username, 'Enrollment Source', 'Credit Card - Individual') self._verify_cell_data_in_csv(student.username, 'Payment Status', 'purchased')
def test_student_used_enrollment_code_for_course_enrollment(self): """ test to check the user enrollment source and payment status in the enrollment detailed report """ student = UserFactory() self.client.login(username=student.username, password='******') student_cart = Order.get_cart_for_user(student) paid_course_reg_item = PaidCourseRegistration.add_to_order(student_cart, self.course.id) # update the quantity of the cart item paid_course_reg_item resp = self.client.post(reverse('shoppingcart.views.update_user_cart'), {'ItemId': paid_course_reg_item.id, 'qty': '4'}) self.assertEqual(resp.status_code, 200) student_cart.purchase() course_reg_codes = CourseRegistrationCode.objects.filter(order=student_cart) redeem_url = reverse('register_code_redemption', args=[course_reg_codes[0].code]) response = self.client.get(redeem_url) self.assertEquals(response.status_code, 200) # check button text self.assertTrue('Activate Course Enrollment' in response.content) response = self.client.post(redeem_url) self.assertEquals(response.status_code, 200) task_input = {'features': []} with patch('instructor_task.tasks_helper._get_current_task'): result = upload_enrollment_report(None, None, self.course.id, task_input, 'generating_enrollment_report') self.assertDictContainsSubset({'attempted': 1, 'succeeded': 1, 'failed': 0}, result) self._verify_cell_data_in_csv(student.username, 'Enrollment Source', 'Used Registration Code') self._verify_cell_data_in_csv(student.username, 'Payment Status', 'purchased')
def test_total_credit_cart_sales_amount(self): """ Test to check the total amount for all the credit card purchases. """ student = UserFactory.create() self.client.login(username=student.username, password="******") student_cart = Order.get_cart_for_user(student) item = self.add_course_to_user_cart(student_cart, self.course.id) resp = self.client.post(reverse('shoppingcart.views.update_user_cart'), { 'ItemId': item.id, 'qty': 4 }) self.assertEqual(resp.status_code, 200) student_cart.purchase() self.client.login(username=self.instructor.username, password="******") CourseFinanceAdminRole(self.course.id).add_users(self.instructor) single_purchase_total = PaidCourseRegistration.get_total_amount_of_purchased_item( self.course.id) bulk_purchase_total = CourseRegCodeItem.get_total_amount_of_purchased_item( self.course.id) total_amount = single_purchase_total + bulk_purchase_total response = self.client.get(self.url) self.assertIn( '{currency}{amount}'.format(currency='$', amount=total_amount), response.content)
def test_purchased_callback(self): reg1 = PaidCourseRegistration.add_to_order(self.cart, self.course_id) self.cart.purchase() self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_id)) reg1 = PaidCourseRegistration.objects.get( id=reg1.id) # reload from DB to get side-effect self.assertEqual(reg1.status, "purchased")
def test_default_currency_in_the_html_response(self): """ Test that checks the default currency_symbol ($) in the response """ CourseFinanceAdminRole(self.course.id).add_users(self.instructor) total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course.id) response = self.client.get(self.url) self.assertTrue('${amount}'.format(amount=total_amount) in response.content)
def test_purchased_callback(self): reg1 = PaidCourseRegistration.add_to_order(self.cart, self.course_key) self.cart.purchase() self.assertTrue(CourseEnrollment.is_enrolled(self.user, self.course_key)) reg1 = PaidCourseRegistration.objects.get(id=reg1.id) # reload from DB to get side-effect self.assertEqual(reg1.status, "purchased") self.assertIsNotNone(reg1.course_enrollment) self.assertEqual(reg1.course_enrollment.id, CourseEnrollment.objects.get(user=self.user, course_id=self.course_key).id)
def test_add_course_to_cart_success(self): self.login_user() reverse("shoppingcart.views.add_course_to_cart", args=[self.course_key.to_deprecated_string()]) resp = self.client.post( reverse("shoppingcart.views.add_course_to_cart", args=[self.course_key.to_deprecated_string()]) ) self.assertEqual(resp.status_code, 200) self.assertTrue(PaidCourseRegistration.contained_in_order(self.cart, self.course_key))
def test_override_currency_settings_in_the_html_response(self): """ Test that checks the default currency_symbol ($) in the response """ CourseFinanceAdminRole(self.course.id).add_users(self.instructor) total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course.id) response = self.client.get(self.url) self.assertIn('{currency}{amount}'.format(currency='Rs', amount=total_amount), response.content)
def test_add_course_to_cart_success(self): self.login_user() resp = self.client.post( reverse('shoppingcart.views.add_course_to_cart', args=[self.course_id])) self.assertEqual(resp.status_code, 200) self.assertTrue( PaidCourseRegistration.part_of_order(self.cart, self.course_id))
def test_report_csv_too_long(self): PaidCourseRegistration.add_to_order(self.cart, self.course_id) self.cart.purchase() self.login_user() self.add_to_download_group(self.user) response = self.client.post(reverse('payment_csv_report'), { 'start_date': '1970-01-01', 'end_date': '2100-01-01' }) ((template, context), unused_kwargs) = render_mock.call_args self.assertEqual(template, 'shoppingcart/download_report.html') self.assertTrue(context['total_count_error']) self.assertFalse(context['date_fmt_error']) self.assertIn( _("There are too many results in your report.") + " (>0)", response.content)
def get_enrollment_info(self, user, course_id): """ Returns the User Enrollment information. """ course = get_course_by_id(course_id, depth=0) is_course_staff = bool(has_access(user, 'staff', course)) manual_enrollment_reason = 'N/A' # check the user enrollment role if user.is_staff: platform_name = configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME) enrollment_role = _('{platform_name} Staff').format(platform_name=platform_name) elif is_course_staff: enrollment_role = _('Course Staff') else: enrollment_role = _('Student') course_enrollment = CourseEnrollment.get_enrollment(user=user, course_key=course_id) if is_course_staff: enrollment_source = _('Staff') else: # get the registration_code_redemption object if exists registration_code_redemption = RegistrationCodeRedemption.registration_code_used_for_enrollment( course_enrollment) # get the paid_course registration item if exists paid_course_reg_item = PaidCourseRegistration.get_course_item_for_user_enrollment( user=user, course_id=course_id, course_enrollment=course_enrollment ) # from where the user get here if registration_code_redemption is not None: enrollment_source = _('Used Registration Code') elif paid_course_reg_item is not None: enrollment_source = _('Credit Card - Individual') else: manual_enrollment = ManualEnrollmentAudit.get_manual_enrollment(course_enrollment) if manual_enrollment is not None: enrollment_source = _( 'manually enrolled by username: {username}' ).format(username=manual_enrollment.enrolled_by.username) manual_enrollment_reason = manual_enrollment.reason else: enrollment_source = _('Manually Enrolled') enrollment_date = course_enrollment.created.strftime("%B %d, %Y") currently_enrolled = course_enrollment.is_active course_enrollment_data = collections.OrderedDict() course_enrollment_data['Enrollment Date'] = enrollment_date course_enrollment_data['Currently Enrolled'] = currently_enrolled course_enrollment_data['Enrollment Source'] = enrollment_source course_enrollment_data['Manual (Un)Enrollment Reason'] = manual_enrollment_reason course_enrollment_data['Enrollment Role'] = enrollment_role return course_enrollment_data
def get_enrollment_info(self, user, course_id): """ Returns the User Enrollment information. """ course = get_course_by_id(course_id, depth=0) is_course_staff = bool(has_access(user, 'staff', course)) # check the user enrollment role if user.is_staff: platform_name = microsite.get_value('platform_name', settings.PLATFORM_NAME) enrollment_role = _('{platform_name} Staff').format( platform_name=platform_name) elif is_course_staff: enrollment_role = _('Course Staff') else: enrollment_role = _('Student') course_enrollment = CourseEnrollment.get_enrollment( user=user, course_key=course_id) if is_course_staff: enrollment_source = _('Staff') else: # get the registration_code_redemption object if exists registration_code_redemption = RegistrationCodeRedemption.registration_code_used_for_enrollment( course_enrollment) # get the paid_course registration item if exists paid_course_reg_item = PaidCourseRegistration.get_course_item_for_user_enrollment( user=user, course_id=course_id, course_enrollment=course_enrollment) # from where the user get here if registration_code_redemption is not None: enrollment_source = _('Used Registration Code') elif paid_course_reg_item is not None: enrollment_source = _('Credit Card - Individual') else: manual_enrollment = ManualEnrollmentAudit.get_manual_enrollment( course_enrollment) if manual_enrollment is not None: enrollment_source = _( 'manually enrolled by user_id {user_id}, enrollment state transition: {transition}' ).format(user_id=manual_enrollment.enrolled_by_id, transition=manual_enrollment.state_transition) else: enrollment_source = _('Manually Enrolled') enrollment_date = course_enrollment.created.strftime("%B %d, %Y") currently_enrolled = course_enrollment.is_active course_enrollment_data = collections.OrderedDict() course_enrollment_data['Enrollment Date'] = enrollment_date course_enrollment_data['Currently Enrolled'] = currently_enrolled course_enrollment_data['Enrollment Source'] = enrollment_source course_enrollment_data['Enrollment Role'] = enrollment_role return course_enrollment_data
def test_generate_receipt_instructions(self): """ Add 2 courses to the order and make sure the instruction_set only contains 1 element (no dups) """ course2 = CourseFactory.create(org="MITx", number="998", display_name="Robot Duper Course") course_mode2 = CourseMode( course_id=course2.id, mode_slug="honor", mode_display_name="honor cert", min_price=self.cost ) course_mode2.save() pr1 = PaidCourseRegistration.add_to_order(self.cart, self.course_key) pr2 = PaidCourseRegistration.add_to_order(self.cart, course2.id) self.cart.purchase() inst_dict, inst_set = self.cart.generate_receipt_instructions() self.assertEqual(2, len(inst_dict)) self.assertEqual(1, len(inst_set)) self.assertIn("dashboard", inst_set.pop()) self.assertIn(pr1.pk_with_subclass, inst_dict) self.assertIn(pr2.pk_with_subclass, inst_dict)
def _section_e_commerce(course, access): """ Provide data for the corresponding dashboard section """ course_key = course.id coupons = Coupon.objects.filter(course_id=course_key).order_by("-is_active") total_amount = None course_price = None course_honor_mode = CourseMode.mode_for_course(course_key, "honor") if course_honor_mode and course_honor_mode.min_price > 0: course_price = course_honor_mode.min_price if access["finance_admin"]: total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(course_key) section_data = { "section_key": "e-commerce", "section_display_name": _("E-Commerce"), "access": access, "course_id": course_key.to_deprecated_string(), "ajax_remove_coupon_url": reverse("remove_coupon", kwargs={"course_id": course_key.to_deprecated_string()}), "ajax_get_coupon_info": reverse("get_coupon_info", kwargs={"course_id": course_key.to_deprecated_string()}), "get_user_invoice_preference_url": reverse( "get_user_invoice_preference", kwargs={"course_id": course_key.to_deprecated_string()} ), "sale_validation_url": reverse("sale_validation", kwargs={"course_id": course_key.to_deprecated_string()}), "ajax_update_coupon": reverse("update_coupon", kwargs={"course_id": course_key.to_deprecated_string()}), "ajax_add_coupon": reverse("add_coupon", kwargs={"course_id": course_key.to_deprecated_string()}), "get_purchase_transaction_url": reverse( "get_purchase_transaction", kwargs={"course_id": course_key.to_deprecated_string()} ), "get_sale_records_url": reverse("get_sale_records", kwargs={"course_id": course_key.to_deprecated_string()}), "get_sale_order_records_url": reverse( "get_sale_order_records", kwargs={"course_id": course_key.to_deprecated_string()} ), "instructor_url": reverse("instructor_dashboard", kwargs={"course_id": course_key.to_deprecated_string()}), "get_registration_code_csv_url": reverse( "get_registration_codes", kwargs={"course_id": course_key.to_deprecated_string()} ), "generate_registration_code_csv_url": reverse( "generate_registration_codes", kwargs={"course_id": course_key.to_deprecated_string()} ), "active_registration_code_csv_url": reverse( "active_registration_codes", kwargs={"course_id": course_key.to_deprecated_string()} ), "spent_registration_code_csv_url": reverse( "spent_registration_codes", kwargs={"course_id": course_key.to_deprecated_string()} ), "set_course_mode_url": reverse( "set_course_mode_price", kwargs={"course_id": course_key.to_deprecated_string()} ), "download_coupon_codes_url": reverse( "get_coupon_codes", kwargs={"course_id": course_key.to_deprecated_string()} ), "coupons": coupons, "total_amount": total_amount, "course_price": course_price, } return section_data
def _section_e_commerce(course, access, paid_mode, coupons_enabled, reports_enabled): """ Provide data for the corresponding dashboard section """ course_key = course.id coupons = Coupon.objects.filter(course_id=course_key).order_by("-is_active") course_price = paid_mode.min_price total_amount = None if access["finance_admin"]: single_purchase_total = PaidCourseRegistration.get_total_amount_of_purchased_item(course_key) bulk_purchase_total = CourseRegCodeItem.get_total_amount_of_purchased_item(course_key) total_amount = single_purchase_total + bulk_purchase_total section_data = { "section_key": "e-commerce", "section_display_name": _("E-Commerce"), "access": access, "course_id": unicode(course_key), "currency_symbol": settings.PAID_COURSE_REGISTRATION_CURRENCY[1], "ajax_remove_coupon_url": reverse("remove_coupon", kwargs={"course_id": unicode(course_key)}), "ajax_get_coupon_info": reverse("get_coupon_info", kwargs={"course_id": unicode(course_key)}), "get_user_invoice_preference_url": reverse( "get_user_invoice_preference", kwargs={"course_id": unicode(course_key)} ), "sale_validation_url": reverse("sale_validation", kwargs={"course_id": unicode(course_key)}), "ajax_update_coupon": reverse("update_coupon", kwargs={"course_id": unicode(course_key)}), "ajax_add_coupon": reverse("add_coupon", kwargs={"course_id": unicode(course_key)}), "get_sale_records_url": reverse("get_sale_records", kwargs={"course_id": unicode(course_key)}), "get_sale_order_records_url": reverse("get_sale_order_records", kwargs={"course_id": unicode(course_key)}), "instructor_url": reverse("instructor_dashboard", kwargs={"course_id": unicode(course_key)}), "get_registration_code_csv_url": reverse("get_registration_codes", kwargs={"course_id": unicode(course_key)}), "generate_registration_code_csv_url": reverse( "generate_registration_codes", kwargs={"course_id": unicode(course_key)} ), "active_registration_code_csv_url": reverse( "active_registration_codes", kwargs={"course_id": unicode(course_key)} ), "spent_registration_code_csv_url": reverse( "spent_registration_codes", kwargs={"course_id": unicode(course_key)} ), "set_course_mode_url": reverse("set_course_mode_price", kwargs={"course_id": unicode(course_key)}), "download_coupon_codes_url": reverse("get_coupon_codes", kwargs={"course_id": unicode(course_key)}), "enrollment_report_url": reverse("get_enrollment_report", kwargs={"course_id": unicode(course_key)}), "exec_summary_report_url": reverse("get_exec_summary_report", kwargs={"course_id": unicode(course_key)}), "list_financial_report_downloads_url": reverse( "list_financial_report_downloads", kwargs={"course_id": unicode(course_key)} ), "list_instructor_tasks_url": reverse("list_instructor_tasks", kwargs={"course_id": unicode(course_key)}), "look_up_registration_code": reverse("look_up_registration_code", kwargs={"course_id": unicode(course_key)}), "coupons": coupons, "sales_admin": access["sales_admin"], "coupons_enabled": coupons_enabled, "reports_enabled": reports_enabled, "course_price": course_price, "total_amount": total_amount, } return section_data
def test_generate_receipt_instructions(self): """ Add 2 courses to the order and make sure the instruction_set only contains 1 element (no dups) """ course2 = CourseFactory.create() course_mode2 = CourseMode(course_id=course2.id, mode_slug="honor", mode_display_name="honor cert", min_price=self.cost) course_mode2.save() pr1 = PaidCourseRegistration.add_to_order(self.cart, self.course_key) pr2 = PaidCourseRegistration.add_to_order(self.cart, course2.id) self.cart.purchase() inst_dict, inst_set = self.cart.generate_receipt_instructions() self.assertEqual(2, len(inst_dict)) self.assertEqual(1, len(inst_set)) self.assertIn("dashboard", inst_set.pop()) self.assertIn(pr1.pk_with_subclass, inst_dict) self.assertIn(pr2.pk_with_subclass, inst_dict)
def test_total_amount_of_purchased_course(self): self.add_course_to_user_cart() self.assertEquals(self.cart.orderitem_set.count(), 1) self.add_coupon(self.course_key, True) resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.coupon_code}) self.assertEqual(resp.status_code, 200) self.cart.purchase(first='FirstNameTesting123', street1='StreetTesting123') # Total amount of a particular course that is purchased by different users total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course_key) self.assertEqual(total_amount, 36) self.client.login(username=self.instructor.username, password="******") cart = Order.get_cart_for_user(self.instructor) PaidCourseRegistration.add_to_order(cart, self.course_key) cart.purchase(first='FirstNameTesting123', street1='StreetTesting123') total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course_key) self.assertEqual(total_amount, 76)
def test_total_amount_of_purchased_course(self): self.add_course_to_user_cart(self.course_key) self.assertEquals(self.cart.orderitem_set.count(), 1) self.add_coupon(self.course_key, True, self.coupon_code) resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.coupon_code}) self.assertEqual(resp.status_code, 200) self.cart.purchase(first='FirstNameTesting123', street1='StreetTesting123') # Total amount of a particular course that is purchased by different users total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course_key) self.assertEqual(total_amount, 36) self.client.login(username=self.instructor.username, password="******") cart = Order.get_cart_for_user(self.instructor) PaidCourseRegistration.add_to_order(cart, self.course_key) cart.purchase(first='FirstNameTesting123', street1='StreetTesting123') total_amount = PaidCourseRegistration.get_total_amount_of_purchased_item(self.course_key) self.assertEqual(total_amount, 76)
def test_add_course_to_cart_success(self): self.login_user() reverse('shoppingcart.views.add_course_to_cart', args=[self.course_key.to_deprecated_string()]) resp = self.client.post( reverse('shoppingcart.views.add_course_to_cart', args=[self.course_key.to_deprecated_string()])) self.assertEqual(resp.status_code, 200) self.assertTrue( PaidCourseRegistration.contained_in_order(self.cart, self.course_key))
def test_purchased_callback_exception(self): reg1 = PaidCourseRegistration.add_to_order(self.cart, self.course_id) reg1.course_id = "changedforsomereason" reg1.save() with self.assertRaises(PurchasedCallbackException): reg1.purchased_callback() self.assertFalse(CourseEnrollment.is_enrolled(self.user, self.course_id)) reg1.course_id = "abc/efg/hij" reg1.save() with self.assertRaises(PurchasedCallbackException): reg1.purchased_callback() self.assertFalse(CourseEnrollment.is_enrolled(self.user, self.course_id))