Changeset - 4eef5eeb81a3
[Not reviewed]
beta
0 4 0
Marcin Kuzminski - 13 years ago 2012-08-07 23:02:50
marcin@python-works.com
fixed sorting by last_login in users admin page
4 files changed with 22 insertions and 1 deletions:
0 comments (0 inline, 0 general)
rhodecode/controllers/admin/users.py
Show inline comments
 
@@ -26,97 +26,100 @@
 
import logging
 
import traceback
 
import formencode
 
from pylons import response
 

	
 
from formencode import htmlfill
 
from pylons import request, session, tmpl_context as c, url, config
 
from pylons.controllers.util import redirect
 
from pylons.i18n.translation import _
 

	
 
from rhodecode.lib.exceptions import DefaultUserException, \
 
    UserOwnsReposException
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator, \
 
    AuthUser
 
from rhodecode.lib.base import BaseController, render
 

	
 
import rhodecode
 
from rhodecode.model.db import User, Permission, UserEmailMap
 
from rhodecode.model.forms import UserForm
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.meta import Session
 
from rhodecode.lib.utils import action_logger
 
from rhodecode.lib.compat import json
 
from rhodecode.lib.utils2 import datetime_to_time
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class UsersController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('user', 'users')
 

	
 
    @LoginRequired()
 
    @HasPermissionAllDecorator('hg.admin')
 
    def __before__(self):
 
        c.admin_user = session.get('admin_user')
 
        c.admin_username = session.get('admin_username')
 
        super(UsersController, self).__before__()
 
        c.available_permissions = config['available_permissions']
 

	
 
    def index(self, format='html'):
 
        """GET /users: All items in the collection"""
 
        # url('users')
 

	
 
        c.users_list = User.query().order_by(User.username).all()
 

	
 
        users_data = []
 
        total_records = len(c.users_list)
 
        _tmpl_lookup = rhodecode.CONFIG['pylons.app_globals'].mako_lookup
 
        template = _tmpl_lookup.get_template('data_table/_dt_elements.html')
 

	
 
        grav_tmpl = lambda user_email, size: (
 
                template.get_def("user_gravatar")
 
                .render(user_email, size, _=_, h=h, c=c))
 

	
 
        user_lnk = lambda user_id, username: (
 
                template.get_def("user_name")
 
                .render(user_id, username, _=_, h=h, c=c))
 

	
 
        user_actions = lambda user_id, username: (
 
                template.get_def("user_actions")
 
                .render(user_id, username, _=_, h=h, c=c))
 

	
 
        for user in c.users_list:
 

	
 
            users_data.append({
 
                "gravatar": grav_tmpl(user. email, 24),
 
                "raw_username": user.username,
 
                "username": user_lnk(user.user_id, user.username),
 
                "firstname": user.name,
 
                "lastname": user.lastname,
 
                "last_login": h.fmt_date(user.last_login),
 
                "last_login_raw": datetime_to_time(user.last_login),
 
                "active": h.bool2icon(user.active),
 
                "admin": h.bool2icon(user.admin),
 
                "ldap": h.bool2icon(bool(user.ldap_dn)),
 
                "action": user_actions(user.user_id, user.username),
 
            })
 

	
 
        c.data = json.dumps({
 
            "totalRecords": total_records,
 
            "startIndex": 0,
 
            "sort": None,
 
            "dir": "asc",
 
            "records": users_data
 
        })
 

	
 
        return render('admin/users/users.html')
 

	
 
    def create(self):
 
        """POST /users: Create a new item"""
 
        # url('users')
 

	
 
        user_model = UserModel()
 
        user_form = UserForm()()
 
        try:
 
            form_result = user_form.to_python(dict(request.POST))
rhodecode/lib/utils2.py
Show inline comments
 
@@ -3,48 +3,49 @@
 
    rhodecode.lib.utils
 
    ~~~~~~~~~~~~~~~~~~~
 

	
 
    Some simple helper functions
 

	
 
    :created_on: Jan 5, 2011
 
    :author: marcink
 
    :copyright: (C) 2011-2012 Marcin Kuzminski <marcin@python-works.com>
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# This program is free software: you can redistribute it and/or modify
 
# it under the terms of the GNU General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import re
 
import time
 
from datetime import datetime
 
from pylons.i18n.translation import _, ungettext
 
from rhodecode.lib.vcs.utils.lazy import LazyProperty
 

	
 

	
 
def __get_lem():
 
    """
 
    Get language extension map based on what's inside pygments lexers
 
    """
 
    from pygments import lexers
 
    from string import lower
 
    from collections import defaultdict
 

	
 
    d = defaultdict(lambda: [])
 

	
 
    def __clean(s):
 
        s = s.lstrip('*')
 
        s = s.lstrip('.')
 

	
 
        if s.find('[') != -1:
 
            exts = []
 
            start, stop = s.find('['), s.find(']')
 

	
 
            for suffix in s[start + 1:stop]:
 
@@ -408,44 +409,50 @@ def credentials_filter(uri):
 

	
 

	
 
def get_changeset_safe(repo, rev):
 
    """
 
    Safe version of get_changeset if this changeset doesn't exists for a
 
    repo it returns a Dummy one instead
 

	
 
    :param repo:
 
    :param rev:
 
    """
 
    from rhodecode.lib.vcs.backends.base import BaseRepository
 
    from rhodecode.lib.vcs.exceptions import RepositoryError
 
    from rhodecode.lib.vcs.backends.base import EmptyChangeset
 
    if not isinstance(repo, BaseRepository):
 
        raise Exception('You must pass an Repository '
 
                        'object as first argument got %s', type(repo))
 

	
 
    try:
 
        cs = repo.get_changeset(rev)
 
    except RepositoryError:
 
        cs = EmptyChangeset(requested_revision=rev)
 
    return cs
 

	
 

	
 
def datetime_to_time(dt):
 
    if dt:
 
        return time.mktime(dt.timetuple())
 

	
 

	
 
MENTIONS_REGEX = r'(?:^@|\s@)([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)(?:\s{1})'
 

	
 

	
 
def extract_mentioned_users(s):
 
    """
 
    Returns unique usernames from given string s that have @mention
 

	
 
    :param s: string to get mentions
 
    """
 
    usrs = set()
 
    for username in re.findall(MENTIONS_REGEX, s):
 
        usrs.add(username)
 

	
 
    return sorted(list(usrs), key=lambda k: k.lower())
 

	
 

	
 
class AttributeDict(dict):
 
    def __getattr__(self, attr):
 
        return self.get(attr, None)
 
    __setattr__ = dict.__setitem__
 
    __delattr__ = dict.__delitem__
rhodecode/public/js/rhodecode.js
Show inline comments
 
@@ -1508,48 +1508,57 @@ var revisionSort = function(a, b, desc, 
 
	  var a_ = fromHTML(a.getData(field));
 
	  var b_ = fromHTML(b.getData(field));
 
	  
 
	  // extract revisions from string nodes 
 
	  a_ = get_rev(a_)
 
	  b_ = get_rev(b_)
 
	      	  
 
	  var comp = YAHOO.util.Sort.compare;
 
	  var compState = comp(a_, b_, desc);
 
	  return compState;
 
};
 
var ageSort = function(a, b, desc, field) {
 
    var a_ = fromHTML(a.getData(field));
 
    var b_ = fromHTML(b.getData(field));
 
    
 
    // extract name from table
 
    a_ = get_date(a_)
 
    b_ = get_date(b_)          
 
    
 
    var comp = YAHOO.util.Sort.compare;
 
    var compState = comp(a_, b_, desc);
 
    return compState;
 
};
 

	
 
var lastLoginSort = function(a, b, desc, field) {
 
	var a_ = a.getData('last_login_raw') || 0;
 
    var b_ = b.getData('last_login_raw') || 0;
 
    
 
    var comp = YAHOO.util.Sort.compare;
 
    var compState = comp(a_, b_, desc);
 
    return compState;
 
};
 

	
 
var nameSort = function(a, b, desc, field) {
 
    var a_ = fromHTML(a.getData(field));
 
    var b_ = fromHTML(b.getData(field));
 

	
 
    // extract name from table
 
    a_ = get_name(a_)
 
    b_ = get_name(b_)          
 
    
 
    var comp = YAHOO.util.Sort.compare;
 
    var compState = comp(a_, b_, desc);
 
    return compState;
 
};
 

	
 
var permNameSort = function(a, b, desc, field) {
 
    var a_ = fromHTML(a.getData(field));
 
    var b_ = fromHTML(b.getData(field));
 
    // extract name from table
 

	
 
    a_ = a_.children[0].innerHTML;
 
    b_ = b_.children[0].innerHTML;      
 
    
 
    var comp = YAHOO.util.Sort.compare;
 
    var compState = comp(a_, b_, desc);
 
    return compState;
rhodecode/templates/admin/users/users.html
Show inline comments
 
@@ -23,83 +23,85 @@
 
            <span>${h.link_to(_(u'ADD NEW USER'),h.url('new_user'))}</span>
 
          </li>
 
        </ul>
 
    </div>
 
    <!-- end box / title -->
 
    <div class="table yui-skin-sam" id="users_list_wrap"></div>
 
    <div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
 
</div>
 

	
 
<script>
 
  var url = "${h.url('formatted_users', format='json')}";
 
  var data = ${c.data|n};
 
  var myDataSource = new YAHOO.util.DataSource(data);
 
  myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
 

	
 
  myDataSource.responseSchema = {
 
	  resultsList: "records",
 
      fields: [
 
          {key: "gravatar"},
 
          {key: "raw_username"},
 
          {key: "username"},
 
          {key: "firstname"},
 
          {key: "lastname"},
 
          {key: "last_login"},
 
          {key: "last_login_raw"},
 
          {key: "active"},
 
          {key: "admin"},
 
          {key: "ldap"},
 
          {key: "action"},
 
      ]
 
   };
 
  myDataSource.doBeforeCallback = function(req,raw,res,cb) {
 
      // This is the filter function
 
      var data     = res.results || [],
 
          filtered = [],
 
          i,l;
 

	
 
      if (req) {
 
          req = req.toLowerCase();
 
          for (i = 0; i<data.length; i++) {
 
        	  var pos = data[i].raw_username.toLowerCase().indexOf(req)
 
              if (pos != -1) {
 
                  filtered.push(data[i]);
 
              }
 
          }
 
          res.results = filtered;
 
      }
 
      YUD.get('user_count').innerHTML = res.results.length;
 
      return res;
 
  }
 

	
 
  // main table sorting
 
  var myColumnDefs = [
 
      {key:"gravatar",label:"",sortable:false,},
 
      {key:"username",label:"${_('username')}",sortable:true,
 
    	  sortOptions: { sortFunction: linkSort }
 
      },
 
      {key:"firstname",label:"${_('firstname')}",sortable:true,},
 
      {key:"lastname",label:"${_('lastname')}",sortable:true,},
 
      {key:"last_login",label:"${_('last login')}",sortable:true,},
 
      {key:"last_login",label:"${_('last login')}",sortable:true,
 
    	  sortOptions: { sortFunction: lastLoginSort }},
 
      {key:"active",label:"${_('active')}",sortable:true,},
 
      {key:"admin",label:"${_('admin')}",sortable:true,},
 
      {key:"ldap",label:"${_('ldap')}",sortable:true,},
 
      {key:"action",label:"${_('action')}",sortable:false},
 
  ];
 

	
 
  var myDataTable = new YAHOO.widget.DataTable("users_list_wrap", myColumnDefs, myDataSource,{
 
    sortedBy:{key:"username",dir:"asc"},
 
    paginator: new YAHOO.widget.Paginator({
 
        rowsPerPage: 15,
 
        alwaysVisible: false,
 
        template : "{PreviousPageLink} {FirstPageLink} {PageLinks} {LastPageLink} {NextPageLink}",
 
        pageLinks: 5,
 
        containerClass: 'pagination-wh',
 
        currentPageClass: 'pager_curpage',
 
        pageLinkClass: 'pager_link',
 
        nextPageLinkLabel: '&gt;',
 
        previousPageLinkLabel: '&lt;',
 
        firstPageLinkLabel: '&lt;&lt;',
 
        lastPageLinkLabel: '&gt;&gt;',
 
        containers:['user-paginator']
 
    }),
 

	
 
    MSG_SORTASC:"${_('Click to sort ascending')}",
0 comments (0 inline, 0 general)