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