+def has_voted(idvote, iduser=-1):
+ vote = query_db('select * from user_choice join choices on id_choice=choices.id where id_vote = ? and id_user = ?', [idvote, iduser], one=True)
+ return (vote is not None)
+
+@app.route('/vote/<idvote>', methods=['GET', 'POST'])
+def vote(idvote):
+ vote = query_db('select votes.*, groups.name as groupname, users.name as author from votes join groups on groups.id=votes.id_group join users on users.id = id_author where votes.id=?', [idvote], one=True)
+ if vote is None:
+ abort(404)
+ if can_see_vote(idvote, get_userid()):
+ if request.method == 'POST':
+ if can_vote(idvote, get_userid()):
+ if vote['is_multiplechoice'] == 0:
+ if query_db('select * from choices where id = ?', [request.form['choice']], one=True) is not None:
+ g.db.execute('insert into user_choice (id_user, id_choice) values (?, ?)',
+ [session.get('user').get('id'), request.form['choice']])
+ g.db.commit()
+ else:
+ choices = query_db('select name, id from choices where id_vote=?', [idvote])
+ for choice in choices:
+ if str(choice['id']) in request.form.keys():
+ g.db.execute('insert into user_choice (id_user, id_choice) values (?, ?)',
+ [session.get('user').get('id'), choice['id']])
+ g.db.commit()
+ else:
+ abort(401)
+ tuples = query_db('select choiceid, choicename, users.id as userid, users.name as username from (select choices.id as choiceid, choices.name as choicename, id_user as userid from choices join user_choice on choices.id = user_choice.id_choice where id_vote = ?) join users on userid = users.id', [idvote])
+ users = dict()
+ for t in tuples:
+ if t['userid'] in users:
+ users[t['userid']]['choices'].append(t['choiceid'])
+ else:
+ users[t['userid']] = dict()
+ users[t['userid']]['userid'] = t['userid']
+ users[t['userid']]['username'] = t['username']
+ users[t['userid']]['choices'] = [t['choiceid']]
+ choices = query_db('select choices.name, choices.id, choices.name, choices.id_vote, count(id_choice) as nb from choices left join user_choice on id_choice = choices.id where id_vote = ? group by id_choice, name, id_vote order by id', [idvote])
+ attachments = query_db('select * from attachments where id_vote=?', [idvote])
+ tmp = query_db('select id_group, count(*) as nb from user_group where id_group = ? group by id_group', [vote['id_group']], one=True)
+ if tmp is None:
+ vote['percent'] = 0
+ else:
+ vote['max_votes'] = tmp['nb']
+ tmp = query_db('select id_vote, count(*) as nb from (select id_user, id_vote from user_choice join choices on id_choice = choices.id group by id_user, id_vote) where id_vote = ? group by id_vote', [idvote], one=True)
+ if tmp is None:
+ vote['percent'] = 0
+ vote['nb_votes'] = 0
+ else:
+ vote['nb_votes'] = tmp['nb']
+ vote['percent'] = int((float(vote['nb_votes']) / float(vote['max_votes'])) * 100)
+ if query_db('select * from user_group where id_group = ? and id_user = ?', [vote['id_group'], get_userid()], one=True) and not vote['is_terminated']:
+ flash(u'Ce vote vous concerne !', 'info')
+ return render_template('vote.html', vote=vote, attachments=attachments, choices=choices, users=users.values(), can_vote=can_vote(idvote, get_userid()))
+ flash(u'Vous n\'avez pas le droit de voir ce vote, désolé.')
+ return redirect(url_for('home'))
+
+@app.route('/vote/deletechoices/<idvote>/<iduser>')
+def vote_deletechoices(idvote, iduser):
+ if int(iduser) != get_userid():
+ abort(401)
+ g.db.execute('delete from user_choice where id_user = ? and id_choice in (select id from choices where id_vote = ?)',
+ [iduser, idvote])
+ g.db.commit()
+ return redirect(url_for('vote', idvote=idvote))
+
+#-------------
+# Votes admin
+
+@app.route('/admin/votes/list')
+def admin_votes():
+ if not session.get('user').get('is_admin'):
+ abort(401)
+ votes = query_db('select *, votes.id as voteid, groups.name as groupname from votes join groups on groups.id=votes.id_group order by id desc')
+ return render_template('admin_votes.html', votes=votes, today=date.today().strftime("%Y-%m-%d"))
+
+@app.route('/admin/votes/add', methods=['GET', 'POST'])
+def admin_vote_add():
+ if not session.get('user').get('is_admin'):
+ abort(401)
+ if request.method == 'POST':
+ if request.form['title']:
+ if query_db('select * from votes where title = ?', [request.form['title']], one=True) is None:
+ date_begin = date.today()
+ date_end = date.today() + timedelta(days=int(request.form['days']))
+ transparent = 0
+ public = 0
+ multiplechoice = 0
+ if 'transparent' in request.form.keys():
+ transparent = 1
+ if 'public' in request.form.keys():
+ public = 1
+ if 'multiplechoice' in request.form.keys():
+ multiplechoice = 1
+ group = query_db('select id from groups where name = ?', [request.form['group']], one=True)
+ if group is None:
+ group[id] = 1
+ g.db.execute('insert into votes (title, description, category, date_begin, date_end, is_transparent, is_public, is_multiplechoice, id_group, id_author) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
+ [request.form['title'], request.form['description'], request.form['category'], date_begin, date_end, transparent, public, multiplechoice, group['id'], session['user']['id']])
+ g.db.commit()
+ vote = query_db('select * from votes where title = ? and date_begin = ? order by id desc',
+ [request.form['title'], date_begin], one=True)
+ if vote is None:
+ flash(u'Une erreur est survenue !', 'error')
+ return redirect(url_for('home'))
+ else:
+ if request.form['pattern'] in PATTERNS.keys():
+ pattern = PATTERNS[request.form['pattern']]
+ for choice in pattern:
+ g.db.execute('insert into choices (name, id_vote) values (?, ?)', [choice, vote['id']])
+ g.db.commit()
+ flash(u"Le vote a été créé", 'info')
+ return redirect(url_for('admin_vote_edit', voteid=vote['id']))
+ else:
+ flash(u'Le titre que vous avez choisi est déjà pris.', 'error')
+ else:
+ flash(u'Vous devez spécifier un titre.', 'error')
+ groups = query_db('select * from groups')
+ return render_template('admin_vote_new.html', groups=groups, patterns=PATTERNS)
+
+@app.route('/admin/votes/edit/<voteid>', methods=['GET', 'POST'])
+def admin_vote_edit(voteid):
+ if not session.get('user').get('is_admin'):
+ abort(401)
+ vote = query_db('select * from votes where id = ?', [voteid], one=True)
+ if vote is None:
+ abort(404)
+ if request.method == 'POST':
+ if request.form['title']:
+ if request.form['days'] > 0:
+ date_end = datetime.strptime(vote['date_begin'], "%Y-%m-%d") + timedelta(days=int(request.form['days']))
+ date_end = date_end.strftime("%Y-%m-%d")
+ transparent = 0
+ public = 0
+ if 'transparent' in request.form.keys():
+ transparent = 1
+ if 'public' in request.form.keys():
+ public = 1
+ isopen = 0
+ isterminated = 0
+ if request.form['status'] == 'Ouvert':
+ choices = query_db('select id_vote, count(*) as nb from choices where id_vote = ? group by id_vote', [voteid], one=True)
+ if choices is not None and choices['nb'] >= 2:
+ isopen = 1
+ else:
+ flash(u'Vous devez proposer au moins deux choix pour ouvrir le vote.', 'error')
+ elif request.form['status'] == u'Terminé':
+ isterminated = 1
+ if vote['is_open']:
+ isopen = 1
+ g.db.execute('update votes set title = ?, description = ?, category = ?, is_transparent = ?, is_public = ?, is_open = ?, is_terminated = ?, date_end = ? where id = ?',
+ [request.form['title'], request.form['description'], request.form['category'], transparent, public, isopen, isterminated, date_end, voteid])
+ g.db.commit()
+ vote = query_db('select * from votes where id = ?', [voteid], one=True)
+ flash(u"Le vote a bien été mis à jour.", "success")
+ else:
+ flash(u'Vous devez spécifier un titre.', 'error')
+ vote['duration'] = (datetime.strptime(vote['date_end'], "%Y-%m-%d")
+ - datetime.strptime(vote['date_begin'], "%Y-%m-%d")).days
+ group = query_db('select name from groups where id = ?', [vote['id_group']], one=True)
+ choices = query_db('select * from choices where id_vote = ?', [voteid])
+ attachments = query_db('select * from attachments where id_vote = ?', [voteid])
+ if date.today().strftime("%Y-%m-%d") > vote['date_end']:
+ 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, choices=choices, attachments=attachments)
+
+@app.route('/admin/votes/addchoice/<voteid>', methods=['POST'])
+def admin_vote_addchoice(voteid):
+ if not session.get('user').get('is_admin'):
+ abort(401)
+ vote = query_db('select * from votes where id = ?', [voteid], one=True)
+ if vote is None:
+ abort(404)
+ g.db.execute('insert into choices (name, id_vote) values (?, ?)', [request.form['title'], voteid])
+ g.db.commit()
+ return redirect(url_for('admin_vote_edit', voteid=voteid))
+
+@app.route('/admin/votes/editchoice/<voteid>/<choiceid>', methods=['POST', 'DELETE'])
+def admin_vote_editchoice(voteid, choiceid):
+ if not session.get('user').get('is_admin'):
+ abort(401)
+ choice = query_db('select * from choices where id = ? and id_vote = ?', [choiceid, voteid], one=True)
+ if choice is None:
+ abort(404)
+ if request.method == 'POST':
+ g.db.execute('update choices set name=? where id = ? and id_vote = ?', [request.form['title'], choiceid, voteid])
+ g.db.commit()
+ return redirect(url_for('admin_vote_edit', voteid=voteid))
+
+@app.route('/admin/votes/deletechoice/<voteid>/<choiceid>')
+def admin_vote_deletechoice(voteid, choiceid):
+ if not session.get('user').get('is_admin'):
+ abort(401)
+ choice = query_db('select * from choices where id = ? and id_vote = ?', [choiceid, voteid], one=True)
+ if choice is None:
+ abort(404)
+ g.db.execute('delete from choices where id = ? and id_vote = ?', [choiceid, voteid])
+ g.db.commit()
+ choices = query_db('select id_vote, count(*) as nb from choices where id_vote = ? group by id_vote', [voteid], one=True)
+ if choices is None or choices['nb'] < 2:
+ g.db.execute('update votes set is_open=0 where id = ?', [voteid])
+ g.db.commit()
+ flash(u'Attention ! Il y a moins de deux choix. Le vote a été fermé.', 'error')
+ return redirect(url_for('admin_vote_edit', voteid=voteid))
+
+@app.route('/admin/votes/addattachment/<voteid>', methods=['POST'])
+def admin_vote_addattachment(voteid):
+ if not session.get('user').get('is_admin'):
+ abort(401)
+ vote = query_db('select * from votes where id = ?', [voteid], one=True)
+ if vote is None:
+ abort(404)
+ g.db.execute('insert into attachments (url, id_vote) values (?, ?)', [request.form['url'], voteid])
+ g.db.commit()
+ return redirect(url_for('admin_vote_edit', voteid=voteid))
+
+@app.route('/admin/votes/deleteattachment/<voteid>/<attachmentid>')
+def admin_vote_deleteattachment(voteid, attachmentid):
+ if not session.get('user').get('is_admin'):
+ abort(401)
+ attachment = query_db('select * from attachments where id = ? and id_vote = ?', [attachmentid, voteid], one=True)
+ if attachment is None:
+ abort(404)
+ g.db.execute('delete from attachments where id = ? and id_vote = ?', [attachmentid, voteid])
+ g.db.commit()
+ return redirect(url_for('admin_vote_edit', voteid=voteid))
+
+#------
+# Main