module SolidusBling class Seller < ApplicationRecord validates :name, presence: true validates :external_id, presence: true belongs_to :account after_save :falsify_all_others def self.upsert_sellers account account.check_token BlingApi.configure { |config| config.access_token = account.access_token } sellers = BlingApi::Seller.get_sellers upsert_sellers = sellers.map { |seller| { name: seller[:nome], external_id: seller[:id], account_id: account.id, active: true } } SolidusBling::Seller.upsert_all(upsert_sellers, unique_by: :external_id) inactivate_sellers(sellers) end def self.default find_by(default: true) end def self.actives where(active: true) end def self.inactivate_sellers sellers_bling ids_sellers_bling = sellers_bling.pluck(:id) ids_sellers_store = pluck(:external_id).map(&:to_i) ids_sellers_inactive = ids_sellers_store - ids_sellers_bling sellers_inactive = where(external_id: ids_sellers_inactive) sellers_inactive.update_all(active: false) end def falsify_all_others self.class.where("id != ?", id).update(default: false) if default end end end