Class: Person

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
Ext::DelayedIndexing, OhNoes::Destroy, Valuation::LifetimeDonations, Valuation::LifetimeMemberships, Valuation::LifetimeTicketValue, Valuation::LifetimeValue
Defined in:
app/models/person.rb

Direct Known Subclasses

Company, Individual

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Ext::DelayedIndexing

included

Methods included from Valuation::LifetimeMemberships

#calculate_lifetime_memberships, #lifetime_orders

Methods included from Valuation::LifetimeDonations

#calculate_lifetime_donations, #lifetime_orders

Methods included from Valuation::LifetimeTicketValue

#calculate_lifetime_ticket_value, #lifetime_orders

Methods included from Valuation::LifetimeValue

#calculate_lifetime_value, #lifetime_orders

Methods included from OhNoes::Destroy

#destroy

Instance Attribute Details

#skip_commitObject

Returns the value of attribute skip_commit.



14
15
16
# File 'app/models/person.rb', line 14

def skip_commit
  @skip_commit
end

#skip_sync_to_mailchimpObject

Returns the value of attribute skip_sync_to_mailchimp.



14
15
16
# File 'app/models/person.rb', line 14

def skip_sync_to_mailchimp
  @skip_sync_to_mailchimp
end

Class Method Details

.companiesObject



44
45
46
# File 'app/models/person.rb', line 44

def self.companies
  where(:type => 'Company')
end

.create_dummy_for(organization) ⇒ Object



321
322
323
324
325
326
327
328
# File 'app/models/person.rb', line 321

def self.create_dummy_for(organization)
  create({
    :first_name      => "Anonymous",
    :email           => "[email protected]",
    :dummy           => true,
    :organization_id => organization.id
  })
end

.dummy_for(organization) ⇒ Object



312
313
314
315
316
317
318
319
# File 'app/models/person.rb', line 312

def self.dummy_for(organization)
  dummy = find(:first, :conditions => { :organization_id => organization.id, :dummy => true })
  if dummy.nil?
    create_dummy_for(organization)
  else
    dummy
  end
end

.find_by_email_and_organization(email, organization) ⇒ Object



303
304
305
306
# File 'app/models/person.rb', line 303

def self.find_by_email_and_organization(email, organization)
  return nil if email.blank?
  find(:first, :conditions => { :email => email, :organization_id => organization.id })
end

.find_by_import(import) ⇒ Object



210
211
212
# File 'app/models/person.rb', line 210

def self.find_by_import(import)
  where('import_id = ?', import.id)
end

.find_by_organization(organization) ⇒ Object



308
309
310
# File 'app/models/person.rb', line 308

def self.find_by_organization(organization)
  find_by_organization_id(organization.id)
end

.find_dupes_in(organization) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'app/models/person.rb', line 88

def self.find_dupes_in(organization)
  hash = {}
  Person.where(:organization_id => organization.id)
        .where(:import_id => nil)
        .includes([:tickets, :actions, :notes, :orders]).each do |p|
    if hash[p.dupe_code].nil?
      hash[p.dupe_code] = Array.wrap(p)
    else
      hash[p.dupe_code] << p
    end
  end
  hash
end

.find_or_create(customer, organization) ⇒ Object

You can pass any object as first param as long as it responds to .first_name, .last_name, and .email



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'app/models/person.rb', line 365

def self.find_or_create(customer, organization)
  warn "[DEPRECATION] find_or_create will be removed in a future release. Please use first_or_create"

  #TODO: Yuk
  if (customer.respond_to? :person_id) && (!customer.person_id.nil?)
    return Person.find(customer.person_id)
  elsif (customer.is_a? Person) && (!customer.id.nil?)
    person = Person.where(:id => customer.id).where(:organization_id => organization.id).first
    return person if person
  end

  person = Person.find_by_email_and_organization(customer.email, organization)

  if person.nil?
    params = {
      :first_name      => customer.first_name,
      :last_name       => customer.last_name,
      :email           => customer.email,
      :organization_id => organization.id
    }
    person = Person.create(params)
  end
  person
end

.first_or_create(attributes = nil, options = {}, &block) ⇒ Object

Raises:

  • (ArgumentError)


338
339
340
341
342
343
344
345
346
347
348
# File 'app/models/person.rb', line 338

def self.first_or_create(attributes=nil, options ={}, &block)
  Rails.logger.debug("Person.first_or_create #{attributes.inspect}")
  attributes[:organization_id] ||= attributes[:organization].try(:id)
  raise(ArgumentError, "You must include an organization when searching for people") if attributes[:organization_id].blank?

  attributes.delete(:organization)
  return Person.where(:id => attributes[:id]).where(:organization_id => attributes[:organization_id]).first if attributes[:id].present?
  return Person.create(attributes, options, &block)                                  if attributes[:email].blank?

  Person.where(:email => attributes[:email]).where(:organization_id => attributes[:organization_id]).first || Person.create(attributes, options, &block)
end

.first_or_initialize(attributes = nil, options = {}, &block) ⇒ Object

Raises:

  • (ArgumentError)


350
351
352
353
354
355
356
357
358
359
# File 'app/models/person.rb', line 350

def self.first_or_initialize(attributes=nil, options ={}, &block)
  attributes[:organization_id] ||= attributes[:organization].try(:id)
  raise(ArgumentError, "You must include an organization when searching for people") if attributes[:organization_id].blank?

  attributes.delete(:organization)
  return Person.where(:id => attributes[:id]).where(:organization_id => attributes[:organization_id]).first if attributes[:id].present?
  return Person.new(attributes, options, &block)                                     if attributes[:email].blank?

  Person.where(:email => attributes[:email]).where(:organization_id => attributes[:organization_id]).first || Person.new(attributes, options, &block)
end

.in_householdObject

ACHTUNG! This where clause is qualified to people so that it playes nicely in advanced search as address also has a household_id column. If you are doing something un-orthodox and have a query which does alias the people table to people, this scope will not work



53
54
55
# File 'app/models/person.rb', line 53

def self.in_household
  where('people.household_id is not null')
end

.individualsObject



40
41
42
# File 'app/models/person.rb', line 40

def self.individuals
  where(:type => 'Individual')
end

.mergablesObject

An array of has_many associations that should be merged when a person record is merged with another When an has_many association is added, it must be added here if the association is to be merged

Tickets are a special case



119
120
121
# File 'app/models/person.rb', line 119

def self.mergables
  [:actions, :phones, :notes, :orders, :memberships, :passes]
end

.merge(winner, loser) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'app/models/person.rb', line 218

def self.merge(winner, loser)
  unless winner.organization == loser.organization
    raise "Trying to merge two people [#{winner.id}] [#{loser.id}] from different organizations [#{winner.organization.id}] [#{winner.organization.id}]"
  end

  unless winner.type == loser.type
    raise "Trying to merge two people [#{winner.id}] [#{loser.id}] with different types [#{winner.type}] [#{loser.type}]"
  end

  mergables.each do |mergable|
    loser.send(mergable).each do |m|
      m.person = winner
      m.save!
    end
  end

  loser.tickets.each do |ticket|
    ticket.update_column(:buyer_id, winner.id)
  end

  loser.tags.each do |t|
    winner.tag_list << t.name unless winner.tag_list.include? t.name
  end

  loser.relationships.each do |r|
    unless Relationship.where(:person_id => winner.id, :relation_id => r.relation.id, :other_id => r.other.id).first
      winner.relationships << r
    end
  end

  winner.lifetime_value += loser.lifetime_value
  winner.lifetime_donations += loser.lifetime_donations
  winner.lifetime_ticket_value += loser.lifetime_ticket_value
  winner.lifetime_memberships += loser.lifetime_memberships

  winner.do_not_email = true if loser.do_not_email?
  winner.do_not_call = true if loser.do_not_call?
  new_lists = loser.subscribed_lists - winner.subscribed_lists
  winner.subscribed_lists = winner.subscribed_lists.concat(loser.subscribed_lists).uniq
  winner.save!
  loser.destroy(with_prejudice: true)

  mailchimp_kit = winner.organization.kits.mailchimp
  MailchimpSyncJob.merged_person(mailchimp_kit, loser.email, winner.id, new_lists) if mailchimp_kit

  return winner
end

.not_in_householdObject



57
58
59
# File 'app/models/person.rb', line 57

def self.not_in_household
  where('people.household_id is null')
end

.recent(organization, limit = 10) ⇒ Object



214
215
216
# File 'app/models/person.rb', line 214

def self.recent(organization, limit = 10)
  Person.where(:organization_id => organization).order('updated_at DESC').limit(limit)
end

Instance Method Details

#add_phone_if_missing(new_phone) ⇒ Object

Will add a phone number ot this record if the number doesn’t already exist



428
429
430
431
432
# File 'app/models/person.rb', line 428

def add_phone_if_missing(new_phone)
  if (!new_phone.blank? and phone_missing?(new_phone))
    phones.create(:number => new_phone, :kind => "Other")
  end
end

#any_current_passes?Boolean

Returns:

  • (Boolean)


507
508
509
# File 'app/models/person.rb', line 507

def any_current_passes?
  passes.not_expired.any?
end

#company?Boolean

Returns:

  • (Boolean)


135
136
137
# File 'app/models/person.rb', line 135

def company?
  self.type == "Company"
end

#create_subscribed_lists_notes!(user) ⇒ Object



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'app/models/person.rb', line 455

def create_subscribed_lists_notes!(user)
  if previous_changes["do_not_email"]
    new_note("#{user.email} changed do not email to #{do_not_email}",Time.now,user,organization.id)
  end

  if previous_changes["do_not_call"]
    new_note("#{user.email} changed do not call to #{do_not_call}",Time.now,user,organization.id)
  end

  if previous_changes["subscribed_lists"]
    mailchimp_kit.attached_lists.each do |list|
      old_lists = previous_changes["subscribed_lists"][0]
      if !old_lists.include?(list[:list_id]) && subscribed_lists.include?(list[:list_id])
        new_note("#{user.email} changed subscription status of the MailChimp list #{list[:list_name]} to subscribed",Time.now,user,organization.id)
      elsif old_lists.include?(list[:list_id]) && !subscribed_lists.include?(list[:list_id])
        new_note("#{user.email} changed subscription status of the MailChimp list #{list[:list_name]} to unsubscribed",Time.now,user,organization.id)
      end
    end
  end
end

#default_to_individualObject



490
491
492
493
# File 'app/models/person.rb', line 490

def default_to_individual
  self.type ||= "Individual"
  self.subtype ||= "Individual"
end

#destroyable?Boolean

Returns:

  • (Boolean)


131
132
133
# File 'app/models/person.rb', line 131

def destroyable?
  actions.empty? && orders.empty? && tickets.empty?
end

#dupe_codeObject



84
85
86
# File 'app/models/person.rb', line 84

def dupe_code
  "#{first_name} | #{last_name} | #{email}"
end

#has_nothing?Boolean

Returns:

  • (Boolean)


127
128
129
# File 'app/models/person.rb', line 127

def has_nothing?
  actions.empty? && phones.empty? && notes.empty? && orders.empty? && tickets.empty? && address.nil? && import_id.nil?
end

#has_something?Boolean

Returns:

  • (Boolean)


123
124
125
# File 'app/models/person.rb', line 123

def has_something?
  !has_nothing?
end

#individual?Boolean

Returns:

  • (Boolean)


139
140
141
# File 'app/models/person.rb', line 139

def individual?
  self.type == "Individual"
end

#naming_details_available?Boolean

Returns:

  • (Boolean)


499
500
501
# File 'app/models/person.rb', line 499

def naming_details_available?
  first_name.present? || last_name.present? || email.present? || company_name.present?
end

#new_note(text, occurred_at, user, organization_id) ⇒ Object



444
445
446
447
448
449
450
451
452
453
# File 'app/models/person.rb', line 444

def new_note(text, occurred_at, user, organization_id)
  note = notes.build({
    :text => text,
    :occurred_at => Time.now
  })
  note.user_id = user.id if user
  note.organization_id = organization_id
  note.save
  note
end

#phone_missing?(phone_number) ⇒ Boolean

Returns:

  • (Boolean)


421
422
423
# File 'app/models/person.rb', line 421

def phone_missing?(phone_number)
  phones.where("number = ?", phone_number).empty?
end

#possessiveObject



102
103
104
105
106
107
108
109
110
111
# File 'app/models/person.rb', line 102

def possessive
  case type
  when "Individual"
    self.first_name.blank? ? "" : "#{self.first_name}'s"
  when "Company"
    "#{self}'s"
  else
    ""
  end
end

#previous_changes_sentenceObject



434
435
436
437
438
439
440
441
442
# File 'app/models/person.rb', line 434

def previous_changes_sentence
  if self.previous_changes.present?
    str = ""
    self.previous_changes.except(:updated_at).each do |field,changes|
      str = str + "#{field.capitalize} changed from '#{changes[0]}' to '#{changes[1]}'. "
    end
    str
  end
end

#relationships_of_relation(relation) ⇒ Object



61
62
63
# File 'app/models/person.rb', line 61

def relationships_of_relation(relation)
  relationships.joins(:relation).where(:relations => {:description => relation})
end

#send_pass_summary_email(passes) ⇒ Object



503
504
505
# File 'app/models/person.rb', line 503

def send_pass_summary_email(passes)
  PassMailer.pass_info_for(self, self.organization.email,passes).deliver
end

#starred_actionsObject



330
331
332
# File 'app/models/person.rb', line 330

def starred_actions
  Action.where({ :person_id => id, :starred => true }).order(:occurred_at)
end

#to_sObject



476
477
478
479
480
481
482
483
484
485
486
487
488
# File 'app/models/person.rb', line 476

def to_s
  if first_name.present? || last_name.present?
    [salutation, first_name, middle_name, last_name, suffix].reject(&:blank?).join(" ")
  elsif company_name.present?
    company_name.to_s
  elsif email.present?
    email.to_s
  elsif id.present?
    "No Name ##{id}"
  else
    "No Name"
  end
end

#unstarred_actionsObject



334
335
336
# File 'app/models/person.rb', line 334

def unstarred_actions
  Action.where({ :person_id => id }).order('occurred_at desc').select{|a| a.unstarred?}
end

#update_address(new_address, time_zone, user = nil, updated_by = nil) ⇒ Object

Needs a serious refactor



406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'app/models/person.rb', line 406

def update_address(new_address, time_zone, user = nil, updated_by = nil)
  unless new_address.nil?
    new_address = Address.unhash(new_address)
    new_address.person = self
    @address = Address.find_or_create(id)
    if !@address.update_with_note(self, user, new_address, time_zone, updated_by)
      ::Rails.logger.error "Could not update address from payment"
      return false
    end
    self.address = @address
    save
  end
  true
end

#update_from_import(absorbee) ⇒ Object

Update self’s fields with absorbee’s fields where self.field is not nil We use this when importing for the “our db wins” conflict resolution

Absorbee will be unchanged

Addresses will be copied. Phones will be ammended. Tags will be ammended. orders and tickets will not be copied.



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/person.rb', line 277

def update_from_import(absorbee)
  ParsedRow.new([], []).person_attributes.keys.each do |key|
    if self.send(key).blank?
      self.send("#{key}=", absorbee.send(key))
    end
  end

  self.type = absorbee.type
  self.subtype = absorbee.subtype

  absorbee.tag_list.each do |t|
    self.tag_list << t unless self.tag_list.include? t
  end

  if self.address.blank?
    self.address.try(:destroy)
    self.address = absorbee.address
  end

  absorbee.phones.each do |phone|
    self.phones << phone if self.phone_missing?(phone.number)
  end

  self
end

#update_name(first_name, last_name) ⇒ Object



390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'app/models/person.rb', line 390

def update_name(first_name, last_name)
  return if (self.first_name == first_name) && (self.last_name == last_name)

  ActiveRecord::Base.transaction do
    str = "Name changed from checkout."
    unless (self.first_name.blank? && self.last_name.blank?)
      str += " Old name was #{self.first_name} #{self.last_name}."
    end
    new_note(str, Time.now, nil, self.organization.id)
    self.first_name = first_name.try(:capitalize)
    self.last_name  = last_name.try(:capitalize)
    self.save
  end
end

#validate_naming_detailsObject



495
496
497
# File 'app/models/person.rb', line 495

def validate_naming_details
  errors.add(:base, "A name or email address must be provided.") unless naming_details_available?
end