2020-06-09 18:51:57 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# This worker perform various requests to the Stripe API (payment service)
|
2021-06-04 18:26:20 +02:00
|
|
|
class SyncObjectsOnStripeWorker
|
2020-06-09 18:51:57 +02:00
|
|
|
include Sidekiq::Worker
|
|
|
|
sidekiq_options lock: :until_executed, on_conflict: :reject, queue: :stripe
|
|
|
|
|
|
|
|
def perform(notify_user_id = nil)
|
|
|
|
logger.debug 'We create all non-existing customers on stripe. This may take a while...'
|
|
|
|
total = User.online_payers.count
|
|
|
|
User.online_payers.each_with_index do |member, index|
|
|
|
|
logger.debug "#{index} / #{total}"
|
|
|
|
begin
|
2021-05-31 16:15:57 +02:00
|
|
|
stp_customer = member.payment_gateway_object.gateway_object.retrieve
|
2020-06-10 16:37:11 +02:00
|
|
|
StripeWorker.new.create_stripe_customer(member.id) if stp_customer.nil? || stp_customer[:deleted]
|
2020-06-09 18:51:57 +02:00
|
|
|
rescue Stripe::InvalidRequestError
|
2020-06-10 16:37:11 +02:00
|
|
|
StripeWorker.new.create_stripe_customer(member.id)
|
2020-06-09 18:51:57 +02:00
|
|
|
end
|
|
|
|
end
|
2021-06-04 18:26:20 +02:00
|
|
|
|
|
|
|
logger.debug 'We create all non-existing coupons on stripe. This may take a while...'
|
|
|
|
total = Coupon.all.count
|
|
|
|
Coupon.all.each_with_index do |coupon, index|
|
|
|
|
logger.debug "#{index} / #{total}"
|
|
|
|
Stripe::Coupon.retrieve(c.code, api_key: Setting.get('stripe_secret_key'))
|
|
|
|
rescue Stripe::InvalidRequestError
|
|
|
|
Stripe::Service.create_coupon(c.id)
|
|
|
|
end
|
|
|
|
|
|
|
|
w = StripeWorker.new
|
|
|
|
[Machine, Training, Space, Plan].each do |klass|
|
|
|
|
logger.debug "We create all non-existing #{klass} on stripe. This may take a while..."
|
|
|
|
total = klass.all.count
|
|
|
|
klass.all.each_with_index do |item, index|
|
|
|
|
logger.debug "#{index} / #{total}"
|
|
|
|
w.perform(:create_or_update_stp_product, klass.name, item.id)
|
|
|
|
end
|
|
|
|
end
|
2020-06-09 18:51:57 +02:00
|
|
|
logger.debug 'Sync is done'
|
|
|
|
return unless notify_user_id
|
|
|
|
|
|
|
|
logger.debug "Notify user #{notify_user_id}"
|
2020-06-10 16:45:48 +02:00
|
|
|
user = User.find(notify_user_id)
|
2021-06-04 18:26:20 +02:00
|
|
|
NotificationCenter.call type: :notify_admin_objects_stripe_sync,
|
2020-06-10 16:45:48 +02:00
|
|
|
receiver: user,
|
|
|
|
attached_object: user
|
2020-06-09 18:51:57 +02:00
|
|
|
end
|
|
|
|
end
|