Class: CustomerRelations::Organization

Inherits:
ApplicationRecord show all
Includes:
StripAttribute
Defined in:
app/models/customer_relations/organization.rb

Constant Summary

Constants inherited from ApplicationRecord

ApplicationRecord::MAX_PLUCK

Class Method Summary collapse

Methods included from StripAttribute

#strip_attributes!

Methods inherited from ApplicationRecord

cached_column_list, #create_or_load_association, declarative_enum, default_select_columns, id_in, id_not_in, iid_in, pluck_primary_key, primary_key_in, #readable_by?, safe_ensure_unique, safe_find_or_create_by, safe_find_or_create_by!, #to_ability_name, underscore, where_exists, where_not_exists, with_fast_read_statement_timeout, without_order

Methods included from SensitiveSerializableHash

#serializable_hash

Class Method Details

.find_by_name(group_id, name) ⇒ Object


24
25
26
27
# File 'app/models/customer_relations/organization.rb', line 24

def self.find_by_name(group_id, name)
  where(group: group_id)
  .where('LOWER(name) = LOWER(?)', name)
end

.move_to_root_group(group) ⇒ Object


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/models/customer_relations/organization.rb', line 29

def self.move_to_root_group(group)
  update_query = <<~SQL
    UPDATE #{CustomerRelations::Contact.table_name}
    SET organization_id = new_organizations.id
    FROM #{table_name} AS existing_organizations
    JOIN #{table_name} AS new_organizations ON new_organizations.group_id = :old_group_id AND LOWER(new_organizations.name) = LOWER(existing_organizations.name)
    WHERE existing_organizations.group_id = :new_group_id AND organization_id = existing_organizations.id
  SQL
  connection.execute(sanitize_sql([
    update_query,
    old_group_id: group.root_ancestor.id,
    new_group_id: group.id
    ]))

  dupes_query = <<~SQL
    DELETE FROM #{table_name} AS existing_organizations
    USING #{table_name} AS new_organizations
    WHERE existing_organizations.group_id = :new_group_id AND new_organizations.group_id = :old_group_id AND LOWER(new_organizations.name) = LOWER(existing_organizations.name)
  SQL
  connection.execute(sanitize_sql([
    dupes_query,
    old_group_id: group.root_ancestor.id,
    new_group_id: group.id
    ]))

  where(group: group).update_all(group_id: group.root_ancestor.id)
end