Merge git://hammerboy.no-ip.org/eventmanager
[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.contrib.auth import authenticate, login
25 from django.newforms import form_for_instance
26 from django.core.mail import EmailMessage
27 from django.db import transaction
28 from django.http import get_host
29 from django.conf import settings
30
31 from eventmanager.decorators import enable_login_form
32 from eventmanager.conteudo.models import Noticia, Menu, Secao
33 from eventmanager.eventos.models import *
34 from eventmanager.forms import *
35
36 from datetime import datetime
37 import sha
38
39 FROM_EMAIL = 'Emsl 2007 <noreply@minaslivre.org>'
40
41 def build_response(request, template, extra={}):
42     """
43     Shortcut to build a response based on a C{template} and build a standard
44     context to this template. This context contains news itens, a list of menus
45     and a list of sections to be shown on index. But don't worry, this context
46     is extensible through the C{extra} parameter.
47
48     @param template: Contains the name of a template found in django
49      C{TEMPLATE_DIRS}
50     @type template: C{str}
51
52     @param extra: Extra variables to be passed to the context being built.
53     @type extra: C{dict}
54     """
55     news = Noticia.objects.order_by('-data_criacao')
56     menus = Menu.objects.all()
57     index_sections = Secao.objects.filter(index=True)
58     login_failed = 'login_failed' in request.GET
59     c = {'news': news, 'menu': menus,
60         'index_sections': index_sections,
61         'login_failed': login_failed}
62     c.update(extra)
63     return render_to_response(template, Context(c),
64             context_instance=RequestContext(request))
65
66
67 @enable_login_form
68 def index(request):
69     return build_response(request, 'index.html')
70
71
72 @transaction.commit_manually
73 @enable_login_form
74 def cadastro_palestrante(request):
75     form = CadastroPalestrante(request.POST or None)
76     ok = False
77     c = {'form': form}
78     if request.POST and form.is_valid():
79         cd = form.cleaned_data
80         badattr = form.errors
81
82         group = Group.objects.get_or_create(name='palestrantes')[0]
83
84         user = User(username=cd['nome_usuario'], email=cd['email'])
85         user.set_password(cd['senha'])
86         user.is_active = False
87         user.save()
88         user.groups.add(group)
89
90         p = Palestrante()
91         p.usuario = user
92
93         p.nome = cd['nome_completo']
94         p.email = cd['email']
95         p.telefone = cd['telefone']
96         p.celular = cd['celular']
97         p.instituicao = cd['instituicao']
98         p.rua = cd['rua']
99         p.numero = cd['numero']
100         p.bairro = cd['bairro']
101         p.cidade = cd['cidade']
102         p.uf = cd['uf']
103         p.minicurriculo = cd['minicurriculo']
104         p.curriculo = cd['curriculo']
105         p.save()
106
107         for i in cd.get('area_interesse', []):
108             p.area_interesse.add(i)
109
110         pid = p.id
111         md5_email = sha.new(cd['email']).hexdigest()
112         email = '%s <%s>' % (cd['nome_completo'], cd['email'])
113         link = '%s/verificar?c=%s&c1=%s' % (get_host(request),
114                 pid, md5_email)
115         t = loader.get_template('email-palestrante.html')
116         ec = Context(dict(fulano=['nome_usuario'], link=link))
117
118         # to be shown in template...
119         c.update({'email': email})
120         try:
121             # XXX: maybe is not a good so prety put things hardcoded =(
122             m = EmailMessage('Encontro Mineiro de Software Livre',
123                 t.render(ec), FROM_EMAIL, [email])
124             m.send()
125         except Exception:
126             badattr['email'] = \
127                 ['Desculpe mas não pude enviar o email de confirmação']
128             transaction.rollback()
129         else:
130             ok = True
131             c.update({'ok': ok})
132             transaction.commit()
133
134     return build_response(request, 'cadastro.html', c)
135
136
137 @enable_login_form
138 def inscricao(request):
139     return build_response(request, 'inscricao.html')
140
141
142 @enable_login_form
143 @transaction.commit_manually
144 def inscricao_individual(request):
145     form = Inscricao(request.POST or None)
146     ok = False
147     if request.POST and form.is_valid():
148         cd = form.cleaned_data
149
150         group = Group.objects.get_or_create(name='participantes')[0]
151
152         user = User(username=cd['nome_usuario'], email=cd['email'])
153         user.set_password(cd['senha'])
154         user.is_active = False
155         user.save()
156         user.groups.add(group)
157         p = Participante()
158         p.usuario = user
159         p.nome = cd['nome_completo']
160         p.rg = cd['rg']
161         p.email = cd['email']
162         p.rua = cd['rua']
163         p.numero = cd['numero']
164         p.bairro = cd['bairro']
165         p.cidade = cd['cidade']
166         p.uf = cd['uf']
167         p.cep = cd['cep']
168         p.refbanco = 0
169         p.telefone = cd['telefone']
170         p.home_page = cd['home_page']
171         p.save()
172
173         u = authenticate(username=cd['nome_usuario'], password=cd['senha'])
174         login(request, u)
175         transaction.commit()
176         ok = True
177
178     c = {'form': form, 'ok': ok}
179     return build_response(request, 'inscricao_individual.html', c)
180
181
182 @enable_login_form
183 @transaction.commit_manually
184 def inscricao_caravana(request):
185     form = InscricaoCaravana(request.POST or None)
186     ok = False
187     if request.POST and form.is_valid():
188         cd = form.cleaned_data
189         group = Group.objects.get_or_create(name='participantes')[0]
190
191         user = User(username=cd['nome_usuario'], email=cd['email'])
192         user.set_password(cd['senha'])
193         user.is_active = False
194         user.save()
195         user.groups.add(group)
196
197         p = Participante()
198         p.usuario = user
199         p.nome = cd['nome_completo']
200         p.rg = cd['rg']
201         p.email = cd['email']
202         p.rua = cd['rua']
203         p.numero = cd['numero']
204         p.bairro = cd['bairro']
205         p.cidade = cd['cidade']
206         p.uf = cd['uf']
207         p.cep = cd['cep']
208         p.refbanco = 0
209         p.telefone = cd['telefone']
210         p.home_page = cd['home_page']
211         p.save()
212
213         c = Caravana()
214         c.coordenador = p
215         c.participantes = cd['lista_nomes']
216         c.save()
217
218         ok = True
219         u = authenticate(username=cd['nome_usuario'], password=cd['senha'])
220         login(request, u)
221         transaction.commit()
222
223     c = {'form': form, 'ok': ok}
224     return build_response(request, 'inscricao_caravana.html', c)
225
226
227 @enable_login_form
228 def inscricao_boleto(request):
229     # dynamic values of the form
230     now = datetime.now()
231     today = datetime.date(now)
232     first_date = datetime.date(datetime(2007, 10, 12))
233     c = {}
234
235     p = request.user.participante_set.get()
236     ca = p.caravana_set.all() and p.caravana_set.get()
237
238     initial = {}
239
240     if p.refbanco == 0:
241         # o número refran deve ser gerado a cada novo boleto e deve ser único,
242         # mesmo para os testes
243         refs = [x.refbanco for x in Participante.objects.all()]
244         new_ref = len(refs)
245         while new_ref in refs or new_ref <= settings.MIN_REF_TRAN:
246             new_ref += 1
247
248         # este dado precisa ser persistente para que possa ser comparado logo acima
249         p.refbanco = new_ref
250         p.save()
251     else:
252         new_ref = p.refbanco
253
254     initial['refTran'] = '1458197%s' % str(new_ref).zfill(10)
255     if today < first_date:
256         initial['valor'] = '3500'
257         initial['dtVenc'] = '12102007'
258
259         # caso seja uma caravana...
260         if ca and len(ca.parsed_participantes()) >= 10:
261             # sim, o valor aqui é 25 -- Desconto
262             initial['valor'] = '%s00' % (len(ca.parsed_participantes()) * 25)
263             c.update({'caravana': 1})
264     else:
265         initial['valor'] = '5000'
266         initial['dtVenc'] = '17102007'
267
268     initial['nome'] = p.nome
269     initial['endereco'] = '%s, %s - %s' % (p.rua, p.numero, p.bairro)
270     initial['cidade'] = p.cidade
271     initial['uf'] = p.uf
272     initial['cep'] = p.cep
273
274     form = Boleto(request.POST or None, initial=initial)
275     c.update({'form': form})
276     c.update(initial)
277     return build_response(request, 'inscricao_boleto.html', c)
278
279
280 @login_required
281 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
282 def submeter_trabalho(request):
283     form = SubmeterTrabalho(request, request.POST or None)
284     ok = False
285
286     if request.POST and form.is_valid():
287         cd = form.cleaned_data
288         t = Trabalho()
289         t.titulo = cd['titulo']
290         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
291         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
292         t.descricao_curta = cd['descricao_curta']
293         t.descricao_longa = cd['descricao_longa']
294         t.recursos = cd['recursos']
295         t.evento = Evento.objects.get(pk=1) # XXX: let the hammer play arround!
296         t.save()
297
298         logged_in = request.user.palestrante_set.get()
299         t.palestrante.add(logged_in)
300         for i in cd.get('outros_palestrantes', []):
301             up = Palestrante.objects.get(pk=int(i))
302             t.palestrante.add(up)
303         ok = True
304
305     c = {'form': form, 'ok': ok}
306     return build_response(request, 'inscrever_palestra.html', c)
307
308
309 @login_required
310 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
311 def meus_trabalhos(request):
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     t = Trabalho.objects.filter(palestrante=p)
319     c = {'trabalhos': t, 'palestrante': 1}
320     return build_response(request, 'meus_trabalhos.html', c)
321
322 @login_required
323 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
324 def editar_trabalho(request,codigo):
325     try:
326         p = Palestrante.objects.get(usuario=request.user)
327     except Palestrante.DoesNotExist:
328         # não palestrante...
329         c = {'palestrante': 0}
330         return build_response(request, 'meus_trabalhos.html', c)
331     trabalho = get_object_or_404(Trabalho, id=codigo,palestrante=p)
332     Formulario = form_for_instance(trabalho)
333     if request.method == 'POST':
334         form = Formulario(request.POST)
335         if form.is_valid():
336             form.save()
337             t = Trabalho.objects.filter(palestrante=p)
338             c = {'trabalhos': t, 'palestrante': 1}
339             c['editado_sucesso']=trabalho.titulo
340             return build_response(request, 'meus_trabalhos.html', c)
341     else:
342         form = Formulario()
343     
344     c = {'formulario':form}
345     return build_response(request, 'editar_trabalho.html', c)
346
347 @login_required
348 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
349 def editar_trabalho(request, codigo):
350     try:
351         p = Palestrante.objects.get(usuario=request.user)
352     except Palestrante.DoesNotExist:
353         # não palestrante...
354         c = {'palestrante': 0}
355         return build_response(request, 'meus_trabalhos.html', c)
356
357     trabalho = get_object_or_404(Trabalho, id=codigo, palestrante=p)
358     Formulario = form_for_instance(trabalho)
359
360     form = Formulario(request.POST or None)
361     if request.POST and form.is_valid():
362         form.save()
363         t = Trabalho.objects.filter(palestrante=p)
364         c = {'trabalhos': t, 'palestrante': 1}
365         c['editado_sucesso'] = trabalho.titulo
366         return build_response(request, 'meus_trabalhos.html', c)
367     
368     c = {'formulario': form}
369     return build_response(request, 'editar_trabalho.html', c)
370
371
372 @login_required
373 def meus_dados(request):
374     form = EditarPalestrante(request.POST or None)
375     palestrante = request.user.palestrante_set.get()
376     ok = False
377
378     for name, field in form.fields.items():
379         field.initial = getattr(palestrante, name)
380
381     if request.POST and form.is_valid():
382         cd = form.cleaned_data
383         for name, field in form.fields.items():
384             setattr(palestrante, name, cd[name])
385         palestrante.save()
386         ok = True
387
388     c = {'form': form, 'ok': ok}
389     return build_response(request, 'editar_palestrante.html', c)
390
391
392 @enable_login_form
393 def chamada_trabalhos(request):
394     return build_response(request, 'chamada_trabalhos.html')
395
396 @enable_login_form
397 def avaliacao(request):
398     return build_response(request, 'avaliacao.html')