예제 #1
0
def solution_state(request, state, key):
    """
    Inactiva y reactiva el estado del la solución/plan
    """
    id = SecurityKey.is_valid_key(request, key, "solution_%s" % state)
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Solution, id=id)
    except:
        Message.error(request, ("Solución no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")
    try:
        if state == "inactivar" and d.is_active == False:
            Message.error(request, ("La solución ya se encuentra inactivo."))
        else:
            if state == "reactivar" and d.is_active == True:
                Message.error(request, ("La solución ya se encuentra activo."))
            else:
                d.is_active = (True if state == "reactivar" else False)
                d.save()
                if d.id:
                    if d.is_active:
                        Message.info(request, ("Solución <b>%(name)s</b> ha sido reactivado correctamente.") % {"name":d.name}, True)
                    else:
                        Message.info(request, ("Solución <b>%(name)s</b> ha sido inactivado correctamente.") % {"name":d.name}, True)
                    return Redirect.to_action(request, "index")
    except Exception, e:
        Message.error(request, e)
        return Redirect.to_action(request, "index")
예제 #2
0
def producto_delete(request, key):
    """
    Elimina producto
    """
    id = SecurityKey.is_valid_key(request, key, "producto_del")
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Producto, id=id)
    except:
        Message.error(request,
                      ("Producto no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")
    try:
        # sid = transaction.savepoint()
        d.delete()
        if not d.id:
            Message.info(
                request,
                ("Producto <b>%(codigo)s</b> ha sido eliminado correctamente.")
                % {"codigo": d.codigo}, True)
            return Redirect.to_action(request, "index")
    except Exception, e:
        # transaction.savepoint_rollback(sid)
        Message.error(request, e)
        return Redirect.to_action(request, "index")
예제 #3
0
def enterprise_delete(request, key):
    """
    Elimina empresa con todas sus sedes
    """
    id = SecurityKey.is_valid_key(request, key, "enterprise_del")
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Enterprise, id=id)
    except:
        Message.error(request, ("Empresa no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")
    try:
        sid = transaction.savepoint()
        association = Association.objects.get(id=DataAccessToken.get_association_id(request.session))
        if Enterprise.objects.filter(headquar__association_id=DataAccessToken.get_association_id(request.session)).count() == 1:
            raise Exception(("Asociación <b>%(name)s</b> no puede quedar sin ninguna sede asociada.") % {"name":association.name})        
        if d.userprofileenterprise_set.count() > 0:
            raise Exception(("Empresa <b>%(name)s</b> tiene usuarios y grupos asignados.") % {"name":d.name})
        # agregue aquí sus otras relgas de negocio
        d.delete()
        if not d.id:
            Message.info(request, ("Empresa <b>%(name)s</b> ha sido eliminado correctamente.") % {"name":d.name}, True)
            return Redirect.to_action(request, "index")
    except Exception, e:
        transaction.savepoint_rollback(sid)
        Message.error(request, e)
        return Redirect.to_action(request, "index")
예제 #4
0
파일: views.py 프로젝트: jdcali/backenddj
def solution_state(request, state, key):
    """
    Inactiva y reactiva el estado del la solución/plan
    """
    id = SecurityKey.is_valid_key(request, key, "solution_%s" % state)
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Solution, id=id)
    except:
        Message.error(request,
                      ("Solución no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")
    try:
        if state == "inactivar" and d.is_active == False:
            Message.error(request, ("La solución ya se encuentra inactivo."))
        else:
            if state == "reactivar" and d.is_active == True:
                Message.error(request, ("La solución ya se encuentra activo."))
            else:
                d.is_active = (True if state == "reactivar" else False)
                d.save()
                if d.id:
                    if d.is_active:
                        Message.info(request, (
                            "Solución <b>%(name)s</b> ha sido reactivado correctamente."
                        ) % {"name": d.name}, True)
                    else:
                        Message.info(request, (
                            "Solución <b>%(name)s</b> ha sido inactivado correctamente."
                        ) % {"name": d.name}, True)
                    return Redirect.to_action(request, "index")
    except Exception, e:
        Message.error(request, e)
        return Redirect.to_action(request, "index")
예제 #5
0
def headquar_delete(request, key):
    """
    Elimina sede
    """
    id = SecurityKey.is_valid_key(request, key, "headquar_del")
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Headquar, id=id)
    except:
        Message.error(request, ("Sede no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")
    try:
        if d.enterprise.headquar_set.count() == 1:
            raise Exception(("Empresa <b>%(name)s</b> no puede quedar sin ninguna sede.") % {"name":d.enterprise.name})
        if d.userprofileheadquar_set.count() > 0:
            raise Exception(("Sede <b>%(name)s de %(empresa)s</b> tiene usuarios y grupos asignados.") % {"name":d.name, "empresa":d.enterprise.name})
        
        # agregue aquí sus otras relgas de negocio
        d.delete()
        if not d.id:
            Message.info(request, ("Sede <b>%(name)s de %(empresa)s</b> ha sido eliminado correctamente.") % {"name":d.name, "empresa":d.enterprise.name}, True)
            return Redirect.to_action(request, "index")
    except Exception, e:
        Message.error(request, e)
        return Redirect.to_action(request, "index")
예제 #6
0
def headquar_change_association(request, key):
    """
    Cambia de asociación a la sede
    """
    id = SecurityKey.is_valid_key(request, key, "headquar_cha")
    if not id:
        return Redirect.to_action(request, "index")
    d = None

    try:
        d = get_object_or_404(Headquar, id=id)
        if d.association:
            d.association_name = d.association.name
    except:
        Message.error(request, ("Sede no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")

    if request.method == "POST":
        try:
            # d.association_id = DataAccessToken.get_association_id(request.session)
            d.association_name = request.POST.get("association_name")
            try:
                d.association = Association.objects.get(name=d.association_name)
            except:
                raise Exception("La asociación <b>%s</b> no existe, vuelva a intentar " % (request.POST.get("association_name")))
            # salvar registro
            d.save()
            if d.id:
                Message.info(request, ("Sede <b>%(name)s</b> ha sido cambiado de asociación correctamente.") % {"name":d.name})
                return Redirect.to_action(request, "index")

        except Exception, e:
            
            Message.error(request, e)
예제 #7
0
파일: views.py 프로젝트: jdcali/backenddj
def solution_edit(request, key):
    """
    Actualiza solución
    """
    id = SecurityKey.is_valid_key(request, key, "solution_upd")
    if not id:
        return Redirect.to_action(request, "index")
    d = None

    try:
        d = get_object_or_404(Solution, id=id)
    except:
        Message.error(request,
                      ("Solución no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")

    if request.method == "POST":
        try:
            d.name = request.POST.get("name")
            d.description = request.POST.get("description")
            if Solution.objects.exclude(id=d.id).filter(
                    name=d.name).count() > 0:
                raise Exception(
                    ("Solución <b>%(name)s</b> ya existe.") % {"name": d.name})

            # salvar registro
            d.save()
            if d.id:
                Message.info(request, (
                    "Solución <b>%(name)s</b> ha sido actualizado correctamente."
                ) % {"name": d.name})
                return Redirect.to_action(request, "index")

        except Exception, e:
            Message.error(request, e)
예제 #8
0
def solution_edit(request, key):
    """
    Actualiza solución
    """
    id = SecurityKey.is_valid_key(request, key, "solution_upd")
    if not id:
        return Redirect.to_action(request, "index")
    d = None

    try:
        d = get_object_or_404(Solution, id=id)
    except:
        Message.error(request, ("Solución no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")

    if request.method == "POST":
        try:
            d.name = request.POST.get("name")
            d.description = request.POST.get("description")
            if Solution.objects.exclude(id=d.id).filter(name=d.name).count() > 0:
                raise Exception(("Solución <b>%(name)s</b> ya existe.") % {"name":d.name})

            # salvar registro
            d.save()
            if d.id:
                Message.info(request, ("Solución <b>%(name)s</b> ha sido actualizado correctamente.") % {"name":d.name})
                return Redirect.to_action(request, "index")

        except Exception, e:
            Message.error(request, e)
예제 #9
0
def solution_delete(request, key):
    """
    Elimina solución
    """
    id = SecurityKey.is_valid_key(request, key, "solution_del")
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Solution, id=id)
    except:
        Message.error(request, ("Solución no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")
    try:
        # rastreando dependencias
        if d.module_set.count() > 0:
            raise Exception(("Solución <b>%(name)s</b> tiene módulos asignados.") % {"name":d.name})
        if d.association_set.count() > 0:
            raise Exception(("Solución <b>%(name)s</b> está asignado en asociaciones.") % {"name":d.name})
        if d.enterprise_set.count() > 0:
            raise Exception(("Solución <b>%(name)s</b> está asignado en empresas.") % {"name":d.name})
        d.delete()
        if not d.id:
            Message.info(request, ("Solución <b>%(name)s</b> ha sido eliminado correctamente.") % {"name":d.name}, True)
            return Redirect.to_action(request, "index")
    except Exception, e:
        Message.error(request, e)
        return Redirect.to_action(request, "index")
# endregion solution
예제 #10
0
파일: views.py 프로젝트: jdcali/backenddj
def enterprise_edit(request, key):
    """
    Actualiza empresa
    """
    id = SecurityKey.is_valid_key(request, key, "enterprise_upd")
    if not id:
        return Redirect.to_action(request, "index")
    d = None

    try:
        d = get_object_or_404(Enterprise, id=id)
    except:
        Message.error(request,
                      ("Empresa no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")

    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")
            # 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})
                return Redirect.to_action(request, "index")

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
예제 #11
0
파일: views.py 프로젝트: jdcali/backenddj
def headquar_edit(request, key):
    """
    Actualiza sede
    """
    id = SecurityKey.is_valid_key(request, key, "headquar_upd")
    if not id:
        return Redirect.to_action(request, "index")
    d = None
    try:
        d = get_object_or_404(Headquar, id=id)
        if d.locality:
            d.locality_name = d.locality.name
    except:
        Message.error(request, ("Sede no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")

    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.name = request.POST.get("name")
            d.phone = request.POST.get("phone")
            d.address = request.POST.get("address")
            d.locality_name = request.POST.get("locality_name").strip()
            if request.POST.get("locality_name").strip():
                d.locality, is_locality_created = Locality.objects.get_or_create(
                    name=request.POST.get(
                        "locality_name").strip(),  # name__iexact
                )
            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 Headquar.objects.values("name").exclude(
                            id=d.id).filter(enterprise_id=d.enterprise_id)):
                raise Exception("La sede <b>%s</b> ya existe " % (d.name))

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

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
예제 #12
0
파일: views.py 프로젝트: jdcali/backenddj
def locality_add(request):
    d = Locality()
    d.msnm = 0
    d.date_create =""
    if request.method == "POST":
        try:
            # Aquí asignar los datos
            d.name = request.POST.get("name")
            d.msnm = request.POST.get("msnm")
            d.date_create = None
            if request.POST.get("date_create"):
                d.date_create = request.POST.get("date_create")
            if request.POST.get("locality_type_id"):
                d.locality_type = LocalityType.objects.get(id=request.POST.get("locality_type_id"))

            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 Locality.objects.values("name").exclude(id=d.id)  # puede .filter()
                ):
                raise Exception(_("Locality <b>%(name)s</b> name's already in use.") % {"name":d.name})  # El nombre x para localidad ya existe.
            # salvar registro
            d.save()
            if d.id:
                Message.info(request, ("Localidad <b>%(name)s</b> ha sido registrado correctamente.") % {"name":d.name}, True)
                # return Redirect.to(request, "/params/locality/index/")#usar to(...) cuando la acción está implementada en otra app, ver sad.views.user_index
                return Redirect.to_action(request, "index")  # usar to_action(...) cuando la acción está implementada en este archivo
        except Exception, e:
            Message.error(request, e)
예제 #13
0
def headquar_add(request):
    """
    Agrega sede
    """
    d = Headquar()
    d.phone = ""
    d.address = ""
    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.name = request.POST.get("name")
            d.phone = request.POST.get("phone")
            d.address = request.POST.get("address")
            d.is_main = False
            d.locality_name = request.POST.get("locality_name")
            if request.POST.get("locality_name"):
                d.locality, is_locality_created = Locality.objects.get_or_create(
                    name=request.POST.get("locality_name"),  # name__iexact
                    )
            d.association_id = DataAccessToken.get_association_id(request.session)
            d.enterprise_id = DataAccessToken.get_enterprise_id(request.session)

            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 Headquar.objects.values("name").exclude(id=d.id).filter(enterprise_id=d.enterprise_id)
                ):
                raise Exception("La sede <b>%s</b> ya existe " % (d.name))
            d.save()
            if d.id:
                Message.info(request, ("Sede <b>%(name)s</b> ha sido registrado correctamente.") % {"name":d.name})
                return Redirect.to_action(request, "index")
        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
예제 #14
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)
예제 #15
0
파일: views.py 프로젝트: jdcali/backenddj
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)
예제 #16
0
def producto_add(request):
    """
    Agrega Producto
    """
    d = Producto()
    d.descripcion = ""
    d.fecha_venc = ""
    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.codigo = request.POST.get("codigox")
            d.descripcion = request.POST.get("descripcion")
            d.precio_venta = request.POST.get("precio_venta")
            d.headquar_id = DataAccessToken.get_headquar_id(request.session)

            if request.POST.get("fecha_venc"):
                d.fecha_venc = request.POST.get("fecha_venc")

            if request.POST.get("categoria_nombre"):
                d.categoria, is_created = Categoria.objects.get_or_create(
                    nombre=request.POST.get("categoria_nombre"), )

            if Producto.objects.filter(codigo=d.codigo).exclude(
                    id=d.id, headquar_id=d.headquar_id).count() > 0:
                raise Exception("El producto <b>%s</b> ya existe " % d.codigo)
            d.save()
            if d.id:
                Message.info(request, (
                    "Producto <b>%(name)s</b> ha sido registrado correctamente."
                ) % {"name": d.codigo}, True)
                return Redirect.to_action(request, "index")
        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
예제 #17
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)
예제 #18
0
def producto_add(request):
    """
    Agrega Producto
    """
    d = Producto()
    d.descripcion = ""
    d.fecha_venc=""
    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.codigo = request.POST.get("codigox")
            d.descripcion = request.POST.get("descripcion")
            d.precio_venta = request.POST.get("precio_venta")
            d.headquar_id = DataAccessToken.get_headquar_id(request.session)
            
            if request.POST.get("fecha_venc"):
                d.fecha_venc = request.POST.get("fecha_venc")
                
            if request.POST.get("categoria_nombre"):
                d.categoria, is_created = Categoria.objects.get_or_create(
                    nombre=request.POST.get("categoria_nombre"),
                    )

            if Producto.objects.filter(codigo=d.codigo).exclude(id=d.id, headquar_id=d.headquar_id).count() > 0:
                raise Exception("El producto <b>%s</b> ya existe " % d.codigo)
            d.save()
            if d.id:
                Message.info(request, ("Producto <b>%(name)s</b> ha sido registrado correctamente.") % {"name":d.codigo}, True)
                return Redirect.to_action(request, "index")
        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
예제 #19
0
파일: views.py 프로젝트: jdcali/backenddj
def locality_edit(request, key):
    id = SecurityKey.is_valid_key(request, key, "locality_upd")
    if not id:
        return Redirect.to_action(request, "index")
    d = None
    try:
        d = get_object_or_404(Locality, id=id)  # Locality.objects.get(id=id)
    except:  # Locality.DoesNotExist
        Message.error(request, _("Locality not found in the database."))
        return Redirect.to_action(request, "index")

    if request.method == "POST":
        try:
            sid = transaction.savepoint()  # begin transaction, no amerita el decorador @transaction.atomic pero dejadlo para las nuevas version 

            # Aquí asignar los datos
            d.name = request.POST.get("name")
            d.msnm = request.POST.get("msnm")
            if request.POST.get("date_create"):
                d.date_create = request.POST.get("date_create")
            d.is_active = True

            # para probar transaction 
            # locality_type=LocalityType()
            # locality_type.name="Rural5"
            # if LocalityType.objects.filter(name = locality_type.name).count() > 0:
            #     raise Exception(_("LocalityType <b>%(name)s</b> name's already in use.") % {"name":locality_type.name}) #trhow new Exception("msg")
            # locality_type.save()
            # d.locality_type=locality_type

            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 Locality.objects.values("name").exclude(id=d.id)  # puede .filter()
                ):
                raise Exception(_("Locality <b>%(name)s</b> name's already in use.") % {"name":d.name})  # trhow new Exception("msg")
            # salvar registro
            d.save()
            # para probar transaction
            # raise Exception("Error para no salvar. Si funciona")
            if d.id:
                # transaction.savepoint_commit(sid) se colocaría solo al final, pero no amerita pk ya está decorado con @transaction.atomic
                Message.info(request, ("Localidad <b>%(name)s</b> ha sido actualizado correctamente.") % {"name":d.name}, True)
                return Redirect.to_action(request, "index")
        except Exception, e:
            transaction.savepoint_rollback(sid)  # para reversar en caso de error en alguna de las tablas
            Message.error(request, e)
예제 #20
0
파일: views.py 프로젝트: jdcali/backenddj
def enterprise_add(request):
    """
    Agrega empresa dentro de una asociación, para ello deberá agregarse con una sede Principal
    """
    d = Enterprise()
    d.sede = "Principal"
    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")
            # 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))

            d.save()

            headquar = Headquar()
            headquar.name = request.POST.get("sede")
            headquar.association_id = DataAccessToken.get_association_id(
                request.session)
            headquar.enterprise = d

            if normalize("NFKD", u"%s" % headquar.name).encode(
                    "ascii", "ignore").lower() in list(
                        normalize("NFKD", u"%s" % col["name"]).encode(
                            "ascii", "ignore").lower()
                        for col in Headquar.objects.values("name").exclude(
                            id=headquar.id).filter(
                                enterprise_id=headquar.enterprise_id)):
                raise Exception("La sede <b>%s</b> ya existe " %
                                (headquar.name))

            headquar.save()

            if d.id:
                Message.info(request, (
                    "Empresa <b>%(name)s</b> ha sido registrado correctamente."
                ) % {"name": d.name})
                return Redirect.to_action(request, "index")
        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
예제 #21
0
def headquar_edit(request, key):
    """
    Actualiza sede
    """
    id = SecurityKey.is_valid_key(request, key, "headquar_upd")
    if not id:
        return Redirect.to_action(request, "index")
    d = None
    try:
        d = get_object_or_404(Headquar, id=id)
        if d.locality:
            d.locality_name = d.locality.name
    except:
        Message.error(request, ("Sede no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")

    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.name = request.POST.get("name")
            d.phone = request.POST.get("phone")
            d.address = request.POST.get("address")
            d.locality_name = request.POST.get("locality_name").strip()
            if request.POST.get("locality_name").strip():
                d.locality, is_locality_created = Locality.objects.get_or_create(
                    name=request.POST.get("locality_name").strip(),  # name__iexact
                    )
            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 Headquar.objects.values("name").exclude(id=d.id).filter(enterprise_id=d.enterprise_id)
                ):
                raise Exception("La sede <b>%s</b> ya existe " % (d.name))

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

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
예제 #22
0
def enterprise_edit(request, key):
    """
    Actualiza empresa
    """
    id = SecurityKey.is_valid_key(request, key, "enterprise_upd")
    if not id:
        return Redirect.to_action(request, "index")
    d = None

    try:
        d = get_object_or_404(Enterprise, id=id)
    except:
        Message.error(request, ("Empresa no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")

    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")
            # 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})
                return Redirect.to_action(request, "index")

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
예제 #23
0
파일: views.py 프로젝트: jdcali/backenddj
def locality_delete(request, key):
    id = SecurityKey.is_valid_key(request, key, "locality_del")
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Locality, id=id)  # Locality.objects.get(id=id)
    except:  # Locality.DoesNotExist
        Message.error(request, _("Locality not found in the database."))
        return Redirect.to_action(request, "index")
    try:
        # rastreando dependencias
        if d.headquart_set.count() > 0:
            raise Exception(("Localidad <b>%(name)s</b> está asignado en headquart.") % {"name":d.name})
        
        d.delete()
        if not d.id:
            Message.info(request, ("Localidad <b>%(name)s</b> ha sido eliminado correctamente.") % {"name":d.name}, True)
            return Redirect.to_action(request, "index")
    except Exception, e:
        Message.error(request, e)
        return Redirect.to_action(request, "index")
예제 #24
0
def producto_edit(request, key):
    """
    Actualiza Producto
    """
    id = SecurityKey.is_valid_key(request, key, "producto_upd")
    if not id:
        return Redirect.to_action(request, "index")
    d = None
    try:
        d = get_object_or_404(Producto, id=id)
        try:
            categoria = Categoria.objects.get(id=d.categoria.id)
            if categoria.id:
                d.categoria_nombre = d.categoria.nombre
        except:
            pass
        
        
    except Exception, e:
        Message.error(request, ("Usuario no se encuentra en la base de datos. %s" % e))
        return Redirect.to_action(request, "index")
예제 #25
0
def producto_edit(request, key):
    """
    Actualiza Producto
    """
    id = SecurityKey.is_valid_key(request, key, "producto_upd")
    if not id:
        return Redirect.to_action(request, "index")
    d = None
    try:
        d = get_object_or_404(Producto, id=id)
        try:
            categoria = Categoria.objects.get(id=d.categoria.id)
            if categoria.id:
                d.categoria_nombre = d.categoria.nombre
        except:
            pass

    except Exception, e:
        Message.error(request,
                      ("Usuario no se encuentra en la base de datos. %s" % e))
        return Redirect.to_action(request, "index")
예제 #26
0
파일: views.py 프로젝트: jdcali/backenddj
def solution_delete(request, key):
    """
    Elimina solución
    """
    id = SecurityKey.is_valid_key(request, key, "solution_del")
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Solution, id=id)
    except:
        Message.error(request,
                      ("Solución no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")
    try:
        # rastreando dependencias
        if d.module_set.count() > 0:
            raise Exception(
                ("Solución <b>%(name)s</b> tiene módulos asignados.") %
                {"name": d.name})
        if d.association_set.count() > 0:
            raise Exception(
                ("Solución <b>%(name)s</b> está asignado en asociaciones.") %
                {"name": d.name})
        if d.enterprise_set.count() > 0:
            raise Exception(
                ("Solución <b>%(name)s</b> está asignado en empresas.") %
                {"name": d.name})
        d.delete()
        if not d.id:
            Message.info(
                request,
                ("Solución <b>%(name)s</b> ha sido eliminado correctamente.") %
                {"name": d.name}, True)
            return Redirect.to_action(request, "index")
    except Exception, e:
        Message.error(request, e)
        return Redirect.to_action(request, "index")


# endregion solution
예제 #27
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)
예제 #28
0
파일: views.py 프로젝트: jdcali/backenddj
def enterprise_delete(request, key):
    """
    Elimina empresa con todas sus sedes
    """
    id = SecurityKey.is_valid_key(request, key, "enterprise_del")
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Enterprise, id=id)
    except:
        Message.error(request,
                      ("Empresa no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")
    try:
        sid = transaction.savepoint()
        association = Association.objects.get(
            id=DataAccessToken.get_association_id(request.session))
        if Enterprise.objects.filter(
                headquar__association_id=DataAccessToken.get_association_id(
                    request.session)).count() == 1:
            raise Exception((
                "Asociación <b>%(name)s</b> no puede quedar sin ninguna sede asociada."
            ) % {"name": association.name})
        if d.userprofileenterprise_set.count() > 0:
            raise Exception(
                ("Empresa <b>%(name)s</b> tiene usuarios y grupos asignados.")
                % {"name": d.name})
        # agregue aquí sus otras relgas de negocio
        d.delete()
        if not d.id:
            Message.info(
                request,
                ("Empresa <b>%(name)s</b> ha sido eliminado correctamente.") %
                {"name": d.name}, True)
            return Redirect.to_action(request, "index")
    except Exception, e:
        transaction.savepoint_rollback(sid)
        Message.error(request, e)
        return Redirect.to_action(request, "index")
예제 #29
0
파일: views.py 프로젝트: jdcali/backenddj
def headquar_change_association(request, key):
    """
    Cambia de asociación a la sede
    """
    id = SecurityKey.is_valid_key(request, key, "headquar_cha")
    if not id:
        return Redirect.to_action(request, "index")
    d = None

    try:
        d = get_object_or_404(Headquar, id=id)
        if d.association:
            d.association_name = d.association.name
    except:
        Message.error(request, ("Sede no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")

    if request.method == "POST":
        try:
            # d.association_id = DataAccessToken.get_association_id(request.session)
            d.association_name = request.POST.get("association_name")
            try:
                d.association = Association.objects.get(
                    name=d.association_name)
            except:
                raise Exception(
                    "La asociación <b>%s</b> no existe, vuelva a intentar " %
                    (request.POST.get("association_name")))
            # salvar registro
            d.save()
            if d.id:
                Message.info(request, (
                    "Sede <b>%(name)s</b> ha sido cambiado de asociación correctamente."
                ) % {"name": d.name})
                return Redirect.to_action(request, "index")

        except Exception, e:

            Message.error(request, e)
예제 #30
0
def producto_delete(request, key):
    """
    Elimina producto
    """
    id = SecurityKey.is_valid_key(request, key, "producto_del")
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Producto, id=id)
    except:
        Message.error(request, ("Producto no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")
    try:
        # sid = transaction.savepoint()
        d.delete()
        if not d.id:
            Message.info(request, ("Producto <b>%(codigo)s</b> ha sido eliminado correctamente.") % {"codigo":d.codigo}, True)
            return Redirect.to_action(request, "index")
    except Exception, e:
        # transaction.savepoint_rollback(sid)
        Message.error(request, e)
        return Redirect.to_action(request, "index")
예제 #31
0
파일: views.py 프로젝트: jdcali/backenddj
def headquar_delete(request, key):
    """
    Elimina sede
    """
    id = SecurityKey.is_valid_key(request, key, "headquar_del")
    if not id:
        return Redirect.to_action(request, "index")
    try:
        d = get_object_or_404(Headquar, id=id)
    except:
        Message.error(request, ("Sede no se encuentra en la base de datos."))
        return Redirect.to_action(request, "index")
    try:
        if d.enterprise.headquar_set.count() == 1:
            raise Exception(
                ("Empresa <b>%(name)s</b> no puede quedar sin ninguna sede.") %
                {"name": d.enterprise.name})
        if d.userprofileheadquar_set.count() > 0:
            raise Exception((
                "Sede <b>%(name)s de %(empresa)s</b> tiene usuarios y grupos asignados."
            ) % {
                "name": d.name,
                "empresa": d.enterprise.name
            })

        # agregue aquí sus otras relgas de negocio
        d.delete()
        if not d.id:
            Message.info(request, (
                "Sede <b>%(name)s de %(empresa)s</b> ha sido eliminado correctamente."
            ) % {
                "name": d.name,
                "empresa": d.enterprise.name
            }, True)
            return Redirect.to_action(request, "index")
    except Exception, e:
        Message.error(request, e)
        return Redirect.to_action(request, "index")
예제 #32
0
파일: views.py 프로젝트: jdcali/backenddj
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)
예제 #33
0
def solution_add(request):
    """
    Agrega solución
    """
    d = Solution()
    d.description = ""
    if request.method == "POST":
        try:
            d.name = request.POST.get("name")
            d.description = request.POST.get("description")
            if Solution.objects.exclude(id=d.id).filter(name=d.name).count() > 0:
                raise Exception(("Solución <b>%(name)s</b> ya existe.") % {"name":d.name})
            d.save()
            if d.id:
                Message.info(request, ("Solución <b>%(name)s</b> ha sido registrado correctamente.") % {"name":d.name})
                return Redirect.to_action(request, "index")
        except Exception, e:
            Message.error(request, e)
예제 #34
0
파일: views.py 프로젝트: jdcali/backenddj
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)
예제 #35
0
파일: views.py 프로젝트: jdcali/backenddj
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)
예제 #36
0
def enterprise_add(request):
    """
    Agrega empresa dentro de una asociación, para ello deberá agregarse con una sede Principal
    """
    d = Enterprise()
    d.sede = "Principal"
    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")
            # 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))

            d.save()

            headquar = Headquar()
            headquar.name = request.POST.get("sede")
            headquar.association_id = DataAccessToken.get_association_id(request.session)
            headquar.enterprise = d

            if normalize("NFKD", u"%s" % headquar.name).encode("ascii", "ignore").lower() in list(
                normalize("NFKD", u"%s" % col["name"]).encode("ascii", "ignore").lower() for col in Headquar.objects.values("name").exclude(id=headquar.id).filter(enterprise_id=headquar.enterprise_id)
                ):
                raise Exception("La sede <b>%s</b> ya existe " % (headquar.name))

            headquar.save()

            if d.id:
                Message.info(request, ("Empresa <b>%(name)s</b> ha sido registrado correctamente.") % {"name":d.name})
                return Redirect.to_action(request, "index")
        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
예제 #37
0
파일: views.py 프로젝트: jdcali/backenddj
def headquar_add(request):
    """
    Agrega sede
    """
    d = Headquar()
    d.phone = ""
    d.address = ""
    if request.method == "POST":
        try:
            sid = transaction.savepoint()
            d.name = request.POST.get("name")
            d.phone = request.POST.get("phone")
            d.address = request.POST.get("address")
            d.is_main = False
            d.locality_name = request.POST.get("locality_name")
            if request.POST.get("locality_name"):
                d.locality, is_locality_created = Locality.objects.get_or_create(
                    name=request.POST.get("locality_name"),  # name__iexact
                )
            d.association_id = DataAccessToken.get_association_id(
                request.session)
            d.enterprise_id = DataAccessToken.get_enterprise_id(
                request.session)

            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 Headquar.objects.values("name").exclude(
                            id=d.id).filter(enterprise_id=d.enterprise_id)):
                raise Exception("La sede <b>%s</b> ya existe " % (d.name))
            d.save()
            if d.id:
                Message.info(
                    request,
                    ("Sede <b>%(name)s</b> ha sido registrado correctamente.")
                    % {"name": d.name})
                return Redirect.to_action(request, "index")
        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
예제 #38
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)
예제 #39
0
파일: views.py 프로젝트: jdcali/backenddj
def locality_add_form(request):
    form = LocalityAddForm()
    if request.method == "POST":
        form = LocalityAddForm(request.POST)
        if form.is_valid():
            #name = form.cleaned_data['name']
            #location = form.cleaned_data['location']
            #locality_type = form.cleaned_data['locality_type'].id
            #p = Locality()
            #p.name = name
            #p.location = location
            #p.locality_type_id = locality_type
            #p.save()
            form.save()
            return Redirect.to_action(request, "index")   
    c = {
        "page_module":_("Locality"),
        "page_title":_("New locality."),
        "form":form,
        #"locality_type_list":locality_type_list,
        }
    return render_to_response('params/locality/add_form.html', c ,context_instance = RequestContext(request))
예제 #40
0
파일: views.py 프로젝트: jdcali/backenddj
def solution_add(request):
    """
    Agrega solución
    """
    d = Solution()
    d.description = ""
    if request.method == "POST":
        try:
            d.name = request.POST.get("name")
            d.description = request.POST.get("description")
            if Solution.objects.exclude(id=d.id).filter(
                    name=d.name).count() > 0:
                raise Exception(
                    ("Solución <b>%(name)s</b> ya existe.") % {"name": d.name})
            d.save()
            if d.id:
                Message.info(request, (
                    "Solución <b>%(name)s</b> ha sido registrado correctamente."
                ) % {"name": d.name})
                return Redirect.to_action(request, "index")
        except Exception, e:
            Message.error(request, e)
예제 #41
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)
예제 #42
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)
예제 #43
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/")
예제 #44
0
파일: views.py 프로젝트: jdcali/backenddj
                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:
예제 #45
0
파일: views.py 프로젝트: jdcali/backenddj
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)
예제 #46
0
파일: views.py 프로젝트: jdcali/backenddj
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/")
예제 #47
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"),
예제 #48
0
            if request.POST.get("fecha_venc"):
                d.fecha_venc = request.POST.get("fecha_venc")
                
            if request.POST.get("categoria_nombre"):
                
                d.categoria, is_created = Categoria.objects.get_or_create(
                    nombre=request.POST.get("categoria_nombre"),
                    )
                
            if Producto.objects.filter(codigo=d.codigo).exclude(id=d.id, headquar_id=d.headquar_id).count() > 0:
                raise Exception("El producto <b>%s</b> ya existe " % d.codigo)
            d.save()
            # raise Exception( "El producto <b>%s</b> ya existe " % d.codigo )
            if d.id:
                Message.info(request, ("Producto <b>%(name)s</b> ha sido actualizado correctamente.") % {"name":d.codigo}, True)
                return Redirect.to_action(request, "index")

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
    categoria_nombre_list = []
    try:
        categoria_nombre_list = json.dumps(list(col["nombre"] + ""  for col in Categoria.objects.values("nombre").filter().order_by("nombre")))
        print "PV=%s" % d.precio_venta
    except Exception, e:
        Message.error(request, e)
    c = {
        "page_module":("Gestión de productos"),
        "page_title":("Actualizar producto."),
        "d":d,
        "categoria_nombre_list":categoria_nombre_list,
예제 #49
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)
예제 #50
0
            if request.POST.get("categoria_nombre"):

                d.categoria, is_created = Categoria.objects.get_or_create(
                    nombre=request.POST.get("categoria_nombre"), )

            if Producto.objects.filter(codigo=d.codigo).exclude(
                    id=d.id, headquar_id=d.headquar_id).count() > 0:
                raise Exception("El producto <b>%s</b> ya existe " % d.codigo)
            d.save()
            # raise Exception( "El producto <b>%s</b> ya existe " % d.codigo )
            if d.id:
                Message.info(request, (
                    "Producto <b>%(name)s</b> ha sido actualizado correctamente."
                ) % {"name": d.codigo}, True)
                return Redirect.to_action(request, "index")

        except Exception, e:
            transaction.savepoint_rollback(sid)
            Message.error(request, e)
    categoria_nombre_list = []
    try:
        categoria_nombre_list = json.dumps(
            list(col["nombre"] + "" for col in Categoria.objects.values(
                "nombre").filter().order_by("nombre")))
        print "PV=%s" % d.precio_venta
    except Exception, e:
        Message.error(request, e)
    c = {
        "page_module": ("Gestión de productos"),
        "page_title": ("Actualizar producto."),