Exemplo n.º 1
0
    def dispatch(self, request, *args, **kwargs):
        key = self.kwargs.get(self.pk_url_kwarg, None)
        pk = SecurityKey.is_valid_key(request, key, 'solution_upd')
        if not pk:
            return HttpResponseRedirect(self.success_url)
        self.kwargs['pk'] = pk
        try:
            self.get_object()
            '''
            ctx_dict = {'activation_key': 'eee',
                        'expiration_days': 2,
                        'site': 'localhost:8000'}
            subject = render_to_string(
                'registration/activation_email_subject.txt',
                ctx_dict)
            # Email subject *must not* contain newlines

            subject = ''.join(subject.splitlines())

            message = render_to_string(
                'registration/activation_email.txt', ctx_dict)
            send_mail(
                subject, message, settings.DEFAULT_FROM_EMAIL,
                ['*****@*****.**'], fail_silently=False)

            # send_mail(
            #    'Subject here', 'Here is the message.', '*****@*****.**',
            #    ['*****@*****.**'], fail_silently=False)
            '''
        except Exception as e:
            messages.error(self.request, e)
            log.warning(force_text(e), extra=log_params(self.request))
            return HttpResponseRedirect(self.success_url)
        return super(SolutionUpdateView,
                     self).dispatch(request, *args, **kwargs)
Exemplo n.º 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")
Exemplo n.º 3
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")
Exemplo n.º 4
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")
Exemplo n.º 5
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
Exemplo n.º 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)
Exemplo n.º 7
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")
Exemplo n.º 8
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")
Exemplo n.º 9
0
    def dispatch(self, request, *args, **kwargs):
        key = self.kwargs.get('pk', None)
        if key:
            pk = SecurityKey.is_valid_key(request, key, 'enterprise_upd')
            if not pk:
                return HttpResponseRedirect(self.success_url)
            self.kwargs['pk'] = pk
            try:
                self.get_object()
            except Exception as e:
                messages.error(self.request, e)
                return HttpResponseRedirect(self.success_url)
        else:
            self.kwargs['pk'] = UserToken.get_enterprise_id(request.session)
            self.success_url = reverse_lazy('space:enterprise-edit_current')
            msg = _(u'%s is not selected or not found in the database.') % _(
                'Enterprise')
            try:
                self.get_object()
            except Exception as e:
                messages.error(self.request, e)
                messages.warning(self.request, msg)
                return HttpResponseRedirect(reverse_lazy('accounts:index'))

        return super(EnterpriseUpdateView, self).dispatch(request, *args, **kwargs)
Exemplo n.º 10
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)
Exemplo n.º 11
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)
Exemplo n.º 12
0
    def dispatch(self, request, *args, **kwargs):
        key = self.kwargs.get(self.pk_url_kwarg, None)
        pk = SecurityKey.is_valid_key(request, key, 'solution_upd')
        if not pk:
            return HttpResponseRedirect(self.success_url)
        self.kwargs['pk'] = pk
        try:
            self.get_object()
            '''
            ctx_dict = {'activation_key': 'eee',
                        'expiration_days': 2,
                        'site': 'localhost:8000'}
            subject = render_to_string(
                'registration/activation_email_subject.txt',
                ctx_dict)
            # Email subject *must not* contain newlines

            subject = ''.join(subject.splitlines())

            message = render_to_string(
                'registration/activation_email.txt', ctx_dict)
            send_mail(
                subject, message, settings.DEFAULT_FROM_EMAIL,
                ['*****@*****.**'], fail_silently=False)

            # send_mail(
            #    'Subject here', 'Here is the message.', '*****@*****.**',
            #    ['*****@*****.**'], fail_silently=False)
            '''
        except Exception, e:
            messages.error(self.request, e)
            log.warning(force_text(e), extra=log_params(self.request))
            return HttpResponseRedirect(self.success_url)
Exemplo n.º 13
0
    def dispatch(self, request, *args, **kwargs):
        key = self.kwargs.get('pk', None)
        if key:
            pk = SecurityKey.is_valid_key(request, key, 'enterprise_upd')
            if not pk:
                return HttpResponseRedirect(self.success_url)
            self.kwargs['pk'] = pk
            try:
                self.get_object()
            except Exception as e:
                messages.error(self.request, e)
                return HttpResponseRedirect(self.success_url)
        else:
            self.kwargs['pk'] = UserToken.get_enterprise_id(request.session)
            self.success_url = reverse_lazy('space:enterprise-edit_current')
            msg = _(u'%s is not selected or not found in the database.') % _(
                'Enterprise')
            try:
                self.get_object()
            except Exception as e:
                messages.error(self.request, e)
                messages.warning(self.request, msg)
                return HttpResponseRedirect(reverse_lazy('accounts:index'))

        return super(EnterpriseUpdateView,
                     self).dispatch(request, *args, **kwargs)
Exemplo n.º 14
0
 def dispatch(self, request, *args, **kwargs):
     key = self.kwargs.get('pk', None)
     if key:
         pk = SecurityKey.is_valid_key(request, key, 'enterprise_upd')
         if not pk:
             return HttpResponseRedirect(self.success_url)
         self.kwargs['pk'] = pk
         try:
             self.get_object()
         except Exception, e:
             messages.error(self.request, e)
             return HttpResponseRedirect(self.success_url)
Exemplo n.º 15
0
 def dispatch(self, request, *args, **kwargs):
     key = self.kwargs['pk']
     state = self.kwargs['state']
     pk = SecurityKey.is_valid_key(request, key, 'enterprise_%s' % state)
     if not pk:
         return HttpResponseRedirect(self.success_url)
     try:
         self.object = self.model.objects.get(pk=pk)
     except Exception, e:
         messages.error(self.request, e)
         log.warning(force_text(e), extra=log_params(self.request))
         return HttpResponseRedirect(self.success_url)
Exemplo n.º 16
0
 def dispatch(self, request, *args, **kwargs):
     key = self.kwargs['pk']
     pk = SecurityKey.is_valid_key(request, key, 'solution_del')
     if not pk:
         return HttpResponseRedirect(self.success_url)
     self.kwargs['pk'] = pk
     try:
         self.get_object()
     except Exception, e:
         messages.error(self.request, e)
         log.warning(force_text(e), extra=log_params(self.request))
         return HttpResponseRedirect(self.success_url)
Exemplo n.º 17
0
    def dispatch(self, request, *args, **kwargs):
        key = self.kwargs.get(self.pk_url_kwarg, None)
        pk = SecurityKey.is_valid_key(request, key, 'headquar_uas')
        if not pk:
            return HttpResponseRedirect(self.success_url)
        self.kwargs['pk'] = pk
        try:
            self.get_object()

        except Exception as e:
            messages.error(self.request, e)
            log.warning(force_text(e), extra=log_params(self.request))
            return HttpResponseRedirect(self.success_url)
        return super(HeadquarAssociationUpdateView, self).dispatch(request, *args, **kwargs)
Exemplo n.º 18
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)
Exemplo n.º 19
0
 def dispatch(self, request, *args, **kwargs):
     key = self.kwargs['pk']
     pk = SecurityKey.is_valid_key(request, key, 'solution_del')
     if not pk:
         return HttpResponseRedirect(self.success_url)
     self.kwargs['pk'] = pk
     try:
         self.get_object()
     except Exception as e:
         messages.error(self.request, e)
         log.warning(force_text(e), extra=log_params(self.request))
         return HttpResponseRedirect(self.success_url)
     return super(SolutionDeleteView,
                  self).dispatch(request, *args, **kwargs)
Exemplo n.º 20
0
def key(uid, action_name):
	"""
	Muestra la llave de seguridad generada por la clase SecurityKey

	Usage::

		{% url 'controller_name' id_value|key:'action_name' %}

	Example::

		{% url 'locality_edit' d.id|key:'locality_upd' %}

	"""
	
	return SecurityKey.get_key(uid, action_name)
Exemplo n.º 21
0
def key(uid, action_name):
    """
	Muestra la llave de seguridad generada por la clase SecurityKey

	Usage::

		{% url 'controller_name' id_value|key:'action_name' %}

	Example::

		{% url 'locality_edit' d.id|key:'locality_upd' %}

	"""

    return SecurityKey.get_key(uid, action_name)
Exemplo n.º 22
0
    def dispatch(self, request, *args, **kwargs):
        key = self.kwargs.get(self.pk_url_kwarg, None)
        pk = SecurityKey.is_valid_key(request, key, 'headquar_uas')
        if not pk:
            return HttpResponseRedirect(self.success_url)
        self.kwargs['pk'] = pk
        try:
            self.get_object()

        except Exception as e:
            messages.error(self.request, e)
            log.warning(force_text(e), extra=log_params(self.request))
            return HttpResponseRedirect(self.success_url)
        return super(HeadquarAssociationUpdateView,
                     self).dispatch(request, *args, **kwargs)
Exemplo n.º 23
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)
Exemplo n.º 24
0
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)
Exemplo n.º 25
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)
Exemplo n.º 26
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)
Exemplo n.º 27
0
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")
Exemplo n.º 28
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")
Exemplo n.º 29
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")
Exemplo n.º 30
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
Exemplo n.º 31
0
    def dispatch(self, request, *args, **kwargs):
        key = self.kwargs['pk']
        state = self.kwargs['state']
        pk = SecurityKey.is_valid_key(request, key, 'solution_%s' % state)
        if not pk:
            return HttpResponseRedirect(self.success_url)
        try:
            self.object = self.model.objects.get(pk=pk)
        except Exception as e:
            messages.error(self.request, e)
            log.warning(force_text(e), extra=log_params(self.request))
            return HttpResponseRedirect(self.success_url)

        msg = _('The %(name)s "%(obj)s" was %(action)s successfully.') % {
            'name': capfirst(force_text(self.model._meta.verbose_name)),
            'obj': force_text(self.object),
            'action':
            (_('reactivated') if state == 'rea' else _('inactivated'))
        }
        mse = _('The %(name)s "%(obj)s" is already %(action)s.') % {
            'name': capfirst(force_text(self.model._meta.verbose_name)),
            'obj': force_text(self.object),
            'action': (_('active') if state == 'rea' else _('inactive'))
        }
        try:
            if state == 'ina' and not self.object.is_active:
                raise Exception(mse)
            else:
                if state == 'rea' and self.object.is_active:
                    raise Exception(mse)
                else:
                    self.object.is_active = (True if state == 'rea' else False)
                    self.object.save()
                    messages.success(self.request, msg)
                    log.warning(msg, extra=log_params(self.request))
        except Exception as e:
            messages.error(self.request, e)
            log.warning(force_text(e), extra=log_params(self.request))
        return HttpResponseRedirect(self.success_url)
Exemplo n.º 32
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)
Exemplo n.º 33
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")
Exemplo n.º 34
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")
Exemplo n.º 35
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")
Exemplo n.º 36
0
    def dispatch(self, request, *args, **kwargs):
        key = self.kwargs['pk']
        state = self.kwargs['state']
        pk = SecurityKey.is_valid_key(request, key, 'solution_%s' % state)
        if not pk:
            return HttpResponseRedirect(self.success_url)
        try:
            self.object = self.model.objects.get(pk=pk)
        except Exception as e:
            messages.error(self.request, e)
            log.warning(force_text(e), extra=log_params(self.request))
            return HttpResponseRedirect(self.success_url)

        msg = _('The %(name)s "%(obj)s" was %(action)s successfully.') % {
            'name': capfirst(force_text(self.model._meta.verbose_name)),
            'obj': force_text(self.object),
            'action': (_('reactivated') if state == 'rea' else _('inactivated'))
        }
        mse = _('The %(name)s "%(obj)s" is already %(action)s.') % {
            'name': capfirst(force_text(self.model._meta.verbose_name)),
            'obj': force_text(self.object),
            'action': (_('active') if state == 'rea' else _('inactive'))
        }
        try:
            if state == 'ina' and not self.object.is_active:
                raise Exception(mse)
            else:
                if state == 'rea' and self.object.is_active:
                    raise Exception(mse)
                else:
                    self.object.is_active = (True if state == 'rea' else False)
                    self.object.save()
                    messages.success(self.request, msg)
                    log.warning(msg, extra=log_params(self.request))
        except Exception as e:
            messages.error(self.request, e)
            log.warning(force_text(e), extra=log_params(self.request))
        return HttpResponseRedirect(self.success_url)