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):
'benefit_type': Benefit.PERCENTAGE,
'benefit_value': benefit_value,
'catalog': catalog,
'end_date': datetime.date(2020, 1, 1),
'end_datetime': datetime.date(2020, 1, 1),
'code': code,
'quantity': quantity,
'start_date': datetime.date(2015, 1, 1),
'start_datetime': datetime.date(2015, 1, 1),
'voucher_type': Voucher.SINGLE_USE,
'categories': [self.category],
'note': note,
......
......@@ -60,10 +60,10 @@ class CouponViewSetTest(CouponMixin, CourseCatalogTestMixin, TestCase):
'benefit_type': Benefit.PERCENTAGE,
'benefit_value': 100,
'catalog': self.catalog,
'end_date': '2020-1-1',
'end_datetime': '2020-1-1',
'code': '',
'quantity': 2,
'start_date': '2015-1-1',
'start_datetime': '2015-1-1',
'voucher_type': Voucher.ONCE_PER_CUSTOMER,
'categories': [self.category],
'note': None,
......@@ -79,27 +79,6 @@ class CouponViewSetTest(CouponMixin, CourseCatalogTestMixin, TestCase):
site.siteconfiguration = site_configuration
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(
(Voucher.ONCE_PER_CUSTOMER, 2, 2),
(Voucher.SINGLE_USE, 2, None)
......@@ -240,21 +219,18 @@ class CouponViewSetTest(CouponMixin, CourseCatalogTestMixin, TestCase):
self.assertEqual(Basket.objects.first().status, 'Submitted')
def test_create_update_data_dict(self):
"""Test the update data dictionary"""
data = {}
"""Test creating update data dictionary"""
fields = ['title', 'start_datetime', 'end_datetime']
for field in CouponVouchers.UPDATEABLE_VOUCHER_FIELDS:
CouponViewSet().create_update_data_dict(
request_data=self.coupon_data,
request_data_key=field['request_data_key'],
update_dict=data,
update_dict_key=field['attribute']
)
data = CouponViewSet().create_update_data_dict(
data=self.coupon_data,
fields=fields
)
self.assertDictEqual(data, {
'end_datetime': self.coupon_data['end_date'],
'start_datetime': self.coupon_data['start_date'],
'name': self.coupon_data['title'],
'end_datetime': self.coupon_data['end_datetime'],
'start_datetime': self.coupon_data['start_datetime'],
'title': self.coupon_data['title'],
})
def test_delete_coupon(self):
......@@ -296,8 +272,8 @@ class CouponViewSetFunctionalTest(CouponMixin, CourseCatalogTestMixin, CourseCat
'title': 'Tešt čoupon',
'client': 'TeštX',
'stock_record_ids': [1, 2],
'start_date': '2015-01-01',
'end_date': '2020-01-01',
'start_datetime': '2015-01-01',
'end_datetime': '2020-01-01',
'code': '',
'benefit_type': Benefit.PERCENTAGE,
'benefit_value': 100,
......@@ -390,11 +366,11 @@ class CouponViewSetFunctionalTest(CouponMixin, CourseCatalogTestMixin, CourseCat
self.assertEqual(response_data['title'], 'New title')
self.assertIsNone(response_data['email_domains'])
def test_update_title(self):
"""Test updating a coupon's title."""
def test_update_name(self):
"""Test updating voucher name."""
data = {
'id': self.coupon.id,
'title': 'New title'
'name': 'New voucher name'
}
response_data = self.get_response_json(
'PUT',
......@@ -406,14 +382,14 @@ class CouponViewSetFunctionalTest(CouponMixin, CourseCatalogTestMixin, CourseCat
new_coupon = Product.objects.get(id=self.coupon.id)
vouchers = new_coupon.attr.coupon_vouchers.vouchers.all()
for voucher in vouchers:
self.assertEqual(voucher.name, 'New title')
self.assertEqual(voucher.name, 'New voucher name')
def test_update_datetimes(self):
"""Test that updating a coupons date updates all of it's voucher dates."""
data = {
'id': self.coupon.id,
'start_date': '2030-01-01',
'end_date': '2035-01-01'
'start_datetime': '2030-01-01',
'end_datetime': '2035-01-01'
}
response_data = self.get_response_json(
'PUT',
......
......@@ -51,20 +51,6 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
return CouponListSerializer
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):
"""Adds coupon to the user's basket.
......@@ -90,8 +76,8 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
title = request.data.get('title')
client_username = request.data.get('client')
stock_record_ids = request.data.get('stock_record_ids')
start_date = dateutil.parser.parse(request.data.get('start_date'))
end_date = dateutil.parser.parse(request.data.get('end_date'))
start_datetime = dateutil.parser.parse(request.data.get('start_datetime'))
end_datetime = dateutil.parser.parse(request.data.get('end_datetime'))
code = request.data.get('code')
benefit_type = request.data.get('benefit_type')
benefit_value = request.data.get('benefit_value')
......@@ -117,7 +103,7 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
except Voucher.DoesNotExist:
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:
course_seat_types = prepare_course_seat_types(course_seat_types)
......@@ -153,22 +139,21 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
coupon_catalog = None
data = {
'partner': partner,
'title': title,
'benefit_type': benefit_type,
'benefit_value': benefit_value,
'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,
'categories': categories,
'code': code,
'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)
......@@ -222,10 +207,10 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
benefit_value=Decimal(data['benefit_value']),
catalog=data['catalog'],
coupon=coupon_product,
end_datetime=data['end_date'],
end_datetime=data['end_datetime'],
code=data['code'] or None,
quantity=int(data['quantity']),
start_datetime=data['start_date'],
start_datetime=data['start_datetime'],
voucher_type=data['voucher_type'],
max_uses=data['max_uses'],
catalog_query=data['catalog_query'],
......@@ -312,28 +297,12 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
coupon = self.get_object()
vouchers = coupon.attr.coupon_vouchers.vouchers
baskets = Basket.objects.filter(lines__product_id=coupon.id, status=Basket.SUBMITTED)
data = {}
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']
)
data = self.create_update_data_dict(data=request.data, fields=CouponVouchers.UPDATEABLE_VOUCHER_FIELDS)
if data:
vouchers.all().update(**data)
range_data = {}
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
)
range_data = self.create_update_data_dict(data=request.data, fields=Range.UPDATABLE_RANGE_FIELDS)
if range_data:
voucher_range = vouchers.first().offers.first().benefit.range
......@@ -372,19 +341,24 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
serializer = self.get_serializer(coupon)
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:
request_data (QueryDict): Request data
request_data_key (str): Request data dictionary key
update_dict (dict): Dictionary containing the coupon update data
update_dict_key (str): Update data dictionary key
data (QueryDict): Request data
fields (list): List of updatable model fields
Returns:
update_dict (dict): Dictionary that will be used to update model objects.
"""
if request_data_key in request_data:
value = request_data.get(request_data_key)
update_dict[update_dict_key] = prepare_course_seat_types(value) \
if update_dict_key == 'course_seat_types' else value
update_dict = {}
for field in fields:
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):
"""
......@@ -441,7 +415,7 @@ class CouponViewSet(EdxOrderPlacementMixin, viewsets.ModelViewSet):
data (dict): The request's data from which the invoice data is retrieved
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:
Invoice.objects.filter(order__basket__lines__product=coupon).update(**invoice_data)
......
......@@ -4,18 +4,9 @@ from django.db import models
class CouponVouchers(models.Model):
UPDATEABLE_VOUCHER_FIELDS = [
{
'request_data_key': 'end_date',
'attribute': 'end_datetime'
},
{
'request_data_key': 'start_date',
'attribute': 'start_datetime'
},
{
'request_data_key': 'title',
'attribute': 'name'
}
'end_datetime',
'start_datetime',
'name'
]
coupon = models.ForeignKey('catalogue.Product', related_name='coupon_vouchers')
vouchers = models.ManyToManyField('voucher.Voucher', blank=True, related_name='coupon_vouchers')
......
......@@ -226,8 +226,8 @@ define([
});
if (!options.patch){
this.set('start_date', moment.utc(this.get('start_date')));
this.set('end_date', moment.utc(this.get('end_date')));
this.set('start_datetime', moment.utc(this.get('start_date')));
this.set('end_datetime', moment.utc(this.get('end_date')));
if (this.get('coupon_type') === 'Enrollment code') {
this.set('benefit_type', 'Percentage');
......@@ -237,11 +237,15 @@ define([
options.data = JSON.stringify(this.toJSON());
} else {
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')) {
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([
'jquery',
'js-cookie',
'moment',
'underscore',
'models/coupon_model',
'test/mock_data/coupons'
],
function ($,
Cookies,
moment,
_,
Coupon,
......@@ -135,6 +137,8 @@ define([
expect(ajaxData.benefit_type).toEqual('Percentage');
expect(ajaxData.benefit_value).toEqual(100);
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 () {
......@@ -146,21 +150,40 @@ define([
args = $.ajax.calls.argsFor(0);
ajaxData = JSON.parse(args[0].data);
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 () {
var model = Coupon.findOrCreate(discountCodeData, {parse: true});
spyOn(moment, 'utc');
var end_date = '2016-11-11T00:00:00Z',
model = Coupon.findOrCreate(discountCodeData, {parse: true}),
start_date = '2015-11-11T00:00:00Z',
title = 'Coupon title';
spyOn(Backbone.RelationalModel.prototype, 'save');
model.save(
{
start_date: '2015-11-11T00:00:00Z',
end_date: '2016-11-11T00:00:00Z'
end_date: end_date,
start_date: start_date,
title: title
},
{patch: true}
);
expect(moment.utc).toHaveBeenCalledWith('2015-11-11T00:00:00Z');
expect(moment.utc).toHaveBeenCalledWith('2016-11-11T00:00:00Z');
expect(Backbone.RelationalModel.prototype.save).toHaveBeenCalledWith(
{
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