2021-04-22 19:24:08 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# A machine reservation added to the shopping cart
|
|
|
|
class CartItem::MachineReservation < CartItem::Reservation
|
|
|
|
# @param plan {Plan} a subscription bought at the same time of the reservation OR an already running subscription
|
|
|
|
# @param new_subscription {Boolean} true is new subscription is being bought at the same time of the reservation
|
|
|
|
def initialize(customer, operator, machine, slots, plan: nil, new_subscription: false)
|
2021-04-26 11:40:26 +02:00
|
|
|
raise TypeError unless machine.is_a? Machine
|
2021-04-22 19:24:08 +02:00
|
|
|
|
|
|
|
super(customer, operator, machine, slots)
|
|
|
|
@plan = plan
|
|
|
|
@new_subscription = new_subscription
|
|
|
|
end
|
|
|
|
|
2021-05-21 18:25:18 +02:00
|
|
|
def to_object
|
2021-05-19 18:12:52 +02:00
|
|
|
::Reservation.new(
|
|
|
|
reservable_id: @reservable.id,
|
|
|
|
reservable_type: Machine.name,
|
2022-07-13 16:28:43 +02:00
|
|
|
slots_reservations_attributes: slots_params,
|
2021-05-21 18:25:18 +02:00
|
|
|
statistic_profile_id: StatisticProfile.find_by(user: @customer).id
|
2021-05-19 18:12:52 +02:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
2022-03-18 19:44:30 +01:00
|
|
|
def type
|
|
|
|
'machine'
|
|
|
|
end
|
|
|
|
|
2022-07-20 17:46:09 +02:00
|
|
|
def valid?(all_items)
|
|
|
|
@slots.each do |slot|
|
|
|
|
same_hour_slots = SlotsReservation.joins(:reservation).where(
|
|
|
|
reservations: { reservable: @reservable },
|
|
|
|
slot_id: slot[:slot_id],
|
|
|
|
canceled_at: nil
|
|
|
|
).count
|
|
|
|
if same_hour_slots.positive?
|
|
|
|
@errors[:slot] = 'slot is reserved'
|
|
|
|
return false
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
super
|
|
|
|
end
|
|
|
|
|
2021-04-22 19:24:08 +02:00
|
|
|
protected
|
|
|
|
|
|
|
|
def credits
|
|
|
|
return 0 if @plan.nil?
|
|
|
|
|
|
|
|
machine_credit = @plan.machine_credits.find { |credit| credit.creditable_id == @reservable.id }
|
2022-10-26 17:35:02 +02:00
|
|
|
credits_hours(machine_credit, new_plan_being_bought: @new_subscription)
|
2021-04-22 19:24:08 +02:00
|
|
|
end
|
|
|
|
end
|