Projet

Général

Profil

0002-wcs-add-cell-pagination-10179.patch

Valentin Deniaud, 21 octobre 2019 15:30

Télécharger (5,76 ko)

Voir les différences:

Subject: [PATCH 2/2] wcs: add cell pagination (#10179)

 combo/apps/wcs/models.py                      | 51 +++++++++++++++++++
 .../templates/combo/wcs/user_all_forms.html   |  6 +++
 combo/public/static/js/combo.public.js        | 12 ++++-
 3 files changed, 68 insertions(+), 1 deletion(-)
combo/apps/wcs/models.py
189 189
    cache_duration = 5
190 190
    api_url = None
191 191
    warn_on_404 = True
192
    paginate_by = 0
192 193

  
193 194
    def get_api_url(self, context):
194 195
        return self.api_url
......
209 210
        wcs_sites = copy.deepcopy(wcs_sites)
210 211
        returns = set([])
211 212
        api_url = self.get_api_url(context)
213

  
214
        if self.paginate_by:
215
            cursor_dir = None
216
            cursor = None
217
            if 'before' in context['request'].GET:
218
                cursor_dir = 'before'
219
            elif 'after' in context['request'].GET:
220
                cursor_dir = 'after'
221
            if cursor_dir:
222
                cursor = context['request'].GET[cursor_dir]
223
                api_url = self.add_pagination(api_url, cursor, cursor_dir)
224

  
212 225
        for wcs_slug, wcs_site in wcs_sites.items():
213 226
            url = wcs_site.get('url')
214 227
            if not url.endswith('/'):
......
242 255
            if returns != set([404]) or self.warn_on_404:
243 256
                logging.error('failed to get data from any %s (%r)', api_url, returns)
244 257

  
258
        if self.paginate_by:
259
            all_forms = []
260
            for site in wcs_sites.values():
261
                if site.get('data'):
262
                    all_forms.extend(site['data'])
263
            field = 'form_receipt_datetime'
264
            all_forms.sort(key=lambda x: x[field], reverse=True)
265
            limit_reached = len(all_forms) <= self.paginate_by
266
            if cursor_dir == 'after':
267
                all_forms = all_forms[:self.paginate_by]
268
                context['before'] = all_forms[0][field]
269
                context['after'] = all_forms[-1][field] if not limit_reached else None
270
            elif cursor_dir == 'before':
271
                all_forms = all_forms[-self.paginate_by:]
272
                context['before'] = all_forms[0][field] if not limit_reached else None
273
                context['after'] = all_forms[-1][field]
274
            else:  # first page
275
                all_forms = all_forms[:self.paginate_by]
276
                context['before'] = None
277
                context['after'] = all_forms[-1][field]
278
            wcs_sites = {'paginated': {'data': all_forms}}
279

  
245 280
        return wcs_sites
246 281

  
247 282
    def get_cell_extra_context(self, context):
248 283
        return {self.variable_name: self.get_data(context)}
249 284

  
285
    def add_pagination(self, url, cursor=None, cursor_dir=None):
286
        pagination_qs = 'limit={limit}'.format(
287
            limit=self.paginate_by + 1  # ask for more to detect end page
288
        )
289
        if cursor:
290
            pagination_qs = '&'.join((
291
                pagination_qs,
292
                '{cursor_direction}={cursor}'.format(cursor_direction=cursor_dir,
293
                                                     cursor=cursor)
294
            ))
295
        if '?' in url:
296
            return '&'.join((url, pagination_qs))
297
        else:
298
            return '?'.join((url, pagination_qs))
299

  
250 300

  
251 301
class WcsDataBaseCell(CellBase, WcsBlurpMixin):
252 302
    is_enabled = classmethod(is_wcs_enabled)
......
307 357
    categories = JSONField(_('Categories'), blank=True)
308 358
    current_forms = models.BooleanField(_('Current Forms'), default=True)
309 359
    done_forms = models.BooleanField(_('Done Forms'), default=False)
360
    paginate_by = 3
310 361

  
311 362
    class Meta:
312 363
        verbose_name = _('User Forms')
combo/apps/wcs/templates/combo/wcs/user_all_forms.html
6 6
  {% include "combo/wcs/list_of_forms.html" with forms=forms %}
7 7
  </div>
8 8
{% endfor %}
9
{% if before %}
10
<a name="before" value="{{ before }}" href="#nothing" class="combo-refresh">{% trans 'Previous' %}</a>
11
{% endif %}
12
{% if after %}
13
<a name="after" value="{{ after }}" href="#nothing" class="combo-refresh">{% trans 'Next' %}</a>
14
{% endif %}
9 15
{% endblock %}
combo/public/static/js/combo.public.js
1
function combo_load_cell(elem) {
1
function combo_load_cell(elem, extra_params) {
2 2
  var $elem = $(elem);
3 3
  var url = $elem.data('ajax-cell-url');
4 4
  var extra_context = $elem.data('extra-context');
......
12 12
  if (extra_context) {
13 13
    qs += 'ctx=' + extra_context;
14 14
  }
15
  if (extra_params) {
16
    qs += '&' + $.param(extra_params)
17
  }
15 18
  $.ajax({url: url + qs,
16 19
          xhrFields: { withCredentials: true },
17 20
          async: true,
......
111 114
        window.location.search = new_qs;
112 115
    }
113 116
  });
117
  $(document).on('click', '.combo-refresh', function (e) {
118
    var $target = $(e.target);
119
    var value = $target.attr('value');
120
    var name = $target[0].name;
121
    var cell = $target.parents('.wcscurrentformscell')[0]
122
    combo_load_cell(cell, {[name]: value});
123
  });
114 124

  
115 125
  $(document).on('click', '.more-items a', function() {
116 126
    $(this).parent().hide();
117
-