-
Notifications
You must be signed in to change notification settings - Fork 711
/
readouts.py
1209 lines (1037 loc) · 48.7 KB
/
readouts.py
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Data aggregators for dashboards
For the purposes of all these numbers, we pretend as if Documents with
is_localizable=False or is_archived=True and Revisions with
is_ready_for_localization=False do not exist.
"""
import logging
from django.conf import settings
from django.db import connections, router
from django.utils.datastructures import SortedDict
import jingo
from jinja2 import Markup
from tower import ugettext as _, ugettext_lazy as _lazy
from kitsune.dashboards import LAST_30_DAYS, PERIODS
from kitsune.sumo.helpers import urlparams
from kitsune.sumo.redis_utils import redis_client, RedisError
from kitsune.sumo.urlresolvers import reverse
from kitsune.wiki.models import Document
from kitsune.wiki.config import (
MEDIUM_SIGNIFICANCE, MAJOR_SIGNIFICANCE,
TYPO_SIGNIFICANCE, REDIRECT_HTML,
HOW_TO_CONTRIBUTE_CATEGORY, ADMINISTRATION_CATEGORY,
CANNED_RESPONSES_CATEGORY, NAVIGATION_CATEGORY, TROUBLESHOOTING_CATEGORY,
HOW_TO_CATEGORY, TEMPLATES_CATEGORY)
log = logging.getLogger('k.dashboards.readouts')
MOST_VIEWED = 1
MOST_RECENT = 2
# FROM clause for selecting most-visited translations:
#
# The "... EXISTS" bit in the transdoc left join prevents transdocs
# for which there are only translated revisions that were reviewed and
# rejected. In this case, we want it to show up as untranslated since
# that's the most "correct" status.
most_visited_translation_from = (
'FROM wiki_document engdoc '
'LEFT JOIN wiki_document transdoc ON '
'transdoc.parent_id=engdoc.id '
'AND transdoc.locale=%s '
'AND EXISTS ('
'SELECT * '
'FROM wiki_revision transrev_inner '
'WHERE transrev_inner.document_id=transdoc.id '
'AND NOT (NOT transrev_inner.is_approved '
'AND transrev_inner.reviewed IS NOT NULL) '
') '
'LEFT JOIN dashboards_wikidocumentvisits ON engdoc.id='
'dashboards_wikidocumentvisits.document_id '
'AND dashboards_wikidocumentvisits.period=%s '
'{extra_joins} '
'WHERE engdoc.locale=%s '
'AND engdoc.is_localizable '
'AND NOT engdoc.is_archived '
'AND engdoc.latest_localizable_revision_id IS NOT NULL '
'{extra_where} '
'ORDER BY dashboards_wikidocumentvisits.visits DESC, '
'COALESCE(transdoc.title, engdoc.title) ASC ').format
REVIEW_STATUSES = {
1: (_lazy(u'Review Needed'), 'wiki.document_revisions', 'review'),
0: (u'', '', 'ok')}
SIGNIFICANCE_STATUSES = {
MEDIUM_SIGNIFICANCE:
(_lazy(u'Update Needed'), 'wiki.edit_document', 'update'),
MAJOR_SIGNIFICANCE:
(_lazy(u'Immediate Update Needed'), 'wiki.edit_document',
'out-of-date')}
# The most significant approved change to the English article between {the
# English revision the current translated revision is based on} and {the latest
# ready-for-localization revision}:
MOST_SIGNIFICANT_CHANGE_READY_TO_TRANSLATE = (
'(SELECT MAX(engrev.significance) '
'FROM wiki_revision engrev, wiki_revision transrev '
'WHERE engrev.is_approved '
'AND transrev.id=transdoc.current_revision_id '
'AND engrev.document_id=transdoc.parent_id '
'AND engrev.id>transrev.based_on_id '
'AND engrev.id<=engdoc.latest_localizable_revision_id'
')')
# Whether there are any unreviewed revs of the translation made since the
# current one:
NEEDS_REVIEW = (
'(SELECT EXISTS '
'(SELECT * '
'FROM wiki_revision transrev '
'WHERE transrev.document_id=transdoc.id '
'AND transrev.reviewed IS NULL '
'AND (transrev.id>transdoc.current_revision_id OR '
'transdoc.current_revision_id IS NULL)'
')'
') ')
# Whether there are unreviewed revisions of the English doc:
NEEDS_REVIEW_ENG = (
'(SELECT EXISTS '
'(SELECT * '
'FROM wiki_revision engrev '
'WHERE engrev.document_id=engdoc.id '
'AND engrev.reviewed IS NULL '
'AND (engrev.id>engdoc.current_revision_id OR '
'engdoc.current_revision_id IS NULL)'
')'
') ')
# Whether the current revision is not ready for localization
UNREADY_FOR_L10N = (
'(SELECT EXISTS '
'(SELECT * '
'FROM wiki_revision rev '
'WHERE rev.document_id=engdoc.id '
'AND (rev.id>engdoc.latest_localizable_revision_id OR '
'engdoc.latest_localizable_revision_id IS NULL) '
'AND rev.is_approved '
'AND NOT rev.is_ready_for_localization '
'AND (rev.significance>%s OR rev.significance IS NULL)'
')'
') ')
# Any ready-for-l10n, nontrivial-significance revision of the English doc newer
# than the one our current translation is based on:
ANY_SIGNIFICANT_UPDATES = (
'(SELECT id FROM wiki_revision engrev '
'WHERE engrev.document_id=engdoc.id '
'AND engrev.id>curtransrev.based_on_id '
'AND engrev.is_ready_for_localization '
'AND engrev.significance>=%s) ')
# Filter by products when a product is selected.
PRODUCT_FILTER = (
'INNER JOIN wiki_document_products docprod ON '
'docprod.document_id=engdoc.id '
'AND docprod.product_id=%s ')
def _cursor():
"""Return a DB cursor for reading."""
return connections[router.db_for_read(Document)].cursor()
def _format_row_with_out_of_dateness(readout_locale, eng_slug, eng_title, slug,
title, visits, significance, needs_review):
"""Format a row for a readout that has the traffic-light-style
categorization of how seriously out of date a translation is."""
if slug: # A translation exists but may not be approved.
locale = readout_locale
status, view_name, status_class = SIGNIFICANCE_STATUSES.get(
significance, REVIEW_STATUSES[needs_review])
status_url = (reverse(view_name, args=[slug], locale=locale)
if view_name else '')
else:
slug = eng_slug
title = eng_title
locale = settings.WIKI_DEFAULT_LANGUAGE
status = _(u'Translation Needed')
# When calling the translate view, specify locale to translate to:
status_url = reverse('wiki.translate', args=[slug],
locale=readout_locale)
status_class = 'untranslated'
return dict(title=title,
url=reverse('wiki.document', args=[slug],
locale=locale),
visits=visits,
status=status,
status_class=status_class,
status_url=status_url)
def overview_rows(locale, product=None):
"""Return the iterable of dicts needed to draw the Overview table."""
# The Overview table is a special case: it has only a static number of
# rows, so it has no expanded, all-rows view, and thus needs no slug, no
# "max" kwarg on rows(), etc. It doesn't fit the Readout signature, so we
# don't shoehorn it in.
def percent_or_100(num, denom):
return int(round(num / float(denom) * 100)) if denom else 100
def single_result(sql, params):
"""Return the first column of the first row returned by a query."""
cursor = _cursor()
cursor.execute(sql, params)
return cursor.fetchone()[0]
total = Document.uncached.filter(
locale=settings.WIKI_DEFAULT_LANGUAGE,
is_archived=False,
current_revision__isnull=False,
is_localizable=True,
latest_localizable_revision__isnull=False)
total = total.exclude(
html__startswith=REDIRECT_HTML)
if product:
total = total.filter(products=product)
total_docs = total.filter(is_template=False).count()
total_templates = total.filter(is_template=True).count()
if product:
extra_joins = PRODUCT_FILTER
prod_param = (product.id,)
else:
extra_joins = ''
prod_param = tuple()
# Translations whose based_on revision has no >10-significance, ready-for-
# l10n revisions after it. It *might* be possible to do this with the ORM
# by passing wheres and tables to extra():
up_to_date_translation_count = (
'SELECT COUNT(*) FROM wiki_document transdoc '
'INNER JOIN wiki_document engdoc ON transdoc.parent_id=engdoc.id '
'INNER JOIN wiki_revision curtransrev '
'ON transdoc.current_revision_id=curtransrev.id '
+ extra_joins +
'WHERE transdoc.locale=%s '
'AND transdoc.is_template=%s '
'AND NOT transdoc.is_archived '
'AND engdoc.latest_localizable_revision_id IS NOT NULL '
'AND engdoc.is_localizable '
'AND engdoc.html NOT LIKE "<p>REDIRECT <a%%" '
'AND NOT EXISTS ' +
ANY_SIGNIFICANT_UPDATES)
translated_docs = single_result(
up_to_date_translation_count,
prod_param + (locale, False, MEDIUM_SIGNIFICANCE))
translated_templates = single_result(
up_to_date_translation_count,
prod_param + (locale, True, MEDIUM_SIGNIFICANCE))
# Of the top 20 most visited English articles, how many have up-to-date
# translations into German?
#
# TODO: Be very suspicious of this query. It selects from a subquery (known
# to MySQL's EXPLAIN as a "derived" table), and MySQL always materializes
# such subqueries and never builds indexes on them. However, it seems to be
# fast in practice.
TOP_N = 20
popular_translated = int(single_result( # Driver returns a Decimal.
'SELECT SUM(istranslated) FROM '
'(SELECT transdoc.current_revision_id IS NOT NULL '
# And there have been no significant updates since the current
# translation:
'AND NOT EXISTS ' +
ANY_SIGNIFICANT_UPDATES +
'AS istranslated ' +
most_visited_translation_from(
extra_joins='LEFT JOIN wiki_revision curtransrev '
'ON transdoc.current_revision_id=curtransrev.id ' +
extra_joins,
extra_where='AND engdoc.category IN (' +
str(TROUBLESHOOTING_CATEGORY) + ',' +
str(HOW_TO_CATEGORY) + ',' +
str(TEMPLATES_CATEGORY) + ')') +
'LIMIT %s) t1 ',
(MEDIUM_SIGNIFICANCE, locale, LAST_30_DAYS) + prod_param +
(settings.WIKI_DEFAULT_LANGUAGE, TOP_N)) or 0) # SUM can return NULL.
return {'most-visited': dict(
title=_('Most-Visited Articles'),
url='#' + MostVisitedTranslationsReadout.slug,
numerator=popular_translated, denominator=TOP_N,
percent=percent_or_100(popular_translated, TOP_N),
description=_('These are the top 20 most visited articles, '
'which account for over 50% of the traffic to '
'the Knowledge Base.')),
'templates': dict(
title=_('Templates'),
url='#' + TemplateTranslationsReadout.slug,
numerator=translated_templates, denominator=total_templates,
percent=percent_or_100(translated_templates, total_templates),
description=_('Templates are a way of reusing pieces of '
'content across KB articles. You can create and '
'update a set of instructions in one place, and '
'then refer to it in other pages.')),
'all': dict(
title=_('All Knowledge Base Articles'),
numerator=translated_docs, denominator=total_docs,
percent=percent_or_100(translated_docs, total_docs),
description=_('This is the number of all Knowledge Base '
'articles that are ready to be localized.'))}
class Readout(object):
"""Abstract class representing one table on the Localization Dashboard
Describing these as atoms gives us the whole-page details views for free.
"""
# title = _lazy(u'Title of Readout')
# description = _lazy(u'Paragraph of explanation')
# short_title= = _lazy(u'Short Title of Readout for In-Page Links')
# slug = 'Unique URL slug for detail page'
# details_link_text = _lazy(u'All articles from this readout...')
column3_label = _lazy(u'Visits in last 30 days')
column4_label = _lazy(u'Status')
modes = [(MOST_VIEWED, _lazy('Most Viewed')),
(MOST_RECENT, _lazy('Most Recent'))]
default_mode = MOST_VIEWED
def __init__(self, request, locale=None, mode=None, product=None):
"""Take request so the template can use contextual macros that need it.
Renders the data for the locale specified by the request, but you can
override it by passing another in `locale`.
"""
self.request = request
self.locale = locale or request.LANGUAGE_CODE
self.mode = mode if mode != None else self.default_mode
# self.mode is allowed to be invalid.
self.product = product
def sort_and_truncate(self, rows, max):
"""Allows a readout to sort and truncate the rows list
This happens after generating the row structures which starts
with what we get back from SQL and incorporates _format_row
and before we render the rows to output.
:arg rows: the list of rows to sort
:arg max: the index at which to truncate
"""
return rows
def rows(self, max=None):
"""Return an iterable of dicts containing the data for the table.
This default implementation calls _query_and_params and _format_row.
You can either implement those or, if you need more flexibility,
override this.
Limit to `max` rows.
"""
cursor = _cursor()
cursor.execute(*self._query_and_params(max))
return self.sort_and_truncate(
[self._format_row(r) for r in cursor.fetchall()], max)
def render(self, max_rows=None):
"""Return HTML table rows, optionally limiting to a number of rows."""
# Compute percents for bar widths:
rows = self.rows(max_rows)
max_visits = max(r['visits'] for r in rows) if rows else 0
for r in rows:
visits = r['visits']
r['percent'] = (0 if visits is None or not max_visits
else int(round(visits / float(max_visits) * 100)))
# Render:
return jingo.render_to_string(
self.request,
'dashboards/includes/kb_readout.html',
{'rows': rows, 'column3_label': self.column3_label,
'column4_label': self.column4_label})
@classmethod
def should_show_to(cls, request):
"""Whether this readout should be shown on the request."""
return True
# To override:
def _query_and_params(self, max):
"""Return a tuple: (query, params to bind it to)."""
raise NotImplementedError
def _format_row(self, row):
"""Turn a DB row tuple into a dict for the template."""
raise NotImplementedError
# Convenience methods:
@staticmethod
def _limit_clause(max):
"""Return a SQL LIMIT clause limiting returned rows to `max`.
Return '' if max is None.
"""
return ' LIMIT %i' % max if max else ''
def get_absolute_url(self, locale, product=None):
if self.slug in L10N_READOUTS:
url = reverse('dashboards.localization_detail',
kwargs={'readout_slug': self.slug}, locale=locale)
elif self.slug in CONTRIBUTOR_READOUTS:
url = reverse('dashboards.contributors_detail',
kwargs={'readout_slug': self.slug}, locale=locale)
else:
raise KeyError('This Readout was not found: %s' % self.slug)
if product:
return urlparams(url, product=product.slug)
return url
class MostVisitedDefaultLanguageReadout(Readout):
"""Most-Visited readout for the default language"""
title = _lazy(u'Most Visited')
# No short_title; the Contributors dash lacks an Overview readout
details_link_text = _lazy(u'All knowledge base articles...')
slug = 'most-visited'
column3_label = _lazy(u'Visits')
modes = PERIODS
default_mode = LAST_30_DAYS
def _query_and_params(self, max):
if self.mode in [m[0] for m in self.modes]:
period = self.mode
else:
period = self.default_mode
# Filter by product if specified.
if self.product:
extra_joins = PRODUCT_FILTER
params = (period, self.product.id, self.locale)
else:
extra_joins = ''
params = (period, self.locale)
# Review Needed: link to /history.
query = (
'SELECT engdoc.slug, engdoc.title, '
'dashboards_wikidocumentvisits.visits, '
'count(engrev.document_id) '
'FROM wiki_document engdoc '
'LEFT JOIN dashboards_wikidocumentvisits ON '
'engdoc.id=dashboards_wikidocumentvisits.document_id '
'AND dashboards_wikidocumentvisits.period=%s '
'LEFT JOIN wiki_revision engrev ON '
'engrev.document_id=engdoc.id '
'AND engrev.reviewed IS NULL '
'AND engrev.id>engdoc.current_revision_id '
+ extra_joins +
'WHERE engdoc.locale=%s AND '
'NOT engdoc.is_archived AND '
'NOT engdoc.category IN ('
+ str(ADMINISTRATION_CATEGORY) + ', '
+ str(NAVIGATION_CATEGORY) + ', '
+ str(CANNED_RESPONSES_CATEGORY) + ', '
+ str(HOW_TO_CONTRIBUTE_CATEGORY) + ') AND '
'NOT engdoc.is_template AND '
'engdoc.html NOT LIKE "<p>REDIRECT <a%%" '
'GROUP BY engdoc.id '
'ORDER BY dashboards_wikidocumentvisits.visits DESC, '
'engdoc.title ASC' + self._limit_clause(max))
return query, params
def _format_row(self, (slug, title, visits, num_unreviewed)):
needs_review = int(num_unreviewed > 0)
status, view_name, dummy = REVIEW_STATUSES[needs_review]
return dict(title=title,
url=reverse('wiki.document', args=[slug],
locale=self.locale),
visits=visits,
status=status,
status_url=reverse(view_name, args=[slug],
locale=self.locale)
if view_name else '')
class CategoryReadout(Readout):
"""Abstract class representing a readout ordered by visits and intended
to be filtered by category."""
column3_label = _lazy(u'Visits')
modes = []
default_mode = None
where_clause = ''
def _query_and_params(self, max):
# Filter by product if specified.
if self.product:
extra_joins = PRODUCT_FILTER
params = (TYPO_SIGNIFICANCE, LAST_30_DAYS, self.product.id,
self.locale)
else:
extra_joins = ''
params = (TYPO_SIGNIFICANCE, LAST_30_DAYS, self.locale)
# Review Needed: link to /history.
query = (
'SELECT engdoc.slug, engdoc.title, '
'dashboards_wikidocumentvisits.visits, '
'engdoc.needs_change, '
+ NEEDS_REVIEW_ENG + ', '
+ UNREADY_FOR_L10N +
'FROM wiki_document engdoc '
'LEFT JOIN dashboards_wikidocumentvisits ON '
'engdoc.id=dashboards_wikidocumentvisits.document_id '
'AND dashboards_wikidocumentvisits.period=%s '
+ extra_joins +
'WHERE engdoc.locale=%s AND '
'NOT engdoc.is_archived '
+ self.where_clause +
'GROUP BY engdoc.id '
'ORDER BY dashboards_wikidocumentvisits.visits DESC, '
'engdoc.title ASC' + self._limit_clause(max))
return query, params
def _format_row(self, (slug, title, visits, needs_changes, needs_review,
unready_for_l10n)):
if needs_review:
status, view_name, dummy = REVIEW_STATUSES[needs_review]
elif needs_changes:
status = _lazy(u'Changes Needed')
view_name = 'wiki.document_revisions'
elif unready_for_l10n:
status = _lazy(u'Changes Not Ready For Localization')
view_name = 'wiki.document_revisions'
else:
status, view_name, dummy = REVIEW_STATUSES[0]
return dict(title=title,
url=reverse('wiki.document', args=[slug],
locale=self.locale),
visits=visits,
status=status,
status_url=reverse(view_name, args=[slug],
locale=self.locale)
if view_name else '')
class TemplateReadout(CategoryReadout):
title = _lazy(u'Templates')
slug = 'templates'
details_link_text = _lazy(u'All templates...')
where_clause = 'AND engdoc.is_template '
class HowToContributeReadout(CategoryReadout):
title = _lazy(u'How To Contribute')
slug = 'how-to-contribute'
details_link_text = _lazy(u'All How To Contribute articles...')
where_clause = 'AND engdoc.category=%s ' % HOW_TO_CONTRIBUTE_CATEGORY
class AdministrationReadout(CategoryReadout):
title = _lazy(u'Administration')
slug = 'administration'
details_link_text = _lazy(u'All Administration articles...')
where_clause = 'AND engdoc.category=%s ' % ADMINISTRATION_CATEGORY
class MostVisitedTranslationsReadout(MostVisitedDefaultLanguageReadout):
"""Most-Visited readout for non-default languages
Adds a few subqueries to determine the status of translations.
Shows the articles that are most visited in English, even if there are no
translations of those articles yet. This draws attention to articles that
we should drop everything to translate.
"""
short_title = _lazy(u'Most Visited')
slug = 'most-visited-translations'
details_link_text = _lazy(u'All translations...')
def _query_and_params(self, max):
if self.mode in [m[0] for m in self.modes]:
period = self.mode
else:
period = self.default_mode
# Filter by product if specified.
if self.product:
extra_joins = PRODUCT_FILTER
params = (self.locale, period, self.product.id,
settings.WIKI_DEFAULT_LANGUAGE)
else:
extra_joins = ''
params = (self.locale, period, settings.WIKI_DEFAULT_LANGUAGE)
# Immediate Update Needed or Update Needed: link to /edit.
# Review Needed: link to /history.
# These match the behavior of the corresponding readouts.
return (
'SELECT engdoc.slug, engdoc.title, transdoc.slug, '
'transdoc.title, dashboards_wikidocumentvisits.visits, ' +
MOST_SIGNIFICANT_CHANGE_READY_TO_TRANSLATE + ', ' +
NEEDS_REVIEW +
most_visited_translation_from(extra_joins=extra_joins,
extra_where='') +
self._limit_clause(max), params)
def _format_row(self, columns):
return _format_row_with_out_of_dateness(self.locale, *columns)
class TemplateTranslationsReadout(Readout):
"""Readout for templates in non-default languages
Shows the templates even if there are no translations of them yet.
This draws attention to templates that we should drop everything to
translate.
"""
title = _lazy(u'Templates')
short_title = _lazy(u'Templates')
slug = 'template-translations'
details_link_text = _lazy(u'All templates...')
column3_label = ''
modes = []
default_mode = None
def _query_and_params(self, max):
# Filter by product if specified.
if self.product:
extra_joins = PRODUCT_FILTER
params = (self.locale, self.product.id,
settings.WIKI_DEFAULT_LANGUAGE)
else:
extra_joins = ''
params = (self.locale, settings.WIKI_DEFAULT_LANGUAGE)
query = (
'SELECT engdoc.slug, engdoc.title, transdoc.slug, '
'transdoc.title, ' +
MOST_SIGNIFICANT_CHANGE_READY_TO_TRANSLATE + ', ' +
NEEDS_REVIEW +
'FROM wiki_document engdoc '
'LEFT JOIN wiki_document transdoc ON '
'transdoc.parent_id=engdoc.id '
'AND transdoc.locale=%s '
+ extra_joins +
'WHERE engdoc.locale=%s '
'AND engdoc.is_localizable '
'AND NOT engdoc.is_archived '
'AND engdoc.latest_localizable_revision_id IS NOT NULL '
'AND engdoc.is_template ')
return query, params
def _format_row(self, (eng_slug, eng_title, slug, title, significance,
needs_review)):
return _format_row_with_out_of_dateness(self.locale, eng_slug,
eng_title, slug, title, None, significance, needs_review)
def sort_and_truncate(self, rows, max):
# Bubble the "update needed" templates to the top, but otherwise
# keep it ordered by title.
#
# As a little side note, 'status' here is either an empty
# string or a _lazy translation of 'Update Needed'. So if it's
# an empty string, then the equality is True and True in
# Python is 1 and 1 comes after 0... Therefore, False comes
# first in ordering.
rows.sort(key=lambda row: (
row['status'] == u'', row['status_class'], row['title']))
return rows[:max]
class NavigationTranslationsReadout(Readout):
"""Readout for navigation articles in non-default languages
Shows the navigation articles even if there are no translations of
them yet. This draws attention to navigation articles that we
should drop everything to translate.
"""
title = _lazy(u'Navigation Articles')
short_title = _lazy(u'Navigation Articles')
slug = 'template-navigation'
details_link_text = _lazy(u'All navigation articles...')
column3_label = ''
modes = []
default_mode = None
def _query_and_params(self, max):
# Filter by product if specified.
if self.product:
extra_joins = PRODUCT_FILTER
params = (self.locale, self.product.id,
settings.WIKI_DEFAULT_LANGUAGE)
else:
extra_joins = ''
params = (self.locale, settings.WIKI_DEFAULT_LANGUAGE)
query = (
'SELECT engdoc.slug, engdoc.title, transdoc.slug, '
'transdoc.title, ' +
MOST_SIGNIFICANT_CHANGE_READY_TO_TRANSLATE + ', ' +
NEEDS_REVIEW +
'FROM wiki_document engdoc '
'LEFT JOIN wiki_document transdoc ON '
'transdoc.parent_id=engdoc.id '
'AND transdoc.locale=%s '
+ extra_joins +
'WHERE engdoc.locale=%s '
'AND engdoc.is_localizable '
'AND NOT engdoc.is_archived '
'AND engdoc.latest_localizable_revision_id IS NOT NULL '
'AND engdoc.category = 50 '
'AND NOT engdoc.is_template '
'ORDER BY COALESCE(transdoc.title, engdoc.title) ASC ' +
self._limit_clause(max))
return query, params
def _format_row(self, (eng_slug, eng_title, slug, title, significance,
needs_review)):
return _format_row_with_out_of_dateness(self.locale, eng_slug,
eng_title, slug, title, None, significance, needs_review)
class UntranslatedReadout(Readout):
title = _lazy(u'Untranslated')
description = _lazy(
u'This indicates there are no approved translations of these articles. '
'Some of the articles may have proposed translations waiting to be '
'reviewed and will appear in the Unreviewed Changes section as well.')
short_title = _lazy(u'Untranslated')
details_link_text = _lazy(u'All untranslated articles...')
slug = 'untranslated'
column4_label = _lazy(u'Updated')
def _query_and_params(self, max):
# Filter by product if specified.
if self.product:
extra_joins = PRODUCT_FILTER
params = (self.locale, LAST_30_DAYS, self.product.id,
settings.WIKI_DEFAULT_LANGUAGE)
else:
extra_joins = ''
params = (self.locale, LAST_30_DAYS,
settings.WIKI_DEFAULT_LANGUAGE)
# Incidentally, we tried this both as a left join and as a search
# against an inner query returning translated docs, and the left join
# yielded a faster-looking plan (on a production corpus).
#
# Find non-archived, localizable documents in categories 10,
# 20 and 60 having at least one ready- for-localization
# revision. Of those, show the ones that have no translation.
query = ('SELECT engdoc.slug, engdoc.title, '
'wiki_revision.reviewed, dashboards_wikidocumentvisits.visits '
'FROM wiki_document engdoc '
'INNER JOIN wiki_revision ON '
'engdoc.latest_localizable_revision_id=wiki_revision.id '
'LEFT JOIN wiki_document translated ON '
'engdoc.id=translated.parent_id AND translated.locale=%s '
'LEFT JOIN dashboards_wikidocumentvisits ON '
'engdoc.id=dashboards_wikidocumentvisits.document_id AND '
'dashboards_wikidocumentvisits.period=%s '
+ extra_joins +
'WHERE '
'(translated.id IS NULL OR translated.current_revision_id IS NULL) '
'AND engdoc.is_localizable AND '
'engdoc.category in (10, 20, 60) AND '
'engdoc.locale=%s AND NOT engdoc.is_archived '
'AND wiki_revision.content NOT LIKE "REDIRECT%%" '
+ self._order_clause() + self._limit_clause(max))
return query, params
def _order_clause(self):
return ('ORDER BY wiki_revision.reviewed DESC, engdoc.title ASC'
if self.mode == MOST_RECENT
else 'ORDER BY dashboards_wikidocumentvisits.visits DESC, '
'engdoc.title ASC')
def _format_row(self, (slug, title, reviewed, visits)):
# Run the data through the model to (potentially) format it and
# take advantage of SPOTs (like for get_absolute_url()):
d = Document(slug=slug, title=title,
locale=settings.WIKI_DEFAULT_LANGUAGE)
return dict(title=d.title,
url=d.get_absolute_url(),
visits=visits,
updated=reviewed)
class OutOfDateReadout(Readout):
title = _lazy(u'Immediate Updates Needed')
description = _lazy(
u'This indicates a major edit which changes the content of the article'
' enough to hurt the value of the localization. Until it is updated, '
'the localized page will warn users that it may be outdated. You '
'should update these articles as soon as possible.')
short_title = _lazy(u'Immediate Updates Needed')
details_link_text = _lazy(u'All translations needing immediate updates...')
slug = 'out-of-date'
column4_label = _lazy(u'Out of date since')
# To show up in this readout, an article's revision since the last
# approved translation must have a maximum significance equal to this
# value:
_max_significance = MAJOR_SIGNIFICANCE
def _query_and_params(self, max):
# Filter by product if specified.
if self.product:
extra_joins = PRODUCT_FILTER
params = (MEDIUM_SIGNIFICANCE, self._max_significance,
LAST_30_DAYS, self.product.id, self.locale)
else:
extra_joins = ''
params = (MEDIUM_SIGNIFICANCE, self._max_significance,
LAST_30_DAYS, self.locale)
# At the moment, the "Out of Date Since" column shows the time since
# the translation was out of date at a MEDIUM level of severity or
# higher. We could arguably knock this up to MAJOR, but technically it
# is out of date when the original gets anything more than typo
# corrections.
# TODO: This is wrong because it uses the reviewed date to calculate
# "Out of date since", instead of using the ready for l10n date.
# To fix it is pretty hairy though. What a query!!!
query = ('SELECT transdoc.slug, transdoc.title, engrev.reviewed, '
'dashboards_wikidocumentvisits.visits '
'FROM wiki_document transdoc '
'INNER JOIN wiki_document engdoc ON transdoc.parent_id=engdoc.id '
'INNER JOIN wiki_revision engrev ON engrev.id='
# The oldest English rev to have an approved, ready-for-
# localization level-30 change since the translated doc had an
# approved rev based on it. NULL if there is none:
'(SELECT min(id) FROM wiki_revision '
# Narrow engrev rows to those representing revision of parent
# doc:
'WHERE wiki_revision.document_id=transdoc.parent_id '
# For the purposes of computing the "Out of Date Since" column,
# the revision that threw the translation out of date had
# better be more recent than the one the current translation is
# based on:
'AND wiki_revision.id>'
'(SELECT based_on_id FROM wiki_revision basedonrev '
'WHERE basedonrev.id=transdoc.current_revision_id) '
'AND wiki_revision.significance>=%s '
'AND %s='
# Completely filter out outer selections where 30 is not the
# max signif of approved English revisions since trans was last
# approved. Other maxes will be shown by other readouts.
# Optimize: try "30 IN" if MySQL's statistics gatherer is
# stupid/nonexistent; the inner query should be able to bail
# out early. [Ed: No effect on EXPLAIN on admittedly light test
# corpus.]
'(SELECT MAX(engsince.significance) '
'FROM wiki_revision engsince '
'WHERE engsince.document_id=transdoc.parent_id '
# Assumes that any approved revision became the current
# revision at some point: we don't let the user go back and
# approve revisions older than the latest approved one.
'AND engsince.is_approved '
# Consider revisions between the one the last translation
# was based on and the latest ready-for-l10n one.
'AND engsince.id>'
# The English revision the current translation's based on:
'(SELECT based_on_id FROM wiki_revision basedonrev '
'WHERE basedonrev.id=transdoc.current_revision_id) '
'AND engsince.id<=engdoc.latest_localizable_revision_id'
')'
') '
# Join up the visits table for stats:
'LEFT JOIN dashboards_wikidocumentvisits ON '
'engrev.document_id=dashboards_wikidocumentvisits.document_id '
'AND dashboards_wikidocumentvisits.period=%s '
+ extra_joins +
# We needn't check is_localizable, since the models ensure every
# document with translations has is_localizable set.
'WHERE transdoc.locale=%s AND NOT transdoc.is_archived AND '
'transdoc.category in (10, 20, 60) '
+ self._order_clause() + self._limit_clause(max))
return query, params
def _order_clause(self):
return ('ORDER BY engrev.reviewed DESC' if self.mode == MOST_RECENT
else 'ORDER BY dashboards_wikidocumentvisits.visits DESC, '
'transdoc.title ASC')
def _format_row(self, (slug, title, reviewed, visits)):
return dict(title=title,
url=reverse('wiki.edit_document', args=[slug]),
visits=visits, updated=reviewed)
class NeedingUpdatesReadout(OutOfDateReadout):
title = _lazy(u'Updates Needed')
description = _lazy(
u"This signifies an edit that doesn't diminish the value of the "
'localized article: for example, rewording a paragraph. Localizers '
'are notified of this edit, but no warning is shown on the localized '
'page. You should update these articles soon.')
short_title = _lazy(u'Updates Needed')
details_link_text = _lazy(u'All translations needing updates...')
slug = 'needing-updates'
_max_significance = MEDIUM_SIGNIFICANCE
class UnreviewedReadout(Readout):
# L10n: Not just changes to translations but also unreviewed changes to
# docs in this locale that are not translations
title = _lazy(u'Unreviewed Changes')
short_title = _lazy(u'Unreviewed', 'document')
details_link_text = _lazy(u'All articles requiring review...')
slug = 'unreviewed'
column4_label = _lazy(u'Changed')
def _query_and_params(self, max):
english_id = ('id' if self.locale == settings.WIKI_DEFAULT_LANGUAGE
else 'parent_id')
# Filter by product if specified.
if self.product:
extra_joins = (
'INNER JOIN wiki_document_products docprod ON '
'docprod.document_id=wiki_document.' + english_id + ' '
'AND docprod.product_id=%s ')
params = (LAST_30_DAYS, self.product.id, self.locale)
else:
extra_joins = ''
params = (LAST_30_DAYS, self.locale)
query = ('SELECT wiki_document.slug, wiki_document.title, '
'MAX(wiki_revision.created) maxcreated, '
'GROUP_CONCAT(DISTINCT auth_user.username '
"ORDER BY wiki_revision.id SEPARATOR ', '), "
'dashboards_wikidocumentvisits.visits '
'FROM wiki_document '
'INNER JOIN wiki_revision ON '
'wiki_document.id=wiki_revision.document_id '
'INNER JOIN auth_user ON wiki_revision.creator_id=auth_user.id '
'LEFT JOIN dashboards_wikidocumentvisits ON '
'wiki_document.' + english_id
+ '=dashboards_wikidocumentvisits.document_id AND '
'dashboards_wikidocumentvisits.period=%s '
+ extra_joins +
'WHERE wiki_revision.reviewed IS NULL '
'AND (wiki_document.current_revision_id IS NULL OR '
'wiki_revision.id>wiki_document.current_revision_id) '
'AND wiki_document.locale=%s AND NOT wiki_document.is_archived '
'GROUP BY wiki_document.id '
+ self._order_clause() + self._limit_clause(max))
return query, params
def _order_clause(self):
return ('ORDER BY maxcreated DESC' if self.mode == MOST_RECENT
else 'ORDER BY dashboards_wikidocumentvisits.visits DESC, '
'wiki_document.title ASC')
def _format_row(self, (slug, title, changed, users, visits)):
return dict(title=title,
url=reverse('wiki.document_revisions',
args=[slug],
locale=self.locale),
visits=visits,
updated=changed,
users=users)
class UnhelpfulReadout(Readout):
title = _lazy(u'Unhelpful Documents')
short_title = _lazy(u'Unhelpful', 'document')
details_link_text = _lazy(u'All unhelpful articles...')
slug = 'unhelpful'
column3_label = _lazy(u'Total Votes')
column4_label = _lazy(u'Helpfulness')
modes = []
default_mode = None
# This class is a namespace and doesn't get instantiated.
key = settings.HELPFULVOTES_UNHELPFUL_KEY
try:
hide_readout = redis_client('helpfulvotes').llen(key) == 0
except RedisError as e:
log.error('Redis error: %s' % e)
hide_readout = True
def rows(self, max=None):
REDIS_KEY = settings.HELPFULVOTES_UNHELPFUL_KEY
try:
redis = redis_client('helpfulvotes')
length = redis.llen(REDIS_KEY)
max_get = max or length
output = redis.lrange(REDIS_KEY, 0, max_get)
except RedisError as e:
log.error('Redis error: %s' % e)