2019-05-29 12:01:24 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# Personal data attached to an user (like first_name, date of birth, etc.)
|
2020-03-25 10:16:47 +01:00
|
|
|
class Profile < ApplicationRecord
|
2015-05-05 03:10:25 +02:00
|
|
|
belongs_to :user
|
|
|
|
has_one :user_avatar, as: :viewable, dependent: :destroy
|
|
|
|
accepts_nested_attributes_for :user_avatar,
|
|
|
|
allow_destroy: true,
|
|
|
|
reject_if: proc { |attributes| attributes['attachment'].blank? }
|
2016-08-02 12:27:45 +02:00
|
|
|
|
2015-05-05 03:10:25 +02:00
|
|
|
validates :first_name, presence: true, length: { maximum: 30 }
|
|
|
|
validates :last_name, presence: true, length: { maximum: 30 }
|
2020-05-13 15:02:03 +02:00
|
|
|
validates_numericality_of :phone, only_integer: true, allow_blank: false, if: -> { Setting.get('phone_required') }
|
2015-05-05 03:10:25 +02:00
|
|
|
|
2021-05-14 17:07:38 +02:00
|
|
|
after_commit :update_invoicing_profile, if: :invoicing_data_was_modified?
|
2019-05-29 12:01:24 +02:00
|
|
|
|
2015-05-05 03:10:25 +02:00
|
|
|
def full_name
|
2016-03-23 18:39:41 +01:00
|
|
|
# if first_name or last_name is nil, the empty string will be used as a temporary replacement
|
|
|
|
(first_name || '').humanize.titleize + ' ' + (last_name || '').humanize.titleize
|
2015-05-05 03:10:25 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def to_s
|
|
|
|
full_name
|
|
|
|
end
|
|
|
|
|
2016-09-14 16:41:45 +02:00
|
|
|
def self.mapping
|
|
|
|
# we protect some fields as they are designed to be managed by the system and must not be updated externally
|
2019-05-29 12:01:24 +02:00
|
|
|
blacklist = %w[id user_id created_at updated_at]
|
2016-09-14 16:41:45 +02:00
|
|
|
# model-relationships must be added manually
|
2021-12-20 14:07:25 +01:00
|
|
|
additional = [%w[avatar string], %w[address string], %w[organization_name string], %w[organization_address string],
|
|
|
|
%w[gender boolean], %w[birthday date]]
|
2020-03-30 16:17:32 +02:00
|
|
|
Profile.columns_hash
|
2019-05-29 12:01:24 +02:00
|
|
|
.map { |k, v| [k, v.type.to_s] }
|
|
|
|
.delete_if { |col| blacklist.include?(col[0]) }
|
|
|
|
.concat(additional)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2019-06-03 17:25:04 +02:00
|
|
|
def invoicing_data_was_modified?
|
2020-03-24 16:45:27 +01:00
|
|
|
saved_change_to_first_name? || saved_change_to_last_name? || new_record?
|
2019-06-03 17:25:04 +02:00
|
|
|
end
|
|
|
|
|
2019-05-29 12:01:24 +02:00
|
|
|
def update_invoicing_profile
|
2019-06-04 16:50:23 +02:00
|
|
|
raise NoProfileError if user.invoicing_profile.nil?
|
|
|
|
|
|
|
|
user.invoicing_profile.update_attributes(
|
|
|
|
first_name: first_name,
|
|
|
|
last_name: last_name
|
|
|
|
)
|
2016-09-14 16:41:45 +02:00
|
|
|
end
|
|
|
|
|
2015-05-05 03:10:25 +02:00
|
|
|
end
|