From 46bd1e4afd077041855b31e7073f8ef4373e00c6 Mon Sep 17 00:00:00 2001
From: Felipe Vieira <felipe.tio@gmail.com>
Date: Tue, 13 Dec 2011 13:52:38 +0000
Subject: [PATCH] problemas com a migracao no banco postgres

---
 .../servidores/management/commands/migra.py   | 106 +++++++++---------
 .../management/commands/sync_ldap.py          |  34 +++---
 sigi/apps/servidores/models.py                |   8 +-
 3 files changed, 79 insertions(+), 69 deletions(-)

diff --git a/sigi/apps/servidores/management/commands/migra.py b/sigi/apps/servidores/management/commands/migra.py
index bbf4bd0..61a934f 100644
--- a/sigi/apps/servidores/management/commands/migra.py
+++ b/sigi/apps/servidores/management/commands/migra.py
@@ -38,58 +38,60 @@ class Command(BaseCommand):
             for (name, value) in pessoa:
                 p[name] = value.strip()
 
+            user = None
+            if not p['email']:
+                username = '' 
+                email = ''
+	    elif not ('@interlegis' in p['email']):
+                username = p['email'].split('@')[0].strip().lower()
+                email = ''
+	    else:
+                username = p['email'].split('@')[0].strip().lower()
+                email = username + '@interlegis.gov.br'
+
             # buscar usuário e servidor da linha atual
             try:
-                # procuro o usuario por email se for interlegis
-                if not p['email'] or not ('@interlegis' in p['email']):
-                    raise MigrationError
-                user = User.objects.get(email__startswith=p['email'])
-                servidor = user.servidor
-            except (MigrationError, User.DoesNotExist):
-                try:
-                    # se nao encontrar procura por nome
-                    if not p['nome_completo']:
+                # procuro o usuario por email do interlegis
+                if email:
+                    try: user = User.objects.get(email=email)
+                    except User.DoesNotExist: pass
+
+                if not user and username:
+                    try: user = User.objects.get(username=username)
+                    except User.DoesNotExist: 
+                    	try: user = User.objects.get(username=username + "__")
+                    	except User.DoesNotExist: pass
+
+                if not user:
+                    if not username:
                         raise MigrationError
-                    servidor = Servidor.objects.get(nome_completo=p['nome_completo'])
-                except (MigrationError, Servidor.DoesNotExist):
-                    try:
-                        # Cria um usuario tratando os casos incompletos
-                        # fulano@interlegis.
-                        username = p['email'].split('@')[0].lower()
-                        user = User.objects.exclude(email='').get(username=username)
-                        try:
-                            servidor = user.servidor
-                        except Servidor.DoesNotExist:
-                            servidor = Servidor.objects.create(
-                                  user=user,
-                                  nome_completo= "%s %s" % (user.first_name, user.last_name)
-                                )
-                    except (MigrationError, User.DoesNotExist):
-                        try:
-                            if not username:
-                                raise MigrationError
-                            if '@interlegis' in p['email']:
-                                # pode ser um antigo usuario do ad
-                                email = username + '@interlegis.gov.br'
-                            else:
-                                # cria um username a partir do email sem
-                                # colidir com os usuarios ldap
-                                username = username + '__'
-                                email = ''
-                            names = p['nome_completo'].split(' ')
-                            first_name = names[0]
-                            last_name = " ".join(names[1:])
-                            user = User.objects.create(
-                                    username = username,
-                                    email = email,
-                                    first_name = first_name,
-                                    last_name = last_name,
-                                    is_active= False
-                                )
-                            servidor = user.servidor
-                        except Exception, e:
-                            print ", ".join(row)
-                            continue
+
+                    if not email:
+                        # cria um username a partir do email sem
+                        # colidir com os usuarios ldap
+                        username = username + '__'
+
+                    names = p['nome_completo'].split(' ')
+                    first_name = names[0]
+                    last_name = " ".join(names[1:])
+
+                    user = User.objects.create(
+                            username = username,
+                            email = email,
+                            first_name = first_name,
+                            last_name = last_name[:30],
+                            is_active= False
+                        )
+
+                servidor = user.servidor
+            except Servidor.DoesNotExist:
+                servidor = Servidor.objects.create(
+                    user=user,
+                    nome_completo= "%s %s" % (user.first_name, user.last_name)
+                )
+            except MigrationError, e:
+                print ", ".join(row)
+                continue
 
             # mapeando dados simples
             servidor.nome_completo = p['nome_completo']
@@ -181,7 +183,7 @@ class Command(BaseCommand):
                 e = servidor.endereco.create(logradouro=p['endereco'])
               e.municipio = BRASILIA
               e.bairro = p['cidade'] # bizarro mas é isso mesmo
-              e.cep = p['cep']
+              e.cep = re.sub("\D", "", p['cep'])
               e.save()
 
             servidor.apontamentos = p['apontamentos']
@@ -189,8 +191,8 @@ class Command(BaseCommand):
 
             if p['cargo'] or p['funcao']:
                 funcao = servidor.funcao_set.get_or_create(
-                        funcao = p['cargo'],
-                        cargo = p['funcao'],
+                        funcao = p['funcao'],
+                        cargo = p['cargo'],
                     )[0]
 
                 if p['data_bap_entrada']:
diff --git a/sigi/apps/servidores/management/commands/sync_ldap.py b/sigi/apps/servidores/management/commands/sync_ldap.py
index 9ad615c..4d24cd8 100644
--- a/sigi/apps/servidores/management/commands/sync_ldap.py
+++ b/sigi/apps/servidores/management/commands/sync_ldap.py
@@ -67,19 +67,27 @@ class Command(BaseCommand):
                     print "User '%s' created." % username
                 try: nome_completo = ldap_user[1]['cn'][0]
                 except: nome_completo = ''
-                try: servidor = Servidor.objects.get(nome_completo=nome_completo)
+                try: 
+                    servidor = user.servidor
+                    if not servidor.nome_completo == nome_completo.decode('utf8'):
+                    	servidor.nome_completo = nome_completo
+                        print "Servidor '%s' updated." % nome_completo
                 except Servidor.DoesNotExist:
-                    servidor = user.servidor_set.create(nome_completo=nome_completo)
-                    print "Servidor '%s' created." % nome_completo
-                else:
-                    if not user.email == email.decode('utf8'):
-                        user.email = email
-                        print "User '%s' email updated." % username
-                    if not user.first_name == first_name.decode('utf8'):
-                        user.first_name = first_name
-                        print "User '%s' first name updated." % username
-                    if not user.last_name == last_name.decode('utf8'):
-                        user.last_name = last_name
-                        print "User '%s' last name updated." % username
+                    try: servidor = Servidor.objects.get(nome_completo=nome_completo)
+                    except Servidor.DoesNotExist:
+                        servidor = user.servidor_set.create(nome_completo=nome_completo)
+                        print "Servidor '%s' created." % nome_completo
+                    else:
+                        if not user.email == email.decode('utf8'):
+                            user.email = email
+                            print "User '%s' email updated." % username
+                        if not user.first_name == first_name.decode('utf8'):
+                            user.first_name = first_name
+                            print "User '%s' first name updated." % username
+                        if not user.last_name == last_name.decode('utf8'):
+                            user.last_name = last_name
+                            print "User '%s' last name updated." % username
+		servidor.user = user
+                servidor.save()
                 user.save()
         print "Users are synchronized."
diff --git a/sigi/apps/servidores/models.py b/sigi/apps/servidores/models.py
index a54d5cf..6e8bae2 100644
--- a/sigi/apps/servidores/models.py
+++ b/sigi/apps/servidores/models.py
@@ -8,7 +8,7 @@ class Subsecretaria(models.Model):
     """ Modelo para representação das Subsecretarias do Interlegis
     """
 
-    nome = models.CharField(max_length=50, null=True)
+    nome = models.CharField(max_length=250, null=True)
     sigla = models.CharField(max_length=10, null=True)
     # servidor responsavel por dirigir a Subsecretaria
     responsavel = models.ForeignKey('servidores.Servidor', related_name='diretor', null=True)
@@ -23,7 +23,7 @@ class Servico(models.Model):
     """ Modelo para representação dos Serviços de uma Subsecretaria
     """
 
-    nome = models.CharField(max_length=50, null=True)
+    nome = models.CharField(max_length=250, null=True)
     sigla = models.CharField(max_length=10, null=True)
     subsecretaria = models.ForeignKey(Subsecretaria, null=True)
     # servidor responsavel por chefiar o serviço
@@ -162,8 +162,8 @@ class Funcao(models.Model):
     servidores no Interlegis
     """
     servidor = models.ForeignKey(Servidor)
-    funcao = models.CharField(max_length=50, null=True)
-    cargo = models.CharField(max_length=50, null=True)
+    funcao = models.CharField(max_length=250, null=True)
+    cargo = models.CharField(max_length=250, null=True)
     inicio_funcao = models.DateField(u'início da função', null=True)
     fim_funcao = models.DateField(u'fim da função', blank=True, null=True)
     descricao = models.TextField(u'descrição', blank=True, null=True)