adicionando campo cpf_cnpj na inscrição individual
[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         group = Group.objects.get_or_create(name='participantes')[0]
150
151         user = User(username=cd['nome_usuario'], email=cd['email'])
152         user.set_password(cd['senha'])
153         user.is_active = False
154         user.save()
155         user.groups.add(group)
156         p = Participante()
157         p.usuario = user
158         p.nome = cd['nome_completo']
159         p.rg = cd['rg']
160         p.email = cd['email']
161         p.rua = cd['rua']
162         p.numero = cd['numero']
163         p.bairro = cd['bairro']
164         p.cidade = cd['cidade']
165         p.uf = cd['uf']
166         p.cep = cd['cep']
167         p.refbanco = 0
168         p.telefone = cd['telefone']
169         p.home_page = cd['home_page']
170         p.comercial = cd['inscricao_comercial']
171         p.cpf_cnpj = cd['cpf_cnpj']
172         p.save()
173
174         u = authenticate(username=cd['nome_usuario'], password=cd['senha'])
175         login(request, u)
176         transaction.commit()
177         ok = True
178
179     c = {'form': form, 'ok': ok}
180     return build_response(request, 'inscricao_individual.html', c)
181
182
183 @enable_login_form
184 @transaction.commit_manually
185 def inscricao_caravana(request):
186     form = InscricaoCaravana(request.POST or None)
187     ok = False
188     if request.POST and form.is_valid():
189         cd = form.cleaned_data
190         group = Group.objects.get_or_create(name='participantes')[0]
191
192         user = User(username=cd['nome_usuario'], email=cd['email'])
193         user.set_password(cd['senha'])
194         user.is_active = False
195         user.save()
196         user.groups.add(group)
197
198         p = Participante()
199         p.usuario = user
200         p.nome = cd['nome_completo']
201         p.rg = cd['rg']
202         p.email = cd['email']
203         p.rua = cd['rua']
204         p.numero = cd['numero']
205         p.bairro = cd['bairro']
206         p.cidade = cd['cidade']
207         p.uf = cd['uf']
208         p.cep = cd['cep']
209         p.refbanco = 0
210         p.telefone = cd['telefone']
211         p.home_page = cd['home_page']
212         p.comercial = False # yeah, always false!
213         p.cpf_cnpj = ''
214         p.save()
215
216         c = Caravana()
217         c.coordenador = p
218         c.participantes = cd['lista_nomes']
219         c.save()
220
221         ok = True
222         u = authenticate(username=cd['nome_usuario'], password=cd['senha'])
223         login(request, u)
224         transaction.commit()
225
226     c = {'form': form, 'ok': ok}
227     return build_response(request, 'inscricao_caravana.html', c)
228
229
230 @enable_login_form
231 def inscricao_boleto(request):
232     # dynamic values of the form
233     now = datetime.now()
234     today = datetime.date(now)
235     first_date = datetime.date(datetime(2007, 10, 12))
236     c = {}
237
238     p = request.user.participante_set.get()
239     ca = p.caravana_set.all() and p.caravana_set.get()
240
241     initial = {}
242
243     if p.refbanco == 0:
244         # o número refTran deve ser gerado a cada novo boleto e deve ser único,
245         # mesmo para os testes
246         refs = [x.refbanco for x in Participante.objects.all()]
247         new_ref = len(refs)
248         while new_ref in refs or new_ref <= settings.MIN_REF_TRAN:
249             new_ref += 1
250
251         # este dado precisa ser persistente para que possa ser comparado logo acima
252         p.refbanco = new_ref
253         p.save()
254     else:
255         new_ref = p.refbanco
256
257     initial['refTran'] = '1458197%s' % str(new_ref).zfill(10)
258     if today < first_date:
259         initial['dtVenc'] = '12102007'
260         if not p.comercial:
261             initial['valor'] = '3500'
262         else:
263             initial['valor'] = '8000'
264
265         # caso seja uma caravana...
266         if ca and len(ca.parsed_participantes()) >= 10:
267             # sim, o valor aqui é 25 -- Desconto
268             initial['valor'] = '%s00' % (len(ca.parsed_participantes()) * 25)
269             c.update({'caravana': 1})
270     else:
271         initial['valor'] = '5000'
272         initial['dtVenc'] = '17102007'
273
274     initial['nome'] = p.nome
275     initial['endereco'] = '%s, %s - %s' % (p.rua, p.numero, p.bairro)
276     initial['cidade'] = p.cidade
277     initial['uf'] = p.uf
278     initial['cep'] = p.cep
279
280     form = Boleto(request.POST or None, initial=initial)
281     c.update({'form': form})
282     c.update(initial)
283     return build_response(request, 'inscricao_boleto.html', c)
284
285
286 @login_required
287 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
288 def submeter_trabalho(request):
289     form = SubmeterTrabalho(request, request.POST or None)
290     ok = False
291
292     if request.POST and form.is_valid():
293         cd = form.cleaned_data
294         t = Trabalho()
295         t.titulo = cd['titulo']
296         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
297         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
298         t.descricao_curta = cd['descricao_curta']
299         t.descricao_longa = cd['descricao_longa']
300         t.recursos = cd['recursos']
301         t.evento = Evento.objects.get(pk=1) # XXX: let the hammer play arround!
302         t.save()
303
304         logged_in = request.user.palestrante_set.get()
305         t.palestrante.add(logged_in)
306         for i in cd.get('outros_palestrantes', []):
307             up = Palestrante.objects.get(pk=int(i))
308             t.palestrante.add(up)
309         ok = True
310
311     c = {'form': form, 'ok': ok}
312     return build_response(request, 'inscrever_palestra.html', c)
313
314
315 @login_required
316 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
317 def meus_trabalhos(request):
318     try:
319         p = Palestrante.objects.get(usuario=request.user)
320     except Palestrante.DoesNotExist:
321         # não palestrante...
322         c = {'palestrante': 0}
323         return build_response(request, 'meus_trabalhos.html', c)
324
325     t = Trabalho.objects.filter(palestrante=p)
326     c = {'trabalhos': t, 'palestrante': 1}
327     return build_response(request, 'meus_trabalhos.html', c)
328
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
340     trabalho = get_object_or_404(Trabalho, id=codigo, palestrante=p)
341     Formulario = form_for_instance(trabalho)
342
343     form = Formulario(request.POST or None)
344     if request.POST and form.is_valid():
345         form.save()
346         t = Trabalho.objects.filter(palestrante=p)
347         c = {'trabalhos': t, 'palestrante': 1}
348         c['editado_sucesso'] = trabalho.titulo
349         return build_response(request, 'meus_trabalhos.html', c)
350     
351     c = {'formulario': form}
352     return build_response(request, 'editar_trabalho.html', c)
353
354
355 @login_required
356 def meus_dados(request):
357     form = EditarPalestrante(request.POST or None)
358     palestrante = request.user.palestrante_set.get()
359     ok = False
360
361     for name, field in form.fields.items():
362         field.initial = getattr(palestrante, name)
363
364     if request.POST and form.is_valid():
365         cd = form.cleaned_data
366         for name, field in form.fields.items():
367             setattr(palestrante, name, cd[name])
368         palestrante.save()
369         ok = True
370
371     c = {'form': form, 'ok': ok}
372     return build_response(request, 'editar_palestrante.html', c)
373
374
375 @enable_login_form
376 def chamada_trabalhos(request):
377     return build_response(request, 'chamada_trabalhos.html')
378
379 @enable_login_form
380 def avaliacao(request):
381     return build_response(request, 'avaliacao.html')