Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / tables.py @ 3e0a032d

History | View | Annotate | Download (13.4 kB)

1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from django.utils.translation import ugettext as _
35
from django.utils.safestring import mark_safe
36
from django.template import Context, Template
37
from django.template.loader import render_to_string
38
from django.core.exceptions import PermissionDenied
39

    
40
from django_tables2 import A
41
import django_tables2 as tables
42

    
43
from astakos.im.models import *
44
from astakos.im.templatetags.filters import truncatename
45
from astakos.im.functions import join_project_checks, can_leave_request, \
46
    cancel_membership_checks
47

    
48
DEFAULT_DATE_FORMAT = "d/m/Y"
49

    
50

    
51
class LinkColumn(tables.LinkColumn):
52

    
53
    def __init__(self, *args, **kwargs):
54
        self.coerce = kwargs.pop('coerce', None)
55
        self.append = kwargs.pop('append', None)
56
        super(LinkColumn, self).__init__(*args, **kwargs)
57

    
58
    def render(self, value, record, bound_column):
59
        link = super(LinkColumn, self).render(value, record, bound_column)
60
        extra = ''
61
        if self.append:
62
            if callable(self.append):
63
                extra = self.append(record, bound_column)
64
            else:
65
                extra = self.append
66
        return mark_safe(link + extra)
67

    
68
    def render_link(self, uri, text, attrs=None):
69
        if self.coerce:
70
            text = self.coerce(text)
71
        return super(LinkColumn, self).render_link(uri, text, attrs)
72

    
73

    
74
# Helper columns
75
class RichLinkColumn(tables.TemplateColumn):
76

    
77
    method = 'POST'
78

    
79
    confirm_prompt = _('Yes')
80
    cancel_prompt = _('No')
81
    confirm = True
82

    
83
    prompt = _('Confirm action ?')
84

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

    
89
    url = None
90
    url_args = ()
91
    resolve_func = None
92

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

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

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

    
121
        return mark_safe(content)
122

    
123
    def get_confirm(self, record, table):
124
        if callable(self.confirm):
125
            return self.confirm(record, table)
126
        return self.confirm
127

    
128
    def resolved_url(self, record, table):
129
        if callable(self.url):
130
            return self.url(record, table)
131

    
132
        if not self.url:
133
            return '#'
134

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

    
141
    def get_action(self, record, table):
142
        if callable(self.action):
143
            return self.action(record, table)
144
        return self.action
145

    
146
    def get_prompt(self, record, table):
147
        if callable(self.prompt):
148
            return self.prompt(record, table)
149
        return self.prompt
150

    
151
    def get_template_context(self, record, table, value, bound_column, **kwargs):
152
        context = {'default': bound_column.default,
153
                   'record': record,
154
                   'value': value,
155
                   'col': self,
156
                   'url': self.resolved_url(record, table),
157
                   'prompt': self.get_prompt(record, table),
158
                   'action': self.get_action(record, table),
159
                   'confirm': self.get_confirm(record, table)
160
                  }
161

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

    
178
        return contexts
179

    
180

    
181
def action_extra_context(application, table, self):
182
    user = table.user
183
    url, action, confirm, prompt = '', '', True, ''
184
    append_url = ''
185

    
186
    can_join = can_leave = can_cancel = False
187
    project = application.get_project()
188

    
189
    if project and project.is_approved():
190
        try:
191
            join_project_checks(project)
192
            can_join = True
193
        except PermissionDenied, e:
194
            pass
195

    
196
        try:
197
            can_leave = can_leave_request(project, user)
198
        except PermissionDenied:
199
            pass
200

    
201
        try:
202
            cancel_membership_checks(project)
203
            can_cancel = True
204
        except PermissionDenied:
205
            pass
206

    
207
    membership = user.get_membership(project)
208
    if membership is not None:
209
        if can_leave and membership.can_leave():
210
            url = 'astakos.im.views.project_leave'
211
            action = _('Leave')
212
            confirm = True
213
            prompt = _('Are you sure you want to leave from the project?')
214
        elif can_cancel and membership.can_cancel():
215
            url = 'astakos.im.views.project_cancel'
216
            action = _('Cancel')
217
            confirm = True
218
            prompt = _('Are you sure you want to cancel the join request?')
219

    
220
    elif can_join:
221
        url = 'astakos.im.views.project_join'
222
        action = _('Join')
223
        confirm = True
224
        prompt = _('Are you sure you want to join this project?')
225
    else:
226
        action = ''
227
        confirm = False
228
        url = None
229

    
230
    url = reverse(url, args=(application.chain, )) + append_url if url else ''
231

    
232
    return {'action': action,
233
            'confirm': confirm,
234
            'url': url,
235
            'prompt': prompt}
236

    
237

    
238
class UserTable(tables.Table):
239

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

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

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

    
249
        super(UserTable, self).__init__(*args, **kwargs)
250

    
251
def project_name_append(application, column):
252
    if application.has_pending_modifications():
253
        return mark_safe("<br /><i class='tiny'>%s</i>" % \
254
                             _('modifications pending'))
255
    return u''
256

    
257
# Table classes
258
class UserProjectApplicationsTable(UserTable):
259
    caption = _('My projects')
260

    
261
    name = LinkColumn('astakos.im.views.project_detail',
262
                      coerce=lambda x: truncatename(x, 25),
263
                      append=project_name_append,
264
                      args=(A('chain'),))
265
    issue_date = tables.DateColumn(verbose_name=_('Application'), format=DEFAULT_DATE_FORMAT)
266
    start_date = tables.DateColumn(format=DEFAULT_DATE_FORMAT)
267
    end_date = tables.DateColumn(verbose_name=_('Expiration'), format=DEFAULT_DATE_FORMAT)
268
    members_count = tables.Column(verbose_name=_("Members"), default=0,
269
                                  orderable=False)
270
    membership_status = tables.Column(verbose_name=_("Status"), empty_values=(),
271
                                      orderable=False)
272
    project_action = RichLinkColumn(verbose_name=_('Action'),
273
                                    extra_context=action_extra_context,
274
                                    orderable=False)
275

    
276

    
277
    def render_membership_status(self, record, *args, **kwargs):
278
        if self.user.owns_application(record) or self.user.is_project_admin():
279
            return record.project_state_display()
280
        else:
281
            try:
282
                project = record.project
283
                return self.user.membership_display(project)
284
            except Project.DoesNotExist:
285
                return _("Unknown")
286

    
287
    def render_members_count(self, record, *args, **kwargs):
288
        append = ""
289
        application = record
290
        project = application.get_project()
291
        if project is None:
292
            append = mark_safe("<i class='tiny'>%s</i>" % (_('pending'),))
293

    
294
        c = project.count_pending_memberships()
295
        if c > 0:
296
            append = mark_safe("<i class='tiny'> - %d %s</i>"
297
                                % (c, _('pending')))
298

    
299
        return mark_safe(str(record.members_count()) + append)
300
        
301
    class Meta:
302
        model = ProjectApplication
303
        fields = ('name', 'membership_status', 'issue_date', 'end_date', 'members_count')
304
        attrs = {'id': 'projects-list', 'class': 'my-projects alt-style'}
305
        template = "im/table_render.html"
306
        empty_text = _('No projects')
307
        exclude = ('start_date', )
308

    
309
class ProjectModificationApplicationsTable(UserProjectApplicationsTable):
310
    name = LinkColumn('astakos.im.views.project_detail',
311
                      verbose_name=_('Action'),
312
                      coerce= lambda x: 'review',
313
                      args=(A('pk'),))
314
    class Meta:
315
        attrs = {'id': 'projects-list', 'class': 'my-projects alt-style'}
316
        fields = ('issue_date', 'membership_status')
317
        exclude = ('start_date', 'end_date', 'members_count', 'project_action')
318

    
319
def member_action_extra_context(membership, table, col):
320

    
321
    context = []
322
    urls, actions, prompts, confirms = [], [], [], []
323

    
324
    if membership.project.is_deactivated():
325
        return context
326

    
327
    if membership.state == ProjectMembership.REQUESTED:
328
        urls = ['astakos.im.views.project_reject_member',
329
                'astakos.im.views.project_accept_member']
330
        actions = [_('Reject'), _('Accept')]
331
        prompts = [_('Are you sure you want to reject this member?'),
332
                   _('Are you sure you want to accept this member?')]
333
        confirms = [True, True]
334

    
335
    if membership.state in ProjectMembership.ACTUALLY_ACCEPTED:
336
        urls = ['astakos.im.views.project_remove_member']
337
        actions = [_('Remove')]
338
        prompts = [_('Are you sure you want to remove this member?')]
339
        confirms = [True, True]
340

    
341

    
342
    for i, url in enumerate(urls):
343
        context.append(dict(url=reverse(url, args=(table.project.pk,
344
                                                   membership.pk)),
345
                            action=actions[i], prompt=prompts[i],
346
                            confirm=confirms[i]))
347
    return context
348

    
349
class ProjectMembersTable(UserTable):
350
    email = tables.Column(accessor="person.email", verbose_name=_('Email'))    
351
    status = tables.Column(accessor="state", verbose_name=_('Status'))
352
    project_action = RichLinkColumn(verbose_name=_('Action'),
353
                                    extra_context=member_action_extra_context,
354
                                    orderable=False)
355

    
356

    
357
    def __init__(self, project, *args, **kwargs):
358
        self.project = project
359
        super(ProjectMembersTable, self).__init__(*args, **kwargs)
360
        if not self.user.owns_project(self.project):
361
            self.exclude = ('project_action', )
362

    
363
    def render_status(self, value, record, *args, **kwargs):
364
        return record.state_display()
365

    
366
    class Meta:
367
        template = "im/table_render.html"
368
        attrs = {'id': 'members-table', 'class': 'members-table alt-style'}
369
        empty_text = _('No members')
370