Terminando o cadastro de inscrições de caravanas
[cascardo/eventmanager.git] / views.py
index 8573791..97da703 100644 (file)
--- a/views.py
+++ b/views.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8; -*-
 """
 Copyright (C) 2007 Lincoln de Sousa <lincoln@archlinux-br.org>
 
@@ -16,28 +17,345 @@ 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.newforms import form_for_instance
+from django.core.mail import EmailMessage
+from django.db import transaction
+from django.http import get_host
+
 from eventmanager.decorators import enable_login_form
-from eventmanager.forms import InscreverPalestra, CadastroPalestrante
-from eventmanager.conteudo.models import Noticia
+from eventmanager.forms import *
+from eventmanager.conteudo.models import Noticia, Menu, Secao
+from eventmanager.eventos.models import *
+import sha
 
-@enable_login_form
-def index(request):
+FROM_EMAIL = 'Emsl 2007 <noreply@minaslivre.org>'
+
+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
+    if request.POST and form.is_valid():
+        cd = form.cleaned_data
+        badattr = form.errors
+        wrong = False
+
+        if not cd['telefone'] and not cd['celular']:
+            badattr['telefone_comercial'] = \
+                    ['Algum número de telefone precisa ser informado']
+            wrong = True
+
+        # don't save duplicated users...
+        try:
+            User.objects.get(username=cd['nome_usuario'])
+            badattr['nome_usuario'] = ['Este nome de usuário já existe!']
+            wrong = True
+            transaction.rollback()
+        except User.DoesNotExist:
+            pass
+
+        if cd['senha'] != cd['senha_2']:
+            badattr['senha_2'] = ['A senha não confere']
+            wrong = True
+            transaction.rollback()
+
+        if not wrong:
+            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')
+            c = Context(dict(fulano=['nome_usuario'], link=link))
+            try:
+                m = EmailMessage('Encontro Mineiro de Software Livre',
+                    t.render(c), 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
+                transaction.commit()
+
+    c = {'form': form, 'ok': ok}
+    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
+        badattr = form.errors
+        wrong = False
+
+        # don't save duplicated users...
+        try:
+            User.objects.get(username=cd['nome_usuario'])
+            badattr['nome_usuario'] = ['Este nome de usuário já existe!']
+            wrong = True
+            transaction.rollback()
+        except User.DoesNotExist:
+            pass
+
+        if not wrong and cd['senha'] != cd['senha_2']:
+            badattr['senha_2'] = ['A senha não confere']
+            wrong = True
+            transaction.rollback()
+
+        if not wrong:
+            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.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.telefone = cd['telefone']
+            p.home_page = cd['home_page']
+            p.save()
+
+            ok = True
+            transaction.commit()
+    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
+        badattr = form.errors
+        wrong = False
+
+        # don't save duplicated users...
+        try:
+            User.objects.get(username=cd['nome_usuario'])
+            badattr['nome_usuario'] = ['Este nome de usuário já existe!']
+            wrong = True
+            transaction.rollback()
+        except User.DoesNotExist:
+            pass
+
+        if not wrong and cd['senha'] != cd['senha_2']:
+            badattr['senha_2'] = ['A senha não confere']
+            wrong = True
+            transaction.rollback()
+
+        if not wrong:
+            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.telefone = cd['telefone']
+            p.home_page = cd['home_page']
+            p.save()
+
+            c = Caravana()
+            c.coordenador = p
+            c.participantes = cd['lista_nomes']
+            c.save()
+
+            ok = True
+            transaction.commit()
+
+    c = {'form': form, 'ok': ok}
+    return build_response(request, 'inscricao_caravana.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) # 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
+def meus_dados(request):
+    form = EditarPalestrante(request.POST or None)
+    palestrante = request.user.palestrante_set.get()
+    ok = False
+
+    for name, field in form.fields.items():
+        field.initial = getattr(palestrante, name)
+
+    if request.POST and form.is_valid():
+        cd = form.cleaned_data
+        for name, field in form.fields.items():
+            setattr(palestrante, name, cd[name])
+        palestrante.save()
+        ok = True
+
+    c = {'form': form, 'ok': ok}
+    return build_response(request, 'editar_palestrante.html', c)
+
+
+@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')