activity_log.rb 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class Karma::ActivityLog < ApplicationModel
  3. belongs_to :object_lookup, class_name: 'ObjectLookup'
  4. self.table_name = 'karma_activity_logs'
  5. =begin
  6. add karma activity log of an object
  7. Karma::ActivityLog.add('ticket create', User.find(1), 'Ticket', 123)
  8. =end
  9. def self.add(action, user, object, o_id, force = false)
  10. activity = Karma::Activity.lookup(name: action)
  11. if object
  12. object_id = ObjectLookup.by_name(object)
  13. end
  14. Karma::ActivityLog.transaction do
  15. last_activity = Karma::ActivityLog.where(user_id: user.id).order(created_at: :desc, id: :desc).lock(true).first
  16. latest_activity = Karma::ActivityLog.where(
  17. user_id: user.id,
  18. object_lookup_id: object_id,
  19. o_id: o_id,
  20. activity_id: activity.id,
  21. ).find_by('created_at >= ?', Time.zone.now - activity.once_ttl.seconds)
  22. return false if !force && latest_activity
  23. score_total = 0
  24. if last_activity
  25. score_total = last_activity.score_total
  26. end
  27. local_score_total = score_total + activity.score
  28. if local_score_total.negative?
  29. local_score_total = 0
  30. end
  31. Karma::ActivityLog.create(
  32. object_lookup_id: object_id,
  33. o_id: o_id,
  34. user_id: user.id,
  35. activity_id: activity.id,
  36. score: activity.score,
  37. score_total: local_score_total,
  38. )
  39. end
  40. # set new karma level
  41. Karma::User.sync(user)
  42. true
  43. end
  44. =begin
  45. remove whole karma activity log of an object
  46. Karma::ActivityLog.remove('Ticket', 123)
  47. =end
  48. def self.remove(object_name, o_id)
  49. object_id = ObjectLookup.by_name(object_name)
  50. Karma::ActivityLog.where(
  51. object_lookup_id: object_id,
  52. o_id: o_id,
  53. ).destroy_all
  54. end
  55. def self.latest(user, limit = 12)
  56. result = []
  57. logs = Karma::ActivityLog.where(user_id: user.id).order(id: :desc).limit(limit)
  58. logs.each do |log|
  59. last = result.last
  60. if last && last[:object_id] == log.object_id && last[:o_id] == log.o_id && last[:created_at] == log.created_at
  61. comment = {
  62. description: Karma::Activity.lookup(id: log.activity_id).description,
  63. score: log.score,
  64. }
  65. last[:comments].push comment
  66. last[:score_total] = score_total
  67. next
  68. end
  69. comment = {
  70. object_id: log.object_id,
  71. o_id: log.o_id,
  72. description: Karma::Activity.lookup(id: log.activity_id).description,
  73. score: log.score,
  74. }
  75. data = {
  76. comments: [comment],
  77. score_total: log.score_total,
  78. created_at: log.created_at,
  79. }
  80. result.push data
  81. end
  82. result
  83. end
  84. end