/
recent_view.rb
104 lines (79 loc) · 3.07 KB
/
recent_view.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
class RecentView < ApplicationModel
include RecentView::Assets
# rubocop:disable Rails/InverseOf
belongs_to :ticket, foreign_key: 'o_id'
belongs_to :object, class_name: 'ObjectLookup', foreign_key: 'recent_view_object_id'
# rubocop:enable Rails/InverseOf
after_create :notify_clients
after_update :notify_clients
after_destroy :notify_clients
def self.log(object, o_id, user)
return if !access(object, o_id, user)
exists_by_object_and_id?(object, o_id)
RecentView.create!(o_id: o_id,
recent_view_object_id: ObjectLookup.by_name(object),
created_by_id: user.id)
end
def self.log_destroy(requested_object, requested_object_id)
return if requested_object == 'RecentView'
RecentView.where(recent_view_object_id: ObjectLookup.by_name(requested_object))
.where(o_id: requested_object_id)
.destroy_all
end
def self.user_log_destroy(user)
RecentView.where(created_by_id: user.id).destroy_all
end
def self.list(user, limit = 10, object_name = nil)
recent_views = RecentView.select('o_id, ' \
'recent_view_object_id, ' \
'created_by_id, ' \
'MAX(created_at) as created_at, ' \
'MAX(id) as id')
.group(:o_id, :recent_view_object_id, :created_by_id)
.where(created_by_id: user.id)
.order('MAX(created_at) DESC, MAX(id) DESC')
.limit(limit)
if object_name.present?
recent_views = recent_views.where(recent_view_object_id: ObjectLookup.by_name(object_name))
end
# hide merged / removed tickets in Ticket Merge dialog
if object_name == 'Ticket'
recent_views = recent_views.limit(limit * 2)
viewable_ticket_ids = Ticket.where('id IN (?) AND state_id in (?)',
recent_views.map(&:o_id),
Ticket::State.by_category(:viewable_agent_new).pluck(:id))
.pluck(:id)
recent_views = recent_views.select { |rv| viewable_ticket_ids.include?(rv.o_id) }
.first(limit)
end
recent_views.select { |rv| access(ObjectLookup.by_id(rv.recent_view_object_id), rv.o_id, user) }
end
def notify_clients
Sessions.send_to(
created_by_id,
{
event: 'RecentView::changed',
data: {}
}
)
end
def self.access(object, o_id, user)
object.to_s
.constantize
.try(:lookup, { id: o_id })
.try(:access?, user, 'read')
rescue NameError
false
end
=begin
cleanup old entries
RecentView.cleanup
optional you can put the max oldest entries as argument
RecentView.cleanup(3.month)
=end
def self.cleanup(diff = 3.months)
RecentView.where('created_at < ?', Time.zone.now - diff).delete_all
true
end
end