commit 3abf6c783fd13cbf6da994f67848901c2df6d20f
Author: Sofia Papagiannaki <papagian@gmail.com>
Date:   Tue Aug 28 13:45:29 2012 +0300

    Progress VIII
    
    send admin notification upon group creation

diff --git a/snf-astakos-app/astakos/im/activation_backends.py b/snf-astakos-app/astakos/im/activation_backends.py
index 71b0abe..8e2b887 100644
--- a/snf-astakos-app/astakos/im/activation_backends.py
+++ b/snf-astakos-app/astakos/im/activation_backends.py
@@ -104,7 +104,7 @@ class ActivationBackend(object):
     def handle_activation(self, user, \
                           activation_template_name='im/activation_email.txt', \
                           greeting_template_name='im/welcome_email.txt', \
-                          admin_email_template_name='im/admin_notification.txt', \
+                          admin_email_template_name='im/account_notification.txt', \
                           switch_accounts_email_template_name='im/switch_accounts_email.txt'):
         """
         If the user is already active returns immediately.
@@ -132,7 +132,11 @@ class ActivationBackend(object):
                     send_activation(user, activation_template_name)
                     return VerificationSent()
             else:
-                send_admin_notification(user, admin_email_template_name)
+                send_admin_notification(
+                    template_name=admin_email_template_name,
+                    dictionary={'user':user, 'group_creation':True},
+                    subject='%s alpha2 testing account notification' % SITENAME
+                )
                 return NotificationSent()
         except BaseException, e:
             logger.exception(e)
diff --git a/snf-astakos-app/astakos/im/functions.py b/snf-astakos-app/astakos/im/functions.py
index 6c1c57a..53a0817 100644
--- a/snf-astakos-app/astakos/im/functions.py
+++ b/snf-astakos-app/astakos/im/functions.py
@@ -105,30 +105,29 @@ def send_activation(user, template_name='im/activation_email.txt'):
     user.activation_sent = datetime.now()
     user.save()
 
-def send_admin_notification(user, template_name='im/admin_notification.txt'):
+def send_admin_notification(template_name,
+    dictionary={},
+    subject='alpha2 testing notification',
+):
     """
-    Send email to DEFAULT_ADMIN_EMAIL to notify for a new user registration.
+    Send notification email to DEFAULT_ADMIN_EMAIL.
     
     Raises SendNotificationError
     """
     if not DEFAULT_ADMIN_EMAIL:
         return
-    message = render_to_string(template_name, {
-            'user': user,
-            'baseurl': BASEURL,
-            'site_name': SITENAME,
-            'support': DEFAULT_CONTACT_EMAIL})
+    message = render_to_string(template_name, dictionary)
     sender = DEFAULT_FROM_EMAIL
     try:
-        send_mail('%s alpha2 testing account notification' % SITENAME, message, sender, [DEFAULT_ADMIN_EMAIL])
+        send_mail(subject, message, sender, [DEFAULT_ADMIN_EMAIL])
     except (SMTPException, socket.error) as e:
         logger.exception(e)
         raise SendNotificationError()
     else:
-        msg = 'Sent admin notification for user %s' % user.email
+        msg = 'Sent admin notification for user %s' % dictionary
         logger._log(LOGGING_LEVEL, msg, [])
 
-def send_helpdesk_notification(user, template_name='im/helpdesk_notification.txt'):
+def send_helpdesk_notification(user, template_name='im/account_notification.txt'):
     """
     Send email to DEFAULT_CONTACT_EMAIL to notify for a new user activation.
     
@@ -136,19 +135,23 @@ def send_helpdesk_notification(user, template_name='im/helpdesk_notification.txt
     """
     if not DEFAULT_CONTACT_EMAIL:
         return
-    message = render_to_string(template_name, {
-            'user': user,
-            'baseurl': BASEURL,
-            'site_name': SITENAME,
-            'support': DEFAULT_ADMIN_EMAIL})
+    message = render_to_string(
+        template_name,
+        {'user': user}
+    )
     sender = DEFAULT_FROM_EMAIL
     try:
-        send_mail('%s alpha2 testing account activated' % SITENAME, message, sender, [DEFAULT_CONTACT_EMAIL])
+        send_mail(
+            '%s alpha2 testing account activated' % SITENAME,
+            message,
+            sender,
+            [DEFAULT_CONTACT_EMAIL]
+        )
     except (SMTPException, socket.error) as e:
         logger.exception(e)
         raise SendNotificationError()
     else:
-        msg = 'Sent helpdesk admin notification for user %s' % user.email
+        msg = 'Sent helpdesk admin notification for %s' % user.email
         logger._log(LOGGING_LEVEL, msg, [])
 
 def send_invitation(invitation, template_name='im/invitation.txt'):
diff --git a/snf-astakos-app/astakos/im/management/commands/user_add.py b/snf-astakos-app/astakos/im/management/commands/user_add.py
index 73e7b32..c2994ed 100644
--- a/snf-astakos-app/astakos/im/management/commands/user_add.py
+++ b/snf-astakos-app/astakos/im/management/commands/user_add.py
@@ -103,7 +103,7 @@ class Command(BaseCommand):
         if options['active']:
             user.is_active = True
         if options['admin']:
-            user.is_admin = True
+            user.is_superuser = True
         
         try:
             user.save()
diff --git a/snf-astakos-app/astakos/im/models.py b/snf-astakos-app/astakos/im/models.py
index 165c1a0..084b757 100644
--- a/snf-astakos-app/astakos/im/models.py
+++ b/snf-astakos-app/astakos/im/models.py
@@ -332,7 +332,7 @@ class AstakosUser(User):
         logger._log(LOGGING_LEVEL, msg, [])
 
     def __unicode__(self):
-        return self.username
+        return '%s (%s)' % (self.realname, self.email)
     
     def conflicting_email(self):
         q = AstakosUser.objects.exclude(username = self.username)
diff --git a/snf-astakos-app/astakos/im/templates/im/account_notification.txt b/snf-astakos-app/astakos/im/templates/im/account_notification.txt
new file mode 100644
index 0000000..3ff57fd
--- /dev/null
+++ b/snf-astakos-app/astakos/im/templates/im/account_notification.txt
@@ -0,0 +1,36 @@
+--- A translation in English follows ---
+
+{% if group_creation %}
+Έχει δημιουργηθεί ο παρακάτω λογαριασμός:
+{% else %}
+Έχει ενεργοποιηθεί ο παρακάτω λογαριασμός:
+{% endif %}
+
+Email:          {{user.email}}
+First name:     {{user.first_name}}
+Last name:      {{user.last_name}}
+Is active:      {{user.is_active}}
+Level:          {{user.level}}
+Invitations:    {{user.invitations}}
+
+{% if group_creation %}
+Για την ενεργοποίησή του μπορείτε να χρησιμοποιήσετε το command line εργαλείο snf-manage user_send_activation
+{% endif %}
+--
+
+{% if group_creation %}
+The following account has been created:
+{% else %}
+The following account has been activated:
+{% endif %}
+
+Email:          {{user.email}}
+First name:     {{user.first_name}}
+Last name:      {{user.last_name}}
+Is active:      {{user.is_active}}
+Level:          {{user.level}}
+Invitations:    {{user.invitations}}
+
+{% if group_creation %}
+For its activation you can use the command line tool snf-manage user_send_activation
+{% endif %}
\ No newline at end of file
diff --git a/snf-astakos-app/astakos/im/templates/im/admin_notification.txt b/snf-astakos-app/astakos/im/templates/im/admin_notification.txt
deleted file mode 100644
index f0b86e8..0000000
--- a/snf-astakos-app/astakos/im/templates/im/admin_notification.txt
+++ /dev/null
@@ -1,24 +0,0 @@
---- A translation in English follows ---
-
-Έχει δημιουργηθεί ο παρακάτω λογαριασμός:
-
-Email:          {{user.email}}
-First name:     {{user.first_name}}
-Last name:      {{user.last_name}}
-Is active:      {{user.is_active}}
-Level:          {{user.level}}
-Invitations:    {{user.invitations}}
-
-Για την ενεργοποίησή του μπορείτε να χρησιμοποιήσετε το command line εργαλείο snf-manage user_send_activation
---
-
-The following account has been created:
-
-Email:          {{user.email}}
-First name:     {{user.first_name}}
-Last name:      {{user.last_name}}
-Is active:      {{user.is_active}}
-Level:          {{user.level}}
-Invitations:    {{user.invitations}}
-
-For its activation you can use the command line tool snf-manage user_send_activation
diff --git a/snf-astakos-app/astakos/im/templates/im/group_creation_notification.txt b/snf-astakos-app/astakos/im/templates/im/group_creation_notification.txt
new file mode 100644
index 0000000..57267ca
--- /dev/null
+++ b/snf-astakos-app/astakos/im/templates/im/group_creation_notification.txt
@@ -0,0 +1,36 @@
+--- A translation in English follows ---
+
+Έχει δημιουργηθεί το παρακάτω group:
+
+Id:                 {{group.id}}}
+Name:               {{group.name}}
+Type:               {{group.kind}}
+Issue date:         {{group.issue_date|date:"d/m/Y"}}
+Expiration date:    {{group.expiration_date|date:"d/m/Y"}}
+Moderation:         {{group.moderation_enabled}}
+Owner:              {{owner}}
+Policies:
+{% for p in policies %}
+    {{p}}
+{% endfor %}
+
+Για την ενεργοποίησή του μπορείτε να χρησιμοποιήσετε το command line εργαλείο:
+snf-manage group_update <group_id> --enable
+--
+
+The following account has been created:
+
+Id:                 {{group.id}}}
+Name:               {{group.name}}
+Type:               {{group.kind}}
+Issue date:         {{group.issue_date|date:"d/m/Y"}}
+Expiration date:    {{group.expiration_date|date:"d/m/Y"}}
+Moderation:         {{group.moderation_enabled}}
+Owner:              {{owner}}
+Policies:
+{% for p in policies %}
+    {{p}}
+{% endfor %}
+
+For its activation you can use the command line tool:
+snf-manage group_update <group_id> --enable
diff --git a/snf-astakos-app/astakos/im/views.py b/snf-astakos-app/astakos/im/views.py
index ecc7d4a..c4dd581 100644
--- a/snf-astakos-app/astakos/im/views.py
+++ b/snf-astakos-app/astakos/im/views.py
@@ -62,7 +62,8 @@ from astakos.im.activation_backends import get_backend, SimpleBackend
 from astakos.im.util import get_context, prepare_response, set_cookie, get_query
 from astakos.im.forms import *
 from astakos.im.functions import send_greeting, send_feedback, SendMailError, \
-    invite as invite_func, logout as auth_logout, activate as activate_func, switch_account_to_shibboleth
+    invite as invite_func, logout as auth_logout, activate as activate_func, \
+    switch_account_to_shibboleth, send_admin_notification, SendNotificationError
 from astakos.im.settings import DEFAULT_CONTACT_EMAIL, DEFAULT_FROM_EMAIL, COOKIE_NAME, COOKIE_DOMAIN, IM_MODULES, SITENAME, LOGOUT_NEXT, LOGGING_LEVEL
 
 logger = logging.getLogger(__name__)
@@ -455,10 +456,19 @@ def activate(request, greeting_email_template_name='im/welcome_email.txt', helpd
         return index(request)
         
     try:
-        local_user = AstakosUser.objects.get(~Q(id = user.id), email=user.email, is_active=True)
+        local_user = AstakosUser.objects.get(
+            ~Q(id = user.id),
+            email=user.email,
+            is_active=True
+        )
     except AstakosUser.DoesNotExist:
         try:
-            activate_func(user, greeting_email_template_name, helpdesk_email_template_name, verify_email=True)
+            activate_func(
+                user,
+                greeting_email_template_name,
+                helpdesk_email_template_name,
+                verify_email=True
+            )
             response = prepare_response(request, user, next, renew=True)
             transaction.commit()
             return response
@@ -475,7 +485,11 @@ def activate(request, greeting_email_template_name='im/welcome_email.txt', helpd
             return index(request)
     else:
         try:
-            user = switch_account_to_shibboleth(user, local_user, greeting_email_template_name)
+            user = switch_account_to_shibboleth(
+                user,
+                local_user,
+                greeting_email_template_name
+            )
             response = prepare_response(request, user, next, renew=True)
             transaction.commit()
             return response
@@ -595,38 +609,54 @@ def group_add(request, kind_name='default'):
     except:
         return HttpResponseBadRequest(_('No such group kind'))
     
-    template_name=None,
     template_loader=loader
-    extra_context=None
     post_save_redirect='/im/group/%(id)s/'
-    login_required=False
     context_processors=None
     model, form_class = get_model_and_form_class(
         model=None,
         form_class=AstakosGroupCreationForm
     )
-    # TODO better approach???
     resources = dict( (str(r.id), r) for r in Resource.objects.select_related().all() )
+    policies = []
     if request.method == 'POST':
         form = form_class(request.POST, request.FILES, resources=resources)
         if form.is_valid():
             new_object = form.save()
+            
+            # save owner
             new_object.owners = [request.user]
+            
+            # save quota policies
             for (rid, limit) in form.resources():
                 try:
                     r = resources[rid]
                 except KeyError, e:
                     logger.exception(e)
-                    # Should I stay or should I go???
+                    # TODO Should I stay or should I go???
                     continue
                 else:
                     new_object.astakosgroupquota_set.create(
                         resource = r,
                         limit = limit
                     )
+                policies.append('%s %d' % (r, limit))
             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_admin_notification(
+                    template_name='im/group_creation_notification.txt',
+                    dictionary={
+                        'group':new_object,
+                        'owner':request.user,
+                        'policies':policies,
+                    },
+                    subject='%s alpha2 testing group creation notification' % SITENAME
+                )
+            except SendNotificationError, e:
+                messages.error(request, e, fail_silently=True)
             return redirect(post_save_redirect, new_object)
     else:
         now = datetime.now()
