ticket_user_ticket_counter_job.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class TicketUserTicketCounterJob < ApplicationJob
  3. include HasActiveJobLock
  4. def lock_key
  5. # "TicketUserTicketCounterJob/23/42"
  6. "#{self.class.name}/#{arguments[0]}/#{arguments[1]}"
  7. end
  8. def perform(customer_id, updated_by_id)
  9. # check if update is needed
  10. customer = User.lookup(id: customer_id)
  11. return if !customer
  12. # count open and closed tickets of customer
  13. ticket_count = {
  14. closed: 0,
  15. open: 0,
  16. }
  17. if customer_id != 1
  18. ticket_count.each_key do |ticket_state_category|
  19. ticket_states = Ticket::State.by_category(ticket_state_category)
  20. ticket_state_ids = ticket_states.map(&:id)
  21. tickets = Ticket.where(
  22. customer_id: customer_id,
  23. state_id: ticket_state_ids,
  24. )
  25. ticket_count[ticket_state_category] = tickets.count
  26. end
  27. end
  28. needs_update = false
  29. ticket_count.each_key do |ticket_state_category|
  30. preferences_key = :"tickets_#{ticket_state_category}"
  31. next if customer[:preferences][preferences_key] == ticket_count[ticket_state_category]
  32. needs_update = true
  33. customer[:preferences][preferences_key] = ticket_count[ticket_state_category]
  34. end
  35. return if !needs_update
  36. customer.updated_by_id = updated_by_id
  37. customer.save
  38. end
  39. end