Commit bc2e3a08 by Marko Jevtic

Rename start and end datetime parameters; Refactor update dictionary creation method;

parent b0a67de1
...@@ -137,10 +137,10 @@ class CouponMixin(object): ...@@ -137,10 +137,10 @@ class CouponMixin(object):
'benefit_type': Benefit.PERCENTAGE, 'benefit_type': Benefit.PERCENTAGE,
'benefit_value': benefit_value, 'benefit_value': benefit_value,
'catalog': catalog, 'catalog': catalog,
'end_date': datetime.date(2020, 1, 1), 'end_datetime': datetime.date(2020, 1, 1),
'code': code, 'code': code,
'quantity': quantity, 'quantity': quantity,
'start_date': datetime.date(2015, 1, 1), 'start_datetime': datetime.date(2015, 1, 1),
'voucher_type': Voucher.SINGLE_USE, 'voucher_type': Voucher.SINGLE_USE,
'categories': [self.category], 'categories': [self.category],
'note': note, 'note': note,
......
...@@ -60,10 +60,10 @@ class CouponViewSetTest(CouponMixin, CourseCatalogTestMixin, TestCase): ...@@ -60,10 +60,10 @@ class CouponViewSetTest(CouponMixin, CourseCatalogTestMixin, TestCase):
'benefit_type': Benefit.PERCENTAGE, 'benefit_type': Benefit.PERCENTAGE,
'benefit_value': 100, 'benefit_value': 100,
'catalog': self.catalog, 'catalog': self.catalog,
'end_date': '2020-1-1', 'end_datetime': '2020-1-1',
'code': '', 'code': '',
'quantity': 2, 'quantity': 2,
'start_date': '2015-1-1', 'start_datetime': '2015-1-1',
'voucher_type': Voucher.ONCE_PER_CUSTOMER, 'voucher_type': Voucher.ONCE_PER_CUSTOMER,
'categories': [self.category], 'categories': [self.category],
'note': None, 'note': None,
...@@ -79,27 +79,6 @@ class CouponViewSetTest(CouponMixin, CourseCatalogTestMixin, TestCase): ...@@ -79,27 +79,6 @@ class CouponViewSetTest(CouponMixin, CourseCatalogTestMixin, TestCase):
site.siteconfiguration = site_configuration site.siteconfiguration = site_configuration
return site return site
def test_retrieve_invoice_data(self):
request_data = {
'invoice_discount_type': Invoice.PERCENTAGE,
'invoice_discount_value': 50,
'invoice_number': 'INV-00055',
'invoice_payment_date': datetime.datetime(2016, 1, 1, tzinfo=pytz.UTC).isoformat(),
'invoice_type': Invoice.PREPAID,
'tax_deducted_source': None
}
invoice_data = CouponViewSet().retrieve_invoice_data(request_data)
self.assertDictEqual(invoice_data, {
'discount_type': request_data['invoice_discount_type'],
'discount_value': request_data['invoice_discount_value'],
'number': request_data['invoice_number'],
'payment_date': request_data['invoice_payment_date'],
'type': request_data['invoice_type'],
'tax_deducted_source': request_data['tax_deducted_source']
})
@ddt.data( @ddt.data(
(Voucher.ONCE_PER_CUSTOMER, 2, 2), (Voucher.ONCE_PER_CUSTOMER, 2, 2),
(Voucher.SINGLE_USE, 2, None) (Voucher.SINGLE_USE, 2, None)
...@@ -240,21 +219,18 @@ class CouponViewSetTest(CouponMixin, CourseCatalogTestMixin, TestCase): ...@@ -240,21 +219,18 @@ class CouponViewSetTest(CouponMixin, CourseCatalogTestMixin, TestCase):
self.assertEqual(Basket.objects.first().status, 'Submitted') self.assertEqual(Basket.objects.first().status, 'Submitted')
def test_create_update_data_dict(self): def test_create_update_data_dict(self):
"""Test the update data dictionary""" """Test creating update data dictionary"""
data = {} fields = ['title', 'start_datetime', 'end_datetime']
for field in CouponVouchers.UPDATEABLE_VOUCHER_FIELDS: data = CouponViewSet().create_update_data_dict(
CouponViewSet().create_update_data_dict( data=self.coupon_data,
request_data=self.coupon_data, fields=fields
request_data_key=field['request_data_key'], )
update_dict=data,
update_dict_key=field['attribute']
)
self.assertDictEqual(data, { self.assertDictEqual(data, {
'end_datetime': self.coupon_data['end_date'], 'end_datetime': self.coupon_data['end_datetime'],
'start_datetime': self.coupon_data['start_date'], 'start_datetime': self.coupon_data['start_datetime'],
'name': self.coupon_data['title'], 'title': self.coupon_data['title'],
}) })
def test_delete_coupon(self): def test_delete_coupon(self):
...@@ -296,8 +272,8 @@ class CouponViewSetFunctionalTest(CouponMixin, CourseCatalogTestMixin, CourseCat ...@@ -296,8 +272,8 @@ class CouponViewSetFunctionalTest(CouponMixin, CourseCatalogTestMixin, CourseCat
'title': 'Tešt čoupon', 'title': 'Tešt čoupon',
'client': 'TeštX', 'client': 'TeštX',
'stock_record_ids': [1, 2], 'stock_record_ids': [1, 2],
'start_date': '2015-01-01', 'start_datetime': '2015-01-01',
'end_date': '2020-01-01', 'end_datetime': '2020-01-01',
'code': '', 'code': '',
'benefit_type': Benefit.PERCENTAGE, 'benefit_type': Benefit.PERCENTAGE,
'benefit_value': 100, 'benefit_value': 100,
...@@ -390,11 +366,11 @@ class CouponViewSetFunctionalTest(CouponMixin, CourseCatalogTestMixin, CourseCat ...@@ -390,11 +366,11 @@ class CouponViewSetFunctionalTest(CouponMixin, CourseCatalogTestMixin, CourseCat
self.assertEqual(response_data['title'], 'New title') self.assertEqual(response_data['title'], 'New title')
self.assertIsNone(response_data['email_domains']) self.assertIsNone(response_data['email_domains'])
def test_update_title(self): def test_update_name(self):
"""Test updating a coupon's title.""" """Test updating voucher name."""
data = { data = {
'id': self.coupon.id, 'id': self.coupon.id,
'title': 'New title' 'name': 'New voucher name'
} }
response_data = self.get_response_json( response_data = self.get_response_json(
'PUT', 'PUT',
...@@ -406,14 +382,14 @@ class CouponViewSetFunctionalTest(CouponMixin, CourseCatalogTestMixin, CourseCat ...@@ -406,14 +382,14 @@ class CouponViewSetFunctionalTest(CouponMixin, CourseCatalogTestMixin, CourseCat
new_coupon = Product.objects.get(id=self.coupon.id) new_coupon = Product.objects.get(id=self.coupon.id)
vouchers = new_coupon.attr.coupon_vouchers.vouchers.all() vouchers = new_coupon.attr.coupon_vouchers.vouchers.all()
for voucher in vouchers: for voucher in vouchers:
self.assertEqual(voucher.name, 'New title') self.assertEqual(voucher.name, 'New voucher name')
def test_update_datetimes(self): def test_update_datetimes(self):
"""Test that updating a coupons date updates all of it's voucher dates.""" """Test that updating a coupons date updates all of it's voucher dates."""
data = { data = {
'id': self.coupon.id, 'id': self.coupon.id,
'start_date': '2030-01-01', 'start_datetime': '2030-01-01',
'end_date': '2035-01-01' 'end_datetime': '2035-01-01'
} }
response_data = self.get_response_json( response_data = self.get_response_json(
'PUT', 'PUT',
......
...@@ -51,20 +51,6 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet): ...@@ -51,20 +51,6 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
return CouponListSerializer return CouponListSerializer
return CouponSerializer return CouponSerializer
def retrieve_invoice_data(self, request_data):
""" Retrieve the invoice information from the request data. """
invoice_data = {}
for field in Invoice.UPDATEABLE_INVOICE_FIELDS:
self.create_update_data_dict(
request_data=request_data,
request_data_key=field,
update_dict=invoice_data,
update_dict_key=field.replace('invoice_', '')
)
return invoice_data
def create(self, request, *args, **kwargs): def create(self, request, *args, **kwargs):
"""Adds coupon to the user's basket. """Adds coupon to the user's basket.
...@@ -90,8 +76,8 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet): ...@@ -90,8 +76,8 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
title = request.data.get('title') title = request.data.get('title')
client_username = request.data.get('client') client_username = request.data.get('client')
stock_record_ids = request.data.get('stock_record_ids') stock_record_ids = request.data.get('stock_record_ids')
start_date = dateutil.parser.parse(request.data.get('start_date')) start_datetime = dateutil.parser.parse(request.data.get('start_datetime'))
end_date = dateutil.parser.parse(request.data.get('end_date')) end_datetime = dateutil.parser.parse(request.data.get('end_datetime'))
code = request.data.get('code') code = request.data.get('code')
benefit_type = request.data.get('benefit_type') benefit_type = request.data.get('benefit_type')
benefit_value = request.data.get('benefit_value') benefit_value = request.data.get('benefit_value')
...@@ -117,7 +103,7 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet): ...@@ -117,7 +103,7 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
except Voucher.DoesNotExist: except Voucher.DoesNotExist:
pass pass
invoice_data = self.retrieve_invoice_data(request.data) invoice_data = self.create_update_data_dict(data=request.data, fields=Invoice.UPDATEABLE_INVOICE_FIELDS)
if course_seat_types: if course_seat_types:
course_seat_types = prepare_course_seat_types(course_seat_types) course_seat_types = prepare_course_seat_types(course_seat_types)
...@@ -153,22 +139,21 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet): ...@@ -153,22 +139,21 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
coupon_catalog = None coupon_catalog = None
data = { data = {
'partner': partner,
'title': title,
'benefit_type': benefit_type, 'benefit_type': benefit_type,
'benefit_value': benefit_value, 'benefit_value': benefit_value,
'catalog': coupon_catalog, 'catalog': coupon_catalog,
'end_date': end_date,
'code': code,
'quantity': quantity,
'start_date': start_date,
'voucher_type': voucher_type,
'categories': categories,
'note': note,
'max_uses': max_uses,
'catalog_query': catalog_query, 'catalog_query': catalog_query,
'categories': categories,
'code': code,
'course_seat_types': course_seat_types, 'course_seat_types': course_seat_types,
'email_domains': email_domains 'email_domains': email_domains,
'end_datetime': end_datetime,
'max_uses': max_uses,
'note': note,
'partner': partner,
'quantity': quantity,
'start_datetime': start_datetime,
'voucher_type': voucher_type
} }
coupon_product = self.create_coupon_product(title, price, data) coupon_product = self.create_coupon_product(title, price, data)
...@@ -222,10 +207,10 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet): ...@@ -222,10 +207,10 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
benefit_value=Decimal(data['benefit_value']), benefit_value=Decimal(data['benefit_value']),
catalog=data['catalog'], catalog=data['catalog'],
coupon=coupon_product, coupon=coupon_product,
end_datetime=data['end_date'], end_datetime=data['end_datetime'],
code=data['code'] or None, code=data['code'] or None,
quantity=int(data['quantity']), quantity=int(data['quantity']),
start_datetime=data['start_date'], start_datetime=data['start_datetime'],
voucher_type=data['voucher_type'], voucher_type=data['voucher_type'],
max_uses=data['max_uses'], max_uses=data['max_uses'],
catalog_query=data['catalog_query'], catalog_query=data['catalog_query'],
...@@ -312,28 +297,12 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet): ...@@ -312,28 +297,12 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
coupon = self.get_object() coupon = self.get_object()
vouchers = coupon.attr.coupon_vouchers.vouchers vouchers = coupon.attr.coupon_vouchers.vouchers
baskets = Basket.objects.filter(lines__product_id=coupon.id, status=Basket.SUBMITTED) baskets = Basket.objects.filter(lines__product_id=coupon.id, status=Basket.SUBMITTED)
data = {} data = self.create_update_data_dict(data=request.data, fields=CouponVouchers.UPDATEABLE_VOUCHER_FIELDS)
for field in CouponVouchers.UPDATEABLE_VOUCHER_FIELDS:
self.create_update_data_dict(
request_data=request.data,
request_data_key=field['request_data_key'],
update_dict=data,
update_dict_key=field['attribute']
)
if data: if data:
vouchers.all().update(**data) vouchers.all().update(**data)
range_data = {} range_data = self.create_update_data_dict(data=request.data, fields=Range.UPDATABLE_RANGE_FIELDS)
for field in Range.UPDATABLE_RANGE_FIELDS:
self.create_update_data_dict(
request_data=request.data,
request_data_key=field,
update_dict=range_data,
update_dict_key=field
)
if range_data: if range_data:
voucher_range = vouchers.first().offers.first().benefit.range voucher_range = vouchers.first().offers.first().benefit.range
...@@ -372,19 +341,24 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet): ...@@ -372,19 +341,24 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
serializer = self.get_serializer(coupon) serializer = self.get_serializer(coupon)
return Response(serializer.data) return Response(serializer.data)
def create_update_data_dict(self, request_data, request_data_key, update_dict, update_dict_key): def create_update_data_dict(self, data, fields):
""" """
Adds the value from request data to the update data dictionary Creates a dictionary for updating model attributes.
Arguments: Arguments:
request_data (QueryDict): Request data data (QueryDict): Request data
request_data_key (str): Request data dictionary key fields (list): List of updatable model fields
update_dict (dict): Dictionary containing the coupon update data
update_dict_key (str): Update data dictionary key Returns:
update_dict (dict): Dictionary that will be used to update model objects.
""" """
if request_data_key in request_data: update_dict = {}
value = request_data.get(request_data_key)
update_dict[update_dict_key] = prepare_course_seat_types(value) \ for field in fields:
if update_dict_key == 'course_seat_types' else value if field in data:
value = prepare_course_seat_types(data.get(field)) if field == 'course_seat_types' else data.get(field)
update_dict[field.replace('invoice_', '')] = value
return update_dict
def update_coupon_benefit_value(self, benefit_value, coupon, vouchers): def update_coupon_benefit_value(self, benefit_value, coupon, vouchers):
""" """
...@@ -441,7 +415,7 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet): ...@@ -441,7 +415,7 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
data (dict): The request's data from which the invoice data is retrieved data (dict): The request's data from which the invoice data is retrieved
and used for the updated. and used for the updated.
""" """
invoice_data = self.retrieve_invoice_data(data) invoice_data = self.create_update_data_dict(data=data, fields=Invoice.UPDATEABLE_INVOICE_FIELDS)
if invoice_data: if invoice_data:
Invoice.objects.filter(order__basket__lines__product=coupon).update(**invoice_data) Invoice.objects.filter(order__basket__lines__product=coupon).update(**invoice_data)
......
...@@ -4,18 +4,9 @@ from django.db import models ...@@ -4,18 +4,9 @@ from django.db import models
class CouponVouchers(models.Model): class CouponVouchers(models.Model):
UPDATEABLE_VOUCHER_FIELDS = [ UPDATEABLE_VOUCHER_FIELDS = [
{ 'end_datetime',
'request_data_key': 'end_date', 'start_datetime',
'attribute': 'end_datetime' 'name'
},
{
'request_data_key': 'start_date',
'attribute': 'start_datetime'
},
{
'request_data_key': 'title',
'attribute': 'name'
}
] ]
coupon = models.ForeignKey('catalogue.Product', related_name='coupon_vouchers') coupon = models.ForeignKey('catalogue.Product', related_name='coupon_vouchers')
vouchers = models.ManyToManyField('voucher.Voucher', blank=True, related_name='coupon_vouchers') vouchers = models.ManyToManyField('voucher.Voucher', blank=True, related_name='coupon_vouchers')
......
...@@ -226,8 +226,8 @@ define([ ...@@ -226,8 +226,8 @@ define([
}); });
if (!options.patch){ if (!options.patch){
this.set('start_date', moment.utc(this.get('start_date'))); this.set('start_datetime', moment.utc(this.get('start_date')));
this.set('end_date', moment.utc(this.get('end_date'))); this.set('end_datetime', moment.utc(this.get('end_date')));
if (this.get('coupon_type') === 'Enrollment code') { if (this.get('coupon_type') === 'Enrollment code') {
this.set('benefit_type', 'Percentage'); this.set('benefit_type', 'Percentage');
...@@ -237,11 +237,15 @@ define([ ...@@ -237,11 +237,15 @@ define([
options.data = JSON.stringify(this.toJSON()); options.data = JSON.stringify(this.toJSON());
} else { } else {
if (_.has(attributes, 'start_date')) { if (_.has(attributes, 'start_date')) {
attributes.start_date = moment.utc(attributes.start_date); attributes.start_datetime = moment.utc(attributes.start_date);
} }
if (_.has(attributes, 'end_date')) { if (_.has(attributes, 'end_date')) {
attributes.end_date = moment.utc(attributes.end_date); attributes.end_datetime = moment.utc(attributes.end_date);
}
if (_.has(attributes, 'title')) {
attributes.name = attributes.title;
} }
} }
......
define([ define([
'jquery', 'jquery',
'js-cookie',
'moment', 'moment',
'underscore', 'underscore',
'models/coupon_model', 'models/coupon_model',
'test/mock_data/coupons' 'test/mock_data/coupons'
], ],
function ($, function ($,
Cookies,
moment, moment,
_, _,
Coupon, Coupon,
...@@ -135,6 +137,8 @@ define([ ...@@ -135,6 +137,8 @@ define([
expect(ajaxData.benefit_type).toEqual('Percentage'); expect(ajaxData.benefit_type).toEqual('Percentage');
expect(ajaxData.benefit_value).toEqual(100); expect(ajaxData.benefit_value).toEqual(100);
expect(ajaxData.quantity).toEqual(1); expect(ajaxData.quantity).toEqual(1);
expect(model.get('start_datetime')).toEqual(moment.utc(model.get('start_date')));
expect(model.get('end_datetime')).toEqual(moment.utc(model.get('end_date')));
}); });
it('should POST discount data', function () { it('should POST discount data', function () {
...@@ -146,21 +150,40 @@ define([ ...@@ -146,21 +150,40 @@ define([
args = $.ajax.calls.argsFor(0); args = $.ajax.calls.argsFor(0);
ajaxData = JSON.parse(args[0].data); ajaxData = JSON.parse(args[0].data);
expect(ajaxData.quantity).toEqual(1); expect(ajaxData.quantity).toEqual(1);
expect(model.get('start_datetime')).toEqual(moment.utc(model.get('start_date')));
expect(model.get('end_datetime')).toEqual(moment.utc(model.get('end_date')));
}); });
it('should format start and end date if they are patch updated', function () { it('should format start and end date if they are patch updated', function () {
var model = Coupon.findOrCreate(discountCodeData, {parse: true}); var end_date = '2016-11-11T00:00:00Z',
spyOn(moment, 'utc'); model = Coupon.findOrCreate(discountCodeData, {parse: true}),
start_date = '2015-11-11T00:00:00Z',
title = 'Coupon title';
spyOn(Backbone.RelationalModel.prototype, 'save');
model.save( model.save(
{ {
start_date: '2015-11-11T00:00:00Z', end_date: end_date,
end_date: '2016-11-11T00:00:00Z' start_date: start_date,
title: title
}, },
{patch: true} {patch: true}
); );
expect(moment.utc).toHaveBeenCalledWith('2015-11-11T00:00:00Z'); expect(Backbone.RelationalModel.prototype.save).toHaveBeenCalledWith(
expect(moment.utc).toHaveBeenCalledWith('2016-11-11T00:00:00Z'); {
end_date: end_date,
end_datetime: moment.utc(end_date),
name: title,
start_date: start_date,
start_datetime: moment.utc(start_date),
title: title
},
{
patch: true,
headers: {'X-CSRFToken': Cookies.get('ecommerce_csrftoken')},
contentType: 'application/json'
}
);
}); });
}); });
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment