1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-18 07:52:23 +01:00
fab-manager/app/services/coupon_apply_service.rb
2016-11-28 10:40:02 +01:00

37 lines
1.2 KiB
Ruby

class CouponApplyService
##
# Apply the provided coupon, if active, to the given price. Usability tests will be run depending on the
# provided parameters.
# If no coupon/coupon code or if the code does not match, return origin price without change
#
# @param total {Number} invoice total, before any coupon is applied
# @param coupon {String|Coupon} Coupon's code OR Coupon object
# @param user_id {Number} user's id against the coupon will be tested for usability
# @return {Number}
##
def call(total, coupon, user_id = nil)
price = total
_coupon = nil
if coupon.instance_of? Coupon
_coupon = coupon
elsif coupon.instance_of? String
_coupon = Coupon.find_by(code: coupon)
end
unless _coupon.nil?
if _coupon.status(user_id, total) == 'active'
if _coupon.type == 'percent_off'
price = price - (price * _coupon.percent_off / 100.0)
elsif _coupon.type == 'amount_off'
# do not apply cash coupon unless it has a lower amount that the total price
if _coupon.amount_off <= price
price -= _coupon.amount_off
end
end
end
end
price
end
end