Fix group creation summary view
authorSofia Papagiannaki <papagian@gmail.com>
Thu, 8 Nov 2012 15:53:00 +0000 (17:53 +0200)
committerSofia Papagiannaki <papagian@gmail.com>
Thu, 8 Nov 2012 15:53:00 +0000 (17:53 +0200)
snf-astakos-app/astakos/im/api/backends/lib/django/__init__.py
snf-astakos-app/astakos/im/api/backends/notifications.py [new file with mode: 0644]
snf-astakos-app/astakos/im/forms.py
snf-astakos-app/astakos/im/functions.py
snf-astakos-app/astakos/im/templates/im/astakosgroup_form_demo.html
snf-astakos-app/astakos/im/templates/im/astakosgroup_form_summary.html
snf-astakos-app/astakos/im/templates/im/group_creation_notification.txt
snf-astakos-app/astakos/im/views.py

index f1b7203..cb6da93 100644 (file)
@@ -65,7 +65,7 @@ def safe(func):
         except Exception, e:
             logger.exception(e)
             transaction.rollback()
-            return FailureResult(getattr(e, 'message', e))
+            return FailureResult(e)
         else:
             transaction.commit()
             return SuccessResult(data)
@@ -297,9 +297,6 @@ class DjangoBackend(BaseBackend):
         permissions = kwargs.pop('permissions', ())
         members = kwargs.pop('members', ())
         owners = kwargs.pop('owners', ())
-        kwargs['kind'] = self._lookup_object(
-            GroupKind, name=kwargs.get('kind', 'course')
-        )
 
         g = self._create_object(AstakosGroup, **kwargs)
 
diff --git a/snf-astakos-app/astakos/im/api/backends/notifications.py b/snf-astakos-app/astakos/im/api/backends/notifications.py
new file mode 100644 (file)
index 0000000..a69ff22
--- /dev/null
@@ -0,0 +1,42 @@
+def _send_admin_notification(template_name,
+                             dictionary=None,
+                             subject='alpha2 testing notification',):
+    """
+    Send notification email to settings.ADMINS.
+
+    Raises SendNotificationError
+    """
+    if not settings.ADMINS:
+        return
+    dictionary = dictionary or {}
+    message = render_to_string(template_name, dictionary)
+    sender = settings.SERVER_EMAIL
+    try:
+        send_mail(subject,
+                  message, sender, [i[1] for i in settings.ADMINS])
+    except (SMTPException, socket.error) as e:
+        logger.exception(e)
+        raise SendNotificationError()
+    else:
+        msg = 'Sent admin notification for user %s' % dictionary
+        logger.log(LOGGING_LEVEL, msg)
+
+class EmailNotification(Notification):
+    def send(self):
+        send_mail(
+            subject,
+            message,
+            sender,
+            recipients
+        )
+    )
+
+class Notification(object):
+    def __init__(self, sender, recipients, subject, message):
+        self.sender = sender
+        self.recipients = recipients
+        self.subject = subject
+        self.message = message
+    
+    def send(self):
+        pass
\ No newline at end of file
index a54e299..ea9aafc 100644 (file)
@@ -542,7 +542,7 @@ class AstakosGroupCreationForm(forms.ModelForm):
         initial=True
     )
     max_participants = forms.IntegerField(
-        widget=forms.HiddenInput(), label='', required=False
+        required=False, min_value=1
     )
 
     class Meta:
@@ -554,8 +554,8 @@ class AstakosGroupCreationForm(forms.ModelForm):
         qd = args.pop(0).copy()
         members_unlimited = qd.pop('members_unlimited', False)
         members_uplimit = qd.pop('members_uplimit', None)
-        max_participants = None if members_unlimited else members_uplimit
-        qd['max_participants']= max_participants.pop(0) if max_participants else None
+#         max_participants = None if members_unlimited else members_uplimit
+#         qd['max_participants']= max_participants.pop(0) if max_participants else None
         
         #substitue QueryDict
         args.insert(0, qd)
@@ -564,11 +564,11 @@ class AstakosGroupCreationForm(forms.ModelForm):
         self.fields.keyOrder = ['kind', 'name', 'homepage', 'desc',
                                 'issue_date', 'expiration_date',
                                 'moderation_enabled', 'max_participants']
-        
         def add_fields((k, v)):
             self.fields[k] = forms.IntegerField(
                 required=False,
-                widget=forms.HiddenInput()
+                widget=forms.HiddenInput(),
+                min_value=1
             )
         map(add_fields,
             ((k, v) for k,v in qd.iteritems() if k.endswith('_uplimit'))
@@ -583,8 +583,82 @@ class AstakosGroupCreationForm(forms.ModelForm):
             ((k, v) for k,v in qd.iteritems() if k.startswith('is_selected_'))
         )
     
+    def policies(self):
+        self.clean()
+        policies = []
+        append = policies.append
+        for name, uplimit in self.cleaned_data.iteritems():
+            subs = name.split('_uplimit')
+            if len(subs) == 2:
+                prefix, suffix = subs
+                s, r = prefix.split(RESOURCE_SEPARATOR)
+                resource = Resource.objects.get(service__name=s, name=r)
+                
+                # keep only resource limits for selected resource groups
+                if self.cleaned_data.get(
+                    'is_selected_%s' % resource.group, True
+                ):
+                    append(dict(service=s, resource=r, uplimit=uplimit))
+        return policies
+
+class AstakosGroupCreationSummaryForm(forms.ModelForm):
+    kind = forms.ModelChoiceField(
+        queryset=GroupKind.objects.all(),
+        label="",
+        widget=forms.HiddenInput()
+    )
+    name = forms.URLField()
+    moderation_enabled = forms.BooleanField(
+        help_text="Check if you want to approve members participation manually",
+        required=False,
+        initial=True
+    )
+    max_participants = forms.IntegerField(
+        required=False, min_value=1
+    )
+
+    class Meta:
+        model = AstakosGroup
+
+    def __init__(self, *args, **kwargs):
+        #update QueryDict
+        args = list(args)
+        qd = args.pop(0).copy()
+        members_unlimited = qd.pop('members_unlimited', False)
+        members_uplimit = qd.pop('members_uplimit', None)
+#         max_participants = None if members_unlimited else members_uplimit
+#         qd['max_participants']= max_participants.pop(0) if max_participants else None
+        
+        #substitue QueryDict
+        args.insert(0, qd)
+        
+        super(AstakosGroupCreationSummaryForm, self).__init__(*args, **kwargs)
+        self.fields.keyOrder = ['kind', 'name', 'homepage', 'desc',
+                                'issue_date', 'expiration_date',
+                                'moderation_enabled', 'max_participants']
+        def add_fields((k, v)):
+            self.fields[k] = forms.IntegerField(
+                required=False,
+                widget=forms.TextInput(),
+                min_value=1
+            )
+        map(add_fields,
+            ((k, v) for k,v in qd.iteritems() if k.endswith('_uplimit'))
+        )
+        
+        def add_fields((k, v)):
+            self.fields[k] = forms.BooleanField(
+                required=False,
+                widget=forms.HiddenInput()
+            )
+        map(add_fields,
+            ((k, v) for k,v in qd.iteritems() if k.startswith('is_selected_'))
+        )
+        for f in self.fields.values():
+            f.widget = forms.HiddenInput()
+
     def clean(self):
-        super(AstakosGroupCreationForm, self).clean()
+        super(AstakosGroupCreationSummaryForm, self).clean()
         self.cleaned_data['policies'] = []
         append = self.cleaned_data['policies'].append
         tbd = [f for f in self.fields if f.startswith('is_selected_')]
@@ -601,9 +675,9 @@ class AstakosGroupCreationForm(forms.ModelForm):
                     'is_selected_%s' % resource.group, True
                 ):
                     append(dict(service=s, resource=r, uplimit=uplimit))
-        (self.cleaned_data.pop(name, None) for name in tbd)
+        for name in tbd:
+            self.cleaned_data.pop(name, None)
         return self.cleaned_data
-        
 
 class AstakosGroupUpdateForm(forms.ModelForm):
     class Meta:
index 5434211..459a37a 100644 (file)
@@ -143,13 +143,13 @@ def _send_admin_notification(template_name,
 
 def send_account_creation_notification(template_name, dictionary=None):
     user = dictionary.get('user', AnonymousUser())
-    subject = _(ACCOUNT_CREATION_SUBJECT) % {'user': user.email}
+    subject = _(ACCOUNT_CREATION_SUBJECT) % {'user':user.get('email', '')}
     return _send_admin_notification(template_name, dictionary, subject=subject)
 
 
 def send_group_creation_notification(template_name, dictionary=None):
     group = dictionary.get('group', astakos.im.models.AstakosGroup())
-    subject = _(GROUP_CREATION_SUBJECT) % {'group': group.name}
+    subject = _(GROUP_CREATION_SUBJECT) % {'group':group.get('name', '')}
     return _send_admin_notification(template_name, dictionary, subject=subject)
 
 
index 6d4470d..679e431 100644 (file)
@@ -21,6 +21,7 @@
         
         {% include "im/form_render.html" %}
                
+<!-- 
                <div class="double-checks">
                <label>Max users per group</label>
                <div class="form-row">
@@ -44,6 +45,7 @@
                </div>
                
        </div> 
+ -->
     </fieldset>     
     
     <fieldset id="icons">
index e43223a..f3ba7e9 100644 (file)
@@ -4,18 +4,22 @@
 
 {% block page.body %}
  
-<!--{{ data }}-->
+{% with form.data as data %}           
 <div class="projects summary">
        <h2>CONFIRM YOUR REQUEST</h2>
        <p>Lorem ipsum</p>
-       <form action="{% url group_add_complete %}" class="quotas-form">
+       <form action="{% url group_add_complete %}" method="post" class="quotas-form">{% csrf_token %}
+<!-- 
                {% for k,v in data.iteritems %}
                        <input type="hidden" name="{{ k }}" value="{{ v }}">
                {% endfor %}
+ -->
+        {% include "im/form_render.html" %}
+               
                <div class="full-dotted">
                         <h3>DETAILS:</h3>
-                        <dl class="alt-style">
-                               <dt>Name</dt>
+                        <dl class="alt-style">                     
+                           <dt>Name</dt>
                                <dd>{{ data.name|strip_http }}&nbsp;</dd>
                                <dt>Homepage Url</dt>
                                <dd>{{ data.homepage }}&nbsp;</dd>
@@ -35,9 +39,8 @@
                 </div>
                 <div class="full-dotted">
                         <h3>RESOURCES:</h3>
-                  <dl class="alt-style">
-                       
-                       {% for r in data.policies %}
+                  <dl class="alt-style">                       
+                       {% for r in policies %}
                                {% with r.service|add:'.'|add:r.resource as t %}
                                {% with resource_catalog|lookup:'resources' as resources %}
                                {% with resources|lookup:t as info %}
@@ -80,5 +83,6 @@
        </form>
     
 </div>
+{% endwith %}
  
 {% endblock %}
index f4e285f..10a327f 100644 (file)
@@ -12,7 +12,7 @@ Owner:                          {{owner}}
 Maximum participant number:    {{group.max_participants}}
 Policies:
 {% for p in policies %}
-    {{p}}
+    {{p.service}}.{{p.resource}}: uplimit:{{p.uplimit}}
 {% endfor %}
 
 Για την ενεργοποίησή του μπορείτε να χρησιμοποιήσετε το command line εργαλείο:
@@ -31,7 +31,7 @@ Owner:                          {{owner}}
 Maximum participant number:    {{group.max_participants}}
 Policies:
 {% for p in policies %}
-    {{p}}
+    {{p.service}}.{{p.resource}}: uplimit:{{p.uplimit}}
 {% endfor %}
 
 For its activation you can use the command line tool:
index 2987280..d616711 100644 (file)
@@ -76,7 +76,8 @@ from astakos.im.forms import (LoginForm, InvitationForm, ProfileForm,
                               AstakosGroupCreationForm, AstakosGroupSearchForm,
                               AstakosGroupUpdateForm, AddGroupMembersForm,
                               AstakosGroupSortForm, MembersSortForm,
-                              TimelineForm, PickResourceForm)
+                              TimelineForm, PickResourceForm,
+                              AstakosGroupCreationSummaryForm)
 from astakos.im.functions import (send_feedback, SendMailError,
                                   logout as auth_logout,
                                   activate as activate_func,
@@ -749,7 +750,8 @@ def group_add(request, kind_name='default'):
             return render_response(
                 template='im/astakosgroup_form_summary.html',
                 context_instance=get_context(request),
-                data=form.cleaned_data,
+                form = AstakosGroupCreationSummaryForm(form.cleaned_data),
+                policies = form.policies(),
                 resource_catalog=resource_catalog,
                 resource_presentation=resource_presentation
             )
@@ -775,43 +777,45 @@ def group_add(request, kind_name='default'):
     return HttpResponse(t.render(c))
 
 
-# @require_http_methods(["POST"])
-# @signed_terms_required
-# @login_required
+@require_http_methods(["POST"])
+@signed_terms_required
+@login_required
 def group_add_complete(request):
-    d = dict(request.POST)
-    d['owners'] = [request.user]
-    result = callpoint.create_groups((d,)).next()
-    if result.is_success:
-        new_object = result.data[0]
-        model = AstakosGroup
-        msg = _("The %(verbose_name)s was created successfully.") %\
-            {"verbose_name": model._meta.verbose_name}
-        messages.success(request, msg, fail_silently=True)
-
-#                # send notification
-#                 try:
-#                     send_group_creation_notification(
-#                         template_name='im/group_creation_notification.txt',
-#                         dictionary={
-#                             'group': new_object,
-#                             'owner': request.user,
-#                             'policies': list(form.cleaned_data['policies']),
-#                         }
-#                     )
-#                 except SendNotificationError, e:
-#                     messages.error(request, e, fail_silently=True)
-        post_save_redirect = '/im/group/%(id)s/'
-        return HttpResponseRedirect(post_save_redirect % new_object)
-    else:
-        msg = _("The %(verbose_name)s creation failed: %(reason)s.") %\
-            {"verbose_name": model._meta.verbose_name,
-             "reason":result.reason}
-        messages.error(request, msg, fail_silently=True)
-    
+    model = AstakosGroup
+    form = AstakosGroupCreationSummaryForm(request.POST)
+    if form.is_valid():
+        d = form.cleaned_data
+        d['owners'] = [request.user]
+        result = callpoint.create_groups((d,)).next()
+        if result.is_success:
+            new_object = result.data[0]
+            msg = _("The %(verbose_name)s was created successfully.") %\
+                {"verbose_name": model._meta.verbose_name}
+            messages.success(request, msg, fail_silently=True)
+            
+            # send notification
+            try:
+                send_group_creation_notification(
+                    template_name='im/group_creation_notification.txt',
+                    dictionary={
+                        'group': new_object,
+                        'owner': request.user,
+                        'policies': d.get('policies', [])
+                    }
+                )
+            except SendNotificationError, e:
+                messages.error(request, e, fail_silently=True)
+            post_save_redirect = '/im/group/%(id)s/'
+            return HttpResponseRedirect(post_save_redirect % new_object)
+        else:
+            msg = _("The %(verbose_name)s creation failed: %(reason)s.") %\
+                {"verbose_name": model._meta.verbose_name,
+                 "reason":result.reason}
+            messages.error(request, msg, fail_silently=True)
     return render_response(
-    template='im/astakosgroup_form_summary.html',
-    context_instance=get_context(request))
+        template='im/astakosgroup_form_summary.html',
+        context_instance=get_context(request),
+        form=form)
 
 
 @require_http_methods(["GET"])
@@ -1003,7 +1007,7 @@ def group_search(request, extra_context=None, **kwargs):
                            sorting=sorting))
 
 
-@require_http_methods(["GET"])
+@require_http_methods(["POST"])
 @signed_terms_required
 @login_required
 def group_all(request, extra_context=None, **kwargs):