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



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
302
303
304
305
306
307
308
309
# File 'app/models/padma_contact.rb', line 275

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', )


378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'app/models/padma_contact.rb', line 378

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



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'app/models/padma_contact.rb', line 255

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


225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'app/models/padma_contact.rb', line 225

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



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'app/models/padma_contact.rb', line 351

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



395
396
397
398
399
400
401
402
403
# File 'app/models/padma_contact.rb', line 395

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



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'app/models/padma_contact.rb', line 199

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])


323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'app/models/padma_contact.rb', line 323

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>)


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

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)


152
153
154
155
156
157
158
159
160
# File 'app/models/padma_contact.rb', line 152

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



162
163
164
# File 'app/models/padma_contact.rb', line 162

def check_duplicates
  @check_duplicates || false
end

#coefficients_totalInteger

Returns total amount of coefficients this contact has assigned

Returns:

  • (Integer)


179
180
181
# File 'app/models/padma_contact.rb', line 179

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>)


95
96
97
# File 'app/models/padma_contact.rb', line 95

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

#communicationsArray<Communication>

Returns:

  • (Array<Communication>)


90
91
92
# File 'app/models/padma_contact.rb', line 90

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

#facebook_idObject



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

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

#former_student_atObject



142
143
144
# File 'app/models/padma_contact.rb', line 142

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



407
408
409
# File 'app/models/padma_contact.rb', line 407

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

#idObject



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

def id
  self._id
end

#id=(id) ⇒ Object



85
86
87
# File 'app/models/padma_contact.rb', line 85

def id= id
  self._id = id
end

#in_active_merge?Boolean

Returns:

  • (Boolean)


183
184
185
# File 'app/models/padma_contact.rb', line 183

def in_active_merge?
  self.in_active_merge
end

#in_professional_training?Boolean

Returns:

  • (Boolean)


118
119
120
# File 'app/models/padma_contact.rb', line 118

def in_professional_training?
  self.in_professional_training
end

#json_rootObject



64
65
66
# File 'app/models/padma_contact.rb', line 64

def json_root
  :contact
end

#linked?Boolean

Returns:

  • (Boolean)


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

def linked?
  self.linked
end

#mobilesObject



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

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

#non_mobile_phonesObject



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

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)


114
115
116
# File 'app/models/padma_contact.rb', line 114

def persisted?
  self._id.present?
end

#possible_duplicatesArray<PadmaContac>

Returns posible duplicates of this contact.

Returns:

  • (Array<PadmaContac>)

    posible duplicates of this contact



167
168
169
170
171
172
173
174
175
# File 'app/models/padma_contact.rb', line 167

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



146
147
148
# File 'app/models/padma_contact.rb', line 146

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>)


100
101
102
# File 'app/models/padma_contact.rb', line 100

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