customer_user.rb 2.7 KB

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