melhorias no formulário de inscrição e fazendo também a confirmação via email na...
[cascardo/eventmanager.git] / views.py
1 # -*- coding: utf-8; -*-
2 """
3 Copyright (C) 2007 Lincoln de Sousa <lincoln@archlinux-br.org>
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public
16 License along with this program; if not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 """
20 from django.shortcuts import render_to_response
21 from django.template import RequestContext, Context, loader
22 from django.contrib.auth.decorators import login_required, user_passes_test
23 from django.contrib.auth.models import Group, User
24 from django.core.mail import EmailMessage
25 from django.db import transaction
26 from django.http import get_host
27
28 from eventmanager.decorators import enable_login_form
29 from eventmanager.forms import *
30 from eventmanager.conteudo.models import Noticia, Menu, Secao
31 from eventmanager.eventos.models import *
32 import sha
33
34 FROM_EMAIL = 'Emsl 2007 <noreply@minaslivre.org>'
35
36 def build_response(request, template, extra={}):
37     """
38     Shortcut to build a response based on a C{template} and build a standard
39     context to this template. This context contains news itens, a list of menus
40     and a list of sections to be shown on index. But don't worry, this context
41     is extensible through the C{extra} parameter.
42
43     @param template: Contains the name of a template found in django
44      C{TEMPLATE_DIRS}
45     @type template: C{str}
46
47     @param extra: Extra variables to be passed to the context being built.
48     @type extra: C{dict}
49     """
50     news = Noticia.objects.order_by('-data_criacao')
51     menus = Menu.objects.all()
52     index_sections = Secao.objects.filter(index=True)
53     c = {'news': news, 'menu': menus,
54         'index_sections': index_sections}
55     c.update(extra)
56     return render_to_response(template, Context(c),
57             context_instance=RequestContext(request))
58
59
60 @enable_login_form
61 def index(request):
62     return build_response(request, 'index.html')
63
64
65 @transaction.commit_manually
66 @enable_login_form
67 def cadastro_palestrante(request):
68     form = CadastroPalestrante(request.POST or None)
69     ok = False
70     if request.POST and form.is_valid():
71         cd = form.cleaned_data
72         badattr = form.errors
73         wrong = False
74
75         if not cd['telefone'] and not cd['celular']:
76             badattr['telefone_comercial'] = ['Algum número de telefone '
77                                              'precisa ser informado']
78             wrong = True
79
80         # don't save duplicated users...
81         try:
82             User.objects.get(username=cd['nome_usuario'])
83             badattr['nome_usuario'] = ['Este nome de usuário já existe!']
84             wrong = True
85             transaction.rollback()
86         except User.DoesNotExist:
87             pass
88
89         if cd['senha'] != cd['senha_2']:
90             badattr['senha_2'] = ['A senha não confere']
91             wrong = True
92             transaction.rollback()
93
94         if not wrong:
95             group = Group.objects.get_or_create(name='palestrantes')[0]
96
97             user = User(username=cd['nome_usuario'], email=cd['email'])
98             user.set_password(cd['senha'])
99             user.is_active = False
100             user.save()
101             user.groups.add(group)
102
103             p = Palestrante()
104             p.usuario = user
105
106             p.nome = cd['nome_completo']
107             p.email = cd['email']
108             p.telefone = cd['telefone']
109             p.celular = cd['celular']
110             p.instituicao = cd['instituicao']
111             p.rua = cd['rua']
112             p.numero = cd['numero']
113             p.bairro = cd['bairro']
114             p.cidade = cd['cidade']
115             p.uf = cd['uf']
116             p.minicurriculo = cd['minicurriculo']
117             p.curriculo = cd['curriculo']
118             p.save()
119
120             for i in cd.get('area_interesse', []):
121                 p.area_interesse.add(i)
122
123             pid = p.id
124             md5_email = sha.new(cd['emai']).hexdigest()
125             email = '%s <%s>' % (cd['nome_completo'], cd['email'])
126             link = '%s/verificar?c=%s&c1=%s' % (get_host(request),
127                     pid, md5_email)
128             t = loader.get_template('email-palestrante.html')
129             c = Context(dict(fulano=['nome_usuario'], link=link))
130             try:
131                 m = EmailMessage('Encontro Mineiro de Software Livre',
132                     t.render(c), FROM_EMAIL, [email])
133                 m.send()
134             except Exception:
135                 transaction.rollback()
136             else:
137                 ok = True
138                 transaction.commit()
139
140     c = {'form': form, 'ok': ok}
141     return build_response(request, 'cadastro.html', c)
142
143
144 @enable_login_form
145 def inscricao(request):
146     post = request.POST
147     post2 = 'post2' in post and post or None
148
149     # exibe o formulário de inscrição de estudantes.
150     if 'estudante' in post:
151         form = InscricaoEstudante(post2)
152
153     # inscrição normal (sem ser estudante)
154     elif not 'estudante' in post or 'empresa' in post:
155         form = InscricaoNormal(post2)
156
157     # primeiro passo...
158     else:
159         form = Inscricao(post or None)
160
161     return build_response(request, 'inscricao.html', {'form': form})
162
163
164 @login_required
165 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
166 def submeter_trabalho(request):
167     form = SubmeterTrabalho(request, request.POST or None)
168     ok = False
169
170     if request.POST and form.is_valid():
171         cd = form.cleaned_data
172         t = Trabalho()
173         t.titulo = cd['titulo']
174         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
175         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
176         t.descricao_curta = cd['descricao_curta']
177         t.descricao_longa = cd['descricao_longa']
178         t.recursos = cd['recursos']
179         t.evento = Evento.objects.get(pk=1) # let the hammer play arround!
180         t.save()
181
182         logged_in = request.user.palestrante_set.get()
183         t.palestrante.add(logged_in)
184         for i in cd.get('outros_palestrantes', []):
185             up = Palestrante.objects.get(pk=int(i))
186             t.palestrante.add(up)
187         ok = True
188
189     c = {'form': form, 'ok': ok}
190     return build_response(request, 'inscrever_palestra.html', c)
191
192
193 @login_required
194 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
195 def meus_trabalhos(request):
196     try:
197         p = Palestrante.objects.get(usuario=request.user)
198     except Palestrante.DoesNotExist:
199         # não palestrante...
200         c = {'palestrante': 0}
201         return build_response(request, 'meus_trabalhos.html', c)
202
203     t = Trabalho.objects.filter(palestrante=p)
204     c = {'trabalhos': t, 'palestrante': 1}
205     return build_response(request, 'meus_trabalhos.html', c)
206
207
208 @login_required
209 def meus_dados(request):
210     form = EditarPalestrante(request.POST or None)
211     palestrante = request.user.palestrante_set.get()
212     ok = False
213
214     for name, field in form.fields.items():
215         field.initial = getattr(palestrante, name)
216
217     if request.POST and form.is_valid():
218         cd = form.cleaned_data
219         for name, field in form.fields.items():
220             setattr(palestrante, name, cd[name])
221         palestrante.save()
222         ok = True
223
224     c = {'form': form, 'ok': ok}
225     return build_response(request, 'editar_palestrante.html', c)
226
227
228 @enable_login_form
229 def chamada_trabalhos(request):
230     return build_response(request, 'chamada_trabalhos.html')
231
232 @enable_login_form
233 def avaliacao(request):
234     return build_response(request, 'avaliacao.html')