1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2024-12-10 21:24:20 +01:00
fab-manager/app/assets/javascripts/directives/coupon.coffee.erb

60 lines
2.1 KiB
Plaintext
Raw Normal View History

Application.Directives.directive 'coupon', [ '$rootScope', 'Coupon', '_t', ($rootScope, Coupon, _t) ->
{
restrict: 'E'
scope:
show: '='
coupon: '='
total: '='
userId: '@'
templateUrl: '<%= asset_path "shared/_coupon.html" %>'
2016-08-09 10:22:01 +02:00
link: ($scope, element, attributes) ->
2016-08-09 10:22:01 +02:00
# Whether code input is shown or not (ie. the link 'I have a coupon' is shown)
$scope.code =
input: false
2016-08-09 10:22:01 +02:00
# Available status are: 'pending', 'valid', 'invalid'
$scope.status = 'pending'
# Binding for the code inputed (see the attached template)
2016-08-09 10:22:01 +02:00
$scope.couponCode = null
# Code validation messages
$scope.messages = []
# Re-compute if the code can be applied when the total of the cart changes
$scope.$watch 'total', (newValue, oldValue) ->
if newValue and newValue != oldValue and $scope.couponCode
$scope.validateCode()
##
# Callback to validate the code
##
2016-08-09 10:22:01 +02:00
$scope.validateCode = ->
$scope.messages = []
2016-08-09 10:22:01 +02:00
if $scope.couponCode == ''
$scope.status = 'pending'
$scope.coupon = null
2016-08-09 10:22:01 +02:00
else
Coupon.validate {code: $scope.couponCode, user_id: $scope.userId, amount: $scope.total}, (res) ->
2016-08-09 10:22:01 +02:00
$scope.status = 'valid'
$scope.coupon = res
if res.type == 'percent_off'
$scope.messages.push(type: 'success', message: _t('the_coupon_has_been_applied_you_get_PERCENT_discount', {PERCENT: res.percent_off}))
else
$scope.messages.push(type: 'success', message: _t('the_coupon_has_been_applied_you_get_AMOUNT_CURRENCY', {AMOUNT: res.amount_off, CURRENCY: $rootScope.currencySymbol}))
, (err) ->
2016-08-09 10:22:01 +02:00
$scope.status = 'invalid'
$scope.coupon = null
$scope.messages.push(type: 'danger', message: _t('unable_to_apply_the_coupon_because_'+err.data.status))
##
# Callback to remove the message at provided index from the displayed list
##
$scope.closeMessage = (index) ->
$scope.messages.splice(index, 1);
}
]