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