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