blob: 9d15bcff0d2f57ebe7501679c174b8b8cccb4788 [file] [log] [blame]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -05001#
2# ex:ts=4:sw=4:sts=4:et
3# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
4#
5# BitBake Toaster Implementation
6#
7# Copyright (C) 2015 Intel Corporation
8#
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License version 2 as
11# published by the Free Software Foundation.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License along
19# with this program; if not, write to the Free Software Foundation, Inc.,
20# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22from django.db.models import Q, Max, Min
23from django.utils import dateparse, timezone
24from datetime import timedelta
25
26class TableFilter(object):
27 """
28 Stores a filter for a named field, and can retrieve the action
29 requested from the set of actions for that filter;
30 the order in which actions are added governs the order in which they
31 are returned in the JSON for the filter
32 """
33
34 def __init__(self, name, title):
35 self.name = name
36 self.title = title
37 self.__filter_action_map = {}
38
39 # retains the ordering of actions
40 self.__filter_action_keys = []
41
42 def add_action(self, action):
43 self.__filter_action_keys.append(action.name)
44 self.__filter_action_map[action.name] = action
45
46 def get_action(self, action_name):
47 return self.__filter_action_map[action_name]
48
49 def to_json(self, queryset):
50 """
51 Dump all filter actions as an object which can be JSON serialised;
52 this is used to generate the JSON for processing in
53 table.js / filterOpenClicked()
54 """
55 filter_actions = []
56
57 # add the "all" pseudo-filter action, which just selects the whole
58 # queryset
59 filter_actions.append({
60 'action_name' : 'all',
61 'title' : 'All',
62 'type': 'toggle',
63 'count' : queryset.count()
64 })
65
66 # add other filter actions
67 for action_name in self.__filter_action_keys:
68 filter_action = self.__filter_action_map[action_name]
69 obj = filter_action.to_json(queryset)
70 obj['action_name'] = action_name
71 filter_actions.append(obj)
72
73 return {
74 'name': self.name,
75 'title': self.title,
76 'filter_actions': filter_actions
77 }
78
79class TableFilterQueryHelper(object):
80 def dateStringsToQ(self, field_name, date_from_str, date_to_str):
81 """
82 Convert the date strings from_date_str and to_date_str into a
83 set of args in the form
84
85 {'<field_name>__gte': <date from>, '<field_name>__lte': <date to>}
86
87 where date_from and date_to are Django-timezone-aware dates; then
88 convert that into a Django Q object
89
90 Returns the Q object based on those criteria
91 """
92
93 # one of the values required for the filter is missing, so set
94 # it to the one which was supplied
95 if date_from_str == '':
96 date_from_str = date_to_str
97 elif date_to_str == '':
98 date_to_str = date_from_str
99
100 date_from_naive = dateparse.parse_datetime(date_from_str + ' 00:00:00')
101 date_to_naive = dateparse.parse_datetime(date_to_str + ' 23:59:59')
102
103 tz = timezone.get_default_timezone()
104 date_from = timezone.make_aware(date_from_naive, tz)
105 date_to = timezone.make_aware(date_to_naive, tz)
106
107 args = {}
108 args[field_name + '__gte'] = date_from
109 args[field_name + '__lte'] = date_to
110
111 return Q(**args)
112
113class TableFilterAction(object):
114 """
115 A filter action which displays in the filter popup for a ToasterTable
116 and uses an associated QuerysetFilter to filter the queryset for that
117 ToasterTable
118 """
119
120 def __init__(self, name, title, criteria):
121 self.name = name
122 self.title = title
123 self.criteria = criteria
124
125 # set in subclasses
126 self.type = None
127
128 def set_filter_params(self, params):
129 """
130 params: (str) a string of extra parameters for the action;
131 the structure of this string depends on the type of action;
132 it's ignored for a toggle filter action, which is just on or off
133 """
134 pass
135
136 def filter(self, queryset):
137 if self.criteria:
138 return queryset.filter(self.criteria)
139 else:
140 return queryset
141
142 def to_json(self, queryset):
143 """ Dump as a JSON object """
144 return {
145 'title': self.title,
146 'type': self.type,
147 'count': self.filter(queryset).count()
148 }
149
150class TableFilterActionToggle(TableFilterAction):
151 """
152 A single filter action which will populate one radio button of
153 a ToasterTable filter popup; this filter can either be on or off and
154 has no other parameters
155 """
156
157 def __init__(self, *args):
158 super(TableFilterActionToggle, self).__init__(*args)
159 self.type = 'toggle'
160
161class TableFilterActionDay(TableFilterAction):
162 """
163 A filter action which filters according to the named datetime field and a
164 string representing a day ("today" or "yesterday")
165 """
166
167 TODAY = 'today'
168 YESTERDAY = 'yesterday'
169
170 def __init__(self, name, title, field, day,
171 query_helper = TableFilterQueryHelper()):
172 """
173 field: (string) the datetime field to filter by
174 day: (string) "today" or "yesterday"
175 """
176 super(TableFilterActionDay, self).__init__(name, title, None)
177 self.type = 'day'
178 self.field = field
179 self.day = day
180 self.query_helper = query_helper
181
182 def filter(self, queryset):
183 """
184 Apply the day filtering before returning the queryset;
185 this is done here as the value of the filter criteria changes
186 depending on when the filtering is applied
187 """
188
189 now = timezone.now()
190
191 if self.day == self.YESTERDAY:
192 increment = timedelta(days=1)
193 wanted_date = now - increment
194 else:
195 wanted_date = now
196
197 wanted_date_str = wanted_date.strftime('%Y-%m-%d')
198
199 self.criteria = self.query_helper.dateStringsToQ(
200 self.field,
201 wanted_date_str,
202 wanted_date_str
203 )
204
205 return queryset.filter(self.criteria)
206
207class TableFilterActionDateRange(TableFilterAction):
208 """
209 A filter action which will filter the queryset by a date range.
210 The date range can be set via set_params()
211 """
212
213 def __init__(self, name, title, field,
214 query_helper = TableFilterQueryHelper()):
215 """
216 field: (string) the field to find the max/min range from in the queryset
217 """
218 super(TableFilterActionDateRange, self).__init__(
219 name,
220 title,
221 None
222 )
223
224 self.type = 'daterange'
225 self.field = field
226 self.query_helper = query_helper
227
228 def set_filter_params(self, params):
229 """
230 This filter depends on the user selecting some input, so it needs
231 to have its parameters set before its queryset is filtered
232
233 params: (str) a string of extra parameters for the filtering
234 in the format "2015-12-09,2015-12-11" (from,to); this is passed in the
235 querystring and used to set the criteria on the QuerysetFilter
236 associated with this action
237 """
238
239 # if params are invalid, return immediately, resetting criteria
240 # on the QuerysetFilter
241 try:
242 date_from_str, date_to_str = params.split(',')
243 except ValueError:
244 self.criteria = None
245 return
246
247 # one of the values required for the filter is missing, so set
248 # it to the one which was supplied
249 self.criteria = self.query_helper.dateStringsToQ(
250 self.field,
251 date_from_str,
252 date_to_str
253 )
254
255 def to_json(self, queryset):
256 """ Dump as a JSON object """
257 data = super(TableFilterActionDateRange, self).to_json(queryset)
258
259 # additional data about the date range covered by the queryset's
260 # records, retrieved from its <field> column
261 data['min'] = queryset.aggregate(Min(self.field))[self.field + '__min']
262 data['max'] = queryset.aggregate(Max(self.field))[self.field + '__max']
263
264 # a range filter has a count of None, as the number of records it
265 # will select depends on the date range entered and we don't know
266 # that ahead of time
267 data['count'] = None
268
269 return data
270
271class TableFilterMap(object):
272 """
273 Map from field names to TableFilter objects for those fields
274 """
275
276 def __init__(self):
277 self.__filters = {}
278
279 def add_filter(self, filter_name, table_filter):
280 """ table_filter is an instance of Filter """
281 self.__filters[filter_name] = table_filter
282
283 def get_filter(self, filter_name):
284 return self.__filters[filter_name]
285
286 def to_json(self, queryset):
287 data = {}
288
289 for filter_name, table_filter in self.__filters.iteritems():
290 data[filter_name] = table_filter.to_json()
291
292 return data