Class: PadmaContact

Inherits:
LogicalModel
  • Object
show all
Defined in:
app/models/padma_contact.rb

Overview

wrapper for PADMA-Contacts API interaction Configuration for LogicalModel on /config/initializers/contacts_client.rb

Constant Summary collapse

TIMEOUT =

miliseconds

5500
PER_PAGE =
9999
VALID_LEVELS =
%W(aspirante sádhaka yôgin chêla graduado asistente docente maestro)
VALID_STATUSES =
%W(student former_student prospect)
VALID_COEFFICIENTS =
%W(unknown fp pmenos perfil pmas)
DEFAULT_BATCH_SIZE =
500

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.async_search(options = {}) ⇒ Object



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'app/models/padma_contact.rb', line 267

def self.async_search(options={})
  options[:page] ||= 1
  options[:per_page] ||= 9999

  options = self.merge_key(options)

  request = Typhoeus::Request.new(
    resource_uri('search'),
    method: :post,
    body: options,
    headers: default_headers
  )
  request.on_complete do |response|
    if response.code >= 200 && response.code < 400
      log_ok(response)

      result_set = self.from_json(response.body)

      # this paginate is will_paginate's Array pagination
      collection = Kaminari.paginate_array(
          result_set[:collection],
          {
              :total_count=>result_set[:total],
              :limit => options[:per_page],
              :offset => options[:per_page] * ([options[:page], 1].max - 1)
          }
      )

      yield collection
    else
      log_failed(response)
    end
  end
  self.hydra.queue(request)
end

.average_age(options = {}) ⇒ Object

Same parameters as search. Returns average age for scoped contacts

Parameters:

@param options [Hash].
Valid options are:
* all other options will be sent in :params to WebService

Usage:

-- Average age of students at 2014-3-31
Person.average_age(account_name: 'martinez', status: 'student', local_status: 'student', )


370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'app/models/padma_contact.rb', line 370

def self.average_age(options = {})
  options = self.merge_key(options)

  response = Typhoeus.post(self.resource_uri+'/calculate/average_age', body: options)

  if response.success?
    log_ok(response)
    resp = ActiveSupport::JSON.decode(response.body)
    return resp['result'].to_f
  else
    log_failed(response)
    return nil
  end
end

.batch_search(search_options = {}, batch_options = {}) ⇒ Object

It’s slower than .search BUT if contacts-ws is timing out this will work because requests are smaller.

Parameters:

  • search_options (Hash) (defaults to: {})
  • batch_options (Hash) (defaults to: {})

Options Hash (search_options):

  • any (Object)

    option valid for .search

Options Hash (batch_options):

  • batch_size (Intger)
    • Size of batches

  • total (Integer)
    • Total amount of contacts.

    To avoid making an extra call for counting



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'app/models/padma_contact.rb', line 247

def self.batch_search(search_options = {}, batch_options = {})
  batch_options[:batch_size] ||= DEFAULT_BATCH_SIZE
  ret = nil

  total = batch_options[:total] || self.count_by_post(search_options)
  if total
    ret = []
    (total.to_f/batch_options[:batch_size]).ceil.times do |i|
      self.async_search(search_options.merge(per_page: batch_options[:batch_size], page: i+1)) do |page_elements|
        if page_elements
          ret += page_elements
        end
      end
    end
  end
  self.hydra.run
  ret.sort!{|a,b| a.first_name <=> b.first_name} if ret
  return ret
end

.count_by_post(options) ⇒ Object

Same as count by will make a POST request instead of GET request

See Also:

  • count


217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'app/models/padma_contact.rb', line 217

def self.count_by_post(options)
  options[:page] = 1
  options[:per_page] = 1

  options = self.merge_key(options)

  response = Typhoeus.post(self.resource_uri+'/search', body: options)
  if response.success?
    log_ok(response)
    result_set = self.from_json(response.body)
    return result_set[:total]
  else
    log_failed(response)
    return nil
  end
end

.find_by_kshema_id(kshema_id) ⇒ Object



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'app/models/padma_contact.rb', line 343

def self.find_by_kshema_id(kshema_id)
  params = { kshema_id: kshema_id}
  params = self.merge_key(params)

  response = Typhoeus::Request.get(self.resource_uri+'/by_kshema_id', params: params)
  if response.success?
    unless response.body == 'null'
      self.new.from_json(response.body)
    else
      return nil
    end
  else
    return nil
  end
end

.get_similar_to(contact_id, options = {}) ⇒ Object

Returns contacts similar to the one specifid by id



387
388
389
390
391
392
393
394
395
# File 'app/models/padma_contact.rb', line 387

def self.get_similar_to(contact_id,options={})
  options[:page] = 1
  options[:per_page] = 9999
  similar = nil
  do_with_resource_path("#{@resource_path}/#{contact_id}/similar") do
    similar = paginate(options)
  end
  similar
end

Links contact to given account

returns:

Examples:

@contact.link_to()

Parameters:

  • contact_id (String)
  • account_name (String)

Returns:

  • false if linking failed

  • nil if there was a connection problem

  • true if successfull



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'app/models/padma_contact.rb', line 191

def self.link(contact_id, )
  params = { account_name:  }
  params = self.merge_key(params)

  response = nil
  Timeout::timeout(self.timeout/1000) do
    response = Typhoeus::Request.post( self.resource_uri(contact_id)+"/link", :params => params, :timeout => self.timeout )
  end
  case response.code
    when 200
      log_ok response
      return true
    when 400
      log_failed response
      return false
    else
      log_failed response
      return nil
  end
rescue Timeout::Error
  self.logger.warn "timeout"
  return nil
end

.search(options = {}) ⇒ Object

Search is same as paginate but will make POST /search request instead of GET /index

Parameters:

@param options [Hash].
Valid options are:
* :page - indicated what page to return. Defaults to 1.
* :per_page - indicates how many records to be returned per page. Defauls to 9999
* all other options will be sent in :params to WebService

Usage:

Person.search(:page => params[:page])


315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'app/models/padma_contact.rb', line 315

def self.search(options = {})
  options[:page] ||= 1
  options[:per_page] ||= 9999

  options = self.merge_key(options)

  response = Typhoeus.post(self.resource_uri+'/search', body: options)


  if response.success?
    log_ok(response)
    result_set = self.from_json(response.body)

    # this paginate is will_paginate's Array pagination
    return Kaminari.paginate_array(
        result_set[:collection],
        {
            :total_count=>result_set[:total],
            :limit => options[:per_page],
            :offset => options[:per_page] * ([options[:page], 1].max - 1)
        }
    )
  else
    log_failed(response)
    return nil
  end
end

Instance Method Details

#activities(options = {}) ⇒ Array<ActivityStream::Activity>

Returns:

  • (Array<ActivityStream::Activity>)


98
99
100
# File 'app/models/padma_contact.rb', line 98

def activities(options={})
  ActivityStream::Activity.paginate(options.merge({where: {target_id: self.id, target_type: 'Contact'}}))
end

#ageInteger/NilClass

Returns age in years of the contact or nil if age not available

Returns:

  • (Integer/NilClass)


144
145
146
147
148
149
150
151
152
# File 'app/models/padma_contact.rb', line 144

def age
  birthday = self.date_attributes.select{|da| da.is_a_complete_birthday?}[0]
  now = Time.now.utc.to_date
  if birthday
    now.year - birthday.year.to_i - ((now.month > birthday.month.to_i || (now.month == birthday.month.to_i && now.day >= birthday.day.to_i)) ? 0 : 1)
  else
    nil
  end
end

#check_duplicatesObject



154
155
156
# File 'app/models/padma_contact.rb', line 154

def check_duplicates
  @check_duplicates || false
end

#coefficients_totalInteger

Returns total amount of coefficients this contact has assigned

Returns:

  • (Integer)


171
172
173
# File 'app/models/padma_contact.rb', line 171

def coefficients_total
  self.coefficients_counts.nil?? 0 : self.coefficients_counts.inject(0){|sum,key_value| sum += key_value[1]}
end

#commentsArray<Comment>

Returns:

  • (Array<Comment>)


87
88
89
# File 'app/models/padma_contact.rb', line 87

def comments
  Comment.where(contact_id: self.id)
end

#communicationsArray<Communication>

Returns:

  • (Array<Communication>)


82
83
84
# File 'app/models/padma_contact.rb', line 82

def communications
  Communication.where(contact_id: self.id)
end

#facebook_idObject



122
123
124
# File 'app/models/padma_contact.rb', line 122

def facebook_id
  self.contact_attributes.select{|attr| attr.is_a?(SocialNetworkId) && attr.category == "facebook"}.first if self.contact_attributes
end

#former_student_atObject



134
135
136
# File 'app/models/padma_contact.rb', line 134

def former_student_at
  local_statuses.select{|s|s['value']=='former_student'}.map{|s|s['account_name']} if self.local_statuses
end

#get_similar(options = {}) ⇒ Object

Returns contacts similar to current on



399
400
401
# File 'app/models/padma_contact.rb', line 399

def get_similar(options={})
 self.class.get_similar_to(id,options) 
end

#idObject



73
74
75
# File 'app/models/padma_contact.rb', line 73

def id
  self._id
end

#id=(id) ⇒ Object



77
78
79
# File 'app/models/padma_contact.rb', line 77

def id= id
  self._id = id
end

#in_active_merge?Boolean

Returns:

  • (Boolean)


175
176
177
# File 'app/models/padma_contact.rb', line 175

def in_active_merge?
  self.in_active_merge
end

#in_professional_training?Boolean

Returns:

  • (Boolean)


110
111
112
# File 'app/models/padma_contact.rb', line 110

def in_professional_training?
  self.in_professional_training
end

#json_rootObject



56
57
58
# File 'app/models/padma_contact.rb', line 56

def json_root
  :contact
end

#linked?Boolean

Returns:

  • (Boolean)


102
103
104
# File 'app/models/padma_contact.rb', line 102

def linked?
  self.linked
end

#mobilesObject



126
127
128
# File 'app/models/padma_contact.rb', line 126

def mobiles
  self.contact_attributes.select{|attr| attr.is_a?(Telephone) && attr.category == "mobile"} if self.contact_attributes
end

#non_mobile_phonesObject



130
131
132
# File 'app/models/padma_contact.rb', line 130

def non_mobile_phones
  self.contact_attributes.select{|attr| attr.is_a?(Telephone) && attr.category != "mobile"} if self.contact_attributes
end

#persisted?Boolean

Returns:

  • (Boolean)


106
107
108
# File 'app/models/padma_contact.rb', line 106

def persisted?
  self._id.present?
end

#possible_duplicatesArray<PadmaContac>

Returns posible duplicates of this contact.

Returns:

  • (Array<PadmaContac>)

    posible duplicates of this contact



159
160
161
162
163
164
165
166
167
# File 'app/models/padma_contact.rb', line 159

def possible_duplicates
  possible_duplicates = []
  unless self.errors[:possible_duplicates].empty?
    self.errors[:possible_duplicates][0][0].each do |pd|
      possible_duplicates << PadmaContact.new(pd) #"#{pd["first_name"]} #{pd["last_name"]}"
    end
  end
  possible_duplicates
end

#prospect_atObject



138
139
140
# File 'app/models/padma_contact.rb', line 138

def prospect_at
  local_statuses.select{|s|s['value']=='prospect'}.map{|s|s['account_name']} if self.local_statuses
end

#subscription_changesArray<Communication>

Returns:

  • (Array<Communication>)


92
93
94
# File 'app/models/padma_contact.rb', line 92

def subscription_changes
  SubscriptionChange.where(contact_id: self.id)
end