status.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Whatsapp::Webhook::Message::Status
  3. include Mixin::RequiredSubPaths
  4. attr_reader :data, :channel, :ticket, :related_article
  5. def initialize(data:, channel:)
  6. @data = data
  7. @channel = channel
  8. end
  9. def process
  10. @related_article = find_related_article
  11. raise Whatsapp::Webhook::Payload::ProcessableError, __('No related article found to process the status message on.') if @related_article.nil?
  12. @ticket = @related_article.ticket
  13. return if ticket_done?
  14. create_article
  15. update_related_article
  16. update_ticket
  17. end
  18. private
  19. def ticket_done?
  20. state_ids = Ticket::State.where(name: %w[closed merged removed]).pluck(:id)
  21. state_ids.include?(@ticket.state_id)
  22. end
  23. def body
  24. raise NotImplementedError
  25. end
  26. def status
  27. @status ||= @data[:entry]
  28. .first[:changes]
  29. .first[:value][:statuses]
  30. .first
  31. end
  32. def find_related_article
  33. Ticket::Article.where(message_id: status[:id])&.first
  34. end
  35. def update_related_article?
  36. true
  37. end
  38. def article_timestamp_key
  39. raise NotImplementedError
  40. end
  41. def update_related_article_attributes
  42. preferences = @related_article.preferences
  43. preferences[:whatsapp][article_timestamp_key] = status[:timestamp]
  44. { preferences: }
  45. end
  46. def update_related_article
  47. return if !update_related_article? || update_related_article_attributes.blank?
  48. UserInfo.with_user_id(@related_article.updated_by_id) do
  49. @related_article.update!(update_related_article_attributes)
  50. end
  51. end
  52. def create_article?
  53. false
  54. end
  55. def create_article
  56. return if !create_article?
  57. Ticket::Article.create!(
  58. ticket_id: @ticket.id,
  59. type_id: Ticket::Article::Type.lookup(name: 'note').id,
  60. sender_id: Ticket::Article::Sender.lookup(name: 'System').id,
  61. from: "#{@channel.options[:name]} (#{@channel.options[:phone_number]})",
  62. internal: true,
  63. body: "Unable to handle WhatsApp message: #{body}",
  64. content_type: 'text/plain',
  65. preferences: {
  66. delivery_article_id_related: @related_article.id,
  67. delivery_message: true,
  68. },
  69. updated_by_id: 1,
  70. created_by_id: 1,
  71. )
  72. end
  73. def update_ticket?
  74. false
  75. end
  76. def update_ticket_attributes
  77. raise NotImplementedError
  78. end
  79. def update_ticket
  80. return if !update_ticket? || update_ticket_attributes.blank?
  81. UserInfo.with_user_id(@ticket.updated_by_id) do
  82. @ticket.update!(update_ticket_attributes)
  83. end
  84. end
  85. end