recent_view.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
  2. class RecentView < ApplicationModel
  3. belongs_to :object_lookup, class_name: 'ObjectLookup'
  4. after_create :notify_clients
  5. after_update :notify_clients
  6. after_destroy :notify_clients
  7. def self.log( object, o_id, user )
  8. # access check
  9. return if !access( object, o_id, user )
  10. # lookups
  11. object_lookup_id = ObjectLookup.by_name( object )
  12. # create entry
  13. record = {
  14. o_id: o_id,
  15. recent_view_object_id: object_lookup_id.to_i,
  16. created_by_id: user.id,
  17. }
  18. RecentView.create(record)
  19. end
  20. def self.log_destroy( requested_object, requested_object_id )
  21. return if requested_object == 'RecentView'
  22. RecentView.where( recent_view_object_id: ObjectLookup.by_name( requested_object ) ).
  23. where( o_id: requested_object_id ).
  24. destroy_all
  25. end
  26. def self.user_log_destroy( user )
  27. RecentView.where( created_by_id: user.id ).destroy_all
  28. end
  29. def self.list( user, limit = 10, type = nil )
  30. if !type
  31. recent_views = RecentView.where( created_by_id: user.id ).
  32. order('created_at DESC, id DESC').
  33. limit(limit)
  34. else
  35. recent_views = RecentView.select('DISTINCT(o_id), recent_view_object_id').where( created_by_id: user.id, recent_view_object_id: ObjectLookup.by_name(type) ) .
  36. order('created_at DESC, id DESC').
  37. limit(limit)
  38. end
  39. list = []
  40. recent_views.each { |item|
  41. data = item.attributes
  42. data['object'] = ObjectLookup.by_id( data['recent_view_object_id'] )
  43. data.delete( 'recent_view_object_id' )
  44. # access check
  45. next if !access( data['object'], data['o_id'], user )
  46. # add to result list
  47. list.push data
  48. }
  49. list
  50. end
  51. def self.list_full( user, limit = 10 )
  52. recent_viewed = self.list( user, limit )
  53. # get related object
  54. assets = ApplicationModel.assets_of_object_list(recent_viewed)
  55. {
  56. stream: recent_viewed,
  57. assets: assets,
  58. }
  59. end
  60. def notify_clients
  61. Sessions.send_to(
  62. self.created_by_id,
  63. {
  64. event: 'RecentView::changed',
  65. data: {}
  66. }
  67. )
  68. end
  69. private
  70. def self.access(object, o_id, user)
  71. # check if object exists
  72. begin
  73. return if !Kernel.const_get( object )
  74. record = Kernel.const_get( object ).lookup( id: o_id )
  75. return if !record
  76. rescue
  77. return
  78. end
  79. # check permission
  80. return if !record.respond_to?(:permission)
  81. record.permission( current_user: user )
  82. end
  83. end