Commit 6cbc80264b2bf434bb61fe1fcef6b2779186562c

Authored by janek37
1 parent da5ab9b9

ukrywanie kandydatów i zmiotek w widoku czytelniczki + spora refaktoryzacja

dictionary/ajax_lexeme_slickgrid.py
1 1 # -*- coding: utf-8 -*-
2 2 from hashlib import md5
  3 +import locale
3 4  
4 5 from django.db.models import Count, Q
5 6 from django.core.cache import cache
6 7 from django.utils.encoding import force_unicode
7 8  
8   -from dictionary.models import Lexeme, LexemeAttribute, PartOfSpeech, LexemeList, \
9   - LexemeIndex
  9 +from dictionary.models import Lexeme, LexemeAttribute, PartOfSpeech, \
  10 + LexemeList, LexemeIndex
10 11 from dictionary.ajax_slickgrid import SlickGridQuery
11 12 from common.decorators import ajax
12 13 from common.util import bisect_left, reverse, json_encode
  14 +from dictionary.util import check_query_params
13 15  
14   -import locale
15 16 locale.setlocale(locale.LC_ALL, 'pl_PL.UTF-8')
16 17  
17 18 ASPECT = LexemeAttribute.objects.get(name=u'aspekt')
... ... @@ -31,8 +32,8 @@ class LexemeQuery(SlickGridQuery):
31 32 'pos': lambda lexeme: lexeme.part_of_speech_id,
32 33 'patterns': lambda lexeme: lexeme.lip_data()['patterns'],
33 34 'genders': lambda lexeme:
34   - getattr(lexeme.attribute_value(ASPECT), 'value', '')
35   - or lexeme.lip_data()['genders'],
  35 + getattr(lexeme.attribute_value(ASPECT), 'value', '') or
  36 + lexeme.lip_data()['genders'],
36 37 'vocabs': lambda lexeme:
37 38 '/'.join(lexeme.vocabularies.values_list('id', flat=True)),
38 39 'owner': lambda lexeme: lexeme.owner_vocabulary_id,
... ... @@ -61,9 +62,10 @@ class LexemeQuery(SlickGridQuery):
61 62 'abbr_pos': 'part_of_speech__abbr_name',
62 63 }
63 64  
64   - def __init__(self, visible_vocabs, *args, **kwargs):
65   - self.visible_vocabs = list(visible_vocabs)
  65 + def __init__(self, *args, **kwargs):
66 66 super(LexemeQuery, self).__init__(*args, **kwargs)
  67 + self.visible_vocabs = self.query_params['visible_vocabs']
  68 + self.reader = self.query_params['reader']
67 69 self.lexeme_list = self.get_lexeme_list()
68 70  
69 71 def a_fronte(self):
... ... @@ -132,9 +134,13 @@ class LexemeQuery(SlickGridQuery):
132 134 'op': 'in',
133 135 'data': tuple(matching_values),
134 136 }
  137 +
135 138 # optymalizacja warunków "różne od"
136   - ident = lambda x: x
137   - int_list = lambda l: [int(i) for i in l] if l else []
  139 + def ident(x): return x
  140 +
  141 + def int_list(l):
  142 + return [int(i) for i in l] if l else []
  143 +
138 144 indirect_fields = {
139 145 'containing_vocabulary': (
140 146 'slownik', 'leksemy_w_slownikach', 'l_id', ident),
... ... @@ -156,8 +162,8 @@ class LexemeQuery(SlickGridQuery):
156 162 int_list),
157 163 }
158 164 if lookup == '-in' and (
159   - field in indirect_fields
160   - or field.startswith('extra') and attr.closed):
  165 + field in indirect_fields or
  166 + field.startswith('extra') and attr.closed):
161 167 key = 'extra' if field.startswith('extra') else field
162 168 field1, table, field2, f = indirect_fields[key]
163 169 for value in f(new_rule['data']):
... ... @@ -188,6 +194,8 @@ class LexemeQuery(SlickGridQuery):
188 194  
189 195 def get_queryset(self):
190 196 lexemes = super(LexemeQuery, self).get_queryset()
  197 + if self.reader:
  198 + lexemes = lexemes.exclude(status__in=Lexeme.HIDDEN_STATUSES)
191 199 return lexemes.distinct().filter(
192 200 vocabularies__id__in=self.visible_vocabs)
193 201  
... ... @@ -234,9 +242,7 @@ class LexemeQuery(SlickGridQuery):
234 242 return index
235 243  
236 244 def cache_key(self):
237   - key = json_encode(
238   - (self.sort_rules, self.filter, self.visible_vocabs),
239   - ensure_ascii=True)
  245 + key = json_encode(self.query_params, ensure_ascii=True)
240 246 return md5(key.encode()).hexdigest()
241 247  
242 248 def get_cached_lexemes(self, refresh=True):
... ... @@ -355,34 +361,33 @@ class LexemeQuery(SlickGridQuery):
355 361 fields = [
356 362 column_translation.get(column, column) for column in columns]
357 363 for row in lexemes.values(*fields):
358   - print >>output_file, '\t'.join(
  364 + print >> output_file, '\t'.join(
359 365 unicode(row[field]) for field in fields)
360 366  
361 367  
362 368 # Zapytanie o indeks wiersza o pewnym id przy danym sortowaniu
363 369 @ajax(login_required=False, method='get')
364   -def row_index(request, id, sort_rules, filter, visible_vocabs):
365   - query = LexemeQuery(
366   - filter=filter, sort_rules=sort_rules, visible_vocabs=visible_vocabs)
  370 +def row_index(request, id, query_params):
  371 + check_query_params(request, query_params)
  372 + query = LexemeQuery(query_params)
367 373 return {'index': query.row_index(id)}
368 374  
369 375  
370 376 @ajax(login_required=False, method='get')
371   -def search_index(request, sort_rules, filter, visible_vocabs, search=''):
372   - query = LexemeQuery(
373   - filter=filter, sort_rules=sort_rules, visible_vocabs=visible_vocabs)
  377 +def search_index(request, query_params, search=''):
  378 + check_query_params(request, query_params)
  379 + query = LexemeQuery(query_params)
374 380 return {'index': query.search_index(search)}
375 381  
376 382  
377 383 @ajax(login_required=False, method='get')
378   -def get_lexemes(request, from_page, to_page, rows, sort_rules, filter,
379   - visible_vocabs, force_reload=False):
380   - request.session['sort_rules'] = sort_rules
381   - request.session['filter'] = filter
  384 +def get_lexemes(request, from_page, to_page, rows, query_params,
  385 + force_reload=False):
  386 + check_query_params(request, query_params)
  387 + request.session['sort_rules'] = query_params['sort_rules']
  388 + request.session['filter'] = query_params['filter']
382 389 columns = request.session.get('columns')
383   - query = LexemeQuery(
384   - filter=filter, sort_rules=sort_rules, visible_vocabs=visible_vocabs,
385   - columns=columns)
  390 + query = LexemeQuery(query_params, columns=columns)
386 391 start, response_rowcount = query.count_pages(from_page, to_page, rows)
387 392 if query.lexeme_list:
388 393 count = query.lexeme_list.lexemeindex_set.count()
... ... @@ -393,7 +398,8 @@ def get_lexemes(request, from_page, to_page, rows, sort_rules, filter,
393 398 id_list = query.get_id_list(force_reload)
394 399 count = len(id_list)
395 400 sublist = id_list[start:start + response_rowcount]
396   - lexemes_qs = prefetch(Lexeme.all_objects.filter(id__in=sublist)) # brzydka łata
  401 + # brzydka łata
  402 + lexemes_qs = prefetch(Lexeme.all_objects.filter(id__in=sublist))
397 403 lexemes_dict = dict((l.id, l) for l in lexemes_qs)
398 404 lexemes = [lexemes_dict[lexeme_id] for lexeme_id in sublist]
399 405 return {
... ... @@ -404,9 +410,9 @@ def get_lexemes(request, from_page, to_page, rows, sort_rules, filter,
404 410  
405 411  
406 412 @ajax(login_required=False, method='get')
407   -def search_by_form(request, sort_rules, filter, exponent, visible_vocabs):
408   - query = LexemeQuery(
409   - filter=filter, sort_rules=sort_rules, visible_vocabs=visible_vocabs)
  413 +def search_by_form(request, query_params, exponent):
  414 + check_query_params(request, query_params)
  415 + query = LexemeQuery(query_params)
410 416 lexemes = query.get_sorted_queryset().filter(lexemeform__form=exponent)
411 417 rows = [row for row in query.prepare_rows(lexemes)]
412 418 for row in rows:
... ...
dictionary/ajax_lexeme_view.py
... ... @@ -253,10 +253,13 @@ def insert_new_lexeme(lexeme, request):
253 253 sort_rules = request.session.get('sort_rules')
254 254 if filter is None or sort_rules is None:
255 255 return
256   - query = LexemeQuery(
257   - filter=filter, sort_rules=sort_rules,
258   - visible_vocabs=visible_vocabularies(request.user).values_list(
259   - 'id', flat=True))
  256 + query = LexemeQuery({
  257 + 'filter': filter,
  258 + 'sort_rules': sort_rules,
  259 + 'visible_vocabs':
  260 + visible_vocabularies(request.user).values_list('id', flat=True),
  261 + 'reader': False,
  262 + })
260 263 id_list = query.get_cached_lexemes()
261 264 if id_list is not None:
262 265 index = bisect_left(id_list, lexeme.entry, cmp=query.lexeme_cmp())
... ... @@ -659,10 +662,13 @@ def dynamic_action_fields(request, field_name):
659 662  
660 663 @ajax(method='post', permission_required='dictionary.change_lexeme')
661 664 def execute_group_actions(request, actions, filter):
662   - query = LexemeQuery(
663   - filter=filter, sort_rules=[],
664   - visible_vocabs=visible_vocabularies(request.user).values_list(
665   - 'id', flat=True))
  665 + query = LexemeQuery({
  666 + 'filter': filter,
  667 + 'sort_rules': [],
  668 + 'visible_vocabs':
  669 + visible_vocabularies(request.user).values_list('id', flat=True),
  670 + 'reader': False
  671 + })
666 672 pk_list = query.get_id_list()
667 673 lexemes = Lexeme.objects.filter(pk__in=pk_list)
668 674 for l in lexemes:
... ...
dictionary/ajax_slickgrid.py
... ... @@ -28,9 +28,10 @@ class SlickGridQuery(object):
28 28 '-isnull': '-isnull',
29 29 }
30 30  
31   - def __init__(self, filter, sort_rules, columns=None):
32   - self.filter = filter
33   - self.sort_rules = sort_rules
  31 + def __init__(self, query_params, columns=None):
  32 + self.query_params = query_params
  33 + self.filter = query_params['filter']
  34 + self.sort_rules = query_params['sort_rules']
34 35 if columns:
35 36 self.columns = tuple(columns)
36 37 else:
... ...
dictionary/management/commands/prepare_lexeme_lists.py
... ... @@ -15,7 +15,6 @@ class Command(BaseCommand):
15 15 vocabularies = sorted(
16 16 visible_vocabularies(AnonymousUser()).values_list('id', flat=True))
17 17  
18   -
19 18 def handle(self, *args, **options):
20 19 transaction.enter_transaction_management()
21 20 for a_fronte in (True, False):
... ... @@ -23,7 +22,12 @@ class Command(BaseCommand):
23 22 filter=json_encode(self.filter), a_fronte=a_fronte,
24 23 vocabularies=json_encode(self.vocabularies))
25 24 sort_rules = ['a_fronte' if a_fronte else 'a_tergo']
26   - query = LexemeQuery(self.vocabularies, self.filter, sort_rules)
  25 + query = LexemeQuery({
  26 + 'filter': self.filter,
  27 + 'sort_rules': sort_rules,
  28 + 'visible_vocabs': self.vocabularies,
  29 + 'reader': True
  30 + })
27 31 query.reload_lexeme_list()
28 32 transaction.commit()
29 33 transaction.leave_transaction_management()
30 34 \ No newline at end of file
... ...
dictionary/static/js/lexeme-view.js
... ... @@ -82,8 +82,7 @@ $.each(column_names, function(key, name) {
82 82  
83 83 $.extend(slickgrid, {
84 84 loader: new Slick.Data.RemoteModel(
85   - $dj.ajax_get_page, $dj.ajax_search_index,
86   - {visible_vocabs: visible_vocab_ids}),
  85 + $dj.ajax_get_page, $dj.ajax_search_index),
87 86 grid_caption: gettext("Leksemy"),
88 87 grid_element_id: 'lexeme-grid',
89 88 main_field: 'entry',
... ... @@ -229,30 +228,14 @@ $.extend(slickgrid, {
229 228 }
230 229 },
231 230  
232   - row_index: function(id) {
  231 + query_params: function() {
233 232 "use strict";
234   - $.ajaxJSON({
235   - url: $dj.ajax_row_index,
236   - method: 'get',
237   - data: {
238   - id: id,
239   - sort_rules: slickgrid.loader.getSort(),
240   - filter: slickgrid.loader.getFilter(),
241   - visible_vocabs: visible_vocab_ids
242   - },
243   - callback: function(data) {
244   - var index = data.index;
245   - if (index === null) {
246   - slickgrid.load_content(id);
247   - slickgrid.last_active_row = undefined;
248   - slickgrid.grid.resetActiveCell();
249   - } else {
250   - slickgrid.set_active_when_loaded = index;
251   - slickgrid.grid.scrollRowToCenter(index);
252   - slickgrid.ensure_data();
253   - }
254   - }
255   - });
  233 + return {
  234 + sort_rules: slickgrid.loader.getSort(),
  235 + filter: slickgrid.loader.getFilter(),
  236 + visible_vocabs: visible_vocab_ids,
  237 + reader: $dj.reader
  238 + };
256 239 },
257 240  
258 241 init_sort: function() {
... ... @@ -288,10 +271,8 @@ $.extend(slickgrid, {
288 271 url: $dj.ajax_search_by_form,
289 272 method: 'get',
290 273 data: {
291   - filter: slickgrid.loader.getFilter(),
292   - sort_rules: slickgrid.loader.getSort(),
293 274 exponent: slickgrid.search_string(),
294   - visible_vocabs: visible_vocab_ids
  275 + query_params: slickgrid.query_params()
295 276 },
296 277 callback: function(data) {
297 278 var table = $('#search-by-form-table');
... ...
dictionary/static/js/remotemodel.js
1   -/* global Slick */
  1 +/* global Slick, slickgrid */
2 2  
3 3 (function ($) {
4 4 "use strict";
5   - function RemoteModel(data_url, search_index_url, extra_data) {
  5 + function RemoteModel(data_url, search_index_url) {
6 6 // private
7 7 var PAGESIZE = 50;
8 8 var data = {length: 0};
... ... @@ -93,11 +93,9 @@
93 93 rows: PAGESIZE,
94 94 from_page: fromPage,
95 95 to_page: toPage,
96   - sort_rules: sort_rules,
97   - filter: filter,
98   - force_reload: force_reload
  96 + force_reload: force_reload,
  97 + query_params: slickgrid.query_params()
99 98 };
100   - $.extend(ajax_data, extra_data);
101 99 force_reload = false;
102 100  
103 101 ajax_request = $.ajaxJSON({
... ... @@ -165,11 +163,9 @@
165 163  
166 164 function searchRow(search_text, callback) {
167 165 var data = {
168   - filter: filter,
169   - sort_rules: sort_rules,
170   - search: search_text
  166 + search: search_text,
  167 + query_params: slickgrid.query_params()
171 168 };
172   - $.extend(data, extra_data);
173 169 $.ajaxJSON({
174 170 url: search_index_url,
175 171 method: 'get',
... ...
dictionary/static/js/slickgrid.js
... ... @@ -79,6 +79,30 @@ var slickgrid = {
79 79 slickgrid.search();
80 80 },
81 81  
  82 + row_index: function(id) {
  83 + "use strict";
  84 + $.ajaxJSON({
  85 + url: $dj.ajax_row_index,
  86 + method: 'get',
  87 + data: {
  88 + id: id,
  89 + query_params: slickgrid.query_params()
  90 + },
  91 + callback: function(data) {
  92 + var index = data.index;
  93 + if (index === null) {
  94 + slickgrid.load_content(id);
  95 + slickgrid.last_active_row = undefined;
  96 + slickgrid.grid.resetActiveCell();
  97 + } else {
  98 + slickgrid.set_active_when_loaded = index;
  99 + slickgrid.grid.scrollRowToCenter(index);
  100 + slickgrid.ensure_data();
  101 + }
  102 + }
  103 + });
  104 + },
  105 +
82 106 ensure_data: function() {
83 107 "use strict";
84 108 $('#filter-button').children().first().toggleClass('ui-state-highlight',
... ... @@ -542,8 +566,7 @@ $(function() {
542 566 function export_list(filename) {
543 567 "use strict";
544 568 var param = {
545   - filter: JSON.stringify(slickgrid.loader.getFilter()),
546   - sort_rules: JSON.stringify(slickgrid.loader.getSort()),
  569 + query_params: JSON.stringify(slickgrid.query_params()),
547 570 columns: JSON.stringify($.map(
548 571 slickgrid.grid.getColumns(), function(col) {return col.field;})),
549 572 filename: filename
... ...
dictionary/util.py
1 1 # -*- coding: utf-8 -*-
  2 +from common.decorators import AjaxError
2 3  
3 4 from dictionary.models import BaseFormLabel
4 5  
... ... @@ -51,3 +52,8 @@ def compare_patterns(patterns):
51 52 for bfl in differing_bfls])
52 53 for pattern, root in patterns)
53 54 return diffs
  55 +
  56 +
  57 +def check_query_params(request, query_params):
  58 + if not request.user.is_authenticated() and not query_params['reader']:
  59 + raise AjaxError('access denied')
... ...
dictionary/views.py
... ... @@ -14,6 +14,7 @@ from dictionary.models import visible_vocabularies, PartOfSpeech, Lexeme, \
14 14 get_exclusion_classes, editable_vocabularies, \
15 15 CrossReferenceType, PatternType, \
16 16 LexemeAttribute, Gender, BorrowingSource
  17 +from dictionary.util import check_query_params
17 18 from dictionary.wsjp import make_data
18 19  
19 20  
... ... @@ -119,6 +120,7 @@ def lexeme_view(request):
119 120 User.objects.order_by('username').values_list('id', 'username'))
120 121 js_vars = common_lexeme_js_vars(request, visible)
121 122 js_vars.update({
  123 + 'reader': False,
122 124 'ajax_history_table': reverse('history_table'),
123 125 'ajax_odm_forms': reverse('odm_forms'),
124 126 'ajax_edit_form': reverse('lexeme_edit_form'),
... ... @@ -164,6 +166,7 @@ def reader_view(request):
164 166 visible = visible_vocabularies(AnonymousUser())
165 167 js_vars = common_lexeme_js_vars(request, visible)
166 168 js_vars.update({
  169 + 'reader': True,
167 170 'vocabs': {},
168 171 'user_options': [],
169 172 'auto_search': True,
... ... @@ -190,15 +193,12 @@ def reports(request):
190 193  
191 194 @permission_required('dictionary.view_lexeme')
192 195 def export_list(request):
193   - filter = json_decode(request.GET['filter'])
194   - sort_rules = json_decode(request.GET['sort_rules'])
  196 + query_params = json_decode(request.GET['query_params'])
  197 + check_query_params(request, query_params)
195 198 columns = json_decode(request.GET['columns'])
196 199 filename = request.GET.get('filename') or 'lista.txt'
  200 + query = LexemeQuery(query_params)
197 201 response = HttpResponse(content_type='text/plain')
198   - visible_vocabs = list(visible_vocabularies(request.user).values_list(
199   - 'id', flat=True))
200   - query = LexemeQuery(
201   - filter=filter, sort_rules=sort_rules, visible_vocabs=visible_vocabs)
202 202 query.export_list(columns, response)
203 203 response['Content-Disposition'] = ('attachment; filename=%s' % filename)
204 204 return response
... ...
patterns/ajax_pattern_view.py
... ... @@ -39,8 +39,8 @@ class PatternQuery(SlickGridQuery):
39 39  
40 40 # Zapytanie o indeks wiersza o pewnym id przy danym sortowaniu
41 41 @ajax(login_required=False, method='get')
42   -def row_index(request, id, sort_rules, filter):
43   - query = PatternQuery(filter=filter, sort_rules=sort_rules)
  42 +def row_index(request, id, query_params):
  43 + query = PatternQuery(query_params)
44 44 return {'index': query.row_index(id)}
45 45  
46 46  
... ... @@ -48,17 +48,17 @@ def row_index(request, id, sort_rules, filter):
48 48 # pierwszego wiersza, którego hasło rozpoczyna się od search.
49 49 # 'selected_id' < 0, jeśli takiego nie ma
50 50 @ajax(login_required=False, method='get')
51   -def search_index(request, sort_rules, filter, search=''):
52   - query = PatternQuery(filter=filter, sort_rules=sort_rules)
  51 +def search_index(request, query_params, search=''):
  52 + query = PatternQuery(query_params)
53 53 return {'index': query.search_index(search)}
54 54  
55 55  
56 56 @ajax(login_required=False, method='get')
57   -def get_patterns(request, from_page, to_page, rows, sort_rules, filter):
58   - request.session['pattern-sort_rules'] = sort_rules
59   - request.session['pattern-filter'] = filter
  57 +def get_patterns(request, from_page, to_page, rows, query_params):
  58 + request.session['pattern-sort_rules'] = query_params['sort_rules']
  59 + request.session['pattern-filter'] = query_params['filter']
60 60 columns = request.session.get('pattern-columns')
61   - query = PatternQuery(filter=filter, sort_rules=sort_rules, columns=columns)
  61 + query = PatternQuery(query_params, columns=columns)
62 62 rows, count = query.get_page(from_page, to_page, rows)
63 63 return {
64 64 'rows': rows,
... ...
patterns/static/js/pattern-view.js
... ... @@ -51,29 +51,12 @@ $.extend(slickgrid, {
51 51 },
52 52 init_sort: function() {},
53 53 init: function() {},
54   - // copypasta
55   - row_index: function(id) {
  54 +
  55 + query_params: function() {
56 56 "use strict";
57   - $.ajaxJSON({
58   - url: $dj.ajax_row_index,
59   - method: 'get',
60   - data: {
61   - id: id,
62   - sort_rules: slickgrid.loader.getSort(),
63   - filter: slickgrid.loader.getFilter()
64   - },
65   - callback: function(data) {
66   - var index = data.index;
67   - if (index === null) {
68   - slickgrid.load_content(id);
69   - slickgrid.last_active_row = undefined;
70   - slickgrid.grid.resetActiveCell();
71   - } else {
72   - slickgrid.set_active_when_loaded = index;
73   - slickgrid.grid.scrollRowToCenter(index);
74   - slickgrid.ensure_data();
75   - }
76   - }
77   - });
  57 + return {
  58 + sort_rules: slickgrid.loader.getSort(),
  59 + filter: slickgrid.loader.getFilter()
  60 + };
78 61 }
79 62 });
80 63 \ No newline at end of file
... ...