article_customer.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. module Import
  2. module OTRS
  3. class ArticleCustomer
  4. include Import::Helper
  5. def initialize(article)
  6. import(article)
  7. rescue Exceptions::UnprocessableEntity => e
  8. log "ERROR: Can't extract customer from Article #{article[:id]}"
  9. end
  10. class << self
  11. def find(article)
  12. email = local_email(article['From'])
  13. return if !email
  14. user = ::User.find_by(email: email)
  15. user ||= ::User.find_by(login: email)
  16. user
  17. end
  18. def local_email(from)
  19. # TODO: should get unified with User#check_email
  20. email = extract_email(from)
  21. return if !email
  22. email.downcase
  23. end
  24. private
  25. def extract_email(from)
  26. Mail::Address.new(from).address
  27. rescue
  28. return from if from !~ /<\s*([^>]+)/
  29. $1.strip
  30. end
  31. end
  32. private
  33. def import(article)
  34. find_or_create(article)
  35. end
  36. def find_or_create(article)
  37. return if self.class.find(article)
  38. create(article)
  39. end
  40. def create(article)
  41. email = self.class.local_email(article['From'])
  42. ::User.create(
  43. login: email,
  44. firstname: extract_display_name(article['From']),
  45. lastname: '',
  46. email: email,
  47. password: '',
  48. active: true,
  49. role_ids: roles,
  50. updated_by_id: 1,
  51. created_by_id: 1,
  52. )
  53. rescue ActiveRecord::RecordNotUnique
  54. log "User #{email} was handled by another thread, taking this."
  55. return if self.class.find(article)
  56. log "User #{email} wasn't created sleep and retry."
  57. sleep rand 3
  58. retry
  59. end
  60. def roles
  61. [
  62. Role.find_by(name: 'Customer').id
  63. ]
  64. end
  65. def extract_display_name(from)
  66. # do extra decoding because we needed to use field.value
  67. Mail::Field.new('X-From', parsed_display_name(from)).to_s
  68. end
  69. def parsed_display_name(from)
  70. parsed_address = Mail::Address.new(from)
  71. return parsed_address.display_name if parsed_address.display_name
  72. return from if parsed_address.comments.blank?
  73. parsed_address.comments[0]
  74. rescue
  75. from
  76. end
  77. end
  78. end
  79. end