module Lifen class Flow < Base attribute :uuid, String attribute :title, String attribute :user, Lifen::User attribute :users, Array[Lifen::User] def create users_to_attach = users params = {title: title, users: extract_users_uuids(users_to_attach)} json = client.post("central/api/chats?rel=activeUsers", params) json_flow = json.first flow = self.class.new(json_flow) self.user = user self.uuid = flow.uuid self.title = flow.title build_users(json_flow) check_if_users_were_attached!(users_to_attach) self end def save params = {title: title, uuid: uuid} json = client.put("central/api/chats/#{uuid}", params) self.title = json["title"] end def attach_users(users_to_attach) params = extract_users_uuids(users_to_attach) json = client.post("central/api/chats/#{uuid}/attach_users?rel=activeUsers", params) build_users(json) check_if_users_were_attached!(users_to_attach) self end def detach_users(users_to_detach) params = extract_users_uuids(users_to_detach) json = client.post("central/api/chats/#{uuid}/detach_users?rel=activeUsers", params) build_users(json) check_if_users_were_detached!(users_to_detach) self end private def client @client ||= user.client end def build_users(json) self.users = [] Array(json["activeUsers"]).each do |element| element[:first_name] = element["firstName"] element[:last_name] = element["lastName"] self.users << Lifen::User.new(element) end end def extract_users_uuids(users) Array(users).map(&:uuid).compact.uniq end def check_if_users_were_attached!(users_to_attach) missing_users = Array(users_to_attach).map(&:uuid) - users.map(&:uuid) raise Lifen::Error, "Users #{missing_users.join(', ')} were not attached to this flow" if !missing_users.empty? end def check_if_users_were_detached!(users_to_detach) extra_users = users.map(&:uuid) & Array(users_to_detach).map(&:uuid) raise Lifen::Error, "Users #{extra_users.join(', ')} were not detached from this flow" if !extra_users.empty? end end end