Browse Source

Format code for PEP 8 (autopep8, E501 ignored)

Command:
  autopep8 --in-place --ignore E501 -r .
producao
Marcio Mazza 10 years ago
parent
commit
4e69005e3a
  1. 4
      conftest.py
  2. 4
      moodlerouter.py
  3. 1
      scripts/casas_com_PM_e_SAPL.py
  4. 1
      scripts/casas_que_usam_LEGBR_ou_PM.py
  5. 1
      scripts/contatos_de_casas_que_usam_portalmodelo.py
  6. 1
      scripts/csv_writer.py
  7. 1
      scripts/setgerentes/dados_gerentes.py
  8. 1
      sigi/apps/casas/admin.py
  9. 3
      sigi/apps/casas/urls.py
  10. 4
      sigi/apps/convenios/urls.py
  11. 4
      sigi/apps/diagnosticos/models.py
  12. 10
      sigi/apps/diagnosticos/urls.py
  13. 83
      sigi/apps/mdl/models.py
  14. 4
      sigi/apps/metas/urls.py
  15. 1
      sigi/apps/ocorrencias/admin.py
  16. 3
      sigi/apps/parlamentares/reports.py
  17. 3
      sigi/apps/parlamentares/urls.py
  18. 7
      sigi/apps/saberes/admin.py
  19. 37
      sigi/apps/saberes/management/commands/get_moodle_stats.py
  20. 37
      sigi/apps/saberes/models.py
  21. 10
      sigi/apps/saberes/urls.py
  22. 31
      sigi/apps/saberes/views.py
  23. 4
      sigi/apps/servicos/urls.py
  24. 1
      sigi/apps/servidores/forms.py
  25. 4
      sigi/apps/servidores/urls.py
  26. 1
      sigi/apps/utils/__init__.py
  27. 6
      sigi/context_processors.py
  28. 2
      sigi/settings/base.py
  29. 6
      sigi/test_cart.py
  30. 7
      sigi/urls.py

4
conftest.py

@ -21,8 +21,8 @@ class SigiTestApp(DjangoTestApp):
user = self.default_user user = self.default_user
return super(SigiTestApp, self).get(url, params, headers, extra_environ, return super(SigiTestApp, self).get(url, params, headers, extra_environ,
status, expect_errors, user, auto_follow, status, expect_errors, user, auto_follow,
content_type, **kwargs) content_type, **kwargs)
@pytest.fixture(scope='function') @pytest.fixture(scope='function')

4
moodlerouter.py

@ -1,6 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
class MoodleRouter(object): class MoodleRouter(object):
def db_for_read(self, model, **hints): def db_for_read(self, model, **hints):
if model._meta.app_label == 'mdl': if model._meta.app_label == 'mdl':
return 'moodle' return 'moodle'
@ -19,4 +21,4 @@ class MoodleRouter(object):
def allow_migrate(self, db, model): def allow_migrate(self, db, model):
if model._meta.app_label == 'mdl': if model._meta.app_label == 'mdl':
return False return False
return None return None

1
scripts/casas_com_PM_e_SAPL.py

@ -32,4 +32,3 @@ escrever_casas(casas, '/tmp/casas_que_usam_PM_ou_SAPL.csv')
casas_algum_inativo = casas_todas casas_algum_inativo = casas_todas

1
scripts/casas_que_usam_LEGBR_ou_PM.py

@ -15,6 +15,7 @@ ARQUIVO_CSV = '/tmp/casas_que_usam_LEGBR_ou_PM.csv'
class UnicodeWriter: class UnicodeWriter:
""" """
A CSV writer which will write rows to CSV file "f", A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding. which is encoded in the given encoding.

1
scripts/contatos_de_casas_que_usam_portalmodelo.py

@ -16,6 +16,7 @@ ARQUIVO_CSV = '/tmp/contatos_casas_pm.csv'
class UnicodeWriter: class UnicodeWriter:
""" """
A CSV writer which will write rows to CSV file "f", A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding. which is encoded in the given encoding.

1
scripts/csv_writer.py

@ -4,6 +4,7 @@ import csv
class CsvWriter: class CsvWriter:
""" """
A CSV writer which will write rows to CSV file "f", A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding. which is encoded in the given encoding.

1
scripts/setgerentes/dados_gerentes.py

@ -5590,4 +5590,3 @@ atrib = [
(5222203, 'RAFAHLS'), (5222203, 'RAFAHLS'),
(5222302, 'RAFAHLS'), (5222302, 'RAFAHLS'),
] ]

1
sigi/apps/casas/admin.py

@ -164,6 +164,7 @@ class OcorrenciaInline(admin.TabularInline):
class GerentesContasFilter(admin.filters.RelatedFieldListFilter): class GerentesContasFilter(admin.filters.RelatedFieldListFilter):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(GerentesContasFilter, self).__init__(*args, **kwargs) super(GerentesContasFilter, self).__init__(*args, **kwargs)
gerentes = Servidor.objects.filter(casas_que_gerencia__isnull=False).order_by('nome_completo').distinct() gerentes = Servidor.objects.filter(casas_que_gerencia__isnull=False).order_by('nome_completo').distinct()

3
sigi/apps/casas/urls.py

@ -2,7 +2,8 @@
from django.conf.urls import patterns, url from django.conf.urls import patterns, url
urlpatterns = patterns('sigi.apps.casas.views', urlpatterns = patterns(
'sigi.apps.casas.views',
# Informacoes de uma casa legislativa # Informacoes de uma casa legislativa
url(r'^report_complete/$', 'report_complete', name='report-complete-all'), url(r'^report_complete/$', 'report_complete', name='report-complete-all'),

4
sigi/apps/convenios/urls.py

@ -2,7 +2,9 @@
from django.conf.urls import patterns, url from django.conf.urls import patterns, url
urlpatterns = patterns('sigi.apps.convenios.views', urlpatterns = patterns(
'sigi.apps.convenios.views',
url(r'^reports/$', 'report', name='convenios-report'), url(r'^reports/$', 'report', name='convenios-report'),
url(r'^carrinho/$', 'visualizar_carrinho', name='visualizar-carrinho'), url(r'^carrinho/$', 'visualizar_carrinho', name='visualizar-carrinho'),
url(r'^carrinho/excluir_carrinho/$', 'excluir_carrinho', name='excluir-carrinho'), # tagerror url(r'^carrinho/excluir_carrinho/$', 'excluir_carrinho', name='excluir-carrinho'), # tagerror

4
sigi/apps/diagnosticos/models.py

@ -94,7 +94,7 @@ class Diagnostico(BaseEntity):
'host': host, 'host': host,
'url_diagnostico': self.get_absolute_url(), 'url_diagnostico': self.get_absolute_url(),
'status': _(u"Publicado"), 'status': _(u"Publicado"),
}) })
def email_diagnostico_alterado(self, from_email, host): def email_diagnostico_alterado(self, from_email, host):
"""Enviando email quando o status do diagnóstico """Enviando email quando o status do diagnóstico
@ -112,7 +112,7 @@ class Diagnostico(BaseEntity):
'host': host, 'host': host,
'url_diagnostico': self.get_absolute_url(), 'url_diagnostico': self.get_absolute_url(),
'status': _(u"Alterado"), 'status': _(u"Alterado"),
}) })
def get_schemata(self, category=None, *args, **kwargs): def get_schemata(self, category=None, *args, **kwargs):
""" Se existir uma categoria retorna apenas as questões dessa. """ Se existir uma categoria retorna apenas as questões dessa.

10
sigi/apps/diagnosticos/urls.py

@ -5,7 +5,9 @@ from django.views.generic import TemplateView
LOGIN_REDIRECT_URL = '/diagnosticos/mobile/login' LOGIN_REDIRECT_URL = '/diagnosticos/mobile/login'
urlpatterns = patterns('sigi.apps.diagnosticos.views', urlpatterns = patterns(
'sigi.apps.diagnosticos.views',
# Lista de Diagnósticos # Lista de Diagnósticos
url(r'^mobile/$', 'lista', name='lista_diagnosticos'), url(r'^mobile/$', 'lista', name='lista_diagnosticos'),
@ -37,10 +39,12 @@ urlpatterns = patterns('sigi.apps.diagnosticos.views',
) )
urlpatterns += patterns('django.contrib.auth.views', urlpatterns += patterns(
'django.contrib.auth.views',
# Login do Diagnóstico # Login do Diagnóstico
url(r'^mobile/login/$', 'login', {'template_name': url(r'^mobile/login/$', 'login', {'template_name':
'diagnosticos/diagnosticos_login.html'}, name='login'), 'diagnosticos/diagnosticos_login.html'}, name='login'),
# Logout do Diagnóstico # Logout do Diagnóstico
url(r'^mobile/logout/$', 'logout', url(r'^mobile/logout/$', 'logout',

83
sigi/apps/mdl/models.py

@ -3,13 +3,14 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from django.db import models from django.db import models
class CourseStats(models.Model): class CourseStats(models.Model):
# databaseview: (postgresql dialect): # databaseview: (postgresql dialect):
# -- View: sigi_course_stats # -- View: sigi_course_stats
# #
# DROP VIEW sigi_course_stats; # DROP VIEW sigi_course_stats;
# #
# CREATE OR REPLACE VIEW sigi_course_stats AS # CREATE OR REPLACE VIEW sigi_course_stats AS
# SELECT cc.id AS categoryid, c.id AS courseid, # SELECT cc.id AS categoryid, c.id AS courseid,
# CASE # CASE
# WHEN e.enrol = 'ilbeadtutorado' AND ue.status = 1 THEN 'N' -- Rejeitada # WHEN e.enrol = 'ilbeadtutorado' AND ue.status = 1 THEN 'N' -- Rejeitada
@ -29,7 +30,7 @@ class CourseStats(models.Model):
# LEFT JOIN mdl_grade_grades gg ON gg.itemid = gi.id AND gg.userid = ue.userid # LEFT JOIN mdl_grade_grades gg ON gg.itemid = gi.id AND gg.userid = ue.userid
# LEFT JOIN mdl_course_completions co ON co.userid = ue.userid AND co.course = c.id # LEFT JOIN mdl_course_completions co ON co.userid = ue.userid AND co.course = c.id
# GROUP BY cc.id, c.id, completionstatus; # GROUP BY cc.id, c.id, completionstatus;
COMPLETIONSTATUS_CHOICES = ( COMPLETIONSTATUS_CHOICES = (
('N', u'Matrículas rejeitadas'), ('N', u'Matrículas rejeitadas'),
('C', u'Em curso'), ('C', u'Em curso'),
@ -37,7 +38,7 @@ class CourseStats(models.Model):
('L', u'Abandono'), ('L', u'Abandono'),
('A', u'Aprovação'), ('A', u'Aprovação'),
('I', u'Indeterminado'),) ('I', u'Indeterminado'),)
category = models.ForeignKey('CourseCategories', db_column='categoryid', primary_key=True) category = models.ForeignKey('CourseCategories', db_column='categoryid', primary_key=True)
course = models.ForeignKey('Course', db_column='courseid') course = models.ForeignKey('Course', db_column='courseid')
completionstatus = models.CharField(max_length=1, choices=COMPLETIONSTATUS_CHOICES) completionstatus = models.CharField(max_length=1, choices=COMPLETIONSTATUS_CHOICES)
@ -47,10 +48,11 @@ class CourseStats(models.Model):
class Meta: class Meta:
managed = False managed = False
db_table = 'sigi_course_stats' db_table = 'sigi_course_stats'
def __unicode__(self): def __unicode__(self):
return '%s - %s: %s' % (self.category.name, self.course.fullname, self.usercount) return '%s - %s: %s' % (self.category.name, self.course.fullname, self.usercount)
class Cohort(models.Model): class Cohort(models.Model):
id = models.BigIntegerField(primary_key=True) id = models.BigIntegerField(primary_key=True)
context = models.ForeignKey('Context', db_column='contextid') context = models.ForeignKey('Context', db_column='contextid')
@ -71,27 +73,29 @@ class Cohort(models.Model):
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class CohortMembers(models.Model): class CohortMembers(models.Model):
id = models.BigIntegerField(primary_key=True) id = models.BigIntegerField(primary_key=True)
cohort = models.ForeignKey('Cohort', db_column='cohortid') cohort = models.ForeignKey('Cohort', db_column='cohortid')
user = models.ForeignKey('User', db_column='userid') user = models.ForeignKey('User', db_column='userid')
timeadded = models.BigIntegerField() timeadded = models.BigIntegerField()
class Meta: class Meta:
managed = False managed = False
db_table = 'mdl_cohort_members' db_table = 'mdl_cohort_members'
class Context(models.Model): class Context(models.Model):
CONTEXT_SYSTEM = 10 # System context level - only one instance in every system CONTEXT_SYSTEM = 10 # System context level - only one instance in every system
CONTEXT_USER = 30 # User context level - one instance for each user describing what others can do to user CONTEXT_USER = 30 # User context level - one instance for each user describing what others can do to user
CONTEXT_COURSECAT = 40 # Course category context level - one instance for each category CONTEXT_COURSECAT = 40 # Course category context level - one instance for each category
CONTEXT_COURSE = 50 # Course context level - one instances for each course CONTEXT_COURSE = 50 # Course context level - one instances for each course
CONTEXT_MODULE = 70 # Course module context level - one instance for each course module CONTEXT_MODULE = 70 # Course module context level - one instance for each course module
CONTEXT_BLOCK = 80 # Block context level - one instance for each block, sticky blocks are tricky CONTEXT_BLOCK = 80 # Block context level - one instance for each block, sticky blocks are tricky
# because ppl think they should be able to override them at lower contexts. # because ppl think they should be able to override them at lower contexts.
# Any other context level instance can be parent of block context. # Any other context level instance can be parent of block context.
id = models.BigIntegerField(primary_key=True) id = models.BigIntegerField(primary_key=True)
contextlevel = models.BigIntegerField() contextlevel = models.BigIntegerField()
instanceid = models.BigIntegerField() instanceid = models.BigIntegerField()
@ -104,7 +108,8 @@ class Context(models.Model):
def __unicode__(self): def __unicode__(self):
return self.path return self.path
class Course(models.Model): class Course(models.Model):
id = models.BigIntegerField(primary_key=True) id = models.BigIntegerField(primary_key=True)
category = models.ForeignKey('CourseCategories', db_column='category', related_name='courses') category = models.ForeignKey('CourseCategories', db_column='category', related_name='courses')
@ -141,23 +146,24 @@ class Course(models.Model):
class Meta: class Meta:
managed = False managed = False
db_table = 'mdl_course' db_table = 'mdl_course'
ordering = ['sortorder',] ordering = ['sortorder', ]
def __unicode__(self): def __unicode__(self):
return self.fullname return self.fullname
def total_alunos(self): def total_alunos(self):
return sum(e.user_enrolments.count() for e in self.enrols.all()) return sum(e.user_enrolments.count() for e in self.enrols.all())
def total_ativos(self): def total_ativos(self):
return sum(e.user_enrolments.filter(status=0).count() for e in self.enrols.all()) return sum(e.user_enrolments.filter(status=0).count() for e in self.enrols.all())
def get_matriculas(self): def get_matriculas(self):
q = UserEnrolments.objects.none() q = UserEnrolments.objects.none()
for e in self.enrols.all(): for e in self.enrols.all():
q = q | e.user_enrolments.all() q = q | e.user_enrolments.all()
return q return q
class CourseCategories(models.Model): class CourseCategories(models.Model):
id = models.BigIntegerField(primary_key=True) id = models.BigIntegerField(primary_key=True)
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
@ -177,32 +183,32 @@ class CourseCategories(models.Model):
class Meta: class Meta:
managed = False managed = False
db_table = 'mdl_course_categories' db_table = 'mdl_course_categories'
ordering = ['sortorder',] ordering = ['sortorder', ]
def __unicode__(self): def __unicode__(self):
return self.name return self.name
def context(self): def context(self):
return Context.objects.get(instanceid=self.id, contextlevel=Context.CONTEXT_COURSECAT) return Context.objects.get(instanceid=self.id, contextlevel=Context.CONTEXT_COURSECAT)
def total_turmas(self): def total_turmas(self):
return self.coursecount + sum([c.coursecount for c in self.children.all()]) return self.coursecount + sum([c.coursecount for c in self.children.all()])
def total_alunos(self): def total_alunos(self):
total = 0 total = 0
total = total + sum(c.total_alunos() for c in self.courses.all()) total = total + sum(c.total_alunos() for c in self.courses.all())
total = total + sum(c.total_alunos() for c in self.children.all()) total = total + sum(c.total_alunos() for c in self.children.all())
return total return total
def cohortids(self): def cohortids(self):
cids = [c.pk for c in self.context().cohort_set.all()] cids = [c.pk for c in self.context().cohort_set.all()]
for c in self.children.all(): for c in self.children.all():
cids = cids + c.cohortids() cids = cids + c.cohortids()
return cids return cids
def total_alunos_cohort(self): def total_alunos_cohort(self):
return sum([c.members.distinct().count() for c in Cohort.objects.filter(pk__in=self.cohortids())]) return sum([c.members.distinct().count() for c in Cohort.objects.filter(pk__in=self.cohortids())])
def get_all_courses(self, only_visible=False): def get_all_courses(self, only_visible=False):
if only_visible: if only_visible:
q = self.courses.filter(visible=1) q = self.courses.filter(visible=1)
@ -212,6 +218,7 @@ class CourseCategories(models.Model):
q = q | c.get_all_courses(only_visible=only_visible) q = q | c.get_all_courses(only_visible=only_visible)
return q return q
class CourseCompletions(models.Model): class CourseCompletions(models.Model):
id = models.BigIntegerField(primary_key=True) id = models.BigIntegerField(primary_key=True)
user = models.ForeignKey('User', db_column='userid') user = models.ForeignKey('User', db_column='userid')
@ -224,7 +231,8 @@ class CourseCompletions(models.Model):
class Meta: class Meta:
managed = False managed = False
db_table = 'mdl_course_completions' db_table = 'mdl_course_completions'
class Enrol(models.Model): class Enrol(models.Model):
id = models.BigIntegerField(primary_key=True) id = models.BigIntegerField(primary_key=True)
enrol = models.CharField(max_length=20) enrol = models.CharField(max_length=20)
@ -265,13 +273,14 @@ class Enrol(models.Model):
class Meta: class Meta:
managed = False managed = False
db_table = 'mdl_enrol' db_table = 'mdl_enrol'
ordering = ['sortorder',] ordering = ['sortorder', ]
def __unicode__(self): def __unicode__(self):
if not self.name: if not self.name:
return self.enrol return self.enrol
return self.name return self.name
class User(models.Model): class User(models.Model):
id = models.BigIntegerField(primary_key=True) id = models.BigIntegerField(primary_key=True)
auth = models.CharField(max_length=20) auth = models.CharField(max_length=20)
@ -333,8 +342,8 @@ class User(models.Model):
def __unicode__(self): def __unicode__(self):
return u'%s %s' % (self.firstname, self.lastname) return u'%s %s' % (self.firstname, self.lastname)
class UserEnrolments(models.Model): class UserEnrolments(models.Model):
id = models.BigIntegerField(primary_key=True) id = models.BigIntegerField(primary_key=True)
status = models.BigIntegerField() status = models.BigIntegerField()
@ -348,4 +357,4 @@ class UserEnrolments(models.Model):
class Meta: class Meta:
managed = False managed = False
db_table = 'mdl_user_enrolments' db_table = 'mdl_user_enrolments'

4
sigi/apps/metas/urls.py

@ -2,7 +2,9 @@
from django.conf.urls import patterns, url from django.conf.urls import patterns, url
urlpatterns = patterns('sigi.apps.metas.views', urlpatterns = patterns(
'sigi.apps.metas.views',
url(r'^$', 'dashboard', name='metas-dashboardsss'), # tagerror url(r'^$', 'dashboard', name='metas-dashboardsss'), # tagerror
url(r'^mapa/$', 'mapa', name='metas-mapa'), # tagerror url(r'^mapa/$', 'mapa', name='metas-mapa'), # tagerror
url(r'^mapdata/$', 'map_data', name='metas-map_data'), url(r'^mapdata/$', 'map_data', name='metas-map_data'),

1
sigi/apps/ocorrencias/admin.py

@ -61,6 +61,7 @@ class OcorrenciaChangeList(ChangeList):
qs = qs.filter(servidor_registro=servidor) qs = qs.filter(servidor_registro=servidor)
return qs return qs
class OcorrenciaAdmin(BaseModelAdmin): class OcorrenciaAdmin(BaseModelAdmin):
list_display = ('data_criacao', 'casa_legislativa', 'get_municipio', 'get_uf', 'assunto', 'prioridade', 'status', 'data_modificacao', 'setor_responsavel',) list_display = ('data_criacao', 'casa_legislativa', 'get_municipio', 'get_uf', 'assunto', 'prioridade', 'status', 'data_modificacao', 'setor_responsavel',)
list_filter = (OcorrenciaListFilter, 'status', 'prioridade', 'categoria__nome', 'setor_responsavel__nome', ) list_filter = (OcorrenciaListFilter, 'status', 'prioridade', 'categoria__nome', 'setor_responsavel__nome', )

3
sigi/apps/parlamentares/reports.py

@ -10,7 +10,6 @@ from reportlab.lib.units import cm
from sigi.apps.relatorios.reports import ReportDefault from sigi.apps.relatorios.reports import ReportDefault
def string_to_cm(texto): def string_to_cm(texto):
tamanho = 0 tamanho = 0
minEspeciais = { minEspeciais = {
@ -120,7 +119,7 @@ class ParlamentaresLabels(Report):
cep_parlamentar(instance) cep_parlamentar(instance)
), ),
] ]
self.band_detail = DetailBand(width=(self.largura_etiqueta) * cm, height=(self.altura_etiqueta) * cm, margin_left = 0, margin_top = 0, margin_bottom=0.0 * cm, margin_right = 0, elements=my_elements, display_inline=True, default_style={'fontName': 'Helvetica', 'fontSize': self.tamanho_fonte}) self.band_detail = DetailBand(width=(self.largura_etiqueta) * cm, height=(self.altura_etiqueta) * cm, margin_left=0, margin_top=0, margin_bottom=0.0 * cm, margin_right=0, elements=my_elements, display_inline=True, default_style={'fontName': 'Helvetica', 'fontSize': self.tamanho_fonte})
def logradouro_parlamentar(instance): def logradouro_parlamentar(instance):

3
sigi/apps/parlamentares/urls.py

@ -1,7 +1,8 @@
# coding: utf-8 # coding: utf-8
from django.conf.urls import patterns, url from django.conf.urls import patterns, url
urlpatterns = patterns('sigi.apps.parlamentares.views', urlpatterns = patterns(
'sigi.apps.parlamentares.views',
# Reports labels parlamentares # Reports labels parlamentares
url(r'^labels/$', 'labels_report', name='labels-report-all'), url(r'^labels/$', 'labels_report', name='labels-report-all'),

7
sigi/apps/saberes/admin.py

@ -3,10 +3,11 @@ from django.utils.translation import ugettext as _
from django.contrib import admin from django.contrib import admin
from sigi.apps.saberes.models import CategoriasInteresse from sigi.apps.saberes.models import CategoriasInteresse
class CategoriasInteresseAdmin(admin.ModelAdmin): class CategoriasInteresseAdmin(admin.ModelAdmin):
list_display = ('prefixo', 'descricao', 'count_categorias',) list_display = ('prefixo', 'descricao', 'count_categorias',)
def count_categorias(self, obj): def count_categorias(self, obj):
return obj.categorias().count() return obj.categorias().count()
count_categorias.short_description = _("Categorias que casam") count_categorias.short_description = _("Categorias que casam")
admin.site.register(CategoriasInteresse, CategoriasInteresseAdmin) admin.site.register(CategoriasInteresse, CategoriasInteresseAdmin)

37
sigi/apps/saberes/management/commands/get_moodle_stats.py

@ -36,26 +36,26 @@ class Command(BaseCommand):
areas = [] areas = []
numeros = [ numeros = [
{'descricao': _(u'Total de usuários cadastrados'), 'valor': User.objects.count()}, {'descricao': _(u'Total de usuários cadastrados'), 'valor': User.objects.count()},
{'descricao': _(u'Novos usuários cadastrados') , 'valor': User.objects.filter(firstaccess__gte=1392326052).count()} {'descricao': _(u'Novos usuários cadastrados'), 'valor': User.objects.filter(firstaccess__gte=1392326052).count()}
] ]
for ci in CategoriasInteresse.objects.all(): for ci in CategoriasInteresse.objects.all():
if ci.coorte: if ci.coorte:
total_matriculas = ci.total_alunos_coorte() total_matriculas = ci.total_alunos_coorte()
elif ci.apurar_conclusao: elif ci.apurar_conclusao:
data = {x['completionstatus']: x for x in CourseStats.objects.filter(category__in=ci.categorias(subcategorias=True)). \ data = {x['completionstatus']: x for x in CourseStats.objects.filter(category__in=ci.categorias(subcategorias=True)).
values('completionstatus').annotate(total_users=Sum('usercount'),grade_average=Avg('gradeaverage'))} values('completionstatus').annotate(total_users=Sum('usercount'), grade_average=Avg('gradeaverage'))}
total_matriculas = sum(x['total_users'] for k, x in data.items()) total_matriculas = sum(x['total_users'] for k, x in data.items())
else: else:
total_matriculas = CourseStats.objects.filter(category__in=ci.categorias(subcategorias=True)). \ total_matriculas = CourseStats.objects.filter(category__in=ci.categorias(subcategorias=True)). \
aggregate(total_users=Sum('usercount'))['total_users'] aggregate(total_users=Sum('usercount'))['total_users']
dados = [{'descricao': _(u'Total de matrículas'), 'valor': total_matriculas}] dados = [{'descricao': _(u'Total de matrículas'), 'valor': total_matriculas}]
if ci.coorte: if ci.coorte:
for c in ci.categorias(subcategorias=True): for c in ci.categorias(subcategorias=True):
dados.append({'descricao': c.name, 'valor': c.total_alunos_cohort()}) dados.append({'descricao': c.name, 'valor': c.total_alunos_cohort()})
if ci.apurar_conclusao: if ci.apurar_conclusao:
if 'N' in data: if 'N' in data:
dados.append({'descricao': _(u'Matrículas rejeitadas'), 'help_text': _(u'demanda reprimida'), dados.append({'descricao': _(u'Matrículas rejeitadas'), 'help_text': _(u'demanda reprimida'),
@ -65,39 +65,38 @@ class Command(BaseCommand):
'valor': total_alunos}) 'valor': total_alunos})
else: else:
total_alunos = total_matriculas total_alunos = total_matriculas
if 'C' in data: if 'C' in data:
dados.append({'descricao': _(u'Alunos em curso'), 'valor': data['C']['total_users'], dados.append({'descricao': _(u'Alunos em curso'), 'valor': data['C']['total_users'],
'percentual': 100.0 * data['C']['total_users'] / total_alunos }) 'percentual': 100.0 * data['C']['total_users'] / total_alunos})
if 'L' in data: if 'L' in data:
dados.append({'descricao': _(u'Alunos que abandonaram o curso'), 'valor': data['L']['total_users'], dados.append({'descricao': _(u'Alunos que abandonaram o curso'), 'valor': data['L']['total_users'],
'percentual': 100.0 * data['L']['total_users'] / total_alunos }) 'percentual': 100.0 * data['L']['total_users'] / total_alunos})
if 'R' in data: if 'R' in data:
dados.append({'descricao': _(u'Alunos reprovados'), 'valor': data['R']['total_users'], dados.append({'descricao': _(u'Alunos reprovados'), 'valor': data['R']['total_users'],
'percentual': 100.0 * data['R']['total_users'] / total_alunos}) 'percentual': 100.0 * data['R']['total_users'] / total_alunos})
if 'A' in data: if 'A' in data:
dados.append({'descricao': _(u'Alunos aprovados'), 'valor': data['A']['total_users'], dados.append({'descricao': _(u'Alunos aprovados'), 'valor': data['A']['total_users'],
'percentual': 100.0 * data['A']['total_users'] / total_alunos}) 'percentual': 100.0 * data['A']['total_users'] / total_alunos})
if 'I' in data: if 'I' in data:
dados.append({'descricao': _(u'Situação indefinida'), 'valor': data['I']['total_users'], dados.append({'descricao': _(u'Situação indefinida'), 'valor': data['I']['total_users'],
'help_text': _(u'Situação do aluno não pode ser determinada pelo sistema'), 'help_text': _(u'Situação do aluno não pode ser determinada pelo sistema'),
'percentual': 100.0 * data['I']['total_users'] / total_alunos}) 'percentual': 100.0 * data['I']['total_users'] / total_alunos})
if 'A' in data: if 'A' in data:
dados.append({'descricao': _(u'Média das notas dos alunos aprovados (%)'), 'valor': int(data['A']['grade_average'])}) dados.append({'descricao': _(u'Média das notas dos alunos aprovados (%)'), 'valor': int(data['A']['grade_average'])})
if 'R' in data: if 'R' in data:
dados.append({'descricao': _(u'Média das notas dos alunos reprovados (%)'), 'valor': int(data['R']['grade_average'])}) dados.append({'descricao': _(u'Média das notas dos alunos reprovados (%)'), 'valor': int(data['R']['grade_average'])})
areas.append({'titulo': ci.descricao, 'dados': dados}) areas.append({'titulo': ci.descricao, 'dados': dados})
paineis = [{'titulo': _(u'Saberes em números'), 'dados': numeros}] + areas paineis = [{'titulo': _(u'Saberes em números'), 'dados': numeros}] + areas
PainelItem.objects.all().delete() # Clear dashboard PainelItem.objects.all().delete() # Clear dashboard
for p in paineis: for p in paineis:
for d in p['dados']: for d in p['dados']:
PainelItem.objects.create(painel=p['titulo'], descricao=d['descricao'], help_text= d['help_text'] if 'help_text' in PainelItem.objects.create(painel=p['titulo'], descricao=d['descricao'], help_text=d['help_text'] if 'help_text' in
d else '', valor=d['valor'], percentual=d['percentual'] if 'percentual' in d else None) d else '', valor=d['valor'], percentual=d['percentual'] if 'percentual' in d else None)

37
sigi/apps/saberes/models.py

@ -4,7 +4,8 @@ from __future__ import unicode_literals
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.db import models from django.db import models
from django.db.models import Q from django.db.models import Q
from sigi.apps.mdl.models import Course, CourseCategories, CourseCompletions, UserEnrolments from sigi.apps.mdl.models import Course, CourseCategories, CourseCompletions, UserEnrolments
class CategoriasInteresse(models.Model): class CategoriasInteresse(models.Model):
prefixo = models.CharField(_(u"Prefixo das categorias no Moodle"), max_length=100, prefixo = models.CharField(_(u"Prefixo das categorias no Moodle"), max_length=100,
@ -12,60 +13,62 @@ class CategoriasInteresse(models.Model):
descricao = models.CharField(_(u"Descrição"), max_length=100) descricao = models.CharField(_(u"Descrição"), max_length=100)
sigla = models.CharField(_(u"Sigla"), max_length=20) sigla = models.CharField(_(u"Sigla"), max_length=20)
coorte = models.BooleanField(_(u"Usa Cohorte"), default=False, help_text=_(u"Usa cohorte para calcular o número de matrículas/alunos")) coorte = models.BooleanField(_(u"Usa Cohorte"), default=False, help_text=_(u"Usa cohorte para calcular o número de matrículas/alunos"))
apurar_alunos = models.BooleanField(_(u"Apurar alunos"), default=False, help_text=_(u"Indica que deve-se verificar o perfil da"\ apurar_alunos = models.BooleanField(_(u"Apurar alunos"), default=False, help_text=_(u"Indica que deve-se verificar o perfil da"
+ " inscrição para saber se é um aluno ou se a matrícula foi rejeitada")) + " inscrição para saber se é um aluno ou se a matrícula foi rejeitada"))
apurar_conclusao = models.BooleanField(_(u"Apurar conclusão"), default=False, help_text=_(u"Indica se o dashboard mostrará o "\ apurar_conclusao = models.BooleanField(_(u"Apurar conclusão"), default=False, help_text=_(u"Indica se o dashboard mostrará o "
+ "número de alunos aprovados, reprovados e desistentes")) + "número de alunos aprovados, reprovados e desistentes"))
class Meta: class Meta:
verbose_name = _(u'Categorias de interesse') verbose_name = _(u'Categorias de interesse')
def __unicode__(self): def __unicode__(self):
return self.descricao return self.descricao
def categorias(self, subcategorias=False): def categorias(self, subcategorias=False):
def get_sub_categorias(categorias): def get_sub_categorias(categorias):
result = CourseCategories.objects.none() result = CourseCategories.objects.none()
for c in categorias: for c in categorias:
c_children = CourseCategories.objects.filter(parent=c) c_children = CourseCategories.objects.filter(parent=c)
result = result | c_children | get_sub_categorias(c_children) result = result | c_children | get_sub_categorias(c_children)
return result return result
q = CourseCategories.objects.filter(idnumber__startswith=self.prefixo) q = CourseCategories.objects.filter(idnumber__startswith=self.prefixo)
if subcategorias: if subcategorias:
q = q | get_sub_categorias(q) q = q | get_sub_categorias(q)
return q return q
def get_all_courses(self, only_visible=False): def get_all_courses(self, only_visible=False):
q = Course.objects.none() q = Course.objects.none()
for categoria in self.categorias(): for categoria in self.categorias():
q = q | categoria.get_all_courses(only_visible=only_visible) q = q | categoria.get_all_courses(only_visible=only_visible)
return q return q
def get_all_completions(self): def get_all_completions(self):
q = CourseCompletions.objects.none() q = CourseCompletions.objects.none()
for c in self.get_all_courses(): for c in self.get_all_courses():
q = q | c.coursecompletions_set.all() q = q | c.coursecompletions_set.all()
return q return q
def get_all_enrolments(self): def get_all_enrolments(self):
q = UserEnrolments.objects.none() q = UserEnrolments.objects.none()
for c in self.get_all_courses(): for c in self.get_all_courses():
q = q | c.get_matriculas() q = q | c.get_matriculas()
return q return q
def total_alunos_coorte(self): def total_alunos_coorte(self):
return sum(c.total_alunos_cohort() for c in self.categorias()) return sum(c.total_alunos_cohort() for c in self.categorias())
# A temporary model to store Moodle processed data by management command (called from CRON) # A temporary model to store Moodle processed data by management command (called from CRON)
class PainelItem(models.Model): class PainelItem(models.Model):
painel = models.CharField(max_length=255) painel = models.CharField(max_length=255)
descricao = models.CharField(max_length=255) descricao = models.CharField(max_length=255)
help_text = models.CharField(max_length=255) help_text = models.CharField(max_length=255)
valor = models.IntegerField() valor = models.IntegerField()
percentual = models.FloatField(null=True) percentual = models.FloatField(null=True)
class Meta: class Meta:
ordering = ['pk'] ordering = ['pk']

10
sigi/apps/saberes/urls.py

@ -1,7 +1,9 @@
# coding: utf-8 # coding: utf-8
from django.conf.urls import patterns, url from django.conf.urls import patterns, url
urlpatterns = patterns('sigi.apps.saberes.views', urlpatterns = patterns(
url(r'^dashboard/$', 'dashboard', name="saberes-dashboard-view"), 'sigi.apps.saberes.views',
url(r'^dashboard/(?P<area>\w+)/$', 'detail', name="saberes-dashboard-detail"),
) url(r'^dashboard/$', 'dashboard', name="saberes-dashboard-view"),
url(r'^dashboard/(?P<area>\w+)/$', 'detail', name="saberes-dashboard-detail"),
)

31
sigi/apps/saberes/views.py

@ -8,39 +8,41 @@ from django.template import RequestContext
from sigi.apps.mdl.models import User, CourseStats from sigi.apps.mdl.models import User, CourseStats
from sigi.apps.saberes.models import CategoriasInteresse, PainelItem from sigi.apps.saberes.models import CategoriasInteresse, PainelItem
def dashboard(request): def dashboard(request):
paineis = OrderedDict() paineis = OrderedDict()
for p in PainelItem.objects.all(): for p in PainelItem.objects.all():
if p.painel not in paineis: if p.painel not in paineis:
paineis[p.painel] = {'titulo': p.painel, 'dados': []} paineis[p.painel] = {'titulo': p.painel, 'dados': []}
paineis[p.painel]['dados'].append(p) paineis[p.painel]['dados'].append(p)
for p in paineis: for p in paineis:
try: try:
paineis[p]['area'] = CategoriasInteresse.objects.get(descricao=paineis[p]['titulo']) paineis[p]['area'] = CategoriasInteresse.objects.get(descricao=paineis[p]['titulo'])
except: except:
pass pass
extra_context = {'paineis': paineis} extra_context = {'paineis': paineis}
return render_to_response('saberes/dashboard.html', extra_context, context_instance=RequestContext(request)) return render_to_response('saberes/dashboard.html', extra_context, context_instance=RequestContext(request))
def detail(request, area): def detail(request, area):
ci = get_object_or_404(CategoriasInteresse, pk=area) ci = get_object_or_404(CategoriasInteresse, pk=area)
head_flags = [] head_flags = []
table_data = OrderedDict() table_data = OrderedDict()
for c in CourseStats.objects.filter(category__in=ci.categorias(subcategorias=True)).order_by('course__fullname'): for c in CourseStats.objects.filter(category__in=ci.categorias(subcategorias=True)).order_by('course__fullname'):
if c.course_id not in table_data: if c.course_id not in table_data:
table_data[c.course_id] = {'course_name': c.course.fullname, 'total_matriculas': 0} table_data[c.course_id] = {'course_name': c.course.fullname, 'total_matriculas': 0}
table_data[c.course_id]['total_matriculas'] += c.usercount table_data[c.course_id]['total_matriculas'] += c.usercount
table_data[c.course_id][c.completionstatus] = c.usercount table_data[c.course_id][c.completionstatus] = c.usercount
head_flags.append(c.completionstatus) head_flags.append(c.completionstatus)
if c.completionstatus == 'A': if c.completionstatus == 'A':
table_data[c.course_id]['media_aprovados'] = c.gradeaverage table_data[c.course_id]['media_aprovados'] = c.gradeaverage
head_flags.append('MA') head_flags.append('MA')
@ -48,10 +50,10 @@ def detail(request, area):
if c.completionstatus == 'R': if c.completionstatus == 'R':
table_data[c.course_id]['media_reprovados'] = c.gradeaverage table_data[c.course_id]['media_reprovados'] = c.gradeaverage
head_flags.append('MR') head_flags.append('MR')
head_flags = set(head_flags) head_flags = set(head_flags)
table_head = [_(u'Curso / turma'), _(u'Total de matrículas')] table_head = [_(u'Curso / turma'), _(u'Total de matrículas')]
if 'N' in head_flags: if 'N' in head_flags:
table_head.append(_(u'Matrículas rejeitadas')) table_head.append(_(u'Matrículas rejeitadas'))
table_head.append(_(u'Alunos efetivos')) table_head.append(_(u'Alunos efetivos'))
@ -59,7 +61,7 @@ def detail(request, area):
table_data[k]['efetivos'] = table_data[k]['total_matriculas'] - (table_data[k]['N'] if 'N' in table_data[k] else 0) table_data[k]['efetivos'] = table_data[k]['total_matriculas'] - (table_data[k]['N'] if 'N' in table_data[k] else 0)
if 'C' in head_flags: if 'C' in head_flags:
table_head.append(_(u'Em curso')) table_head.append(_(u'Em curso'))
if 'L' in head_flags: if 'L' in head_flags:
table_head.append(_(u'Abandono')) table_head.append(_(u'Abandono'))
if 'R' in head_flags: if 'R' in head_flags:
@ -70,7 +72,6 @@ def detail(request, area):
table_head.append(_(u'Média das notas dos alunos aprovados')) table_head.append(_(u'Média das notas dos alunos aprovados'))
if 'MR' in head_flags: if 'MR' in head_flags:
table_head.append(_(u'Média das notas dos alunos reprovados')) table_head.append(_(u'Média das notas dos alunos reprovados'))
extra_context = {'area': ci, 'table_head': table_head, 'table_data': table_data, 'flags': head_flags} extra_context = {'area': ci, 'table_head': table_head, 'table_data': table_data, 'flags': head_flags}
return render_to_response('saberes/detail.html', extra_context, context_instance=RequestContext(request)) return render_to_response('saberes/detail.html', extra_context, context_instance=RequestContext(request))

4
sigi/apps/servicos/urls.py

@ -5,7 +5,9 @@ from django.views.generic.base import TemplateView
from .views import MapaView from .views import MapaView
urlpatterns = patterns('sigi.apps.servicos.views', urlpatterns = patterns(
'sigi.apps.servicos.views',
url(r'^manifesta/$', 'casa_manifesta_view', name="casa-manifesta-view"), url(r'^manifesta/$', 'casa_manifesta_view', name="casa-manifesta-view"),
url(r'^munatenjson/(?P<servico>\w+)/$', 'municipios_atendidos', name="municipios-atendidos"), url(r'^munatenjson/(?P<servico>\w+)/$', 'municipios_atendidos', name="municipios-atendidos"),
url(r'^mapa/(?P<servico>\w+)/$', MapaView.as_view(), name="servicos-mapa"), url(r'^mapa/(?P<servico>\w+)/$', MapaView.as_view(), name="servicos-mapa"),

1
sigi/apps/servidores/forms.py

@ -12,6 +12,7 @@ def valida_data_inicial_menor_que_final(data, chave_ini, chave_fim):
raise forms.ValidationError(_( raise forms.ValidationError(_(
u"A data de início deve ser menor que a data final. Verifique novamente")) u"A data de início deve ser menor que a data final. Verifique novamente"))
class FeriasForm(forms.ModelForm): class FeriasForm(forms.ModelForm):
class Meta: class Meta:

4
sigi/apps/servidores/urls.py

@ -2,7 +2,9 @@
from django.conf.urls import patterns, url from django.conf.urls import patterns, url
urlpatterns = patterns('sigi.apps.servidores.views', urlpatterns = patterns(
'sigi.apps.servidores.views',
# Reports servidores # Reports servidores
url(r'^servidores_por_funcao.pdf$', 'servidores_por_funcao', name='servidores-funcao-pdf'), url(r'^servidores_por_funcao.pdf$', 'servidores_por_funcao', name='servidores-funcao-pdf'),
url(r'^servidores_por_cargo.pdf$', 'servidores_por_cargo', name='servidores-cargo-pdf'), url(r'^servidores_por_cargo.pdf$', 'servidores_por_cargo', name='servidores-cargo-pdf'),

1
sigi/apps/utils/__init__.py

@ -26,6 +26,7 @@ class SearchField(models.TextField):
kwargs['field_names'] = self.field_names kwargs['field_names'] = self.field_names
return name, path, args, kwargs return name, path, args, kwargs
def to_ascii(txt, codif='utf-8'): def to_ascii(txt, codif='utf-8'):
if not isinstance(txt, basestring): if not isinstance(txt, basestring):
txt = unicode(txt) txt = unicode(txt)

6
sigi/context_processors.py

@ -168,10 +168,10 @@ def busca_informacoes_seit():
for tipo_servico in TipoServico.objects.all(): for tipo_servico in TipoServico.objects.all():
por_mes = [] por_mes = []
for mes in range(1,13): for mes in range(1, 13):
por_mes.append({'mes': '%02d/%s' % (mes,datetime.date.today().year), por_mes.append({'mes': '%02d/%s' % (mes, datetime.date.today().year),
'total': tipo_servico.servico_set.filter(data_desativacao=None, data_ativacao__year=mes_atual.year, data_ativacao__month=mes).count()}) 'total': tipo_servico.servico_set.filter(data_desativacao=None, data_ativacao__year=mes_atual.year, data_ativacao__month=mes).count()})
result.append( result.append(
{'nome': tipo_servico.nome, {'nome': tipo_servico.nome,
'total': tipo_servico.servico_set.filter(data_desativacao=None).count(), 'total': tipo_servico.servico_set.filter(data_desativacao=None).count(),

2
sigi/settings/base.py

@ -40,7 +40,7 @@ TEMPLATE_LOADERS = ('django.template.loaders.filesystem.Loader',
) )
# Database routers # Database routers
DATABASE_ROUTERS = ['moodlerouter.MoodleRouter',] DATABASE_ROUTERS = ['moodlerouter.MoodleRouter', ]
# Application definition # Application definition
INSTALLED_APPS = ( INSTALLED_APPS = (

6
sigi/test_cart.py

@ -8,7 +8,7 @@ from sigi.testutils import pdf_text
@pytest.mark.parametrize("url, some_entries, form_action, name_attr, verbose_name_plural", [ @pytest.mark.parametrize("url, some_entries, form_action, name_attr, verbose_name_plural", [
('/parlamentares/parlamentar/', some_parliamentarians, 'adiciona_parlamentar', 'nome_completo', 'Parlamentares'), ('/parlamentares/parlamentar/', some_parliamentarians, 'adiciona_parlamentar', 'nome_completo', 'Parlamentares'),
('/casas/casalegislativa/', some_parliaments, 'adicionar_casas', 'nome', 'Casas Legislativas'), ('/casas/casalegislativa/', some_parliaments, 'adicionar_casas', 'nome', 'Casas Legislativas'),
]) ])
def test_add_to_cart(url, some_entries, form_action, name_attr, verbose_name_plural, app): def test_add_to_cart(url, some_entries, form_action, name_attr, verbose_name_plural, app):
@ -41,7 +41,7 @@ def test_add_to_cart(url, some_entries, form_action, name_attr, verbose_name_plu
@pytest.mark.parametrize("url, some_entries, all_expression", [ @pytest.mark.parametrize("url, some_entries, all_expression", [
('/parlamentares/parlamentar/', some_parliamentarians, 'todos os parlamentares', ), ('/parlamentares/parlamentar/', some_parliamentarians, 'todos os parlamentares', ),
('/casas/casalegislativa/', some_parliaments, 'todas as casas', ), ('/casas/casalegislativa/', some_parliaments, 'todas as casas', ),
]) ])
def test_no_selection_brings_everyone_to_the_cart(url, some_entries, all_expression, app): def test_no_selection_brings_everyone_to_the_cart(url, some_entries, all_expression, app):
@ -56,7 +56,7 @@ def test_no_selection_brings_everyone_to_the_cart(url, some_entries, all_express
@pytest.mark.parametrize("url, generate_entries", [ @pytest.mark.parametrize("url, generate_entries", [
('/parlamentares/parlamentar/', parliamentarians_from_names, ), ('/parlamentares/parlamentar/', parliamentarians_from_names, ),
('/casas/casalegislativa/', parliaments_from_names, ), ('/casas/casalegislativa/', parliaments_from_names, ),
]) ])
def test_pagination(url, generate_entries, app, live_server): def test_pagination(url, generate_entries, app, live_server):

7
sigi/urls.py

@ -8,7 +8,8 @@ from django.contrib import admin
admin.site.index_template = 'index.html' admin.site.index_template = 'index.html'
admin.autodiscover() admin.autodiscover()
urlpatterns = patterns('', urlpatterns = patterns(
'',
url(r'^parlamentares/parlamentar/', include('sigi.apps.parlamentares.urls')), url(r'^parlamentares/parlamentar/', include('sigi.apps.parlamentares.urls')),
url(r'^casas/casalegislativa/', include('sigi.apps.casas.urls')), url(r'^casas/casalegislativa/', include('sigi.apps.casas.urls')),
@ -28,7 +29,9 @@ urlpatterns = patterns('',
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
if settings.DEBUG: if settings.DEBUG:
urlpatterns = patterns('', urlpatterns = patterns(
'',
url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^404/$', TemplateView.as_view(template_name='404.html')),
url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')),
url(r'^503/$', TemplateView.as_view(template_name='503.html')), url(r'^503/$', TemplateView.as_view(template_name='503.html')),

Loading…
Cancel
Save