stats.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class Stats
  3. =begin
  4. generate stats for user
  5. Stats.generate
  6. returns
  7. result = true # if generation was successfully
  8. =end
  9. def self.generate
  10. # generate stats per agent
  11. users = User.with_permissions('ticket.agent')
  12. agent_count = 0
  13. user_result = {}
  14. users.each do |user|
  15. next if user.id == 1
  16. next if !user.active
  17. agent_count += 1
  18. data = {}
  19. backends = Setting.where(area: 'Dashboard::Stats')
  20. if backends.blank?
  21. raise __("No settings with area 'Dashboard::Stats' defined")
  22. end
  23. backends.each do |stats_item|
  24. # additional permission check
  25. next if stats_item.preferences[:permission] && !user.permissions?(stats_item.preferences[:permission])
  26. backend = stats_item.state_current[:value]
  27. if !backend
  28. raise "Dashboard::Stats backend #{stats_item.name} is not defined"
  29. end
  30. backend = backend.constantize
  31. data[backend] = backend.generate(user)
  32. end
  33. user_result[user] = data
  34. end
  35. # calculate average
  36. backend_average_sum = {}
  37. user_result.each_value do |data|
  38. data.each do |backend_model, backend_result|
  39. next if !backend_result.key?(:used_for_average)
  40. if !backend_average_sum[backend_model]
  41. backend_average_sum[backend_model] = 0
  42. end
  43. backend_average_sum[backend_model] += backend_result[:used_for_average]
  44. end
  45. end
  46. # generate average param and icon state
  47. backend_average_sum.each do |backend_model_average, result|
  48. average = (result.to_f / agent_count).round(1)
  49. user_result.each do |user, data|
  50. next if !data[backend_model_average]
  51. next if !data[backend_model_average].key?(:used_for_average)
  52. data[backend_model_average][:average_per_agent] = average
  53. # generate icon state
  54. backend_model_average.to_s.constantize.average_state(data[backend_model_average], user.id)
  55. end
  56. end
  57. user_result.each do |user, data|
  58. data_for_user = {}
  59. data.each do |backend, result|
  60. data_for_user[backend.to_app_model] = result
  61. end
  62. state_store = StatsStore.sync(
  63. stats_storable: user,
  64. key: 'dashboard',
  65. data: data_for_user,
  66. )
  67. message = {
  68. event: 'resetCollection',
  69. data: {
  70. state_store.class.to_app_model => [state_store],
  71. },
  72. }
  73. Sessions.send_to(user.id, message)
  74. event = {
  75. event: 'dashboard_stats_rebuild',
  76. }
  77. Sessions.send_to(user.id, event)
  78. end
  79. true
  80. end
  81. end