(arrumando) envio de email?
[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['email']).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                 badattr['email'] = ['Não pude enviar o email de confirmação']
136                 transaction.rollback()
137             else:
138                 ok = True
139                 transaction.commit()
140
141     c = {'form': form, 'ok': ok}
142     return build_response(request, 'cadastro.html', c)
143
144
145 @enable_login_form
146 def inscricao(request):
147     post = request.POST
148     post2 = 'post2' in post and post or None
149
150     # exibe o formulário de inscrição de estudantes.
151     if 'estudante' in post:
152         form = InscricaoEstudante(post2)
153
154     # inscrição normal (sem ser estudante)
155     elif not 'estudante' in post or 'empresa' in post:
156         form = InscricaoNormal(post2)
157
158     # primeiro passo...
159     else:
160         form = Inscricao(post or None)
161
162     return build_response(request, 'inscricao.html', {'form': form})
163
164
165 @login_required
166 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
167 def submeter_trabalho(request):
168     form = SubmeterTrabalho(request, request.POST or None)
169     ok = False
170
171     if request.POST and form.is_valid():
172         cd = form.cleaned_data
173         t = Trabalho()
174         t.titulo = cd['titulo']
175         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
176         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
177         t.descricao_curta = cd['descricao_curta']
178         t.descricao_longa = cd['descricao_longa']
179         t.recursos = cd['recursos']
180         t.evento = Evento.objects.get(pk=1) # let the hammer play arround!
181         t.save()
182
183         logged_in = request.user.palestrante_set.get()
184         t.palestrante.add(logged_in)
185         for i in cd.get('outros_palestrantes', []):
186             up = Palestrante.objects.get(pk=int(i))
187             t.palestrante.add(up)
188         ok = True
189
190     c = {'form': form, 'ok': ok}
191     return build_response(request, 'inscrever_palestra.html', c)
192
193
194 @login_required
195 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
196 def meus_trabalhos(request):
197     try:
198         p = Palestrante.objects.get(usuario=request.user)
199     except Palestrante.DoesNotExist:
200         # não palestrante...
201         c = {'palestrante': 0}
202         return build_response(request, 'meus_trabalhos.html', c)
203
204     t = Trabalho.objects.filter(palestrante=p)
205     c = {'trabalhos': t, 'palestrante': 1}
206     return build_response(request, 'meus_trabalhos.html', c)
207
208
209 @login_required
210 def meus_dados(request):
211     form = EditarPalestrante(request.POST or None)
212     palestrante = request.user.palestrante_set.get()
213     ok = False
214
215     for name, field in form.fields.items():
216         field.initial = getattr(palestrante, name)
217
218     if request.POST and form.is_valid():
219         cd = form.cleaned_data
220         for name, field in form.fields.items():
221             setattr(palestrante, name, cd[name])
222         palestrante.save()
223         ok = True
224
225     c = {'form': form, 'ok': ok}
226     return build_response(request, 'editar_palestrante.html', c)
227
228
229 @enable_login_form
230 def chamada_trabalhos(request):
231     return build_response(request, 'chamada_trabalhos.html')
232
233 @enable_login_form
234 def avaliacao(request):
235     return build_response(request, 'avaliacao.html')