1 # -*- coding: utf-8; -*-
3 Copyright (C) 2007 Lincoln de Sousa <lincoln@archlinux-br.org>
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.
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.
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.
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
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 *
38 from datetime import datetime
41 FROM_EMAIL = 'Emsl 2007 <noreply@minaslivre.org>'
43 def build_response(request, template, extra={}):
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.
50 @param template: Contains the name of a template found in django
52 @type template: C{str}
54 @param extra: Extra variables to be passed to the context being built.
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}
65 return render_to_response(template, Context(c),
66 context_instance=RequestContext(request))
71 return build_response(request, 'index.html')
74 @transaction.commit_manually
76 def cadastro_palestrante(request):
77 form = CadastroPalestrante(request.POST or None)
80 if request.POST and form.is_valid():
81 cd = form.cleaned_data
84 group = Group.objects.get_or_create(name='palestrantes')[0]
86 user = User(username=cd['nome_usuario'], email=cd['email'])
87 user.set_password(cd['senha'])
88 user.is_active = False
90 user.groups.add(group)
95 p.nome = cd['nome_completo']
97 p.telefone = cd['telefone']
98 p.celular = cd['celular']
99 p.instituicao = cd['instituicao']
101 p.numero = cd['numero']
102 p.bairro = cd['bairro']
103 p.cidade = cd['cidade']
105 p.minicurriculo = cd['minicurriculo']
106 p.curriculo = cd['curriculo']
109 for i in cd.get('area_interesse', []):
110 p.area_interesse.add(i)
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),
117 t = loader.get_template('email-palestrante.html')
118 ec = Context(dict(fulano=['nome_usuario'], link=link))
120 # to be shown in template...
121 c.update({'email': email})
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])
129 ['Desculpe mas não pude enviar o email de confirmação']
130 transaction.rollback()
136 return build_response(request, 'cadastro.html', c)
140 def inscricao(request):
141 return build_response(request, 'inscricao.html')
145 @transaction.commit_manually
146 def inscricao_individual(request):
147 form = Inscricao(request.POST or None)
149 if request.POST and form.is_valid():
150 cd = form.cleaned_data
151 group = Group.objects.get_or_create(name='participantes')[0]
153 user = User(username=cd['nome_usuario'], email=cd['email'])
154 user.set_password(cd['senha'])
155 user.is_active = False
157 user.groups.add(group)
160 p.nome = cd['nome_completo']
162 p.email = cd['email']
164 p.numero = cd['numero']
165 p.bairro = cd['bairro']
166 p.cidade = cd['cidade']
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']
176 u = authenticate(username=cd['nome_usuario'], password=cd['senha'])
181 c = {'form': form, 'ok': ok}
182 return build_response(request, 'inscricao_individual.html', c)
186 @transaction.commit_manually
187 def inscricao_caravana(request):
188 form = InscricaoCaravana(request.POST or None)
190 if request.POST and form.is_valid():
191 cd = form.cleaned_data
192 group = Group.objects.get_or_create(name='participantes')[0]
194 user = User(username=cd['nome_usuario'], email=cd['email'])
195 user.set_password(cd['senha'])
196 user.is_active = False
198 user.groups.add(group)
202 p.nome = cd['nome_completo']
204 p.email = cd['email']
206 p.numero = cd['numero']
207 p.bairro = cd['bairro']
208 p.cidade = cd['cidade']
212 p.telefone = cd['telefone']
213 p.home_page = cd['home_page']
214 p.comercial = False # yeah, always false!
220 c.participantes = cd['lista_nomes']
224 u = authenticate(username=cd['nome_usuario'], password=cd['senha'])
228 c = {'form': form, 'ok': ok}
229 return build_response(request, 'inscricao_caravana.html', c)
233 def inscricao_boleto(request):
234 # dynamic values of the form
236 today = datetime.date(now)
237 first_date = datetime.date(datetime(2007, 10, 12))
240 p = request.user.participante_set.get()
241 ca = p.caravana_set.all() and p.caravana_set.get()
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()]
250 while new_ref in refs or new_ref <= settings.MIN_REF_TRAN:
253 # este dado precisa ser persistente para que possa ser comparado logo acima
259 initial['refTran'] = '1458197%s' % str(new_ref).zfill(10)
260 if today < first_date:
261 initial['dtVenc'] = '12102007'
263 initial['valor'] = '3500'
265 initial['valor'] = '8000'
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})
273 initial['valor'] = '5000'
274 initial['dtVenc'] = '17102007'
276 initial['nome'] = p.nome
277 initial['endereco'] = '%s, %s - %s' % (p.rua, p.numero, p.bairro)
278 initial['cidade'] = p.cidade
280 initial['cep'] = p.cep
282 form = Boleto(request.POST or None, initial=initial)
283 c.update({'form': form})
285 return build_response(request, 'inscricao_boleto.html', c)
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)
294 if request.POST and form.is_valid():
295 cd = form.cleaned_data
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!
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)
313 c = {'form': form, 'ok': ok}
314 return build_response(request, 'inscrever_palestra.html', c)
318 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
319 def meus_trabalhos(request):
321 p = Palestrante.objects.get(usuario=request.user)
322 except Palestrante.DoesNotExist:
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)
331 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
332 def editar_trabalho(request,codigo):
334 p = Palestrante.objects.get(usuario=request.user)
335 except Palestrante.DoesNotExist:
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)
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)
352 c = {'formulario':form}
353 return build_response(request, 'editar_trabalho.html', c)
356 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
357 def editar_trabalho(request, codigo):
359 p = Palestrante.objects.get(usuario=request.user)
360 except Palestrante.DoesNotExist:
362 c = {'palestrante': 0}
363 return build_response(request, 'meus_trabalhos.html', c)
365 trabalho = get_object_or_404(Trabalho, id=codigo, palestrante=p)
366 Formulario = form_for_instance(trabalho)
368 form = Formulario(request.POST or None)
369 if request.POST and form.is_valid():
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)
376 c = {'formulario': form}
377 return build_response(request, 'editar_trabalho.html', c)
380 def meus_dados(request):
382 entity = request.user.palestrante_set.get()
383 except Palestrante.DoesNotExist:
384 entity = request.user.participante_set.get()
386 FormKlass = form_for_instance(entity)
388 # ugly hammer to hide some fields...
389 del FormKlass.base_fields['usuario']
392 form = FormKlass(request.POST or None)
393 if request.POST and form.is_valid():
397 c = {'form': form, 'ok': ok, 'title': entity.__class__.__name__}
398 return build_response(request, 'editar_usuario.html', c)
402 def dados_palestrante(request, codigo):
405 d = {'dados_usuario': Palestrante.objects.get(id=codigo)}
406 except ObjectDoesNotExist:
408 return build_response(request, 'dados_palestrante.html', d)
412 def dados_palestra(request, codigo):
414 d = {'dados_palestra': Trabalho.objects.get(id=codigo)}
415 except ObjectDoesNotExist:
417 return build_response(request, 'dados_palestra.html',d)
421 def programacao(request):
423 d = {'aprovadas': Trabalho.objects.filter(aprovado=True).order_by('dia')}
424 except ObjectDoesNotExist:
426 return build_response(request, 'programacao.html',d)
430 def chamada_trabalhos(request):
431 return build_response(request, 'chamada_trabalhos.html')
434 def avaliacao(request):
435 return build_response(request, 'avaliacao.html')