Пример #1
0
def sortidesMevesList( request ):

    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials
    
    professor = User2Professor( user )     
    
    q_professor_proposa = Q( professor_que_proposa = professor  )
    q_professors_responsables = Q( professors_responsables = professor  )
    
    
    sortides = ( Sortida
                   .objects
                   .filter( q_professor_proposa | q_professors_responsables )
                   .distinct()
                  )

    table = Table2_Sortides( list( sortides ), origen="Meves" ) 
    table.order_by = '-calendari_desde' 
    
    RequestConfig(request, paginate={"klass":DiggPaginator , "per_page": 10}).configure(table)
        
    return render(
                  request, 
                  'lesMevesSortides.html', 
                  {'table': table,
                   }
                 )       
Пример #2
0
def esborrar( request, pk , origen):

    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials
    
    professor = User2Professor( user )     
    
    instance = get_object_or_404( Sortida, pk = pk )
    
    mortalPotEntrar = (  instance.professor_que_proposa == professor  and  not instance.estat in [ 'R', 'G' ] )
    direccio = ( request.user.groups.filter(name__in=[u"direcció", u"sortides"] ).exists() )
    
    potEntrar = mortalPotEntrar or direccio
    if not potEntrar:
        messages.warning(request, u"No pots esborrar aquesta activitat." )
        return HttpResponseRedirect( request.META.get('HTTP_REFERER') )
    
    instance.credentials = credentials
   
    try:
        instance.delete()
    except:
        messages.warning(request, u"Error esborrant la activitat." )
    
    nexturl =  r'/sortides/sortides{origen}'.format( origen=origen )
    return HttpResponseRedirect( nexturl )
Пример #3
0
def elMeuMur( request, pg ):
    
    credentials = tools.getImpersonateUser(request) 
    (user, l4) = credentials
        
    q = user.destinatari_set.order_by('-missatge__data')
    paginator = Paginator(q.all(), 20)
    try:
        dests = paginator.page(pg)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        dests = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), delive#workflow
        dests = paginator.page(paginator.num_pages)

    if not request.session.has_key('impersonacio'):
        request.user.destinatari_set.filter(
                    moment_lectura__isnull = True,
                    pk__in = [ m.pk for m in dests.object_list ]
                ).update( moment_lectura = datetime.now() )
            
    return render_to_response(
                'missatges.html',
                    {'msgs' : dests,
                     'head': 'Missatges' ,
                    },
                    context_instance=RequestContext(request))
Пример #4
0
def alumnesFallen( request, pk , origen ):

    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials
    
    professor = User2Professor( user )     
    
    instance = get_object_or_404( Sortida, pk = pk )
    instance.flag_clean_nomes_toco_alumnes = True
    potEntrar = ( professor in instance.professors_responsables.all() or request.user.groups.filter(name__in=[u"direcció", u"sortides"] ).exists() )
    if not potEntrar:
        raise Http404 
    
    instance.credentials = credentials
   
    formIncidenciaF = modelform_factory(Sortida, fields=( 'alumnes_que_no_vindran',  ) )

    if request.method == "POST":
        form = formIncidenciaF(request.POST, instance = instance)
        
        if form.is_valid(): 
            try:
                form.save()
                nexturl =  r'/sortides/sortides{origen}'.format( origen = origen )
                return HttpResponseRedirect( nexturl )
            except ValidationError, e:
                form._errors.setdefault(NON_FIELD_ERRORS, []).extend(  e.messages )
Пример #5
0
def elMeuMur(request, pg, tipus='all'):

    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    q = user.destinatari_set.filter(missatge__tipus_de_missatge=tipus.upper()).order_by('-missatge__data') \
        if tipus != 'all' else user.destinatari_set.order_by('-missatge__data')

    if not request.session.has_key('impersonacio'):
        request.user.destinatari_set.filter(
            moment_lectura__isnull=True, ).update(
                moment_lectura=datetime.now())

    table = MissatgesTable(q)
    RequestConfig(request,
                  paginate={
                      "paginator_class": DiggPaginator,
                      "per_page": 25
                  }).configure(table)

    missatges = dict()
    for key, value in MISSATGES.items():
        missatges[key] = list(value.keys())[0]

    return render(
        request,
        'missatges.html',
        {
            'table': table,
            'missatges': missatges,
        },
    )
Пример #6
0
def esborra( request, pk = None ):

    (user, l4) = tools.getImpersonateUser(request)   
    
    if user.todo_set.filter( pk = pk).exists():
        ToDo.objects.get(pk = pk).delete()
    return HttpResponseRedirect( '/todo/list/' )
Пример #7
0
def edita( request, pk = None ):

    (user, l4) = tools.getImpersonateUser(request)
        
    todo = ToDo.objects.get(pk = pk) if pk and user.todo_set.filter( pk = pk ).exists() else None
    
    if request.method == 'POST':
        formF = modelform_factory( ToDo, fields = ( 'data', 'tasca' , 'informacio_adicional', 'estat' , 'prioritat', 'enllac' ))
        form = formF(  request.POST  )
        if not form.instance.pk: 
            form.instance.propietari = user
        if form.is_valid(  ):
            form.save()
            return HttpResponseRedirect( '/todo/list/' )

    else:
        form = modelform_factory( ToDo, fields = ( 'data','tasca' , 'informacio_adicional', 'estat' , 'prioritat', 'enllac' ))
        
        if todo: form = form( instance = todo )
        
        form.base_fields['data'].widget = forms.DateTimeInput(attrs={'class':'DateTimeAnyTime'} )
           
        #form = formF(  )
        
    return render(
              request,
              "form.html", 
              {"form": form,
               "head": 'Edita tasca',
               },
              )
Пример #8
0
def sortidesAllList( request ):

    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials
    
    professor = User2Professor( user )     
    
    sortides = list( Sortida
                     .objects
                     .all()
                     .distinct()                     
                )
 
    table = Table2_Sortides( data=sortides, origen="All" ) 
    table.order_by = '-calendari_desde' 
    
    RequestConfig(request, paginate={"klass":DiggPaginator , "per_page": 10}).configure(table)
        
    url = r"{0}{1}".format( settings.URL_DJANGO_AULA, reverse( 'sortides__sortides__ical' ) )    
        
    return render(
                  request, 
                  'table2.html', 
                  {'table': table,
                   'url': url,
                   }
                 )       
Пример #9
0
def canviDadesUsuari( request):
    credentials = tools.getImpersonateUser(request) 
    (user, _) = credentials
        
    if request.method == "POST":
        form=CanviDadesUsuari(
                                request.POST,                                
                                instance= user )
        form.fields['first_name'].label = 'Nom'
        form.fields['last_name'].label = 'Cognoms'
        if form.is_valid():
            form.save()
            return HttpResponseRedirect( '/' )
    else:
        form=CanviDadesUsuari(instance=user)
        form.fields['first_name'].label = 'Nom'
        form.fields['last_name'].label = 'Cognoms'

    head = u'''Dades d'usuari'''
    infoForm = [ (u'Codi Usuari', user.username), ]      
          
    resposta = render(
                request,
                  "form.html", 
                  {"form": form,
                   "head": head,
                   'infoForm': infoForm,
                   }
                )
    
    return resposta
Пример #10
0
def allow_foto(private_file):
    request = private_file.request
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials
    pertany_al_grup_permes = (user.groups.filter(
        name__in=CUSTOM_GRUPS_PODEN_VEURE_FOTOS).exists())
    return (request.user.is_authenticated and pertany_al_grup_permes)
Пример #11
0
def alertaAssistencia(request):
    credentials = getImpersonateUser(request)
    (user, l4) = credentials

    head = u'''Alerta alumnes'''

    if request.method == 'POST':
        form = alertaAssistenciaForm(request.POST)
        if form.is_valid():
            report = alertaAssitenciaReport(
                data_inici=form.cleaned_data['data_inici'],
                data_fi=form.cleaned_data['data_fi'],
                nivell=form.cleaned_data['nivell'],
                tpc=form.cleaned_data['tpc'],
                ordenacio=form.cleaned_data['ordenacio'],
            )

            return render_to_response('report.html', {
                'report': report,
                'head': 'Informació alumnes',
            },
                                      context_instance=RequestContext(request))

    else:
        form = alertaAssistenciaForm()

    return render_to_response('alertaAbsentisme.html', {
        'head': head,
        'form': form
    },
                              context_instance=RequestContext(request))
Пример #12
0
def consultaAulaPerFranja(request):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials


    if request.method == 'POST':
        formDisponibilitatAula = disponibilitatAulaPerFranjaForm(request.POST)

        if formDisponibilitatAula.is_valid():
            franja = formDisponibilitatAula.cleaned_data['franja']
            data = formDisponibilitatAula.cleaned_data['data']
            year = data.year
            month = data.month
            date = data.day
            next_url = r'/aules/detallFranjaReserves/{0}/{1}/{2}/{3}'
            return HttpResponseRedirect(next_url.format(year, month, date, franja.pk))

    else:
        formDisponibilitatAula = disponibilitatAulaPerFranjaForm()

    for f in formDisponibilitatAula.fields:
        formDisponibilitatAula.fields[f].widget.attrs['class'] = 'form-control ' + formDisponibilitatAula.fields[f].widget.attrs.get('class',"") 
        

    return render(
        request,
        'form.html',
        {'form': formDisponibilitatAula,
         'head': u'Consultar disponibilitat aula per franja',
         'titol_formulari': u"Assistent Reserva d'Aula (1/3)",
         },
    )
Пример #13
0
def afegeixGuardia(request, dia=None, mes=None, year=None):

    credentials = getImpersonateUser(request)
    (user, _) = credentials

    head = u'Fer guardia'

    url_next = '/presencia/mostraImpartir/%d/%d/%d/' % (int(year), int(mes),
                                                        int(dia))
    if request.method == 'POST':
        form = afegeixGuardiaForm(request.POST)

        if form.is_valid():

            professor = form.cleaned_data['professor']
            franges = form.cleaned_data['franges']
            dia_impartir = date(int(year), int(mes), int(dia))
            professor_guardia = User2Professor(user)
            Impartir.objects.filter(dia_impartir=dia_impartir,
                                    horari__professor=professor,
                                    horari__hora__in=franges).update(
                                        professor_guardia=professor_guardia)

            return HttpResponseRedirect(url_next)

    else:
        form = afegeixGuardiaForm()
    return render_to_response('form.html', {
        'form': form,
        'head': head
    },
                              context_instance=RequestContext(request))
Пример #14
0
def consultaAulaPerAula(request):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    formset = []
    if request.method == 'POST':
        formDisponibilitatAula = disponibilitatAulaPerAulaForm(request.POST)

        if formDisponibilitatAula.is_valid():
            aula = formDisponibilitatAula.cleaned_data['aula']
            data = formDisponibilitatAula.cleaned_data['data']
            year = data.year
            month = data.month
            date = data.day
            next_url = r'/aules/detallAulaReserves/{0}/{1}/{2}/{3}'
            return HttpResponseRedirect(next_url.format(year, month, date, aula.pk))

    else:
        formDisponibilitatAula = disponibilitatAulaPerAulaForm()

    return render(
        request,
        'form.html',
        {'form': formDisponibilitatAula,
         'head': u'Consultar disponibilitat aula',
         'titol_formulari': u"Assistent Reserva d'Aula (1/3)",
         },
    )
Пример #15
0
def index(request):

    #Obtenir l'usuari actual.
    credentials = getImpersonateUser(request)
    (user, _) = credentials
    professor = User2Professor(user)

    if request.method == 'POST':
        form = EscollirGrupForm(professor, request.POST)
        if form.is_valid():
            grup = form.cleaned_data['grup_list']
            nomesPropies = form.cleaned_data['nomesPropies']
            if nomesPropies: nomesPropies = 'True'
            else: nomesPropies = 'False'
            return detallgrup(request,
                              grup.id,
                              dataReferenciaStr='',
                              nomesPropies=nomesPropies)
    else:
        form = EscollirGrupForm(professor)
    return render(
        request,
        'form.html',
        {
            'form': form,
        },
    )
Пример #16
0
def menu(request):
    #How do I make a variable available to all my templates?
    #http://readthedocs.org/docs/django/1.2.4/faq/usage.html#how-do-i-make-a-variable-available-to-all-my-templates
    
    if request.user.is_anonymous():        
        return HttpResponseRedirect( settings.LOGIN_URL )         
    else:
        #si és un alumne l'envio a mirar el seu informe
        if Group.objects.get(name='alumne') in request.user.groups.all():
            return HttpResponseRedirect( '/open/elMeuInforme/')
        
        #comprova que no té passwd per defecte:
        defaultPasswd, _ = ParametreKronowin.objects.get_or_create( nom_parametre = 'passwd', defaults={'valor_parametre':'1234'}  )
        if check_password( defaultPasswd.valor_parametre, request.user.password ):
            return HttpResponseRedirect( reverse( 'usuari__dades__canvi_passwd' ) )
        
        #si no té les dades informades:
        if not request.user.first_name or not request.user.last_name:
            return HttpResponseRedirect( '/usuaris/canviDadesUsuari/')

        #prenc impersonate user:
        (user, _) = tools.getImpersonateUser(request)    
        
        #si és professor ves a mostra impartir:
        professor = User2Professor( user ) 
        if professor is not None:
            return HttpResponseRedirect( '/presencia/mostraImpartir/' )    

    
    return render_to_response(
            'main_page.html', 
            { },
            context_instance=RequestContext(request))    
Пример #17
0
def sincronitzaSaga(request):

    (user, l4) = tools.getImpersonateUser(request)
    professor = User2Professor(user)

    from aula.apps.extSaga.sincronitzaSaga import sincronitza

    if request.method == 'POST':

        form = sincronitzaSagaForm(request.POST, request.FILES)

        if form.is_valid():
            f = request.FILES['fitxerSaga']
            path = default_storage.save('tmp/saga.csv', ContentFile(f.read()))
            tmp_file = os.path.join(settings.MEDIA_ROOT, path)
            with open(tmp_file, 'r', encoding="latin1") as f1:
                resultat = sincronitza(f1, user)
            default_storage.delete(path)
            return render(
                request,
                'resultat.html',
                {
                    'head': 'Resultat importació SAGA',
                    'msgs': resultat
                },
            )

    else:
        form = sincronitzaSagaForm()

    return render(
        request,
        'sincronitzaSaga.html',
        {'form': form},
    )
Пример #18
0
def sortidesAllList(request):

    credentials = tools.getImpersonateUser(request)
    (user, _) = credentials

    professor = User2Professor(user)

    sortides = list(Sortida.objects.all().distinct())

    table = Table2_Sortides(data=sortides, origen="All")
    table.order_by = '-calendari_desde'

    RequestConfig(request,
                  paginate={
                      "paginator_class": DiggPaginator,
                      "per_page": 10
                  }).configure(table)

    url = r"{0}{1}".format(settings.URL_DJANGO_AULA,
                           reverse('sortides__sortides__ical'))

    return render(request, 'table2.html', {
        'table': table,
        'url': url,
    })
Пример #19
0
def consultaRecursPerRecurs(request):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    formset = []
    if request.method == 'POST':
        formDisponibilitatRecurs = disponibilitatRecursPerRecursForm(
            request.POST)

        if formDisponibilitatRecurs.is_valid():
            recurs = formDisponibilitatRecurs.cleaned_data['recurs']
            data = formDisponibilitatRecurs.cleaned_data['data']
            year = data.year
            month = data.month
            date = data.day
            next_url = r'/recursos/detallRecursReserves/{0}/{1}/{2}/{3}'
            return HttpResponseRedirect(
                next_url.format(year, month, date, recurs.pk))

    else:
        formDisponibilitatRecurs = disponibilitatRecursPerRecursForm()

    return render(
        request,
        'form.html',
        {
            'form': formDisponibilitatRecurs,
            'head': u'Consultar disponibilitat material',
            'titol_formulari': u"Assistent Reserva de Material (1/3)",
        },
    )
Пример #20
0
def sincronitzaSaga(request):

    (user, l4) = tools.getImpersonateUser(request)
    professor = User2Professor(user)

    from aula.apps.extSaga.sincronitzaSaga import sincronitza

    if request.method == "POST":

        form = sincronitzaSagaForm(request.POST, request.FILES)

        if form.is_valid():
            f = request.FILES["fitxerSaga"]
            resultat = sincronitza(f, user)

            return render_to_response(
                "resultat.html",
                {"head": "Resultat importació SAGA", "msgs": resultat},
                context_instance=RequestContext(request),
            )

    else:
        form = sincronitzaSagaForm()

    return render_to_response("sincronitzaSaga.html", {"form": form}, context_instance=RequestContext(request))
Пример #21
0
def alertaAssistencia(request):
    credentials = getImpersonateUser(request) 
    (user, l4) = credentials   
    
    head=u'''Alerta alumnes''' 
    
    if request.method == 'POST':
        form = alertaAssistenciaForm(request.POST)
        if form.is_valid():
            report = alertaAssitenciaReport( 
                            data_inici = form.cleaned_data['data_inici'],
                            data_fi = form.cleaned_data['data_fi'],
                            nivell = form.cleaned_data['nivell'],                                         
                            tpc = form.cleaned_data['tpc']  ,
                            ordenacio = form.cleaned_data['ordenacio']  ,                      
                                             )
            
            return render_to_response(
                        'report.html',
                            {'report': report,
                             'head': 'Informació alumnes' ,
                            },
                            context_instance=RequestContext(request))            
 
    else:
        form = alertaAssistenciaForm()
        
    return render_to_response(
            'alertaAbsentisme.html', 
            {'head': head ,
             'form': form },
            context_instance=RequestContext(request))      
Пример #22
0
def sortidesMevesList(request):

    credentials = tools.getImpersonateUser(request)
    (user, _) = credentials

    professor = User2Professor(user)

    q_professor_proposa = Q(professor_que_proposa=professor)
    q_professors_responsables = Q(professors_responsables=professor)
    q_professors_acompanyants = Q(altres_professors_acompanyants=professor)

    sortides = (Sortida.objects.filter(q_professor_proposa
                                       | q_professors_responsables
                                       | q_professors_acompanyants).distinct())

    table = Table2_Sortides(list(sortides), origen="Meves")
    table.order_by = '-calendari_desde'

    RequestConfig(request, paginate={
        "klass": DiggPaginator,
        "per_page": 10
    }).configure(table)

    return render(request, 'lesMevesSortides.html', {
        'table': table,
    })
Пример #23
0
def sincronitzaEsfera(request):

    (user, l4) = tools.getImpersonateUser(request)
    professor = User2Professor( user )     
    
    from aula.apps.extEsfera.sincronitzaEsfera import sincronitza

    if request.method == 'POST':
        
        form = sincronitzaEsferaForm(request.POST, request.FILES)
        
        if form.is_valid():
            f=request.FILES['fitxerEsfera']
            resultat=sincronitza(f, user)
            
            return render(
                    request,
                    'resultat.html', 
                    {'head': 'Resultat importació Esfer@' ,
                     'msgs': resultat },
                    )
        
    else:
        form = sincronitzaEsferaForm()
        
    return render(
                    request,
                    'sincronitzaEsfera.html',
                    {'form': form },
                )
Пример #24
0
def fusiona(request, pk):
    """ XXX define doc """

    credentials = tools.getImpersonateUser(request)
    resultat = {
        'errors': [],
        'warnings': [],
        'infos': [u'Procés realitzat correctament']
    }
    try:
        fusiona_alumnes_by_pk(int(pk), credentials)
    except Exception as e:
        resultat = {
            'errors': [
                unicode(e),
            ],
            'warnings': [],
            'infos': []
        }

    return render(
        request,
        'resultat.html',
        {
            'head': u'Error a l\'esborrar actuació.',
            'msgs': resultat
        },
    )
Пример #25
0
def sincronitzaSaga(request):

    (user, l4) = tools.getImpersonateUser(request)
    professor = User2Professor(user)

    from aula.apps.extSaga.sincronitzaSaga import sincronitza

    if request.method == 'POST':

        form = sincronitzaSagaForm(request.POST, request.FILES)

        if form.is_valid():
            f = request.FILES['fitxerSaga']
            resultat = sincronitza(f, user)

            return render(
                request,
                'resultat.html',
                {
                    'head': 'Resultat importació SAGA',
                    'msgs': resultat
                },
            )

    else:
        form = sincronitzaSagaForm()

    return render(
        request,
        'sincronitzaSaga.html',
        {'form': form},
    )
Пример #26
0
def menu(request):
    #How do I make a variable available to all my templates?
    #http://readthedocs.org/docs/django/1.2.4/faq/usage.html#how-do-i-make-a-variable-available-to-all-my-templates

    if request.user.is_anonymous:
        return HttpResponseRedirect(settings.LOGIN_URL)
    else:
        #si és un alumne l'envio a mirar el seu informe
        if Group.objects.get(name='alumne') in request.user.groups.all():
            return HttpResponseRedirect('/open/elMeuInforme/')

        #comprova que no té passwd per defecte:
        defaultPasswd, _ = ParametreKronowin.objects.get_or_create(
            nom_parametre='passwd', defaults={'valor_parametre': '1234'})
        if check_password(defaultPasswd.valor_parametre,
                          request.user.password):
            return HttpResponseRedirect(reverse('usuari__dades__canvi_passwd'))

        #si no té les dades informades:
        if not request.user.first_name or not request.user.last_name:
            return HttpResponseRedirect('/usuaris/canviDadesUsuari/')

        #prenc impersonate user:
        (user, _) = tools.getImpersonateUser(request)

        #si és professor ves a mostra impartir:
        professor = User2Professor(user)
        if professor is not None:
            return HttpResponseRedirect('/presencia/mostraImpartir/')

    return render(
        request,
        'main_page.html',
        {},
    )
Пример #27
0
def consultaAulaPerFranja(request):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials


    if request.method == 'POST':
        formDisponibilitatAula = disponibilitatAulaPerFranjaForm(request.POST)

        if formDisponibilitatAula.is_valid():
            franja = formDisponibilitatAula.cleaned_data['franja']
            data = formDisponibilitatAula.cleaned_data['data']
            year = data.year
            month = data.month
            date = data.day
            next_url = r'/aules/detallFranjaReserves/{0}/{1}/{2}/{3}'
            return HttpResponseRedirect(next_url.format(year, month, date, franja.pk))

    else:
        formDisponibilitatAula = disponibilitatAulaPerFranjaForm()

    for f in formDisponibilitatAula.fields:
        formDisponibilitatAula.fields[f].widget.attrs['class'] = 'form-control ' + formDisponibilitatAula.fields[f].widget.attrs.get('class',"") 
        

    return render(
        request,
        'form.html',
        {'form': formDisponibilitatAula,
         'head': u'Consultar disponibilitat aula per franja',
         'titol_formulari': u"Assistent Reserva d'Aula (1/3)",
         },
    )
Пример #28
0
def sincronitzaKronowin(request):
    credentials = tools.getImpersonateUser(request) 
    (user, l4) = credentials   
    
    if request.method == 'POST':
        form = sincronitzaKronowinForm(request.POST, request.FILES)
        if form.is_valid():
            resultat=s.sincronitza(request.FILES['fitxer_kronowin'], request.user)

            #LOGGING
            Accio.objects.create( 
                    tipus = 'SK',
                    usuari = user,
                    l4 = l4,
                    impersonated_from = request.user if request.user != user else None,
                    text = u"""Sincronitzar horaris des d'arxiu Kronowin."""
                )
            
        return render_to_response(
                        'resultat.html', 
                        {'head': u'Resultat sincronització Kronowin' ,
                         'msgs': resultat },
                        context_instance=RequestContext(request))    
    else:
        form = sincronitzaKronowinForm()
    return render_to_response(
                        'sincronitzaKronowin.html', 
                        {'form': form},
                        context_instance=RequestContext(request))
Пример #29
0
def canviDePasswd( request ):     
    
    (user, _) = tools.getImpersonateUser(request)
      
    infoForm = [ ('Usuari',user.username,),]
    if request.method == 'POST':
        form = canviDePasswdForm(  request.POST  )

        if form.is_valid(  ):         
            passwdOLD = form.cleaned_data['p0']               
            passwdNEW = form.cleaned_data['p1']               
          

            userOK = authenticate(username=user.username, password=passwdOLD)

            if userOK is not None:              
                user.set_password( passwdNEW )
                user.save()

                url_next = '/' 
                return HttpResponseRedirect( url_next )        
            else:
                form._errors.setdefault(NON_FIELD_ERRORS, []).append( u'Comprova que la paraula de pas actual proporcionada sigui la correcta.' )

    else:
        form = canviDePasswdForm(   )
        
    return render(
                request,
                'form.html',
                    {'form': form,
                     'infoForm':infoForm,
                     'head': u'Canvi de Contrasenya' 
                     }
                    )
Пример #30
0
def feina( request, pk_imparticio  ):

    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials
    
    professor = User2Professor( user ) 
    
    imparticio = get_object_or_404( Impartir, pk = pk_imparticio )
    
    try:
        feina = Feina.objects.get( impartir =  imparticio)  
    except Feina.DoesNotExist:    
        feina = Feina()
        feina.impartir = imparticio

    head = u"Feina per a {0}".format( imparticio )
    
    frmFact = modelform_factory( Feina, fields = ( 'feina_a_fer', 'comentaris_professor_guardia', )  )    
    
    if request.method == "POST":
        form = frmFact( request.POST, instance = feina )
        if form.is_valid():
            feina = form.save(commit =False )
            feina.professor_darrera_modificacio = professor
            feina.save()
            return HttpResponseRedirect( r'/presencia/passaLlista/{0}'.format( imparticio.pk ) )
    else:
        form = frmFact(  instance = feina )
        
    return render(
                request,
                'form.html', 
                {'form': form, 
                 'head': head},
                )
Пример #31
0
def complementFormulariImpresioTria( request  ):

    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials
    
    head = u"Selecciona dia a imprimir"
    
    if request.method == "POST":
        form = complementFormulariImpresioTriaForm( request.POST )
        if form.is_valid():
            dia = form.cleaned_data['dia']
            professors = form.cleaned_data['professors']
            return reportBaixaCarpeta( request, dia, professors )
    else:
        form = complementFormulariImpresioTriaForm(  )
       
    return render(
                request,
                'form.html', 
                {'form': form, 
                 'head': head},
                )



    
        
Пример #32
0
def esborra(request, pk=None):

    (user, l4) = tools.getImpersonateUser(request)

    if user.todo_set.filter(pk=pk).exists():
        ToDo.objects.get(pk=pk).delete()
    return HttpResponseRedirect('/todo/list/')
Пример #33
0
def sincronitzaKronowin(request):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    if request.method == 'POST':
        form = sincronitzaKronowinForm(request.POST, request.FILES)
        if form.is_valid():
            resultat = s.sincronitza(request.FILES['fitxer_kronowin'],
                                     request.user)

            #LOGGING
            Accio.objects.create(
                tipus='SK',
                usuari=user,
                l4=l4,
                impersonated_from=request.user
                if request.user != user else None,
                text=u"""Sincronitzar horaris des d'arxiu Kronowin.""")

        return render(
            request,
            'resultat.html',
            {
                'head': u'Resultat sincronització Kronowin',
                'msgs': resultat
            },
        )
    else:
        form = sincronitzaKronowinForm()
    return render(
        request,
        'sincronitzaKronowin.html',
        {'form': form},
    )
Пример #34
0
def esborrar(request, pk, origen):

    credentials = tools.getImpersonateUser(request)
    (user, _) = credentials

    professor = User2Professor(user)

    instance = get_object_or_404(Sortida, pk=pk)

    mortalPotEntrar = (instance.professor_que_proposa == professor
                       and not instance.estat in ['R', 'G'])
    direccio = (request.user.groups.filter(
        name__in=[u"direcció", u"sortides"]).exists())

    potEntrar = mortalPotEntrar or direccio
    if not potEntrar:
        messages.warning(request, u"No pots esborrar aquesta activitat.")
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    instance.credentials = credentials

    try:
        instance.delete()
    except:
        messages.warning(request, u"Error esborrant la activitat.")

    nexturl = r'/sortides/sortides{origen}'.format(origen=origen)
    return HttpResponseRedirect(nexturl)
Пример #35
0
def complementFormulariTria(request):

    credentials = tools.getImpersonateUser(request)
    (user, _) = credentials

    head = u"Selecciona professor i dia"

    if request.method == "POST":
        form = complementFormulariTriaForm(request.POST)
        if form.is_valid():
            professor = form.cleaned_data['professor']
            dia = form.cleaned_data['dia']
            return HttpResponseRedirect(
                r'/baixes/complementFormulariOmple/{0}/{1}'.format(
                    professor.pk, dia.strftime('%d/%m/%Y')))
    else:
        form = complementFormulariTriaForm()

    return render(
        request,
        'form.html',
        {
            'form': form,
            'head': head
        },
    )
Пример #36
0
def consultaAulaPerAula(request):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    formset = []
    if request.method == 'POST':
        formDisponibilitatAula = disponibilitatAulaPerAulaForm(request.POST)

        if formDisponibilitatAula.is_valid():
            aula = formDisponibilitatAula.cleaned_data['aula']
            data = formDisponibilitatAula.cleaned_data['data']
            year = data.year
            month = data.month
            date = data.day
            next_url = r'/aules/detallAulaReserves/{0}/{1}/{2}/{3}'
            return HttpResponseRedirect(next_url.format(year, month, date, aula.pk))

    else:
        formDisponibilitatAula = disponibilitatAulaPerAulaForm()

    return render(
        request,
        'form.html',
        {'form': formDisponibilitatAula,
         'head': u'Consultar disponibilitat aula',
         'titol_formulari': u"Assistent Reserva d'Aula (1/3)",
         },
    )
Пример #37
0
def canviDadesUsuari(request):
    credentials = tools.getImpersonateUser(request)
    (user, _) = credentials

    if request.method == "POST":
        form = CanviDadesUsuari(request.POST, instance=user)
        form.fields['first_name'].label = 'Nom'
        form.fields['last_name'].label = 'Cognoms'
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = CanviDadesUsuari(instance=user)
        form.fields['first_name'].label = 'Nom'
        form.fields['last_name'].label = 'Cognoms'

    head = u'''Dades d'usuari'''
    infoForm = [
        (u'Codi Usuari', user.username),
    ]

    resposta = render(request, "form.html", {
        "form": form,
        "head": head,
        'infoForm': infoForm,
    })

    return resposta
Пример #38
0
def elMeuMur(request, pg):

    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    q = user.destinatari_set.order_by('-missatge__data')
    paginator = Paginator(q.all(), 20)
    try:
        dests = paginator.page(pg)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        dests = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), delive#workflow
        dests = paginator.page(paginator.num_pages)

    if not request.session.has_key('impersonacio'):
        request.user.destinatari_set.filter(
            moment_lectura__isnull=True,
            pk__in=[m.pk for m in dests.object_list
                    ]).update(moment_lectura=datetime.now())

    return render_to_response('missatges.html', {
        'msgs': dests,
        'head': 'Missatges',
    },
                              context_instance=RequestContext(request))
Пример #39
0
def enviaBenvinguda(request, pk):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    professor = User2Professor(user)

    alumne = Alumne.objects.get(pk=int(pk))

    url_next = '/open/dadesRelacioFamilies/#{0}'.format(alumne.pk)

    #seg-------------------
    te_permis = l4 or professor in alumne.tutorsDeLAlumne()
    if not te_permis:
        raise Http404()

    filera = []

    try:
        cosMissatge = enviaBenvingudaAlumne(alumne)
    except Exception as e:
        cosMissatge = {'errors': [e], 'infos': [], 'warnings': []}

    cosMissatge['url_next'] = url_next

    return render(
        request,
        'resultat.html',
        {
            'msgs': cosMissatge,
            'head': u"Acció Envia Benviguda a {0}".format(alumne),
        },
    )
Пример #40
0
def alumnesFallen(request, pk, origen):

    credentials = tools.getImpersonateUser(request)
    (user, _) = credentials

    professor = User2Professor(user)

    instance = get_object_or_404(Sortida, pk=pk)
    instance.flag_clean_nomes_toco_alumnes = True
    potEntrar = (professor in instance.professors_responsables.all()
                 or request.user.groups.filter(
                     name__in=[u"direcció", u"sortides"]).exists())
    if not potEntrar:
        raise Http404

    instance.credentials = credentials

    formIncidenciaF = modelform_factory(Sortida,
                                        fields=('alumnes_que_no_vindran', ))

    if request.method == "POST":
        form = formIncidenciaF(request.POST, instance=instance)

        if form.is_valid():
            try:
                form.save()
                nexturl = r'/sortides/sortides{origen}'.format(origen=origen)
                return HttpResponseRedirect(nexturl)
            except ValidationError, e:
                form._errors.setdefault(NON_FIELD_ERRORS,
                                        []).extend(e.messages)
Пример #41
0
def bloquejaDesbloqueja(request, pk):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    professor = User2Professor(user)

    alumne = Alumne.objects.get(pk=int(pk))

    url_next = '/open/dadesRelacioFamilies/#{0}'.format(alumne.pk)

    #seg-------------------
    te_permis = l4 or professor in alumne.tutorsDeLAlumne()
    if not te_permis:
        raise Http404()

    actiu = alumne.esta_relacio_familia_actiu()

    if actiu:
        resultat = bloqueja(
            alumne,
            u'Bloquejat per {0} amb data {1}'.format(professor,
                                                     datetime.now()))
    else:
        resultat = desbloqueja(alumne)
    resultat['url_next'] = url_next

    return render(
        request,
        'resultat.html',
        {
            'msgs': resultat,
            'head': 'Canvi configuració accés família de {0}'.format(alumne),
        },
    )
Пример #42
0
def afegeixGuardia(request, dia=None, mes=None, year=None):
    
    credentials = getImpersonateUser(request) 
    (user, _ ) = credentials
        
    head=u'Fer guardia' 

    url_next = '/presencia/mostraImpartir/%d/%d/%d/'% ( 
                                    int(year),
                                    int(mes),
                                    int(dia ) )    
    if request.method == 'POST':
        form = afegeixGuardiaForm(request.POST)
        
        if form.is_valid():
            
            professor = form.cleaned_data['professor']
            franges = form.cleaned_data['franges']
            dia_impartir = date( int(year), int(mes), int(dia)  )
            professor_guardia = User2Professor( user )
            Impartir.objects.filter( dia_impartir = dia_impartir,
                                     horari__professor = professor,
                                     horari__hora__in = franges 
                                    ).update( professor_guardia = professor_guardia  )

            return HttpResponseRedirect( url_next )
                                    
                             
    else:
        form = afegeixGuardiaForm()
    return render_to_response(
                'form.html', 
                {'form': form, 
                 'head': head},
                context_instance=RequestContext(request))
Пример #43
0
def elMeuMur( request, pg ,tipus = 'all'):
    
    credentials = tools.getImpersonateUser(request) 
    (user, l4) = credentials

    q = user.destinatari_set.filter(missatge__tipus_de_missatge=tipus.upper()).order_by('-missatge__data') \
        if tipus != 'all' else user.destinatari_set.order_by('-missatge__data')

    if not request.session.has_key('impersonacio'):
        request.user.destinatari_set.filter(
                    moment_lectura__isnull = True,
                ).update( moment_lectura = datetime.now() )

    table = MissatgesTable(q)
    RequestConfig(request, paginate={"klass":DiggPaginator , "per_page": 25}).configure(table)

    missatges = dict()
    for key,value in MISSATGES.items():
        missatges [key] = value.keys()[0]

    return render(
                    request,
                    'missatges.html',
                    {'table': table,
                     'missatges': missatges,
                    },
                 )
Пример #44
0
def bloquejaDesbloqueja( request , pk ):
    credentials = tools.getImpersonateUser(request) 
    (user, l4 ) = credentials

    professor = User2Professor( user )     
            
    alumne =  Alumne.objects.get( pk = int(pk) )
    
    url_next = '/open/dadesRelacioFamilies/#{0}'.format(alumne.pk)

    #seg-------------------
    te_permis = l4 or  professor in alumne.tutorsDeLAlumne() 
    if  not te_permis:
        raise Http404()
        
    actiu =  alumne.esta_relacio_familia_actiu() 
    
    if actiu:
        resultat = bloqueja( alumne, u'Bloquejat per {0} amb data {1}'.format( professor, datetime.now() ) )
    else:
        resultat = desbloqueja( alumne )
    resultat['url_next'] = url_next
    
    return render_to_response(
                'resultat.html',
                    {'msgs': resultat ,
                     'head': 'Canvi configuració accés família de {0}'.format( alumne ) ,
                    },
                    context_instance=RequestContext(request)) 
Пример #45
0
def complementFormulariOmple( request, pk_professor, dia, mes, year  ):

    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials
    
    professor = User2Professor( user ) 
    
    data = date( int(year), int(mes), int(dia) )
    
    head = u"Feina professor absent {0} {1}".format( professor, data )
    
    imparticions = Impartir.objects.filter( dia_impartir = data, horari__professor__pk = pk_professor   )
    
    
    formsetFac = modelformset_factory(model = Feina, extra=0, can_delete=False,  
                                      fields=('professor_fa_guardia','feina_a_fer','comentaris_per_al_professor_guardia',))

    if request.method == "POST":
        formset = formsetFac( request.POST, queryset=Feina.objects.filter( impartir__in = imparticions ) )
        if formset.is_valid():
            formset.save()
            for form in formset:
                if (form.instance.professor_fa_guardia):
                    form.instance.impartir.professor_guardia = form.instance.professor_fa_guardia
                    form.instance.impartir.save()                    
            return HttpResponseRedirect( r'/' )
    else:
        #crear els que no existeixin:
        for i in imparticions:
            feina, _ = Feina.objects.get_or_create( impartir = i , 
                                         defaults = {'professor_darrera_modificacio':professor, } )
            if bool( i.professor_guardia ):
                feina.professor_fa_guardia = i.professor_guardia
                feina.save()
                
        formset = formsetFac( queryset=Feina.objects.filter( impartir__in = imparticions ) )

    for form in formset:
        instance = form.instance
        form.formSetDelimited = True
        guardies = Impartir.objects.filter( 
                                horari__assignatura__nom_assignatura = 'G',
                                horari__hora = instance.impartir.horari.hora,
                                dia_impartir = instance.impartir.dia_impartir
                                            ).distinct()
                                            
        form.infoForm = (
                           ( u'Hora', instance.impartir.horari.hora),
                           ( u'Assignatura', instance.impartir.horari.assignatura),
                           ( u'Grup', instance.impartir.horari.grup),
                           ( u'Aula', instance.impartir.horari.nom_aula),
                           ( u'Professors de Guardia', u', '.join( [ unicode(p) for p in Professor.objects.filter( horari__impartir__in = guardies ).distinct() ] )  )
                         )

    return render_to_response(
                'formset.html', 
                {'formset': formset, 
                 'head': head},
                context_instance=RequestContext(request))    
Пример #46
0
def calendariDevelop(request):
    credentials = tools.getImpersonateUser(request)
    (user, _) = credentials

    return render_to_response('calendariDevelop.html', {
        'head': 'Calendari desenvolupament.',
    },
                              context_instance=RequestContext(request))
Пример #47
0
def fusiona(request,pk):

    credentials = tools.getImpersonateUser(request)
    resultat = { 'errors': [], 'warnings':  [], 'infos':  [ u'Procés realitzat correctament' ]  }
    try:
        fusiona_alumnes_by_pk( int( pk ) , credentials)
    except Exception, e:
        resultat = { 'errors': [ unicode(e), ], 'warnings':  [], 'infos':  []  }
Пример #48
0
def configuraConnexio(request, pk):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    professor = User2Professor(user)

    alumne = Alumne.objects.get(pk=int(pk))

    #seg-------------------
    te_permis = l4 or professor in alumne.tutorsDeLAlumne()
    if not te_permis:
        raise Http404()

    edatAlumne = None
    try:
        edatAlumne = alumne.edat()
    except:
        pass

    infoForm = [
        ('Alumne', unicode(alumne)),
        #( 'Telèfon Alumne', alumne.telefons),
        ('Telèfon Alumne', alumne.rp1_telefon + u', ' + alumne.rp2_telefon +
         u', ' + alumne.altres_telefons),
        #( 'Nom tutors', alumne.tutors),
        ('Nom tutors', alumne.rp1_nom + u', ' + alumne.rp2_nom),
        #('Correu tutors (Saga)', alumne.correu_tutors),
        ('Correu tutors (Saga)', alumne.rp1_correu + u', ' + alumne.rp2_correu
         ),
        ('Edat alumne', edatAlumne),
    ]

    AlumneFormSet = modelform_factory(
        Alumne,
        fields=('correu_relacio_familia_pare', 'correu_relacio_familia_mare',
                'periodicitat_faltes', 'periodicitat_incidencies'),
    )

    if request.method == 'POST':
        form = AlumneFormSet(request.POST, instance=alumne)
        if form.is_valid():
            form.save()
            url_next = '/open/dadesRelacioFamilies#{0}'.format(alumne.pk)
            return HttpResponseRedirect(url_next)

    else:
        form = AlumneFormSet(instance=alumne)

    return render(
        request,
        'form.html',
        {
            'form': form,
            'infoForm': infoForm,
            'head': u'Gestió relació familia amb empreses',
            'formSetDelimited': True
        },
    )
Пример #49
0
def assignaComentarisAAules(request):
    (user, l4) = tools.getImpersonateUser(request)
    professor = User2Professor(user)

    errors = []
    warnings = []
    infos = []

    if request.method == 'POST':
        form = carregaComentarisAulaForm(request.POST, request.FILES)

        if form.is_valid():
            f = request.FILES['fitxerComentaris']

            reader = csv.DictReader(f)
            info_nAulesLlegides = 0
            info_nAulesCreades = 0
            info_nComentarisAfegits = 0
            AulesCreades = []
            ComentarisAfegits = []

            f.seek(0)
            for row in reader:
                info_nAulesLlegides += 1
                nom_aula = unicode(row['CODI'],'iso-8859-1')
                descripcio_aula = unicode(row['NOM'],'iso-8859-1')
                if nom_aula !='':
                    a, created = Aula.objects.get_or_create(nom_aula=nom_aula,
                                                            defaults={
                                                                'horari_lliure': False,
                                                                'reservable': True})
                    if created:
                        info_nAulesCreades += 1
                        AulesCreades.append(a.nom_aula)
                        warnings.append(u'{0}: Aula creada nova'.format(a.nom_aula))
                    a.descripcio_aula = descripcio_aula
                    info_nComentarisAfegits += 1
                    ComentarisAfegits.append(descripcio_aula)
                    a.save()
                else:
                    errors.append('S\'han trobat aules sense nom!!!')
            warnings.append(u'Total aules noves creades: {0}'.format(info_nAulesCreades))
            infos.append(u'Total comentaris afegits: {0}'.format(info_nComentarisAfegits))
            resultat = {'errors': errors, 'warnings': warnings, 'infos': infos}
            return render(
                request,
                'resultat.html',
                {'head': 'Resultat càrrega comentaris aules',
                 'msgs': resultat},
            )
    else:
        form = carregaComentarisAulaForm()

    return render(
        request,
        'afegirComentarisAAules.html',
        {'form': form},
    )
Пример #50
0
def enviaMissatgeProfessorsPas(request):
    credentials = tools.getImpersonateUser(request)
    (user, l4) = credentials

    formset = []
    msgFormF = modelform_factory(Missatge, fields=('text_missatge',))

    if request.method == 'POST':
        msg = Missatge(remitent=user)
        msg.credentials = credentials
        formProfessorConserge = triaProfessorsConsergesSelect2Form(data=request.POST)
        msgForm = msgFormF(data=request.POST, instance=msg)

        if formProfessorConserge.is_valid() and msgForm.is_valid():
            msg.tipus_de_missatge = 'MISSATGERIA'
            msg.save()
            professors_conserges = formProfessorConserge.cleaned_data['professors_conserges']
            destinataris_txt = ", ".join( unicode(pc) for pc in professors_conserges)
            for professor_conserge in professors_conserges:
                msg.envia_a_usuari(professor_conserge.getUser(), 'IN')

            # envio al que ho envia:
            missatge = ACUS_REBUT_ENVIAT_A_PROFE_O_PAS
            tipus_de_missatge = tipusMissatge(missatge)
            msg2 = Missatge(remitent=user,
                           text_missatge=missatge.format(
                               destinataris_txt,
                               msg.text_missatge),
                            tipus_de_missatge= tipus_de_missatge)
            msg2.envia_a_usuari(user, 'PI')
            msg2.destinatari_set.filter(destinatari = user).update(moment_lectura=datetime.now())

            messages.info(request, u"Missatge a {destinataris} enviat correctament".format(destinataris=destinataris_txt))

            if user.groups.filter(name="consergeria").exists():
                url = '/missatgeria/enviaMissatgeProfessorsPas/'
            else:
                url = '/missatgeria/elMeuMur/'
            return HttpResponseRedirect(url)
    else:
        formProfessorConserge = triaProfessorsConsergesSelect2Form()
        msgForm = msgFormF()

    formset.append(formProfessorConserge)
    formset.append(msgForm)

    for form in formset:
        for field in form.fields:
            form.fields[field].widget.attrs['class'] = "form-control"

    return render(
        request,
        'formset.html',
        {'formset': formset,
         'titol_formulari': u"Missatge a professors i/o PAS",
         'head': u"Missatge a membres del professorat o consergeria",
         },
        )
Пример #51
0
def enviaMissatgeTutors( request ):
    
    credentials = tools.getImpersonateUser(request) 
    (user, l4) = credentials   
    
    formset = []
    msgFormF = modelform_factory(Missatge, fields=( 'text_missatge', ) )
    
    if request.method == 'POST':        
        msg = Missatge( remitent = user )
        msg.credentials = credentials
        formAlumne = triaAlumneForm( data = request.POST)
        formData= dataForm( data = request.POST  )
        msgForm = msgFormF( data = request.POST, instance = msg )        
        
        if formAlumne.is_valid() and msgForm.is_valid() and formData.is_valid():
            alumne = formAlumne.cleaned_data['alumne']
            tutors = alumne.tutorsDeLAlumne()
            data = formData.cleaned_data['data']
            if len( tutors ) == 0:
                formAlumne._errors.setdefault(NON_FIELD_ERRORS, []).append(  u'''No trobat el tutor d'aquest alumne. Cal trucar al cap d'estudis.'''  )
            else:
                msg.save()
                strTutors = u''
                separador = ''
                for tutor in tutors:
                    txt = u'''Missatge relatiu al teu alumne tutorat {0}: Amb data {1}, {2}'''.format( unicode(alumne), unicode(data), msg.text_missatge)
                    msg.text_missatge = txt
                    msg.envia_a_usuari(tutor.getUser(), 'IN')
                    msg.enllac = '/tutoria/justificaFaltes/{0}/{1}/{2}/{3}'.format( alumne.pk, data.year, data.month, data.day )
                    msg.save()
                    strTutors += separador + u'Sr(a)' + unicode(tutor )
                    separador = u', '
                txtMsg = msg.text_missatge
                
                #envio al que ho envia:
                msg = Missatge( remitent = user, text_missatge = u'''Avís a tutors de l'alumne {0} enviat a {1}. El text de l'avís és: "{2}"'''.format( alumne, strTutors, txtMsg ) )
                msg.envia_a_usuari(user, 'PI')
                
                url = '/missatgeria/elMeuMur/'  
                return HttpResponseRedirect( url )  
    else:
        formAlumne = triaAlumneForm( )
        formData = dataForm(  label='Data', help_text=u'El text del missatge començarà per: Amb data ______, ' )        
        msgForm = msgFormF(  )
    
    formData.fields['data'].required = True
    
    formset.append( formAlumne )
    formset.append( formData )
    formset.append( msgForm )
        
    return render_to_response(
                'formset.html',
                    {'formset': formset,
                     'head': 'Avís a tutors.' ,
                    },
                    context_instance=RequestContext(request))
Пример #52
0
def assignaComentarisAAules(request):
    (user, l4) = tools.getImpersonateUser(request)
    professor = User2Professor(user)

    errors = []
    warnings = []
    infos = []

    if request.method == 'POST':
        form = carregaComentarisAulaForm(request.POST, request.FILES)

        if form.is_valid():
            f = request.FILES['fitxerComentaris']

            reader = csv.DictReader(f)
            info_nAulesLlegides = 0
            info_nAulesCreades = 0
            info_nComentarisAfegits = 0
            AulesCreades = []
            ComentarisAfegits = []

            f.seek(0)
            for row in reader:
                info_nAulesLlegides += 1
                nom_aula = unicode(row['CODI'],'iso-8859-1')
                descripcio_aula = unicode(row['NOM'],'iso-8859-1')
                if nom_aula !='':
                    a, created = Aula.objects.get_or_create(nom_aula=nom_aula,
                                                            defaults={
                                                                'horari_lliure': False,
                                                                'reservable': True})
                    if created:
                        info_nAulesCreades += 1
                        AulesCreades.append(a.nom_aula)
                        warnings.append(u'{0}: Aula creada nova'.format(a.nom_aula))
                    a.descripcio_aula = descripcio_aula
                    info_nComentarisAfegits += 1
                    ComentarisAfegits.append(descripcio_aula)
                    a.save()
                else:
                    errors.append('S\'han trobat aules sense nom!!!')
            warnings.append(u'Total aules noves creades: {0}'.format(info_nAulesCreades))
            infos.append(u'Total comentaris afegits: {0}'.format(info_nComentarisAfegits))
            resultat = {'errors': errors, 'warnings': warnings, 'infos': infos}
            return render(
                request,
                'resultat.html',
                {'head': 'Resultat càrrega comentaris aules',
                 'msgs': resultat},
            )
    else:
        form = carregaComentarisAulaForm()

    return render(
        request,
        'afegirComentarisAAules.html',
        {'form': form},
    )
Пример #53
0
def calendariDevelop(request):
    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials

    return render_to_response(
                'calendariDevelop.html',
                    {
                     'head': 'Calendari desenvolupament.' ,
                    },
                    context_instance=RequestContext(request))         
Пример #54
0
def modificaEstatControlAssistencia(request, codiEstat, idAlumne, idImpartir):
    '''
    Modifica el control d'assistència d'un sol resistre.
    '''
    try:
        profeActual = User2Professor(request.user)
        credentials = getImpersonateUser(request)
        (user, l4) = credentials

        estats = LlistaEstats()
        segEstat = estats.obtenirSeguentEstatAPartirCodi(codiEstat)
        if (settings.CUSTOM_NOMES_TUTOR_POT_JUSTIFICAR):
            #Si el profe convencional no pot justificar ens saltem un estat
            #TODO: Només podem justificar si som tutor del grup.
            if segEstat.codi == 'J':
                segEstat = estats.obtenirSeguentEstatAPartirCodi(segEstat.codi)

        #Comprovar que sigui el profe assignat a l'hora o error.
        impartir = Impartir.objects.get(id=idImpartir)

        #Controlem que el profe tingui permisos per modificar la hora.
        _comprovarQueLaHoraPertanyAlProfessorOError(credentials, impartir)

        ca = ControlAssistencia.objects.get(impartir_id=idImpartir,
                                            alumne_id=idAlumne)
        codiResultat = _modificaEstatControlAssistencia(
            segEstat, ca, profeActual, user, credentials)

        #Actualitzar el control impartir.
        impartir.dia_passa_llista = datetime.datetime.now()
        impartir.professor_passa_llista = profeActual
        impartir.currentUser = user
        impartir.save()

        #Log
        from aula.apps.usuaris.models import Accio
        Accio.objects.create(
            tipus='PL',
            usuari=user,
            l4=l4,
            impersonated_from=request.user if request.user != user else None,
            text=u"""Passar llista, presenciaSetmanal: {0}.""".format(
                impartir))

        #print ("Retorno correctament ", codiResultat)
        return HttpResponse(codiResultat)
    except ValidationError as e:
        cadenaError = u''
        for v in e.message_dict[NON_FIELD_ERRORS]:
            cadenaError += unicode(v) + u"<br>"
        return HttpResponse(CONST_ERROR_CODE + cadenaError, status=500)
    except Exception as e:
        #print (CONST_ERROR_CODE, str(traceback.format_exc()))
        #return HttpResponse(CONST_ERROR_CODE + unicode(e) + u"-" + unicode(traceback.format_exc(), 'utf-8'))
        return HttpResponse(CONST_ERROR_CODE + str(e), status=500)
Пример #55
0
def gestionaAlumnesTutor( request , pk ):
    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials

    professor = Professor.objects.get( pk = int(pk) )
        
    head=u'Tutors Individualitzats'
    infoForm = []    
    formset = []
    
    if request.method == 'POST':
        totBe = True
        nous_alumnes_tutor = []
        for grup in Grup.objects.filter( alumne__isnull = False ).distinct().order_by('descripcio_grup'):
            #http://www.ibm.com/developerworks/opensource/library/os-django-models/index.html?S_TACT=105AGX44&S_CMP=EDU
            form=triaMultiplesAlumnesForm(
                                    request.POST,
                                    prefix=str( grup.pk ),
                                    queryset =  grup.alumne_set.all()  ,                                    
                                    etiqueta = unicode( grup )  
                                    )
            formset.append( form )        
            if form.is_valid():
                for alumne in form.cleaned_data['alumnes']:
                    nous_alumnes_tutor.append( alumne )
            else:
                totBe = False
        if totBe:
            professor.tutorindividualitzat_set.all().delete()
            for alumne in nous_alumnes_tutor:
                ti = TutorIndividualitzat( professor = professor, alumne = alumne  )
                ti.credentials = credentials
                ti.save()
               
            return HttpResponseRedirect( '/alumnes/llistaTutorsIndividualitzats/' )
    else:
        for grup in Grup.objects.filter( alumne__isnull = False ).distinct().order_by('descripcio_grup'):
            #http://www.ibm.com/developerworks/opensource/library/os-django-models/index.html?S_TACT=105AGX44&S_CMP=EDU
            inicial= [c.pk for c in grup.alumne_set.filter( tutorindividualitzat__professor = professor ) ]
            form=triaMultiplesAlumnesForm(
                                    prefix=str( grup.pk ),
                                    queryset =  grup.alumne_set.all()  ,                                    
                                    etiqueta = unicode( grup )  ,
                                    initial =  {'alumnes': inicial }
                                    )
            formset.append( form )
        
    return render(
                request,
                  "formset.html", 
                  {"formset": formset,
                   "head": head,
                   "formSetDelimited": True,
                   }
                )
Пример #56
0
def marcarComHoraSenseAlumnes(request, pk):
    credentials = getImpersonateUser(request)
    (user, l4) = credentials

    head = u'Afegir alumnes a la llista'

    pk = int(pk)
    impartir = Impartir.objects.get(pk=pk)

    #seg-------------------------------
    pertany_al_professor = user.pk in [ impartir.horari.professor.pk,   \
                                        impartir.professor_guardia.pk if impartir.professor_guardia else -1 ]
    if not (l4 or pertany_al_professor):
        raise Http404()

    if request.method == "POST":
        form = marcarComHoraSenseAlumnesForm(request.POST)
        if form.is_valid(
        ) and form.cleaned_data['marcar_com_hora_sense_alumnes']:
            expandir = form.cleaned_data['expandir_a_totes_les_meves_hores']

            from aula.apps.presencia.afegeixTreuAlumnesLlista import marcaSenseAlumnesThread
            afegeix = marcaSenseAlumnesThread(expandir=expandir,
                                              impartir=impartir)
            afegeix.start()

            #LOGGING
            Accio.objects.create(
                tipus='LL',
                usuari=user,
                l4=l4,
                impersonated_from=request.user
                if request.user != user else None,
                text=u"""Marcar classe sense alumnes {0}""".format(impartir))

            import time
            while afegeix and not afegeix.primerDiaFet():
                time.sleep(0.5)

            url_next = '/presencia/mostraImpartir/%d/%d/%d/' % (
                impartir.dia_impartir.year, impartir.dia_impartir.month,
                impartir.dia_impartir.day)

            return HttpResponseRedirect(url_next)
    else:
        form = marcarComHoraSenseAlumnesForm(
            initial={
                'marcar_com_hora_sense_alumnes': True,
            })

    return render_to_response("form.html", {
        "form": form,
        "head": head,
    },
                              context_instance=RequestContext(request))
Пример #57
0
def gestionaAlumnesTutor( request , pk ):
    credentials = tools.getImpersonateUser(request) 
    (user, _ ) = credentials

    professor = Professor.objects.get( pk = int(pk) )
        
    head=u'Tutors Individualitzats'
    infoForm = []    
    formset = []
    
    if request.method == 'POST':
        totBe = True
        nous_alumnes_tutor = []
        for grup in Grup.objects.filter( alumne__isnull = False ).distinct():
            #http://www.ibm.com/developerworks/opensource/library/os-django-models/index.html?S_TACT=105AGX44&S_CMP=EDU
            form=triaMultiplesAlumnesForm(
                                    request.POST,
                                    prefix=str( grup.pk ),
                                    queryset =  grup.alumne_set.all()  ,                                    
                                    etiqueta = unicode( grup )  
                                    )
            formset.append( form )        
            if form.is_valid():
                for alumne in form.cleaned_data['alumnes']:
                    nous_alumnes_tutor.append( alumne )
            else:
                totBe = False
        if totBe:
            professor.tutorindividualitzat_set.all().delete()
            for alumne in nous_alumnes_tutor:
                ti = TutorIndividualitzat( professor = professor, alumne = alumne  )
                ti.credentials = credentials
                ti.save()
               
            return HttpResponseRedirect( '/alumnes/llistaTutorsIndividualitzats/' )
    else:
        for grup in Grup.objects.filter( alumne__isnull = False ).distinct():
            #http://www.ibm.com/developerworks/opensource/library/os-django-models/index.html?S_TACT=105AGX44&S_CMP=EDU
            inicial= [c.pk for c in grup.alumne_set.filter( tutorindividualitzat__professor = professor ) ]
            form=triaMultiplesAlumnesForm(
                                    prefix=str( grup.pk ),
                                    queryset =  grup.alumne_set.all()  ,                                    
                                    etiqueta = unicode( grup )  ,
                                    initial =  {'alumnes': inicial }
                                    )
            formset.append( form )
        
    return render(
                request,
                  "formset.html", 
                  {"formset": formset,
                   "head": head,
                   "formSetDelimited": True,
                   }
                )
Пример #58
0
def enviaMissatgeAdministradors( request ):
    
    credentials = tools.getImpersonateUser(request) 
    (user, l4) = credentials   
    
    formset = []
    msgFormF = modelform_factory(Missatge, fields=( 'text_missatge', ) )
    
    if request.method == 'POST':        
        msg = Missatge( remitent = user )
        msg.credentials = credentials
        msgForm = msgFormF( data = request.POST, instance = msg )        
        
        if msgForm.is_valid():           
            administradors = Group.objects.get_or_create( name = 'administradors' )[0].user_set.all()
            if len( administradors ) == 0:
                msgForm._errors.setdefault(NON_FIELD_ERRORS, []).append(  u'''No estan definits els administradors, sorry.'''  )
            else:
                missatge = ERROR_AL_PROGRAMA
                msg.text_missatge = missatge.format(msg.text_missatge)
                tipus_de_missatge = tipusMissatge(missatge)
                msg.tipus_de_missatge = tipus_de_missatge
                msg.save()
                strAdmins = u''
                separador = ''
                for administrador in administradors:
                    msg.envia_a_usuari(administrador, 'VI')
                    strAdmins += separador + u'Sr(a)' + unicode( administrador )
                    separador = u', '
                txtMsg = msg.text_missatge
                
                #envio al que ho envia:
                missatge = ACUS_REBUT_ERROR_AL_PROGRAMA
                tipus_de_missatge = tipusMissatge(missatge)
                msg = Missatge( remitent = user, text_missatge = missatge.format( txtMsg ), tipus_de_missatge = tipus_de_missatge )
                msg.envia_a_usuari(user, 'PI')
                
                url = '/missatgeria/elMeuMur/'
                return HttpResponseRedirect( url )  
    else:
        msgForm = msgFormF(  )
    
    formset.append( msgForm )

    for form in formset:
        for field in form.fields:
            form.fields[field].widget.attrs['class'] = "form-control"

    return render(
                request,
                'formset.html',
                    {'formset': formset,
                     'head': u'''Avís a administradors. En cas d'error, sisplau, detalla clarament totes les passes per reproduir l'error.''' ,
                    },
                )
Пример #59
0
def marcarComHoraSenseAlumnes(request, pk):
    credentials = getImpersonateUser(request) 
    (user, l4) = credentials   
    
    head=u'Afegir alumnes a la llista' 

    pk = int(pk)
    impartir = Impartir.objects.get ( pk = pk )
    
    #seg-------------------------------
    pertany_al_professor = user.pk in [ impartir.horari.professor.pk,   \
                                        impartir.professor_guardia.pk if impartir.professor_guardia else -1 ]
    if not ( l4 or pertany_al_professor):
        raise Http404() 

    
    if request.method == "POST":
        form = marcarComHoraSenseAlumnesForm( request.POST  )
        if form.is_valid() and form.cleaned_data['marcar_com_hora_sense_alumnes']:   
            expandir = form.cleaned_data['expandir_a_totes_les_meves_hores']
                          
            from aula.apps.presencia.afegeixTreuAlumnesLlista import marcaSenseAlumnesThread
            afegeix=marcaSenseAlumnesThread(expandir = expandir, impartir=impartir )
            afegeix.start()

            #LOGGING
            Accio.objects.create( 
                    tipus = 'LL',
                    usuari = user,
                    l4 = l4,
                    impersonated_from = request.user if request.user != user else None,
                    text = u"""Marcar classe sense alumnes {0}""".format(
                                impartir )                                                        
                        )
                
            import time
            while afegeix and not afegeix.primerDiaFet(): time.sleep(  0.5 )

            url_next = '/presencia/mostraImpartir/%d/%d/%d/'% ( 
                                    impartir.dia_impartir.year,
                                    impartir.dia_impartir.month,
                                    impartir.dia_impartir.day )    
                            
            return HttpResponseRedirect(url_next )
    else:
        form = marcarComHoraSenseAlumnesForm( initial= { 'marcar_com_hora_sense_alumnes': True, }  )

    return render_to_response(
                  "form.html", 
                  {"form": form,
                   "head": head,
                   },
                  context_instance=RequestContext(request))