2021-04-22 19:24:08 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# A discount coupon applied to the whole shopping cart
|
2022-12-28 17:51:27 +01:00
|
|
|
class CartItem::Coupon < ApplicationRecord
|
2023-02-03 12:49:17 +01:00
|
|
|
self.table_name = 'cart_item_coupons'
|
|
|
|
|
2022-12-28 17:51:27 +01:00
|
|
|
belongs_to :operator_profile, class_name: 'InvoicingProfile'
|
|
|
|
belongs_to :customer_profile, class_name: 'InvoicingProfile'
|
|
|
|
belongs_to :coupon
|
|
|
|
|
|
|
|
def operator
|
|
|
|
operator_profile.user
|
2021-04-22 19:24:08 +02:00
|
|
|
end
|
|
|
|
|
2022-12-28 17:51:27 +01:00
|
|
|
def customer
|
|
|
|
customer_profile.user
|
2021-04-22 19:24:08 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def price(cart_total = 0)
|
|
|
|
cs = CouponService.new
|
|
|
|
new_total = cs.apply(cart_total, coupon)
|
|
|
|
|
|
|
|
amount = new_total - cart_total
|
|
|
|
|
|
|
|
{ amount: amount, total_with_coupon: new_total, total_without_coupon: cart_total }
|
|
|
|
end
|
2022-03-18 19:44:30 +01:00
|
|
|
|
|
|
|
def type
|
|
|
|
'coupon'
|
|
|
|
end
|
2022-06-07 16:55:24 +02:00
|
|
|
|
|
|
|
def valid?(_all_items)
|
2022-12-28 17:51:27 +01:00
|
|
|
return true if coupon.nil?
|
2022-06-07 16:55:24 +02:00
|
|
|
|
2022-12-28 17:51:27 +01:00
|
|
|
if coupon.status(customer.id) != 'active'
|
|
|
|
errors.add(:coupon, 'invalid coupon')
|
2022-06-07 16:55:24 +02:00
|
|
|
return false
|
|
|
|
end
|
|
|
|
true
|
|
|
|
end
|
2021-04-22 19:24:08 +02:00
|
|
|
end
|