tables.py 11.1 KB
Newer Older
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
# Copyright 2011-2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.
33

34
35
from collections import defaultdict

36
from django.utils.translation import ugettext as _
37
38
39
40
from django.utils.safestring import mark_safe
from django.template import Context, Template
from django.template.loader import render_to_string

41
from django_tables2 import A
42
43
import django_tables2 as tables

44
from astakos.im.models import *
45
from astakos.im.templatetags.filters import truncatename
46
47
48
49
50
51
52
53
54
55
56
57
58
59

DEFAULT_DATE_FORMAT = "d/m/Y"


MEMBER_STATUS_DISPLAY = {
    100: _('Owner'),
      0: _('Requested'),
      1: _('Pending'),
      2: _('Accepted'),
      3: _('Removing'),
      4: _('Removed'),
     -1: _('Unregistered'),
}

60
61
62
63
64
65
66
67
68
69
70
71
class TruncatedLinkColumn(tables.LinkColumn):

    def __init__(self, *args, **kwargs):
        self.truncate_chars = kwargs.pop('truncate_chars', 10)
        super(TruncatedLinkColumn, self).__init__(*args, **kwargs)


    def render_link(self, uri, text, attrs=None):
        text = truncatename(text, self.truncate_chars)
        return super(TruncatedLinkColumn, self).render_link(uri, text, attrs)


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
# Helper columns
class RichLinkColumn(tables.TemplateColumn):

    method = 'POST'

    confirm_prompt = _('Yes')
    cancel_prompt = _('No')
    confirm = True

    prompt = _('Confirm action ?')

    action_tpl = None
    action = _('Action')
    extra_context = lambda record, table, column: {}

    url = None
    url_args = ()
    resolve_func = None

    def __init__(self, *args, **kwargs):
        kwargs['template_name'] = kwargs.get('template_name',
                                             'im/table_rich_link_column.html')
        for attr in ['method', 'confirm_prompt',
                     'cancel_prompt', 'prompt', 'url',
                     'url_args', 'action', 'confirm',
                     'resolve_func', 'extra_context']:
            setattr(self, attr, kwargs.pop(attr, getattr(self, attr)))

        super(RichLinkColumn, self).__init__(*args, **kwargs)

    def render(self, record, table, value, bound_column, **kwargs):
        # If the table is being rendered using `render_table`, it hackily
        # attaches the context to the table as a gift to `TemplateColumn`. If
        # the table is being rendered via `Table.as_html`, this won't exist.
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        content = ''
        for extra_context in self.get_template_context(record, table, value,
                                                       bound_column, **kwargs):
            context = getattr(table, 'context', Context())
            context.update(extra_context)
            try:
                if self.template_code:
                    content += Template(self.template_code).render(context)
                else:
                    content += render_to_string(self.template_name, context)
            finally:
                context.pop()

        return mark_safe(content)
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

    def get_confirm(self, record, table):
        if callable(self.confirm):
            return self.confirm(record, table)
        return self.confirm

    def resolved_url(self, record, table):
        if callable(self.url):
            return self.url(record, table)

        if not self.url:
            return '#'

        args = list(self.url_args)
        for index, arg in enumerate(args):
            if isinstance(arg, A):
                args[index] = arg.resolve(record)
        return reverse(self.url, args=args)

    def get_action(self, record, table):
        if callable(self.action):
            return self.action(record, table)
        return self.action

    def get_prompt(self, record, table):
        if callable(self.prompt):
            return self.prompt(record, table)
        return self.prompt

    def get_template_context(self, record, table, value, bound_column, **kwargs):
        context = {'default': bound_column.default,
                   'record': record,
                   'value': value,
                   'col': self,
                   'url': self.resolved_url(record, table),
                   'prompt': self.get_prompt(record, table),
                   'action': self.get_action(record, table),
                   'confirm': self.get_confirm(record, table)
                  }

160
161
        # decide whether to return dict or a list of dicts in case we want to
        # display multiple actions within a cell.
162
        if self.extra_context:
163
164
165
166
167
168
169
170
171
            contexts = []
            extra_contexts = self.extra_context(record, table, self)
            if isinstance(extra_contexts, list):
                for extra_context in extra_contexts:
                    newcontext = dict(context)
                    newcontext.update(extra_context)
                    contexts.append(newcontext)
            else:
                context.update(extra_contexts)
172
                contexts = [context]
173
174
        else:
            contexts = [context]
175

176
        return contexts
177
178
179
180
181
182
183
184
185
186
187
188


def action_extra_context(project, table, self):
    user = table.user
    url, action, confirm, prompt = '', '', True, ''
    append_url = ''

    if user.owns_project(project):
        url = 'astakos.im.views.project_update'
        action = _('Update')
        confirm = False
        prompt = ''
189
    elif user.is_project_accepted_member(project):
190
191
192
193
        url = 'astakos.im.views.project_leave'
        action = _('- Leave')
        confirm = True
        prompt = _('Are you sure you want to leave from the project ?')
194
    elif not user.is_project_member(project):
195
196
197
198
        url = 'astakos.im.views.project_join'
        action = _('+ Join')
        confirm = True
        prompt = _('Are you sure you want to join this project ?')
199
    else:
200
201
202
        action = ''
        confirm = False
        url = None
203

204
205
206
207
    url = reverse(url, args=(project.pk, )) + append_url if url else ''
    return {'action': action,
            'confirm': confirm,
            'url': url,
208
209
210
            'prompt': prompt}


211
class UserTable(tables.Table):
212
213
214
215
216
217
218
219
220
221

    def __init__(self, *args, **kwargs):
        self.user = None

        if 'request' in kwargs and kwargs.get('request').user:
            self.user = kwargs.get('request').user

        if 'user' in kwargs:
            self.user = kwargs.pop('user')

222
223
224
225
226
227
        super(UserTable, self).__init__(*args, **kwargs)


# Table classes
class UserProjectApplicationsTable(UserTable):
    caption = _('My projects')
228

229
230
231
    name = TruncatedLinkColumn('astakos.im.views.project_detail',
                                                truncate_chars=25,
                                                args=(A('pk'),))
232
233
    issue_date = tables.DateColumn(format=DEFAULT_DATE_FORMAT)
    start_date = tables.DateColumn(format=DEFAULT_DATE_FORMAT)
Olga Brani's avatar
Olga Brani committed
234
    end_date = tables.DateColumn(format=DEFAULT_DATE_FORMAT)
235
    members_count = tables.Column(verbose_name=_("Enrolled"), default=0,
236
                                  sortable=False)
Olga Brani's avatar
Olga Brani committed
237
238
    membership_status = tables.Column(verbose_name=_("Status"), empty_values=(),
                                      sortable=False)
239
240
241
    project_action = RichLinkColumn(verbose_name=_('Action'),
                                    extra_context=action_extra_context,
                                    sortable=False)
242

243

Olga Brani's avatar
Olga Brani committed
244
    def render_membership_status(self, record, *args, **kwargs):
245
        status = record.user_status(self.user)
Olga Brani's avatar
Olga Brani committed
246
247
248
249
        if status == 100:
            return record.state
        else:
            return MEMBER_STATUS_DISPLAY.get(status, 'Unknown')
250
251
252

    class Meta:
        model = ProjectApplication
Olga Brani's avatar
Olga Brani committed
253
        fields = ('name', 'membership_status', 'issue_date', 'start_date','end_date', 'members_count')
254
255
        attrs = {'id': 'projects-list', 'class': 'my-projects alt-style'}
        template = "im/table_render.html"
256
257
258
259
        empty_text = _('No projects')


def member_action_extra_context(membership, table, col):
260
261

    context = []
262
    urls, actions, prompts, confirms = [], [], [], []
263
264
265
266
267
268
269
270
271
272
273
274
275
276

    if membership.state == ProjectMembership.REQUESTED:
        urls = ['astakos.im.views.project_reject_member',
                'astakos.im.views.project_accept_member']
        actions = [_('Reject'), _('Approve')]
        prompts = [_('Are you sure you want to reject this member ?'),
                   _('Are you sure you want to approve this member ?')]
        confirms = [True, True]

    if membership.state == ProjectMembership.ACCEPTED:
        urls = ['astakos.im.views.project_remove_member']
        actions = [_('Remove')]
        prompts = [_('Are you sure you want to remove this member ?')]
        confirms = [True, True]
277
278


279
280
281
282
283
284
285
    for i, url in enumerate(urls):
        context.append(dict(url=reverse(url, args=(table.project.pk,
                                                   membership.person.pk)),
                            action=actions[i], prompt=prompts[i],
                            confirm=confirms[i]))
    return context

286
class ProjectApplicationMembersTable(UserTable):
287
288
    name = tables.Column(accessor="person.last_name", verbose_name=_('Name'))
    status = tables.Column(accessor="state", verbose_name=_('Status'))
289
290
291
292
293
294
295
296
297
298
    project_action = RichLinkColumn(verbose_name=_('Action'),
                                    extra_context=member_action_extra_context,
                                    sortable=False)


    def __init__(self, project, *args, **kwargs):
        self.project = project
        super(ProjectApplicationMembersTable, self).__init__(*args, **kwargs)
        if not self.user.owns_project(self.project):
            self.exclude = ('project_action', )
299
300
301


    def render_name(self, value, record, *args, **kwargs):
302
        return record.person.realname
303
304
305
306
307
308
309
310
311

    def render_status(self, value, *args, **kwargs):
        return MEMBER_STATUS_DISPLAY.get(value, 'Unknown')

    class Meta:
        template = "im/table_render.html"
        model = ProjectMembership
        fields = ('name', 'status')
        attrs = {'id': 'members-table', 'class': 'members-table alt-style'}
312
        empty_text = _('No members')
313