fix after pybabel compile
[cavote.git] / main.py
diff --git a/main.py b/main.py
index e3f0947..7df6af3 100755 (executable)
--- a/main.py
+++ b/main.py
@@ -3,16 +3,21 @@
 
 from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash
-from gettext import gettext
+from gettext import translation
+import locale
+import os
+
+current_locale, encoding = locale.getdefaultlocale()
+locale_path = 'translations/'
+language = translation('messages', locale_path, [current_locale])
+gettext = language.ugettext
+
 #from flask_openid import OpenID
 #from flaskext.babel import Babel, gettext, ngettext
 import sqlite3
 from datetime import date, time, timedelta, datetime
 import time
 from contextlib import closing
-import locale
-locale.setlocale(locale.LC_ALL, '')
-import os
 import hashlib
 import smtplib
 import string
@@ -344,7 +349,7 @@ def admin_user_edit(iduser):
                         g.db.execute('delete from user_group where id_user = ? and id_group = ?', [iduser, group['id']])
                         g.db.commit()
                 for group in groups:
-                    group = query_db('select id from groups where id = ?', group, one=True)
+                    group = query_db('select id from groups where id = ?', [group], one=True)
                     if group is None:
                         flash(u'Le groupe portant l\'id %s n\'existe pas.' % group, 'warning')
                     else:
@@ -432,9 +437,9 @@ def votes(votes):
                  left join (' + nb_votes + ') on id = id_vote'
     basequery = 'select *, votes.id as voteid, groups.name as groupname from (' + basequery + ') as votes \
                  join groups on groups.id = id_group \
-                 where is_open=1 and is_hidden=0'
+                 where is_hidden=0'
     if votes == 'all':
-        votes = query_db(basequery + ' order by date_end')
+        votes = query_db(basequery + ' and is_open=1 order by date_end')
     elif votes == 'archive':
         votes = query_db(basequery + ' and is_terminated=1 order by date_end desc')
     elif votes == 'current':
@@ -530,9 +535,10 @@ def vote(idvote):
                                   order by random()')
                     g.db.execute('delete from user_choice_buffer_anonymous')
                     g.db.commit()
-                g.db.execute('insert into user_vote (id_user, id_vote) \
-                              values (?, ?)'
-                            , [session.get('user').get('id'), vote['id']])
+                comment = request.form.get('comment', None)
+                g.db.execute('insert into user_vote (id_user, id_vote, comment) \
+                              values (?, ?, ?)'
+                            , [session.get('user').get('id'), vote['id'], comment])
                 g.db.commit()
             else:
                 abort(401)
@@ -558,7 +564,7 @@ def vote(idvote):
         # ACTION: query users' choices joined with users' identity if not anonymous
         user_choices = query_db('select user_choice.id_user as userid, users.name as username, \
                                         choices.id as choiceid, choices.name as choice_name, \
-                                        user_choice.weight as weight \
+                                        user_choice.weight as weight, user_vote.comment as comment \
                                  from choices \
                                  join user_choice on choices.id = user_choice.id_choice \
                                  left join users on userid = users.id \
@@ -615,11 +621,12 @@ def vote(idvote):
         # ACTION: list user results per user
         users = OrderedDict()
         if vote['is_anonymous']:
-            user_votes = query_db('select users.name, id_user as userid \
+            user_votes = query_db('select users.name, id_user as userid, comment \
                                    from user_vote \
                                    join users on users.id = id_user where id_vote = ?', [idvote])
             for uc in user_votes:
                 users[uc['userid']] = { 'username':uc['name']
+                                      , 'comment':uc['comment']
                                       , 'choices':{}
                                       , 'userid':uc['userid'] }
         else:
@@ -633,6 +640,7 @@ def vote(idvote):
                 else:
                     users[uc['userid']] = { 'userid':uc['userid']
                                           , 'username':uc['username']
+                                          , 'comment':uc['comment']
                                           , 'choices':{uc['choiceid']:value} }
         attachments = query_db('select * from attachments where id_vote=?', [idvote])
         if query_db('select * from user_group where id_group = ? and id_user = ?'
@@ -671,7 +679,10 @@ def admin_votes():
     votes = query_db('select *, votes.id as voteid, groups.name as groupname from votes \
                       join groups on groups.id=votes.id_group \
                       where is_hidden=0 order by id desc')
-    return render_template('admin_votes.html', votes=votes, today=date.today().strftime("%Y-%m-%d"))
+    return render_template('admin_votes.html', votes=votes
+      , today=date.today().strftime("%Y-%m-%d")
+      , can_delete_votes=CAN_DELETE_VOTES
+      )
 
 @app.route('/admin/votes/add', methods=['GET', 'POST'])
 def admin_vote_add():
@@ -764,33 +775,39 @@ def admin_vote_edit(voteid):
                 public = 1
             isopen = 0
             isterminated = 0
+            print "POST"
             if request.form['status'] == 'Ouvert':
-                choices = query_db('select id_vote, count(*) as nb \
-                                    from choices where id_vote = ? \
+                choices = query_db('select id_vote, count(*) as nb, groups.name as group_name \
+                                    from choices \
+                                    join votes on votes.id = choices.id_vote \
+                                    join groups on groups.id = votes.id_group \
+                                    where id_vote = ? \
                                     group by id_vote', [voteid], one=True)
                 if choices is not None and choices['nb'] >= 1:
                     isopen = 1
                     previousvote = query_db('select id, is_open, id_group from votes where id = ?', [voteid], one=True)
-                    if previousvote is None or previousvote['is_open'] == 0:
+                    if (previousvote is None or previousvote['is_open'] == 0) and 'mail_notice' in request.form:
                         users_to_vote = query_db('select users.email, users.name from users \
                                                   join user_group on users.id=user_group.id_user \
                                                   where user_group.id_group = ?', [previousvote['id_group']])
                         for user in users_to_vote:
                             link = request.url_root + url_for('vote', idvote=voteid)
                             BODY = string.join((
-                                "From: %s" % EMAIL,
-                                "To: %s" % user['email'],
-                                "Subject: [Cavote] %s" % gettext(u"A vote has been opened for your group"),
-                                "Date: %s" % time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()).decode('utf-8'),
-                                "Content-type: text/plain; charset=utf-8",
-                                "X-Mailer: %s" % VERSION,
+                                u"From: %s" % EMAIL,
+                                u"To: %s" % user['email'],
+                                u"Subject: [vote] [%s] %s" % (choices['group_name'], request.form['title']),
+                                u"Date: %s" % time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()).decode('utf-8'),
+                                u"Content-type: text/plain; charset=utf-8",
+                                u"X-Mailer: %s" % VERSION,
                                 "",
-                                "%(text)s %(title)s" % {"text": gettext(u"A vote has been opened and you are in a group concerned by it :"), "title": request.form['title']},
-                                "",
-                                gettext(u"This link will bring you to the form where you will be able to vote :"),
+                                u"%(text0)s%(group)s" % \
+                                  { "text0":gettext(u"A new vote concerns you within the group: ") \
+                                  , "group":choices['group_name'] }, \
                                 link,
                                 "",
-                                gettext(u"If you think this mail is not for you, please ignore and delete it.")
+                                gettext(u"If you think this mail is not for you, please ignore and delete it."),
+                                gettext(u"For more informations, you can contact:"),
+                                EMAIL
                                 ), "\r\n")
                             server = smtplib.SMTP(SMTP_SERVER)
                             server.sendmail(EMAIL, [user['email']], BODY.encode('utf-8'))
@@ -816,7 +833,7 @@ def admin_vote_edit(voteid):
     choices = query_db('select * from choices where id_vote = ?', [voteid])
     values_ = query_db('select * from cardinals where id = ?', [vote['id_cardinal']], one=True)['name']
     attachments = query_db('select * from attachments where id_vote = ?', [voteid])
-    if date.today().strftime("%Y-%m-%d") > vote['date_end']:
+    if date.today().strftime("%Y-%m-%d") > vote['date_end'] and not vote['is_terminated']:
         flash(u'La deadline du vote est expirée, vous devriez terminer le vote.')
     return render_template('admin_vote_edit.html', vote=vote, group=group, values_=values_, choices=choices, attachments=attachments, quorums=QUORUMS)
 
@@ -824,11 +841,13 @@ def admin_vote_edit(voteid):
 def admin_vote_del(idvote):
     if not session.get('user').get('is_admin'):
         abort(401)
-    vote = query_db('select * from votes where id = ?', [idvote], one=True)
-    if vote is None:
-        abort(404)
-    g.db.execute('update votes set is_hidden=1 where id = ?', [idvote])
-    g.db.commit()
+    if not CAN_DELETE_VOTES:
+        flash(u'La configuration interdit la suppression des votes.', 'error')
+    else:
+      if vote is None:
+          abort(404)
+      g.db.execute('update votes set is_hidden=1 where id = ?', [idvote])
+      g.db.commit()
     return redirect(url_for('admin_votes'))
 
 @app.route('/admin/votes/addchoice/<voteid>', methods=['POST'])