Terminando o cadastro de inscrições de caravanas
[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     if request.POST and form.is_valid():
74         cd = form.cleaned_data
75         badattr = form.errors
76         wrong = False
77
78         if not cd['telefone'] and not cd['celular']:
79             badattr['telefone_comercial'] = \
80                     ['Algum número de telefone precisa ser informado']
81             wrong = True
82
83         # don't save duplicated users...
84         try:
85             User.objects.get(username=cd['nome_usuario'])
86             badattr['nome_usuario'] = ['Este nome de usuário já existe!']
87             wrong = True
88             transaction.rollback()
89         except User.DoesNotExist:
90             pass
91
92         if cd['senha'] != cd['senha_2']:
93             badattr['senha_2'] = ['A senha não confere']
94             wrong = True
95             transaction.rollback()
96
97         if not wrong:
98             group = Group.objects.get_or_create(name='palestrantes')[0]
99
100             user = User(username=cd['nome_usuario'], email=cd['email'])
101             user.set_password(cd['senha'])
102             user.is_active = False
103             user.save()
104             user.groups.add(group)
105
106             p = Palestrante()
107             p.usuario = user
108
109             p.nome = cd['nome_completo']
110             p.email = cd['email']
111             p.telefone = cd['telefone']
112             p.celular = cd['celular']
113             p.instituicao = cd['instituicao']
114             p.rua = cd['rua']
115             p.numero = cd['numero']
116             p.bairro = cd['bairro']
117             p.cidade = cd['cidade']
118             p.uf = cd['uf']
119             p.minicurriculo = cd['minicurriculo']
120             p.curriculo = cd['curriculo']
121             p.save()
122
123             for i in cd.get('area_interesse', []):
124                 p.area_interesse.add(i)
125
126             pid = p.id
127             md5_email = sha.new(cd['email']).hexdigest()
128             email = '%s <%s>' % (cd['nome_completo'], cd['email'])
129             link = '%s/verificar?c=%s&c1=%s' % (get_host(request),
130                     pid, md5_email)
131             t = loader.get_template('email-palestrante.html')
132             c = Context(dict(fulano=['nome_usuario'], link=link))
133             try:
134                 m = EmailMessage('Encontro Mineiro de Software Livre',
135                     t.render(c), FROM_EMAIL, [email])
136                 m.send()
137             except Exception:
138                 badattr['email'] = \
139                     ['Desculpe mas não pude enviar o email de confirmação']
140                 transaction.rollback()
141             else:
142                 ok = True
143                 transaction.commit()
144
145     c = {'form': form, 'ok': ok}
146     return build_response(request, 'cadastro.html', c)
147
148
149 @enable_login_form
150 def inscricao(request):
151     return build_response(request, 'inscricao.html')
152
153
154 @enable_login_form
155 @transaction.commit_manually
156 def inscricao_individual(request):
157     form = Inscricao(request.POST or None)
158     ok = False
159     if request.POST and form.is_valid():
160         cd = form.cleaned_data
161         badattr = form.errors
162         wrong = False
163
164         # don't save duplicated users...
165         try:
166             User.objects.get(username=cd['nome_usuario'])
167             badattr['nome_usuario'] = ['Este nome de usuário já existe!']
168             wrong = True
169             transaction.rollback()
170         except User.DoesNotExist:
171             pass
172
173         if not wrong and cd['senha'] != cd['senha_2']:
174             badattr['senha_2'] = ['A senha não confere']
175             wrong = True
176             transaction.rollback()
177
178         if not wrong:
179             group = Group.objects.get_or_create(name='participantes')[0]
180
181             user = User(username=cd['nome_usuario'], email=cd['email'])
182             user.set_password(cd['senha'])
183             user.is_active = False
184             user.save()
185             user.groups.add(group)
186
187             p = Participante()
188             p.nome = cd['nome_completo']
189             p.rg = cd['rg']
190             p.email = cd['email']
191             p.rua = cd['rua']
192             p.numero = cd['numero']
193             p.bairro = cd['bairro']
194             p.cidade = cd['cidade']
195             p.uf = cd['uf']
196             p.telefone = cd['telefone']
197             p.home_page = cd['home_page']
198             p.save()
199
200             ok = True
201             transaction.commit()
202     c = {'form': form, 'ok': ok}
203     return build_response(request, 'inscricao_individual.html', c)
204
205
206 @enable_login_form
207 @transaction.commit_manually
208 def inscricao_caravana(request):
209     form = InscricaoCaravana(request.POST or None)
210     ok = False
211     if request.POST and form.is_valid():
212         cd = form.cleaned_data
213         badattr = form.errors
214         wrong = False
215
216         # don't save duplicated users...
217         try:
218             User.objects.get(username=cd['nome_usuario'])
219             badattr['nome_usuario'] = ['Este nome de usuário já existe!']
220             wrong = True
221             transaction.rollback()
222         except User.DoesNotExist:
223             pass
224
225         if not wrong and cd['senha'] != cd['senha_2']:
226             badattr['senha_2'] = ['A senha não confere']
227             wrong = True
228             transaction.rollback()
229
230         if not wrong:
231             group = Group.objects.get_or_create(name='participantes')[0]
232
233             user = User(username=cd['nome_usuario'], email=cd['email'])
234             user.set_password(cd['senha'])
235             user.is_active = False
236             user.save()
237             user.groups.add(group)
238
239             p = Participante()
240             p.usuario = user
241             p.nome = cd['nome_completo']
242             p.rg = cd['rg']
243             p.email = cd['email']
244             p.rua = cd['rua']
245             p.numero = cd['numero']
246             p.bairro = cd['bairro']
247             p.cidade = cd['cidade']
248             p.uf = cd['uf']
249             p.telefone = cd['telefone']
250             p.home_page = cd['home_page']
251             p.save()
252
253             c = Caravana()
254             c.coordenador = p
255             c.participantes = cd['lista_nomes']
256             c.save()
257
258             ok = True
259             transaction.commit()
260
261     c = {'form': form, 'ok': ok}
262     return build_response(request, 'inscricao_caravana.html', c)
263
264
265 @login_required
266 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
267 def submeter_trabalho(request):
268     form = SubmeterTrabalho(request, request.POST or None)
269     ok = False
270
271     if request.POST and form.is_valid():
272         cd = form.cleaned_data
273         t = Trabalho()
274         t.titulo = cd['titulo']
275         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
276         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
277         t.descricao_curta = cd['descricao_curta']
278         t.descricao_longa = cd['descricao_longa']
279         t.recursos = cd['recursos']
280         t.evento = Evento.objects.get(pk=1) # let the hammer play arround!
281         t.save()
282
283         logged_in = request.user.palestrante_set.get()
284         t.palestrante.add(logged_in)
285         for i in cd.get('outros_palestrantes', []):
286             up = Palestrante.objects.get(pk=int(i))
287             t.palestrante.add(up)
288         ok = True
289
290     c = {'form': form, 'ok': ok}
291     return build_response(request, 'inscrever_palestra.html', c)
292
293
294 @login_required
295 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
296 def meus_trabalhos(request):
297     try:
298         p = Palestrante.objects.get(usuario=request.user)
299     except Palestrante.DoesNotExist:
300         # não palestrante...
301         c = {'palestrante': 0}
302         return build_response(request, 'meus_trabalhos.html', c)
303
304     t = Trabalho.objects.filter(palestrante=p)
305     c = {'trabalhos': t, 'palestrante': 1}
306     return build_response(request, 'meus_trabalhos.html', c)
307
308
309 @login_required
310 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
311 def editar_trabalho(request, codigo):
312     try:
313         p = Palestrante.objects.get(usuario=request.user)
314     except Palestrante.DoesNotExist:
315         # não palestrante...
316         c = {'palestrante': 0}
317         return build_response(request, 'meus_trabalhos.html', c)
318     trabalho = get_object_or_404(Trabalho, id=codigo, palestrante=p)
319     Formulario = form_for_instance(trabalho)
320     if request.method == 'POST':
321         form = Formulario(request.POST)
322         if form.is_valid():
323             form.save()
324             t = Trabalho.objects.filter(palestrante=p)
325             c = {'trabalhos': t, 'palestrante': 1}
326             c['editado_sucesso']=trabalho.titulo
327             return build_response(request, 'meus_trabalhos.html', c)
328     else:
329         form = Formulario()
330     
331     c = {'formulario':form}
332     return build_response(request, 'editar_trabalho.html', c)
333
334
335 @login_required
336 def meus_dados(request):
337     form = EditarPalestrante(request.POST or None)
338     palestrante = request.user.palestrante_set.get()
339     ok = False
340
341     for name, field in form.fields.items():
342         field.initial = getattr(palestrante, name)
343
344     if request.POST and form.is_valid():
345         cd = form.cleaned_data
346         for name, field in form.fields.items():
347             setattr(palestrante, name, cd[name])
348         palestrante.save()
349         ok = True
350
351     c = {'form': form, 'ok': ok}
352     return build_response(request, 'editar_palestrante.html', c)
353
354
355 @enable_login_form
356 def chamada_trabalhos(request):
357     return build_response(request, 'chamada_trabalhos.html')
358
359 @enable_login_form
360 def avaliacao(request):
361     return build_response(request, 'avaliacao.html')