module Eco module API class UseCases class DefaultCases class TransferAccountCase < DefaultCase def process @cases.define("transfer-account", type: :sync) do |entries, people, session, options, usecase| remove_account = session.job_group("main").new("remove account", usecase: usecase, type: :update, sets: :account) add_account = session.job_group("post").new("add account", usecase: usecase, type: :update, sets: :account) strict_search = session.config.people.strict_search? && (!options[:search]&.key?(:strict) || options.dig(:search, :strict)) done = []; pending = [] pairs = entries.each_with_object([]) do |source| entry_hash = source.internal_entry unless entry_hash.key?("destination-id") session.logger.error("You haven't defined a column 'destination-id' to whom the account should be transferred") exit(1) end if peer_id = entry_hash["destination-id"] if peer = entries.entry(id: peer_id, external_id: peer_id) if done.include?(peer) session.logger.error("You paired '#{peer_id}' twice. A person can only receive account from 1 user") exit(1) end pending.delete(source) pending.delete(peer) done.push(source).push(pair) [source, peer] else pending.push(source) nil end else pending.push(source) end end.compact # Data input integrity check unless pending.empty? msg = "You haven't defined a pair for the following ids:" msg += pending.each_with_object("") do |entry, str| str << "\n#{entry.id || entry.external_id}" end session.logger.error(msg) exit(1) end pairs.each do |pair| src_entry, dst_entry = pair unless src_person = people.find(src_entry, strict: strict_search) session.logger.error("This person does not exist: #{src_entry.to_s(:identify)}") exit(1) end unless dst_person = people.find(dst_entry, strict: strict_search) session.logger.error("This person does not exist: #{dst_person.to_s(:identify)}") exit(1) end unless account_doc = src_person.account&.doc session.logger.error("You are trying to move account from a person that doesn't have: #{src_person.id | src_person.external_id}") exit(1) end if dst_person.email.to_s.strip.empty? session.logger.error("A person you are trying to add account doesn't have email: #{dst_person.id | dst_person.external_id}") exit(1) end src_person.account = nil remove_account.add(src_person) add_account.add(dst_person) do |person| # only if we got to remove the account of the original person if account_doc && src_person.as_update == {} person.account = account_doc end end end end end end end end end end