X-Git-Url: http://git.cascardo.info/?p=cascardo%2Feventmanager.git;a=blobdiff_plain;f=views.py;h=6b370ff2d2d914535bc30dccfaa39a804919da24;hp=8573791c3da5f674b59eec2d0e80638184ce37e0;hb=HEAD;hpb=ae2d1712268a6d77f235330e33bc5fbdc0201fae diff --git a/views.py b/views.py index 8573791..6b370ff 100644 --- a/views.py +++ b/views.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8; -*- """ Copyright (C) 2007 Lincoln de Sousa @@ -16,28 +17,426 @@ License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ -from django.shortcuts import render_to_response -from django.template import RequestContext, Context +from django.shortcuts import render_to_response, get_object_or_404 +from django.template import RequestContext, Context, loader +from django.contrib.auth.decorators import login_required, user_passes_test +from django.contrib.auth.models import Group, User +from django.contrib.auth import authenticate, login +from django.contrib.admin.views.decorators import staff_member_required +from django.newforms import form_for_instance +from django.core.exceptions import ObjectDoesNotExist +from django.core.mail import EmailMessage +from django.db import transaction +from django.http import get_host +from django.conf import settings + from eventmanager.decorators import enable_login_form -from eventmanager.forms import InscreverPalestra, CadastroPalestrante -from eventmanager.conteudo.models import Noticia +from eventmanager.conteudo.models import Noticia, Menu, Secao +from eventmanager.eventos.models import * +from eventmanager.forms import * +from eventmanager.controllers import * -@enable_login_form -def index(request): +from datetime import datetime +import sha + +FROM_EMAIL = 'Emsl 2007 ' + +def build_response(request, template, extra={}): + """ + Shortcut to build a response based on a C{template} and build a standard + context to this template. This context contains news itens, a list of menus + and a list of sections to be shown on index. But don't worry, this context + is extensible through the C{extra} parameter. + + @param template: Contains the name of a template found in django + C{TEMPLATE_DIRS} + @type template: C{str} + + @param extra: Extra variables to be passed to the context being built. + @type extra: C{dict} + """ news = Noticia.objects.order_by('-data_criacao') - c = Context({'news': news}) - return render_to_response('index.html', c, + menus = Menu.objects.all() + index_sections = Secao.objects.filter(index=True) + login_failed = 'login_failed' in request.GET + c = {'news': news, 'menu': menus, + 'index_sections': index_sections, + 'login_failed': login_failed} + c.update(extra) + return render_to_response(template, Context(c), context_instance=RequestContext(request)) + @enable_login_form -def cadastro(request): - form = CadastroPalestrante() - c = Context({'form': form}) - return render_to_response('cadastro.html', c, - context_instance=RequestContext(request)) +def index(request): + return build_response(request, 'index.html') -def inscrever_palestra(request): - form = InscreverPalestra() - c = Context({'form': form}) - return render_to_response('inscrever_palestra.html', c, - context_instance=RequestContext(request)) + +@transaction.commit_manually +@enable_login_form +def cadastro_palestrante(request): + form = CadastroPalestrante(request.POST or None) + ok = False + c = {'form': form} + if request.POST and form.is_valid(): + cd = form.cleaned_data + badattr = form.errors + + group = Group.objects.get_or_create(name='palestrantes')[0] + + user = User(username=cd['nome_usuario'], email=cd['email']) + user.set_password(cd['senha']) + user.is_active = False + user.save() + user.groups.add(group) + + p = Palestrante() + p.usuario = user + + p.nome = cd['nome_completo'] + p.email = cd['email'] + p.telefone = cd['telefone'] + p.celular = cd['celular'] + p.instituicao = cd['instituicao'] + p.rua = cd['rua'] + p.numero = cd['numero'] + p.bairro = cd['bairro'] + p.cidade = cd['cidade'] + p.uf = cd['uf'] + p.minicurriculo = cd['minicurriculo'] + p.curriculo = cd['curriculo'] + p.save() + + for i in cd.get('area_interesse', []): + p.area_interesse.add(i) + + pid = p.id + md5_email = sha.new(cd['email']).hexdigest() + email = '%s <%s>' % (cd['nome_completo'], cd['email']) + link = '%s/verificar?c=%s&c1=%s' % (get_host(request), + pid, md5_email) + t = loader.get_template('email-palestrante.html') + ec = Context(dict(fulano=['nome_usuario'], link=link)) + + # to be shown in template... + c.update({'email': email}) + try: + # XXX: maybe is not a good so prety put things hardcoded =( + m = EmailMessage('Encontro Mineiro de Software Livre', + t.render(ec), FROM_EMAIL, [email]) + m.send() + except Exception: + badattr['email'] = \ + ['Desculpe mas não pude enviar o email de confirmação'] + transaction.rollback() + else: + ok = True + c.update({'ok': ok}) + transaction.commit() + + return build_response(request, 'cadastro.html', c) + + +@enable_login_form +def inscricao(request): + return build_response(request, 'inscricao.html') + + +@enable_login_form +@transaction.commit_manually +def inscricao_individual(request): + form = Inscricao(request.POST or None) + ok = False + if request.POST and form.is_valid(): + cd = form.cleaned_data + group = Group.objects.get_or_create(name='participantes')[0] + + user = User(username=cd['nome_usuario'], email=cd['email']) + user.set_password(cd['senha']) + user.is_active = False + user.save() + user.groups.add(group) + p = Participante() + p.usuario = user + p.nome = cd['nome_completo'] + p.rg = cd['rg'] + p.email = cd['email'] + p.rua = cd['rua'] + p.numero = cd['numero'] + p.bairro = cd['bairro'] + p.cidade = cd['cidade'] + p.uf = cd['uf'] + p.cep = cd['cep'] + p.refbanco = 0 + p.telefone = cd['telefone'] + p.home_page = cd['home_page'] + p.comercial = cd['inscricao_comercial'] + p.cpf_cnpj = cd['cpf_cnpj'] + p.save() + + u = authenticate(username=cd['nome_usuario'], password=cd['senha']) + login(request, u) + transaction.commit() + ok = True + + c = {'form': form, 'ok': ok} + return build_response(request, 'inscricao_individual.html', c) + + +@enable_login_form +@transaction.commit_manually +def inscricao_caravana(request): + form = InscricaoCaravana(request.POST or None) + ok = False + if request.POST and form.is_valid(): + cd = form.cleaned_data + group = Group.objects.get_or_create(name='participantes')[0] + + user = User(username=cd['nome_usuario'], email=cd['email']) + user.set_password(cd['senha']) + user.is_active = False + user.save() + user.groups.add(group) + + p = Participante() + p.usuario = user + p.nome = cd['nome_completo'] + p.rg = cd['rg'] + p.email = cd['email'] + p.rua = cd['rua'] + p.numero = cd['numero'] + p.bairro = cd['bairro'] + p.cidade = cd['cidade'] + p.uf = cd['uf'] + p.cep = cd['cep'] + p.refbanco = 0 + p.telefone = cd['telefone'] + p.home_page = cd['home_page'] + p.comercial = False # yeah, always false! + p.cpf_cnpj = '' + p.save() + + c = Caravana() + c.coordenador = p + c.participantes = cd['lista_nomes'] + c.save() + + ok = True + u = authenticate(username=cd['nome_usuario'], password=cd['senha']) + login(request, u) + transaction.commit() + + c = {'form': form, 'ok': ok} + return build_response(request, 'inscricao_caravana.html', c) + + +@enable_login_form +def inscricao_boleto(request): + # dynamic values of the form + now = datetime.now() + today = datetime.date(now) + first_date = datetime.date(datetime(2007, 10, 16)) + c = {} + + p = request.user.participante_set.get() + ca = p.caravana_set.all() and p.caravana_set.get() + + initial = {} + + if p.refbanco == 0: + # o número refTran deve ser gerado a cada novo boleto e deve ser único, + # mesmo para os testes + refs = [x.refbanco for x in Participante.objects.all()] + new_ref = len(refs) + while new_ref in refs or new_ref <= settings.MIN_REF_TRAN: + new_ref += 1 + + # este dado precisa ser persistente para que possa ser comparado logo acima + p.refbanco = new_ref + p.save() + else: + new_ref = p.refbanco + + initial['refTran'] = '1458197%s' % str(new_ref).zfill(10) + if today <= first_date: + initial['dtVenc'] = '16102007' + if not p.comercial: + initial['valor'] = '3500' + else: + initial['valor'] = '8000' + + # caso seja uma caravana... + if ca and len(ca.parsed_participantes()) >= 10: + # sim, o valor aqui é 25 -- Desconto + initial['valor'] = '%s00' % (len(ca.parsed_participantes()) * 25) + c.update({'caravana': 1}) + else: + initial['valor'] = '5000' + initial['dtVenc'] = '17102007' + + initial['nome'] = p.nome + initial['endereco'] = '%s, %s - %s' % (p.rua, p.numero, p.bairro) + initial['cidade'] = p.cidade + initial['uf'] = p.uf + initial['cep'] = p.cep + + form = Boleto(request.POST or None, initial=initial) + c.update({'form': form}) + c.update(initial) + return build_response(request, 'inscricao_boleto.html', c) + + +@login_required +@user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/') +def submeter_trabalho(request): + form = SubmeterTrabalho(request, request.POST or None) + ok = False + + if request.POST and form.is_valid(): + cd = form.cleaned_data + t = Trabalho() + t.titulo = cd['titulo'] + t.tipo = TipoTrabalho.objects.get(pk=cd['tipo']) + t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0] + t.descricao_curta = cd['descricao_curta'] + t.descricao_longa = cd['descricao_longa'] + t.recursos = cd['recursos'] + t.evento = Evento.objects.get(pk=1) # XXX: let the hammer play arround! + t.save() + + logged_in = request.user.palestrante_set.get() + t.palestrante.add(logged_in) + for i in cd.get('outros_palestrantes', []): + up = Palestrante.objects.get(pk=int(i)) + t.palestrante.add(up) + ok = True + + c = {'form': form, 'ok': ok} + return build_response(request, 'inscrever_palestra.html', c) + + +@login_required +@user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/') +def meus_trabalhos(request): + try: + p = Palestrante.objects.get(usuario=request.user) + except Palestrante.DoesNotExist: + # não palestrante... + c = {'palestrante': 0} + return build_response(request, 'meus_trabalhos.html', c) + t = Trabalho.objects.filter(palestrante=p) + c = {'trabalhos': t, 'palestrante': 1} + return build_response(request, 'meus_trabalhos.html', c) + +@login_required +@user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/') +def editar_trabalho(request,codigo): + try: + p = Palestrante.objects.get(usuario=request.user) + except Palestrante.DoesNotExist: + # não palestrante... + c = {'palestrante': 0} + return build_response(request, 'meus_trabalhos.html', c) + trabalho = get_object_or_404(Trabalho, id=codigo,palestrante=p) + Formulario = form_for_instance(trabalho) + if request.method == 'POST': + form = Formulario(request.POST) + if form.is_valid(): + form.save() + t = Trabalho.objects.filter(palestrante=p) + c = {'trabalhos': t, 'palestrante': 1} + c['editado_sucesso']=trabalho.titulo + return build_response(request, 'meus_trabalhos.html', c) + else: + form = Formulario() + + c = {'formulario':form} + return build_response(request, 'editar_trabalho.html', c) + +@login_required +@user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/') +def editar_trabalho(request, codigo): + try: + p = Palestrante.objects.get(usuario=request.user) + except Palestrante.DoesNotExist: + # não palestrante... + c = {'palestrante': 0} + return build_response(request, 'meus_trabalhos.html', c) + + trabalho = get_object_or_404(Trabalho, id=codigo, palestrante=p) + Formulario = form_for_instance(trabalho) + + form = Formulario(request.POST or None) + if request.POST and form.is_valid(): + form.save() + t = Trabalho.objects.filter(palestrante=p) + c = {'trabalhos': t, 'palestrante': 1} + c['editado_sucesso'] = trabalho.titulo + return build_response(request, 'meus_trabalhos.html', c) + + c = {'formulario': form} + return build_response(request, 'editar_trabalho.html', c) + +@login_required +def meus_dados(request): + try: + entity = request.user.palestrante_set.get() + except Palestrante.DoesNotExist: + entity = request.user.participante_set.get() + + FormKlass = form_for_instance(entity) + + # ugly hammer to hide some fields... + del FormKlass.base_fields['usuario'] + + ok = False + form = FormKlass(request.POST or None) + if request.POST and form.is_valid(): + form.save() + ok = True + + c = {'form': form, 'ok': ok, 'title': entity.__class__.__name__} + return build_response(request, 'editar_usuario.html', c) + + +@enable_login_form +def dados_palestrante(request, codigo): + d = {} + try: + d = {'dados_usuario': Palestrante.objects.get(id=codigo)} + except ObjectDoesNotExist: + d = {} + return build_response(request, 'dados_palestrante.html', d) + + +@enable_login_form +def dados_palestra(request, codigo): + try: + d = {'dados_palestra': Trabalho.objects.get(id=codigo)} + except ObjectDoesNotExist: + d = {} + return build_response(request, 'dados_palestra.html',d) + + +@enable_login_form +def programacao(request): + ap = Trabalho.objects.filter(aprovado=True) + ord = ap.order_by('dia', 'time_start', 'room') + d = {'aprovadas': ord} + return build_response(request, 'programacao.html',d) + +@enable_login_form +@staff_member_required +def grade(request): + ap = Trabalho.objects.filter(aprovado=True) + ord = ap.order_by('dia', 'time_start', 'room') + d = {'aprovadas': ord} + return build_response(request, 'grade.html', d) + +@enable_login_form +def chamada_trabalhos(request): + return build_response(request, 'chamada_trabalhos.html') + +@enable_login_form +def avaliacao(request): + return build_response(request, 'avaliacao.html')