amount_check.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module MonitoringHelper
  3. class AmountCheck
  4. CHECKS_MAP = [
  5. { param: :max_critical, notice: 'critical', type: 'gt' },
  6. { param: :min_critical, notice: 'critical', type: 'lt' },
  7. { param: :max_warning, notice: 'warning', type: 'gt' },
  8. { param: :min_warning, notice: 'warning', type: 'lt' },
  9. ].freeze
  10. TIMESCALE_MAP = {
  11. 's' => :seconds,
  12. 'm' => :minutes,
  13. 'h' => :hours,
  14. 'd' => :days
  15. }.freeze
  16. attr_reader :params
  17. def initialize(params)
  18. @params = params
  19. end
  20. def check_amount
  21. if given_params.blank?
  22. return {
  23. count: ticket_count
  24. }
  25. end
  26. if (failed_message = given_params.lazy.map { |row, value| check_single_row(row, value) }.find(&:present?))
  27. return failed_message
  28. end
  29. {
  30. state: 'ok',
  31. count: ticket_count,
  32. }
  33. end
  34. private
  35. def given_periode
  36. params[:periode]
  37. end
  38. def given_params
  39. CHECKS_MAP.filter_map do |row|
  40. next if params[row[:param]].blank?
  41. value = params[row[:param]].to_i
  42. raise Exceptions::UnprocessableEntity, "#{row[:param]} needs to be an integer!" if value.zero?
  43. [row, value]
  44. end
  45. end
  46. def created_at_threshold
  47. raise Exceptions::UnprocessableEntity, 'periode is missing!' if given_periode.blank?
  48. timescale = TIMESCALE_MAP[ given_periode.last ]
  49. raise Exceptions::UnprocessableEntity, 'periode needs to have s, m, h or d as last!' if !timescale
  50. periode = given_periode.first.to_i
  51. raise Exceptions::UnprocessableEntity, 'periode needs to be an integer!' if periode.zero?
  52. periode.send(timescale).ago
  53. end
  54. def ticket_count
  55. @ticket_count ||= Ticket.where(created_at: created_at_threshold..).count
  56. end
  57. def check_single_row(row, value)
  58. message = case row[:type]
  59. when 'gt'
  60. if ticket_count > value
  61. "The limit of #{value} was exceeded with #{ticket_count} in the last #{given_periode}"
  62. end
  63. when 'lt'
  64. if ticket_count <= value
  65. "The minimum of #{value} was undercut by #{ticket_count} in the last #{given_periode}"
  66. end
  67. end
  68. return if !message
  69. {
  70. state: row[:notice],
  71. message: message,
  72. count: ticket_count,
  73. }
  74. end
  75. end
  76. end