mais code cleanup e gerenciamento da tranzação manualmente na view inscricao_caravana
[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, get_object_or_404
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.newforms import form_for_instance
25 from django.core.mail import EmailMessage
26 from django.db import transaction
27 from django.http import get_host
28
29 from eventmanager.decorators import enable_login_form
30 from eventmanager.forms import *
31 from eventmanager.conteudo.models import Noticia, Menu, Secao
32 from eventmanager.eventos.models import *
33 import sha
34
35 FROM_EMAIL = 'Emsl 2007 <noreply@minaslivre.org>'
36
37 def build_response(request, template, extra={}):
38     """
39     Shortcut to build a response based on a C{template} and build a standard
40     context to this template. This context contains news itens, a list of menus
41     and a list of sections to be shown on index. But don't worry, this context
42     is extensible through the C{extra} parameter.
43
44     @param template: Contains the name of a template found in django
45      C{TEMPLATE_DIRS}
46     @type template: C{str}
47
48     @param extra: Extra variables to be passed to the context being built.
49     @type extra: C{dict}
50     """
51     news = Noticia.objects.order_by('-data_criacao')
52     menus = Menu.objects.all()
53     index_sections = Secao.objects.filter(index=True)
54     login_failed = 'login_failed' in request.GET
55     c = {'news': news, 'menu': menus,
56         'index_sections': index_sections,
57         'login_failed': login_failed}
58     c.update(extra)
59     return render_to_response(template, Context(c),
60             context_instance=RequestContext(request))
61
62
63 @enable_login_form
64 def index(request):
65     return build_response(request, 'index.html')
66
67
68 @transaction.commit_manually
69 @enable_login_form
70 def cadastro_palestrante(request):
71     form = CadastroPalestrante(request.POST or None)
72     ok = False
73     c = {'form': form}
74     if request.POST and form.is_valid():
75         cd = form.cleaned_data
76         badattr = form.errors
77
78         group = Group.objects.get_or_create(name='palestrantes')[0]
79
80         user = User(username=cd['nome_usuario'], email=cd['email'])
81         user.set_password(cd['senha'])
82         user.is_active = False
83         user.save()
84         user.groups.add(group)
85
86         p = Palestrante()
87         p.usuario = user
88
89         p.nome = cd['nome_completo']
90         p.email = cd['email']
91         p.telefone = cd['telefone']
92         p.celular = cd['celular']
93         p.instituicao = cd['instituicao']
94         p.rua = cd['rua']
95         p.numero = cd['numero']
96         p.bairro = cd['bairro']
97         p.cidade = cd['cidade']
98         p.uf = cd['uf']
99         p.minicurriculo = cd['minicurriculo']
100         p.curriculo = cd['curriculo']
101         p.save()
102
103         for i in cd.get('area_interesse', []):
104             p.area_interesse.add(i)
105
106         pid = p.id
107         md5_email = sha.new(cd['email']).hexdigest()
108         email = '%s <%s>' % (cd['nome_completo'], cd['email'])
109         link = '%s/verificar?c=%s&c1=%s' % (get_host(request),
110                 pid, md5_email)
111         t = loader.get_template('email-palestrante.html')
112         ec = Context(dict(fulano=['nome_usuario'], link=link))
113
114         # to be shown in template...
115         c.update({'email': email})
116         try:
117             # XXX: maybe is not a good so prety put things hardcoded =(
118             m = EmailMessage('Encontro Mineiro de Software Livre',
119                 t.render(ec), FROM_EMAIL, [email])
120             m.send()
121         except Exception:
122             badattr['email'] = \
123                 ['Desculpe mas não pude enviar o email de confirmação']
124             transaction.rollback()
125         else:
126             ok = True
127             c.update({'ok': ok})
128             transaction.commit()
129
130     return build_response(request, 'cadastro.html', c)
131
132
133 @enable_login_form
134 def inscricao(request):
135     return build_response(request, 'inscricao.html')
136
137
138 @enable_login_form
139 @transaction.commit_manually
140 def inscricao_individual(request):
141     form = Inscricao(request.POST or None)
142     ok = False
143     if request.POST and form.is_valid():
144         cd = form.cleaned_data
145
146         group = Group.objects.get_or_create(name='participantes')[0]
147
148         user = User(username=cd['nome_usuario'], email=cd['email'])
149         user.set_password(cd['senha'])
150         user.is_active = False
151         user.save()
152         user.groups.add(group)
153
154         p = Participante()
155         p.usuario = user
156         p.nome = cd['nome_completo']
157         p.rg = cd['rg']
158         p.email = cd['email']
159         p.rua = cd['rua']
160         p.numero = cd['numero']
161         p.bairro = cd['bairro']
162         p.cidade = cd['cidade']
163         p.uf = cd['uf']
164         p.telefone = cd['telefone']
165         p.home_page = cd['home_page']
166         p.save()
167
168         ok = True
169         transaction.commit()
170
171     c = {'form': form, 'ok': ok}
172     return build_response(request, 'inscricao_individual.html', c)
173
174
175 @enable_login_form
176 @transaction.commit_manually
177 def inscricao_caravana(request):
178     form = InscricaoCaravana(request.POST or None)
179     ok = False
180     if request.POST and form.is_valid():
181         cd = form.cleaned_data
182         group = Group.objects.get_or_create(name='participantes')[0]
183
184         user = User(username=cd['nome_usuario'], email=cd['email'])
185         user.set_password(cd['senha'])
186         user.is_active = False
187         user.save()
188         user.groups.add(group)
189
190         p = Participante()
191         p.usuario = user
192         p.nome = cd['nome_completo']
193         p.rg = cd['rg']
194         p.email = cd['email']
195         p.rua = cd['rua']
196         p.numero = cd['numero']
197         p.bairro = cd['bairro']
198         p.cidade = cd['cidade']
199         p.uf = cd['uf']
200         p.telefone = cd['telefone']
201         p.home_page = cd['home_page']
202         p.save()
203
204         c = Caravana()
205         c.coordenador = p
206         c.participantes = cd['lista_nomes']
207         c.save()
208
209         ok = True
210         transaction.commit()
211
212     c = {'form': form, 'ok': ok}
213     return build_response(request, 'inscricao_caravana.html', c)
214
215
216 @login_required
217 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
218 def submeter_trabalho(request):
219     form = SubmeterTrabalho(request, request.POST or None)
220     ok = False
221
222     if request.POST and form.is_valid():
223         cd = form.cleaned_data
224         t = Trabalho()
225         t.titulo = cd['titulo']
226         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
227         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
228         t.descricao_curta = cd['descricao_curta']
229         t.descricao_longa = cd['descricao_longa']
230         t.recursos = cd['recursos']
231         t.evento = Evento.objects.get(pk=1) # let the hammer play arround!
232         t.save()
233
234         logged_in = request.user.palestrante_set.get()
235         t.palestrante.add(logged_in)
236         for i in cd.get('outros_palestrantes', []):
237             up = Palestrante.objects.get(pk=int(i))
238             t.palestrante.add(up)
239         ok = True
240
241     c = {'form': form, 'ok': ok}
242     return build_response(request, 'inscrever_palestra.html', c)
243
244
245 @login_required
246 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
247 def meus_trabalhos(request):
248     try:
249         p = Palestrante.objects.get(usuario=request.user)
250     except Palestrante.DoesNotExist:
251         # não palestrante...
252         c = {'palestrante': 0}
253         return build_response(request, 'meus_trabalhos.html', c)
254
255     t = Trabalho.objects.filter(palestrante=p)
256     c = {'trabalhos': t, 'palestrante': 1}
257     return build_response(request, 'meus_trabalhos.html', c)
258
259
260 @login_required
261 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
262 def editar_trabalho(request, codigo):
263     try:
264         p = Palestrante.objects.get(usuario=request.user)
265     except Palestrante.DoesNotExist:
266         # não palestrante...
267         c = {'palestrante': 0}
268         return build_response(request, 'meus_trabalhos.html', c)
269
270     trabalho = get_object_or_404(Trabalho, id=codigo, palestrante=p)
271     Formulario = form_for_instance(trabalho)
272
273     form = Formulario(request.POST or None)
274     if request.POST and form.is_valid():
275         form.save()
276         t = Trabalho.objects.filter(palestrante=p)
277         c = {'trabalhos': t, 'palestrante': 1}
278         c['editado_sucesso'] = trabalho.titulo
279         return build_response(request, 'meus_trabalhos.html', c)
280     
281     c = {'formulario': form}
282     return build_response(request, 'editar_trabalho.html', c)
283
284
285 @login_required
286 def meus_dados(request):
287     form = EditarPalestrante(request.POST or None)
288     palestrante = request.user.palestrante_set.get()
289     ok = False
290
291     for name, field in form.fields.items():
292         field.initial = getattr(palestrante, name)
293
294     if request.POST and form.is_valid():
295         cd = form.cleaned_data
296         for name, field in form.fields.items():
297             setattr(palestrante, name, cd[name])
298         palestrante.save()
299         ok = True
300
301     c = {'form': form, 'ok': ok}
302     return build_response(request, 'editar_palestrante.html', c)
303
304
305 @enable_login_form
306 def chamada_trabalhos(request):
307     return build_response(request, 'chamada_trabalhos.html')
308
309 @enable_login_form
310 def avaliacao(request):
311     return build_response(request, 'avaliacao.html')