Class: SpreeCmCommissioner::SubscriptionsOrderCreator

Inherits:
BaseInteractor
  • Object
show all
Defined in:
app/interactors/spree_cm_commissioner/subscriptions_order_creator.rb

Instance Method Summary collapse

Instance Method Details

#callObject



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
# File 'app/interactors/spree_cm_commissioner/subscriptions_order_creator.rb', line 5

def call
  if today.day < 15
    period_start = (today - 1.month).change(day: 15)
    period_end = today.change(day: 14)
    boundary_date = today.prev_month.change(day: 14)
  else
    period_start = today.change(day: 15)
    period_end = (today + 1.month).change(day: 14)
    boundary_date = today.change(day: 14)
  end
  last_invoice_date = customer.last_invoice_date || boundary_date

  period = period_start..period_end
  return context.fail!(error: 'Invoice for this month is already existed') if period.cover?(last_invoice_date)

  active_subscriptions = active_subscriptions_query(boundary_date)
  return context.fail!(error: 'There are no active subscriptions') if active_subscriptions.blank?

  missed_months = missed_months(last_invoice_date, boundary_date)
  missed_months.times do |i|
    month = i
    generate_invoice(last_invoice_date, month, active_subscriptions)
  end
  context.customer.update(last_invoice_date: today)
end