forked from openfoodfoundation/openfoodnetwork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvoucher_adjustments_controller.rb
77 lines (60 loc) · 1.93 KB
/
voucher_adjustments_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# frozen_string_literal: true
class VoucherAdjustmentsController < BaseController
before_action :set_order
def create
if add_voucher
VoucherAdjustmentsService.calculate(@order)
@order.update_totals_and_states
update_payment_section
elsif @order.errors.present?
render_error
end
end
def destroy
@order.voucher_adjustments.find_by(id: params[:id])&.destroy
update_payment_section
end
private
def set_order
@order = current_order
end
def add_voucher
if voucher_params[:voucher_code].blank?
@order.errors.add(:voucher_code, I18n.t('split_checkout.errors.voucher_not_found'))
return false
end
voucher = Voucher.find_by(code: voucher_params[:voucher_code], enterprise: @order.distributor)
if voucher.nil?
@order.errors.add(:voucher_code, I18n.t('split_checkout.errors.voucher_not_found'))
return false
end
adjustment = voucher.create_adjustment(voucher.code, @order)
unless adjustment.valid?
@order.errors.add(:voucher_code, I18n.t('split_checkout.errors.add_voucher_error'))
adjustment.errors.each { |error| @order.errors.import(error) }
return false
end
true
end
def update_payment_section
render cable_ready: cable_car.replace(
selector: "#checkout-payment-methods",
html: render_to_string(partial: "split_checkout/payment", locals: { step: "payment" })
)
end
def render_error
flash.now[:error] = @order.errors.full_messages.to_sentence
render status: :unprocessable_entity, cable_ready: cable_car.
replace("#flashes", partial("shared/flashes", locals: { flashes: flash })).
replace(
"#voucher-section",
partial(
"split_checkout/voucher_section",
locals: { order: @order, voucher_adjustment: @order.voucher_adjustments.first }
)
)
end
def voucher_params
params.require(:order).permit(:voucher_code)
end
end