Пример #1
0
def producto_index(request, field="descripcion", value="None", order="-id"):
    """
    Página principal para trabajar con productos
    """
    try:
        headquar = get_object_or_404(Headquar, id=DataAccessToken.get_headquar_id(request.session))
    except:
        Message.error(request, ("Sede no seleccionado o no se encuentra en la base de datos."))
        return Redirect.to(request, "/home/choice_headquar/")

    field = (field if not request.REQUEST.get("field") else request.REQUEST.get("field")).strip()
    value = (value if not request.REQUEST.get("value") else request.REQUEST.get("value")).strip()
    order = (order if not request.REQUEST.get("order") else request.REQUEST.get("order")).strip()

    producto_page = None
    try:
        value_f = "" if value == "None" else value
        column_contains = u"%s__%s" % (field, "contains")
        producto_list = Producto.objects.filter(headquar=headquar).filter(**{ column_contains: value_f }).order_by(order)
        paginator = Paginator(producto_list, 20)
        try:
            producto_page = paginator.page(request.GET.get("page"))
        except PageNotAnInteger:
            producto_page = paginator.page(1)
        except EmptyPage:
            producto_page = paginator.page(paginator.num_pages)
    except Exception, e:
        Message.error(request, e)
Пример #2
0
def association_edit_current(request):
    """
    Actualiza datos de la asociación a la que ingresó el usuario
    """
    d = Association()
    try:
        d = get_object_or_404(Association, id=DataAccessToken.get_association_id(request.session))
    except:
        Message.error(request, ("Asociación no seleccionada o no se encuentra en la base de datos."))
        return Redirect.to(request, "/home/choice_headquar/")

    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.name = request.POST.get("name")
            d.type_a = request.POST.get("type_a")
            d.solution_id = request.POST.get("solution_id")
            # solution=Solution.objects.get(id=d.solution_id) #no es necesario
            d.logo = request.POST.get("asociacion_logo")
            if normalize("NFKD", u"%s" % d.name).encode("ascii", "ignore").lower() in list(
                normalize("NFKD", u"%s" % col["name"]).encode("ascii", "ignore").lower() for col in Association.objects.values("name").exclude(id=d.id)
                ):
                raise Exception(("Asociación <b>%(name)s</b> ya existe.") % {"name":d.name})

            # salvar registro
            d.save()
            raise Exception(("Asociación <b>%(name)s</b> ya existe.") % {"name":d.name})
            if d.id:
                Message.info(request, ("Asociación <b>%(name)s</b> ha sido actualizado correctamente.") % {"name":d.name})

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
Пример #3
0
def enterprise_index(request):
    """
    Página principal para trabajar con empresas
    """
    try:
        d = get_object_or_404(Association,
                              id=DataAccessToken.get_association_id(
                                  request.session))
    except:
        Message.error(request, (
            "Asociación no seleccionada o no se encuentra en la base de datos."
        ))
        return Redirect.to(request, "/home/choice_headquar/")
    enterprise_list = None
    try:
        subq = "SELECT COUNT(*) as count_sedes FROM space_headquar WHERE space_headquar.enterprise_id = space_enterprise.id"  # mejor usar {{ d.headquar_set.all.count }} y listo, trate de no usar {{ d.num_sedes_all }}
        # enterprise_list = Enterprise.objects.filter(headquar__association_id=DataAccessToken.get_association_id(request.session)).annotate(num_sedes=Count("headquar")).order_by("-id").distinct().extra(select={"num_sedes_all": subq})
        enterprise_list = Enterprise.objects.filter(
            headquar__association_id=DataAccessToken.get_association_id(
                request.session)).annotate(
                    num_sedes=Count("headquar")).order_by("-id").distinct()
        # enterprise_list2= Enterprise.objects.filter(headquar__enterprise_id=DataAccessToken.get_enterprise_id(request.session)).annotate(num_sedes_all=Count("headquar")).distinct()
        # enterprise_list =enterprise_list1.add(num_sedes_all="e")
        # enterprise_list = chain(enterprise_list1, enterprise_list2)
        # enterprise_list= [s.id for s in sets.Set(enterprise_list1).intersection(sets.Set(enterprise_list2))]
        # enterprise_list=enterprise_list.distinct()
    except Exception, e:
        Message.error(request, e)
Пример #4
0
def headquar_index(request):
    """
    Página principal para trabajar con sedes
    """
    try:
        enterprise = get_object_or_404(Enterprise, id=DataAccessToken.get_enterprise_id(request.session))
    except:
        Message.error(request, ("Empresa no seleccionada o no se encuentra en la base de datos."))
        return Redirect.to(request, "/home/choice_headquar/")
    try:
        headquar_list = Headquar.objects.filter(enterprise_id=DataAccessToken.get_enterprise_id(request.session)).order_by("-id")
    except Exception, e:
        Message.error(request, e)
Пример #5
0
def enterprise_edit_current(request):
    """
    Actualiza datos de la empresa a la que ingresó el usuario
    """
    d = Enterprise()
    try:
        d = get_object_or_404(Enterprise,
                              id=DataAccessToken.get_enterprise_id(
                                  request.session))
    except:
        Message.error(
            request,
            ("Empresa no seleccionada o no se encuentra en la base de datos."))
        return Redirect.to(request, "/home/choice_headquar/")

    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.name = request.POST.get("name")
            d.tax_id = request.POST.get("tax_id")
            d.type_e = request.POST.get("type_e")
            d.solution_id = request.POST.get("solution_id")
            d.logo = request.POST.get("empresa_logo")
            # solution=Solution.objects.get(id=d.solution_id) #no es necesario
            if normalize("NFKD", u"%s" % d.name).encode(
                    "ascii", "ignore").lower() in list(
                        normalize("NFKD", u"%s" % col["name"]).encode(
                            "ascii", "ignore").lower()
                        for col in Enterprise.objects.values("name").exclude(
                            id=d.id)):
                raise Exception(
                    ("Empresa <b>%(name)s</b> ya existe.") % {"name": d.name})

            if Enterprise.objects.exclude(id=d.id).filter(
                    tax_id=d.tax_id).count() > 0:
                raise Exception("La empresa con RUC <b>%s</b> ya existe " %
                                (d.tax_id))

            # salvar registro
            d.save()
            if d.id:
                Message.info(request, (
                    "Empresa <b>%(name)s</b> ha sido actualizado correctamente."
                ) % {"name": d.name})

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
Пример #6
0
def association_edit_current(request):
    """
    Actualiza datos de la asociación a la que ingresó el usuario
    """
    d = Association()
    try:
        d = get_object_or_404(Association,
                              id=DataAccessToken.get_association_id(
                                  request.session))
    except:
        Message.error(request, (
            "Asociación no seleccionada o no se encuentra en la base de datos."
        ))
        return Redirect.to(request, "/home/choice_headquar/")

    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.name = request.POST.get("name")
            d.type_a = request.POST.get("type_a")
            d.solution_id = request.POST.get("solution_id")
            # solution=Solution.objects.get(id=d.solution_id) #no es necesario
            d.logo = request.POST.get("asociacion_logo")
            if normalize("NFKD", u"%s" % d.name).encode(
                    "ascii", "ignore").lower() in list(
                        normalize("NFKD", u"%s" % col["name"]).encode(
                            "ascii", "ignore").lower()
                        for col in Association.objects.values("name").exclude(
                            id=d.id)):
                raise Exception(("Asociación <b>%(name)s</b> ya existe.") %
                                {"name": d.name})

            # salvar registro
            d.save()
            raise Exception(
                ("Asociación <b>%(name)s</b> ya existe.") % {"name": d.name})
            if d.id:
                Message.info(request, (
                    "Asociación <b>%(name)s</b> ha sido actualizado correctamente."
                ) % {"name": d.name})

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
Пример #7
0
def headquar_index(request):
    """
    Página principal para trabajar con sedes
    """
    try:
        enterprise = get_object_or_404(Enterprise,
                                       id=DataAccessToken.get_enterprise_id(
                                           request.session))
    except:
        Message.error(
            request,
            ("Empresa no seleccionada o no se encuentra en la base de datos."))
        return Redirect.to(request, "/home/choice_headquar/")
    try:
        headquar_list = Headquar.objects.filter(
            enterprise_id=DataAccessToken.get_enterprise_id(
                request.session)).order_by("-id")
    except Exception, e:
        Message.error(request, e)
Пример #8
0
def enterprise_index(request):
    """
    Página principal para trabajar con empresas
    """
    try:
        d = get_object_or_404(Association, id=DataAccessToken.get_association_id(request.session))
    except:
        Message.error(request, ("Asociación no seleccionada o no se encuentra en la base de datos."))
        return Redirect.to(request, "/home/choice_headquar/")
    enterprise_list = None
    try:
        subq = "SELECT COUNT(*) as count_sedes FROM space_headquar WHERE space_headquar.enterprise_id = space_enterprise.id"  # mejor usar {{ d.headquar_set.all.count }} y listo, trate de no usar {{ d.num_sedes_all }}
        # enterprise_list = Enterprise.objects.filter(headquar__association_id=DataAccessToken.get_association_id(request.session)).annotate(num_sedes=Count("headquar")).order_by("-id").distinct().extra(select={"num_sedes_all": subq})
        enterprise_list = Enterprise.objects.filter(headquar__association_id=DataAccessToken.get_association_id(request.session)).annotate(num_sedes=Count("headquar")).order_by("-id").distinct()
        # enterprise_list2= Enterprise.objects.filter(headquar__enterprise_id=DataAccessToken.get_enterprise_id(request.session)).annotate(num_sedes_all=Count("headquar")).distinct()
        # enterprise_list =enterprise_list1.add(num_sedes_all="e")
        # enterprise_list = chain(enterprise_list1, enterprise_list2)
        # enterprise_list= [s.id for s in sets.Set(enterprise_list1).intersection(sets.Set(enterprise_list2))]
        # enterprise_list=enterprise_list.distinct()
    except Exception, e:
        Message.error(request, e)
Пример #9
0
def producto_index(request, field="descripcion", value="None", order="-id"):
    """
    Página principal para trabajar con productos
    """
    try:
        headquar = get_object_or_404(Headquar,
                                     id=DataAccessToken.get_headquar_id(
                                         request.session))
    except:
        Message.error(
            request,
            ("Sede no seleccionado o no se encuentra en la base de datos."))
        return Redirect.to(request, "/home/choice_headquar/")

    field = (field if not request.REQUEST.get("field") else
             request.REQUEST.get("field")).strip()
    value = (value if not request.REQUEST.get("value") else
             request.REQUEST.get("value")).strip()
    order = (order if not request.REQUEST.get("order") else
             request.REQUEST.get("order")).strip()

    producto_page = None
    try:
        value_f = "" if value == "None" else value
        column_contains = u"%s__%s" % (field, "contains")
        producto_list = Producto.objects.filter(headquar=headquar).filter(
            **{
                column_contains: value_f
            }).order_by(order)
        paginator = Paginator(producto_list, 20)
        try:
            producto_page = paginator.page(request.GET.get("page"))
        except PageNotAnInteger:
            producto_page = paginator.page(1)
        except EmptyPage:
            producto_page = paginator.page(paginator.num_pages)
    except Exception, e:
        Message.error(request, e)
Пример #10
0
def enterprise_edit_current(request):
    """
    Actualiza datos de la empresa a la que ingresó el usuario
    """
    d = Enterprise()
    try:
        d = get_object_or_404(Enterprise, id=DataAccessToken.get_enterprise_id(request.session))
    except:
        Message.error(request, ("Empresa no seleccionada o no se encuentra en la base de datos."))
        return Redirect.to(request, "/home/choice_headquar/")

    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.name = request.POST.get("name")
            d.tax_id = request.POST.get("tax_id")
            d.type_e = request.POST.get("type_e")
            d.solution_id = request.POST.get("solution_id")
            d.logo = request.POST.get("empresa_logo")
            # solution=Solution.objects.get(id=d.solution_id) #no es necesario
            if normalize("NFKD", u"%s" % d.name).encode("ascii", "ignore").lower() in list(
                normalize("NFKD", u"%s" % col["name"]).encode("ascii", "ignore").lower() for col in Enterprise.objects.values("name").exclude(id=d.id)
                ):
                raise Exception(("Empresa <b>%(name)s</b> ya existe.") % {"name":d.name})

            if Enterprise.objects.exclude(id=d.id).filter(tax_id=d.tax_id).count() > 0:
                raise Exception("La empresa con RUC <b>%s</b> ya existe " % (d.tax_id))

            # salvar registro
            d.save()
            if d.id:
                Message.info(request, ("Empresa <b>%(name)s</b> ha sido actualizado correctamente.") % {"name":d.name})

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
Пример #11
0
def add_enterprise(request):

    d = Enterprise()
    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.enterprise_name = request.POST.get("enterprise_name")
            d.enterprise_tax_id = request.POST.get("enterprise_tax_id")
            d.association_name = request.POST.get("association_name")
            d.association_type_a = request.POST.get("association_type_a")
            d.solution_id = request.POST.get("solution_id")
            
            solution = Solution.objects.get(id=d.solution_id)
            d.logo = request.POST.get("empresa_logo")
            user = request.user
            
            association = Association(name=d.association_name, type_a=d.association_type_a, solution=solution, logo=d.logo)
            if normalize("NFKD", u"%s" % d.association_name).encode("ascii", "ignore").lower() in list(
                normalize("NFKD", u"%s" % col["name"]).encode("ascii", "ignore").lower() for col in Association.objects.values("name")
                ):
                raise Exception("La asociación <b>%s</b> ya existe " % (d.association_name))
            association.save()

            enterprise = Enterprise(name=d.enterprise_name, tax_id=d.enterprise_tax_id, type_e=d.association_type_a, solution=solution, logo=d.logo)
            if normalize("NFKD", u"%s" % d.enterprise_name).encode("ascii", "ignore").lower() in list(
                normalize("NFKD", u"%s" % col["name"]).encode("ascii", "ignore").lower() for col in Enterprise.objects.values("name")
                ):
                raise Exception("La empresa <b>%s</b> ya existe " % (d.enterprise_name))
            if Enterprise.objects.filter(tax_id=d.enterprise_tax_id).count() > 0:
                raise Exception("La empresa con RUC <b>%s</b> ya existe " % (d.enterprise_tax_id))
            enterprise.save()

            headquar = Headquar(name="Principal", association=association, enterprise=enterprise)
            headquar.save()
            
            # asigna permisos al usuario para manipular datos de cierta sede, empresa o asociación
            group_dist_list = []
            for module in solution.module_set.all():  # .distinct()    
                for group in module.initial_groups.all() :
                    if len(group_dist_list) == 0 :
                        group_dist_list.append(group.id)
                        user.groups.add(group)
                        
                        user_profile_association = UserProfileAssociation()
                        user_profile_association.user = user
                        user_profile_association.association = association
                        user_profile_association.group = group
                        user_profile_association.save()

                        user_profile_enterprise = UserProfileEnterprise()
                        user_profile_enterprise.user = user
                        user_profile_enterprise.enterprise = enterprise
                        user_profile_enterprise.group = group
                        user_profile_enterprise.save()
                        
                        user_profile_headquar = UserProfileHeadquar()
                        user_profile_headquar.user = user
                        user_profile_headquar.headquar = headquar
                        user_profile_headquar.group = group
                        user_profile_headquar.save()
                    else :
                        if group.id not in group_dist_list:
                            group_dist_list.append(group.id)
                            user.groups.add(group)

                            user_profile_association = UserProfileAssociation()
                            user_profile_association.user = user
                            user_profile_association.association = association
                            user_profile_association.group = group
                            user_profile_association.save()

                            user_profile_enterprise = UserProfileEnterprise()
                            user_profile_enterprise.user = user
                            user_profile_enterprise.enterprise = enterprise
                            user_profile_enterprise.group = group
                            user_profile_enterprise.save()
                            
                            user_profile_headquar = UserProfileHeadquar()
                            user_profile_headquar.user = user
                            user_profile_headquar.headquar = headquar
                            user_profile_headquar.group = group
                            user_profile_headquar.save()
            Message.info(request, ("Empresa <b>%(name)s</b> ha sido registrado correctamente!.") % {"name":d.enterprise_name})
            return Redirect.to(request, "/accounts/choice_headquar/")
        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
Пример #12
0
def load_access(request, headquar_id, module_id):
    if request.is_ajax():
        return HttpResponse("ESTA OPERACION NO DEBE SER CARGADO CON AJAX, Presione F5")
    else:
        try:
            try:
                headquar = Headquar.objects.get(id=headquar_id)
            except:
                Message.error(request, ("Sede no seleccionado o no se encuentra en la base de datos."))
                return Redirect.to(request, "/accounts/choice_headquar/")
            try:
                module = Module.objects.get(id=module_id)
            except:
                Message.error(request, ("Módulo no seleccionado o no se encuentra en la base de datos."))
                return Redirect.to(request, "/accounts/choice_headquar/")

            if not request.user.is_superuser:  # vovler a verificar si tiene permisos
                # obteniendo las sedes a la cual tiene acceso
                headquar_list = Headquar.objects.filter(userprofileheadquar__user__id=request.user.id).distinct()
                if headquar not in headquar_list:
                    raise Exception(("Acceso denegado. No tiene privilegio para ingresar a esta sede: %s %s." % (headquar.enterprise.name, headquar.name)))
                # obteniendo los módulos a la cual tiene acceso
                group_list = Group.objects.filter(userprofileheadquar__headquar__id=headquar.id, userprofileheadquar__user__id=request.user.id).distinct()
                module_list = Module.objects.filter(groups__in=group_list).distinct()
                
                if module not in module_list:
                    raise Exception(("Acceso denegado. No tiene privilegio para ingresar a este módulo: %s de %s %s." % (module.name, headquar.enterprise.name, headquar.name)))
                
            # cargando permisos de datos para el usuario
            DataAccessToken.set_association_id(request, headquar.association.id)
            DataAccessToken.set_enterprise_id(request, headquar.enterprise.id)
            DataAccessToken.set_headquar_id(request, headquar.id)

            try:
                profile = Profile.objects.get(user_id=request.user.id)
                if profile.id:
                    profile.last_headquar_id = headquar_id
                    profile.last_module_id = module_id
                    profile.save()
            except:
                person = Person(first_name=request.user.first_name, last_name=request.user.last_name)
                person.save()

                profile = Profile(user=request.user, last_headquar_id=headquar_id, last_module_id=module_id)
                profile.person = person
                profile.save()
                pass

            # Message.info(request, ("La sede %(name)s ha sido cargado correctamente.") % {"name":headquar_id} )
            if module.BACKEND == module.module:
                return Redirect.to(request, "/mod_backend/dashboard/")
            if module.VENTAS == module.module:
                return Redirect.to(request, "/mod_ventas/dashboard/")
            if module.PRO == module.module:
                return Redirect.to(request, "/mod_pro/dashboard/")
            # TODO agregue aqui su nuevo modulo
            else:
                Message.error(request, "Módulo no definido")
                return HttpResponseRedirect("/accounts/choice_headquar/")
        except Exception, e:
            Message.error(request, e)
        return HttpResponseRedirect("/accounts/choice_headquar/")
Пример #13
0
                ):
                raise Exception("La persona <b>%s %s</b> y %s:<b>%s</b> ya existe " % (d.first_name, d.last_name, identity_type_display, d.identity_num))
            if Person.objects.exclude(id=person.id).filter(identity_type=d.identity_type, identity_num=d.identity_num).count() > 0:
                raise Exception("La persona con %s:<b>%s</b> ya existe " % (identity_type_display, d.identity_num))
            
            person.first_name = request.POST.get("first_name")
            person.last_name = request.POST.get("last_name")
            person.identity_type = request.POST.get("identity_type")
            person.identity_num = request.POST.get("identity_num")
            person.photo = request.POST.get("persona_fotografia")

            person.save()
            d.photo = person.photo
            if d.id:
                Message.info(request, ("Usuario <b>%(name)s</b> ha sido actualizado correctamente.") % {"name":d.username}, True)
                return Redirect.to(request, "/accounts/choice_headquar/")

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
            
    try:
        
        user_profile_headquar_list = UserProfileHeadquar.objects.filter(user=d).order_by("headquar")
        user_profile_enterprise_list = UserProfileEnterprise.objects.filter(user=d).order_by("enterprise")
        user_profile_association_list = UserProfileAssociation.objects.filter(user=d).order_by("association")

    except Exception, e:
        Message.error(request, e)
    c = {
        "page_module":("Perfil del usuario"),
Пример #14
0
def load_access(request, headquar_id, module_id):
    if request.is_ajax():
        return HttpResponse(
            "ESTA OPERACION NO DEBE SER CARGADO CON AJAX, Presione F5")
    else:
        try:
            try:
                headquar = Headquar.objects.get(id=headquar_id)
            except:
                Message.error(request, (
                    "Sede no seleccionado o no se encuentra en la base de datos."
                ))
                return Redirect.to(request, "/accounts/choice_headquar/")
            try:
                module = Module.objects.get(id=module_id)
            except:
                Message.error(request, (
                    "Módulo no seleccionado o no se encuentra en la base de datos."
                ))
                return Redirect.to(request, "/accounts/choice_headquar/")

            if not request.user.is_superuser:  # vovler a verificar si tiene permisos
                # obteniendo las sedes a la cual tiene acceso
                headquar_list = Headquar.objects.filter(
                    userprofileheadquar__user__id=request.user.id).distinct()
                if headquar not in headquar_list:
                    raise Exception((
                        "Acceso denegado. No tiene privilegio para ingresar a esta sede: %s %s."
                        % (headquar.enterprise.name, headquar.name)))
                # obteniendo los módulos a la cual tiene acceso
                group_list = Group.objects.filter(
                    userprofileheadquar__headquar__id=headquar.id,
                    userprofileheadquar__user__id=request.user.id).distinct()
                module_list = Module.objects.filter(
                    groups__in=group_list).distinct()

                if module not in module_list:
                    raise Exception((
                        "Acceso denegado. No tiene privilegio para ingresar a este módulo: %s de %s %s."
                        % (module.name, headquar.enterprise.name,
                           headquar.name)))

            # cargando permisos de datos para el usuario
            DataAccessToken.set_association_id(request,
                                               headquar.association.id)
            DataAccessToken.set_enterprise_id(request, headquar.enterprise.id)
            DataAccessToken.set_headquar_id(request, headquar.id)

            try:
                profile = Profile.objects.get(user_id=request.user.id)
                if profile.id:
                    profile.last_headquar_id = headquar_id
                    profile.last_module_id = module_id
                    profile.save()
            except:
                person = Person(first_name=request.user.first_name,
                                last_name=request.user.last_name)
                person.save()

                profile = Profile(user=request.user,
                                  last_headquar_id=headquar_id,
                                  last_module_id=module_id)
                profile.person = person
                profile.save()
                pass

            # Message.info(request, ("La sede %(name)s ha sido cargado correctamente.") % {"name":headquar_id} )
            if module.BACKEND == module.module:
                return Redirect.to(request, "/mod_backend/dashboard/")
            if module.VENTAS == module.module:
                return Redirect.to(request, "/mod_ventas/dashboard/")
            if module.PRO == module.module:
                return Redirect.to(request, "/mod_pro/dashboard/")
            # TODO agregue aqui su nuevo modulo
            else:
                Message.error(request, "Módulo no definido")
                return HttpResponseRedirect("/accounts/choice_headquar/")
        except Exception, e:
            Message.error(request, e)
        return HttpResponseRedirect("/accounts/choice_headquar/")
Пример #15
0
def add_enterprise(request):

    d = Enterprise()
    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.enterprise_name = request.POST.get("enterprise_name")
            d.enterprise_tax_id = request.POST.get("enterprise_tax_id")
            d.association_name = request.POST.get("association_name")
            d.association_type_a = request.POST.get("association_type_a")
            d.solution_id = request.POST.get("solution_id")

            solution = Solution.objects.get(id=d.solution_id)
            d.logo = request.POST.get("empresa_logo")
            user = request.user

            association = Association(name=d.association_name,
                                      type_a=d.association_type_a,
                                      solution=solution,
                                      logo=d.logo)
            if normalize("NFKD", u"%s" % d.association_name).encode(
                    "ascii", "ignore").lower() in list(
                        normalize("NFKD", u"%s" % col["name"]).encode(
                            "ascii", "ignore").lower()
                        for col in Association.objects.values("name")):
                raise Exception("La asociación <b>%s</b> ya existe " %
                                (d.association_name))
            association.save()

            enterprise = Enterprise(name=d.enterprise_name,
                                    tax_id=d.enterprise_tax_id,
                                    type_e=d.association_type_a,
                                    solution=solution,
                                    logo=d.logo)
            if normalize("NFKD", u"%s" % d.enterprise_name).encode(
                    "ascii", "ignore").lower() in list(
                        normalize("NFKD", u"%s" % col["name"]).encode(
                            "ascii", "ignore").lower()
                        for col in Enterprise.objects.values("name")):
                raise Exception("La empresa <b>%s</b> ya existe " %
                                (d.enterprise_name))
            if Enterprise.objects.filter(
                    tax_id=d.enterprise_tax_id).count() > 0:
                raise Exception("La empresa con RUC <b>%s</b> ya existe " %
                                (d.enterprise_tax_id))
            enterprise.save()

            headquar = Headquar(name="Principal",
                                association=association,
                                enterprise=enterprise)
            headquar.save()

            # asigna permisos al usuario para manipular datos de cierta sede, empresa o asociación
            group_dist_list = []
            for module in solution.module_set.all():  # .distinct()
                for group in module.initial_groups.all():
                    if len(group_dist_list) == 0:
                        group_dist_list.append(group.id)
                        user.groups.add(group)

                        user_profile_association = UserProfileAssociation()
                        user_profile_association.user = user
                        user_profile_association.association = association
                        user_profile_association.group = group
                        user_profile_association.save()

                        user_profile_enterprise = UserProfileEnterprise()
                        user_profile_enterprise.user = user
                        user_profile_enterprise.enterprise = enterprise
                        user_profile_enterprise.group = group
                        user_profile_enterprise.save()

                        user_profile_headquar = UserProfileHeadquar()
                        user_profile_headquar.user = user
                        user_profile_headquar.headquar = headquar
                        user_profile_headquar.group = group
                        user_profile_headquar.save()
                    else:
                        if group.id not in group_dist_list:
                            group_dist_list.append(group.id)
                            user.groups.add(group)

                            user_profile_association = UserProfileAssociation()
                            user_profile_association.user = user
                            user_profile_association.association = association
                            user_profile_association.group = group
                            user_profile_association.save()

                            user_profile_enterprise = UserProfileEnterprise()
                            user_profile_enterprise.user = user
                            user_profile_enterprise.enterprise = enterprise
                            user_profile_enterprise.group = group
                            user_profile_enterprise.save()

                            user_profile_headquar = UserProfileHeadquar()
                            user_profile_headquar.user = user
                            user_profile_headquar.headquar = headquar
                            user_profile_headquar.group = group
                            user_profile_headquar.save()
            Message.info(
                request,
                ("Empresa <b>%(name)s</b> ha sido registrado correctamente!.")
                % {"name": d.enterprise_name})
            return Redirect.to(request, "/accounts/choice_headquar/")
        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
Пример #16
0
                raise Exception("La persona con %s:<b>%s</b> ya existe " %
                                (identity_type_display, d.identity_num))

            person.first_name = request.POST.get("first_name")
            person.last_name = request.POST.get("last_name")
            person.identity_type = request.POST.get("identity_type")
            person.identity_num = request.POST.get("identity_num")
            person.photo = request.POST.get("persona_fotografia")

            person.save()
            d.photo = person.photo
            if d.id:
                Message.info(request, (
                    "Usuario <b>%(name)s</b> ha sido actualizado correctamente."
                ) % {"name": d.username}, True)
                return Redirect.to(request, "/accounts/choice_headquar/")

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)

    try:

        user_profile_headquar_list = UserProfileHeadquar.objects.filter(
            user=d).order_by("headquar")
        user_profile_enterprise_list = UserProfileEnterprise.objects.filter(
            user=d).order_by("enterprise")
        user_profile_association_list = UserProfileAssociation.objects.filter(
            user=d).order_by("association")

    except Exception, e: