customer_user.rb 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. module Import
  2. module OTRS
  3. class CustomerUser
  4. include Import::Helper
  5. include Import::OTRS::Helper
  6. MAPPING = {
  7. ChangeTime: :updated_at,
  8. CreateTime: :created_at,
  9. CreateBy: :created_by_id,
  10. ChangeBy: :updated_by_id,
  11. UserComment: :note,
  12. UserEmail: :email,
  13. UserFirstname: :firstname,
  14. UserLastname: :lastname,
  15. UserLogin: :login,
  16. UserPassword: :password,
  17. UserPhone: :phone,
  18. UserFax: :fax,
  19. UserMobile: :mobile,
  20. UserStreet: :street,
  21. UserZip: :zip,
  22. UserCity: :city,
  23. UserCountry: :country,
  24. }.freeze
  25. def initialize(customer)
  26. import(customer)
  27. end
  28. private
  29. def import(customer)
  30. create_or_update(map(customer))
  31. end
  32. def create_or_update(customer)
  33. return if updated?(customer)
  34. create(customer)
  35. end
  36. def updated?(customer)
  37. @local_customer = ::User.find_by(login: customer[:login])
  38. return false if !@local_customer
  39. # do not update user if it is already agent
  40. return true if @local_customer.role_ids.include?(Role.find_by(name: 'Agent').id)
  41. # only update roles if different (reduce sql statements)
  42. if @local_customer.role_ids == customer[:role_ids]
  43. customer.delete(:role_ids)
  44. end
  45. log "update User.find_by(login: #{customer[:login]})"
  46. @local_customer.update!(customer)
  47. true
  48. end
  49. def create(customer)
  50. log "add User.find_by(login: #{customer[:login]})"
  51. @local_customer = ::User.new(customer)
  52. @local_customer.save
  53. reset_primary_key_sequence('users')
  54. end
  55. def map(customer)
  56. mapped = map_default(customer)
  57. mapped[:created_at] ||= DateTime.current
  58. mapped[:updated_at] ||= DateTime.current
  59. mapped[:email].downcase!
  60. mapped[:login].downcase!
  61. mapped
  62. end
  63. def map_default(customer)
  64. {
  65. created_by_id: 1,
  66. updated_by_id: 1,
  67. active: active?(customer),
  68. source: 'OTRS Import',
  69. organization_id: organization_id(customer),
  70. role_ids: role_ids,
  71. }
  72. .merge(from_mapping(customer))
  73. end
  74. def role_ids
  75. [
  76. Role.find_by(name: 'Customer').id
  77. ]
  78. end
  79. def organization_id(customer)
  80. return if !customer['UserCustomerID']
  81. organization = Import::OTRS::Customer.by_customer_id(customer['UserCustomerID'])
  82. return if !organization
  83. organization.id
  84. end
  85. end
  86. end
  87. end