module Mks module Rate class RateChangeRequestService def create(params, created_by) change_request = RateChangeRequest.new(params) unless params[:rates] change_request.errors.add(:base, 'Request has no rates') return [change_request, false] end change_request.created_by = created_by change_request.status = 'SUBMITTED' begin RateChangeRequest.transaction do change_request.save! return [change_request, true] end rescue => _ return [change_request, false] end end def approve(request, approver) if update_rates(request.rates) request.status = 'APPROVED' request.approved_by = approver return request.save end false end def update_rates(rates) service_rates = [] rates.each do |rate| rate = rate.symbolize_keys service_rate = ServiceRate.find_by(chargeable_service_id: rate[:chargeable_service_id], equipment_item_id: rate[:equipment_item_id]) if service_rate service_rate.base_rate = rate[:base_rate] || service_rate.base_rate service_rate.utilization_rate = rate[:utilization_rate] || service_rate.utilization_rate else service_rate = ServiceRate.new(rate.except(:chargeable_service_name, :equipment_item_name)) end service_rates << service_rate end ServiceRate.transaction do service_rates.each(&:save!) end true rescue ActiveRecord::RecordInvalid false end end end end