예제 #1
0
def passwd(request):
    if request.method == 'POST':
        if 'action' in request.POST:
            action = request.POST['action']
            if action == 'changepass':
                try:
                    f = CambioClaveForm(request.POST)
                    if f.is_valid():
                        with transaction.atomic():
                            if f.cleaned_data['nueva'] == DEFAULT_PASSWORD:
                                return HttpResponse(json.dumps({"result": "bad", "mensaje": "No puede usar la clave por defecto."}), mimetype="application/json")
                            data = {}
                            addUserData(request, data)
                            usuario = data['usuario']
                            if usuario.check_password(f.cleaned_data['anterior']):
                                usuario.set_password(f.cleaned_data['nueva'])
                                usuario.save()
                                return ok_json()
                            return bad_json(mensaje=u"Clave anterior no coincide.")
                    else:
                        raise Exception

                except Exception:
                    return bad_json(mensaje=u"No se pudo cambiar la clave.")

        return bad_json(error=0)
    else:
        try:
            data = {}
            addUserData(request, data)
            data['title'] = u'Cambio de clave'
            data['form'] = CambioClaveForm()
            return render_to_response("changepassbs.html", data, request)
        except Exception:
            return HttpResponseRedirect('/')
예제 #2
0
def get_data(request):
    try:
        m = request.GET['model']
        if 'q' in request.GET:
            q = request.GET['q']
            if ':' in m:
                sp = m.split(':')
                model = eval(sp[0])
                query = model.flexbox_query(q)
                for n in range(1, len(sp)):
                    query = eval('query.filter(%s)' % (sp[n]))
            else:
                model = eval(request.GET['model'])
                query = model.flexbox_query(q)
        else:
            model = eval(request.GET['model'])
            query = model.flexbox_query('')

        data = {"results": [{"id": x.id, "name": x.flexbox_repr(), "alias": x.flexbox_alias()} for x in query]}
        return HttpResponse(json.dumps(data), content_type='application/json')

    except Exception:
        return bad_json(error=1)
예제 #3
0
def view(request):
    ex = None
    data = {'title': u'Panel del Cliente'}
    addUserData(request, data)
    if Cliente.objects.filter(usuario=request.user).exists():
        data['cliente'] = cliente = Cliente.objects.filter(usuario=request.user)[0]
    else:
        return HttpResponseRedirect("/salir")

    if request.method == 'POST':
        if 'action' in request.POST:
            action = request.POST['action']

            if action == 'valorar_servicio':
                detalle_factura = DetalleFactura.objects.get(pk=int(request.POST['id']))
                f = ValoracionForm(request.POST)
                if f.is_valid():
                    try:
                        with transaction.atomic():
                            detalle_factura.valoracion_servicio = f.cleaned_data['valoracion']
                            detalle_factura.recomendaciones_servicio = f.cleaned_data['recomendaciones']
                            detalle_factura.save()
                            salva_auditoria(request, detalle_factura, ACCION_MODIFICAR)
                            return ok_json()

                    except Exception:
                        return bad_json(error=1)
                else:
                    return bad_json(error=1)

            elif action == 'valorar_producto':
                detalle_factura = DetalleFactura.objects.get(pk=int(request.POST['id']))
                f = ValoracionForm(request.POST)
                if f.is_valid():
                    try:
                        with transaction.atomic():
                            detalle_factura.valoracion_producto = f.cleaned_data['valoracion']
                            detalle_factura.recomendaciones_producto = f.cleaned_data['recomendaciones']
                            detalle_factura.save()
                            salva_auditoria(request, detalle_factura, ACCION_MODIFICAR)
                            return ok_json()

                    except Exception:
                        return bad_json(error=1)
                else:
                    return bad_json(error=1)

        return bad_json(error=0)

    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'cliente_servicios_recibidos':
                try:
                    data['detalles_facturas'] = DetalleFactura.objects.filter(servicio__isnull=False,
                                                                              factura__cliente=cliente).distinct().order_by('factura')
                    return render_to_response("panelclientes/cliente_servicios_recibidos.html", data)
                except Exception as ex:
                    pass

            elif action == 'valorar_servicio':
                try:
                    data['detalle_factura'] = df = DetalleFactura.objects.get(pk=int(request.GET['id']))
                    data['form'] = ValoracionForm(initial={'valoracion': df.valoracion_servicio,
                                                           'recomendaciones': df.recomendaciones_servicio})
                    return render_to_response("panelclientes/valorar_servicio.html", data)
                except Exception as ex:
                    pass

            elif action == 'cliente_productos_comprados':
                try:
                    data['detalles_facturas'] = DetalleFactura.objects.filter(producto__isnull=False, factura__cliente=cliente).distinct().order_by('factura')
                    return render_to_response("panelclientes/cliente_productos_comprados.html", data)
                except Exception as ex:
                    pass

            elif action == 'valorar_producto':
                try:
                    data['detalle_factura'] = df = DetalleFactura.objects.get(pk=int(request.GET['id']))
                    data['form'] = ValoracionForm(initial={'valoracion': df.valoracion_producto,
                                                           'recomendaciones': df.recomendaciones_producto})
                    return render_to_response("panelclientes/valorar_producto.html", data)
                except Exception as ex:
                    pass

            elif action == 'cliente_servicios_futuros':
                try:
                    data['servicios_futuros'] = cliente.mis_servicios_futuros()
                    return render_to_response("panelclientes/cliente_servicios_futuros.html", data)
                except Exception as ex:
                    pass

            elif action == 'cliente_paquetes':
                try:
                    data['paquetes'] = ""
                    return render_to_response("panelclientes/cliente_paquetes.html", data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(url_back(request, mensaje_excepcion(ex.args[0])))

        else:
            return render_to_response("panelclientes/view.html", data)
예제 #4
0
def view(request):
    ex = None
    data = {'title': u'Productos'}
    addUserData(request, data)

    if request.method == 'POST':
        action = request.POST['action']
        if action == 'add':
            f = ProductoForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        producto = Producto(
                            tipo=f.cleaned_data['tipo'],
                            codigo=f.cleaned_data['codigo'],
                            descripcion=f.cleaned_data['descripcion'],
                            unidadmedida=f.cleaned_data['unidadmedida'],
                            tipoproducto=f.cleaned_data['tipoproducto'],
                            alias=f.cleaned_data['alias'],
                            codigobarra=f.cleaned_data['codigobarra'],
                            minimo=f.cleaned_data['minimo'],
                            con_iva=f.cleaned_data['con_iva'],
                            precio=f.cleaned_data['precio'],
                            precio_cliente_normal=f.
                            cleaned_data['precio_cliente_normal'],
                            precio_cliente_corporativo=f.
                            cleaned_data['precio_cliente_corporativo'],
                            precio_cliente_vip=f.
                            cleaned_data['precio_cliente_vip'])
                        producto.save()

                        # Guardar Historial de cambios de precios
                        historialprecio = HistorialPrecioProducto(
                            producto=producto,
                            precio=producto.precio,
                            precio_cliente_normal=producto.
                            precio_cliente_normal,
                            precio_cliente_corporativo=producto.
                            precio_cliente_corporativo,
                            precio_cliente_vip=producto.precio_cliente_vip,
                            usuario=request.user,
                            modulo='P',  # C - Compra, P - Productos
                            accion=ACCION_ADICIONAR)
                        historialprecio.save()

                        salva_auditoria(request, producto, ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'edit':
            producto = Producto.objects.get(pk=request.POST['id'])
            f = ProductoForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        flag1 = producto.precio != f.cleaned_data['precio']
                        flag2 = producto.precio_cliente_normal != f.cleaned_data[
                            'precio_cliente_normal']
                        flag3 = producto.precio_cliente_corporativo != f.cleaned_data[
                            'precio_cliente_corporativo']
                        flag4 = producto.precio_cliente_vip != f.cleaned_data[
                            'precio_cliente_vip']
                        producto.codigo = f.cleaned_data['codigo']
                        producto.codigobarra = f.cleaned_data['codigobarra']
                        producto.descripcion = f.cleaned_data['descripcion']
                        producto.tipoproducto = f.cleaned_data['tipoproducto']
                        producto.unidadmedida = f.cleaned_data['unidadmedida']
                        producto.alias = f.cleaned_data['alias']
                        producto.minimo = f.cleaned_data['minimo']
                        producto.con_iva = f.cleaned_data['con_iva']
                        producto.precio = f.cleaned_data['precio']
                        producto.precio_cliente_normal = f.cleaned_data[
                            'precio_cliente_normal']
                        producto.precio_cliente_corporativo = f.cleaned_data[
                            'precio_cliente_corporativo']
                        producto.precio_cliente_vip = f.cleaned_data[
                            'precio_cliente_vip']
                        producto.save()

                        # Guardar Historial si hubo cambios de precios
                        if flag1 or flag2 or flag3 or flag4:
                            historialprecio = HistorialPrecioProducto(
                                producto=producto,
                                precio=producto.precio,
                                precio_cliente_normal=producto.
                                precio_cliente_normal,
                                precio_cliente_corporativo=producto.
                                precio_cliente_corporativo,
                                precio_cliente_vip=producto.precio_cliente_vip,
                                fecha=datetime.now().date(),
                                usuario=request.user,
                                modulo='P',
                                accion=ACCION_MODIFICAR)
                            historialprecio.save()

                        for pp in producto.paqueteproducto_set.all():
                            pp.paquete.save()

                        salva_auditoria(request, producto, ACCION_MODIFICAR)
                    return ok_json()

                except Exception:
                    return bad_json(error=2)
            else:
                return bad_json(error=2)

        elif action == 'delete':
            producto = Producto.objects.get(pk=request.POST['id'])
            try:
                with transaction.atomic():
                    salva_auditoria(request, producto, ACCION_ELIMINAR)
                    producto.delete()
                return ok_json()
            except Exception:
                return bad_json(error=3)

        elif action == 'get_next_codigo':
            t = int(request.POST['tid'])
            if t == TIPO_PRODUCTO_PARA_VENTA:
                tipo = 'V'
            elif t == TIPO_PRODUCTO_PARA_CONSUMO:
                tipo = 'C'
            else:
                tipo = 'R'
            categoria = TipoProducto.objects.get(pk=request.POST['cid'])
            try:
                codigo = "P{}-{}-0001".format(tipo, categoria.codigo)
                ultimo_producto = categoria.get_ultimo_producto()
                if ultimo_producto:
                    codigo = "P{}-{}-{}".format(
                        tipo, categoria.codigo,
                        str(ultimo_producto.secuencia_codigo() + 1).zfill(4))
                return ok_json(data={"codigo": codigo})
            except Exception:
                return bad_json(error=1)

        elif action == 'cargarfoto':
            form = FotoProductoForm(request.POST, request.FILES)
            producto = Producto.objects.get(pk=request.POST['id'])
            if form.is_valid():
                try:
                    with transaction.atomic():
                        newfile = request.FILES['foto']
                        newfile._name = generar_nombre("foto_", newfile._name)
                        producto.foto = newfile
                        producto.save()
                    return ok_json()
                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'favorito':
            try:
                producto = Producto.objects.get(pk=request.POST['idprod'])
                try:
                    with transaction.atomic():
                        producto.favorito = False if producto.favorito else True
                        producto.save()
                        return ok_json()
                except Exception:
                    return bad_json(error=1)
            except:
                return bad_json(error=1)

        return bad_json(error=0)

    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'add':
                try:
                    data['title'] = u'Crear Producto'
                    data['form'] = ProductoForm()
                    return render_to_response('productos/add.html', data)
                except Exception as ex:
                    pass

            elif action == 'edit':
                try:
                    data['title'] = u'Modificar Producto'
                    data['producto'] = producto = Producto.objects.get(
                        pk=request.GET['id'])
                    form = ProductoForm(initial=model_to_dict(producto))
                    form.for_editproducto()
                    data['form'] = form
                    return render_to_response('productos/edit.html', data)
                except Exception as ex:
                    pass

            elif action == 'delete':
                try:
                    data['title'] = u'Eliminar Producto'
                    data['producto'] = Producto.objects.get(
                        pk=request.GET['id'])
                    return render_to_response('productos/delete.html', data)
                except Exception as ex:
                    pass

            elif action == 'cargarfoto':
                try:
                    data['title'] = u'Cargar Foto del Producto '
                    data['producto'] = Producto.objects.get(
                        pk=request.GET['id'])
                    data['form'] = FotoProductoForm()
                    return render_to_response('productos/cargarfoto.html',
                                              data)
                except Exception as ex:
                    pass

            elif action == 'catalogo':
                try:
                    data['title'] = u'Catalogo de Productos'
                    data['categorias'] = categorias = TipoProducto.objects.all(
                    )
                    categoria = categorias[0]
                    if 'cid' in request.GET:
                        cid = int(request.GET['cid'])
                        categoria = categorias.filter(pk=cid)[0]
                    inventarios = categoria.productos_con_existencias()

                    cantidad_filas = 0
                    if inventarios:
                        if inventarios.count() > 8:
                            cantidad_filas = int(
                                math.ceil(inventarios.count() / 8.0))
                        else:
                            cantidad_filas = 1
                    salto = 8
                    lista = []
                    for i in range(cantidad_filas):
                        a = i * salto
                        lista.append((i, inventarios[a:(a + salto)]))

                    data['lista'] = lista
                    data['cantidad_filas'] = cantidad_filas
                    data['categoria'] = categoria
                    return render_to_response('productos/catalogo.html', data)
                except Exception as ex:
                    pass

            elif action == 'catalogopdf':
                try:
                    data['title'] = u'Catálogo de Productos por Categoria'
                    categoria = TipoProducto.objects.get(
                        pk=int(request.GET['cid']))

                    inventarios = categoria.productos_con_existencias()
                    cantidad_productos = inventarios.count()
                    cantidad_paginas = int(math.ceil(cantidad_productos /
                                                     12.0))

                    paginas = []
                    salto = 4
                    inicio = 0
                    fin = 4
                    for p in range(1, cantidad_paginas + 1):
                        grupo1 = inventarios[inicio:fin]
                        inicio = fin
                        fin += salto
                        grupo2 = inventarios[inicio:fin]
                        inicio = fin
                        fin += salto
                        grupo3 = inventarios[inicio:fin]
                        inicio = fin
                        fin += salto
                        paginas.append((p, grupo1, grupo2, grupo3))

                    data['paginas'] = paginas
                    data['categoria'] = categoria
                    data['request'] = request
                    html = render_to_string('productos/catalogopdf.html', data,
                                            request)
                    return generar_pdf(html)
                except Exception as ex:
                    pass

            elif action == 'todospdf':
                try:
                    data['title'] = u'Catálogo de todos los Productos'
                    data[
                        'categorias'] = categorias = TipoProducto.objects.filter(
                            producto__inventarioreal__cantidad__gt=0).distinct(
                            )

                    lista = collections.OrderedDict()
                    listado_final = collections.OrderedDict()
                    for c in categorias:
                        lista_productos_ordenados = []
                        for inventario in c.productos_con_existencias():
                            lista_productos_ordenados.append(inventario)
                        lista[c] = lista_productos_ordenados

                    salto = 4
                    for x, y in lista.items():
                        inicio = 0
                        fin = 4
                        listado = []
                        for p in range(1, x.cantidad_paginas_catalogo() + 1):
                            grupo1 = y[inicio:fin]
                            inicio = fin
                            fin += salto
                            grupo2 = y[inicio:fin]
                            inicio = fin
                            fin += salto
                            grupo3 = y[inicio:fin]
                            inicio = fin
                            fin += salto
                            listado.append((p, grupo1, grupo2, grupo3))
                        listado_final[x] = listado

                    data['listado_final'] = listado_final
                    data['request'] = request
                    html = render_to_string('productos/todospdf.html', data,
                                            request)
                    return generar_pdf(html)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(
                url_back(request, mensaje_excepcion(ex.args[0])))

        else:
            search = None
            tipo = None
            tipodestino = None

            if 't' in request.GET and int(request.GET['t']) > 0:
                tipo = int(request.GET['t'])

            if 'tipo' in request.GET and int(request.GET['tipo']) > 0:
                tipodestino = int(request.GET['tipo'])

            if 's' in request.GET:
                search = request.GET['s']

            productos = Producto.objects.filter(activo=True).select_related(
                'unidadmedida', 'tipoproducto')
            if search:
                productos = productos.filter(
                    Q(codigo__icontains=search)
                    | Q(descripcion__icontains=search))

            if tipo and tipodestino:
                productos = productos.filter(tipoproducto__id=tipo,
                                             tipo=tipodestino)

            if tipo:
                productos = productos.filter(tipoproducto__id=tipo)

            if tipodestino:
                productos = productos.filter(tipo=tipodestino)

            paging = MiPaginador(productos, 30)
            p = 1
            try:
                if 'page' in request.GET:
                    p = int(request.GET['page'])
                page = paging.page(p)
            except:
                page = paging.page(p)

            data['paging'] = paging
            data['rangospaging'] = paging.rangos_paginado(p)
            data['page'] = page
            data['search'] = search if search else ""
            data['productos'] = page.object_list
            data['categoriaid'] = int(tipo) if tipo else ""
            data['tipoid'] = int(tipodestino) if tipodestino else ""
            data['tipos_productos'] = TipoProducto.objects.all()
            return render_to_response("productos/productos.html", data)
예제 #5
0
def view(request):
    ex = None
    data = {'title': u'Gestión de Clientes'}
    addUserData(request, data)
    if request.method == 'POST':
        action = request.POST['action']
        if action == 'add':
            f = ClienteForm(request.POST, request.FILES)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        tipo = int(f.cleaned_data['tipo'])
                        ruc = f.cleaned_data['ruc']
                        identificacion = f.cleaned_data['identificacion']
                        usuario_nombre = f.cleaned_data['usuario']
                        if identificacion and Cliente.objects.filter(identificacion=identificacion).exists():
                            return bad_json(mensaje=u"Ya existe un cliente con ese número de identificación.")
                        if ruc and Cliente.objects.filter(ruc=ruc).exists():
                            return bad_json(mensaje=u"Ya existe un cliente con ese número de RUC.")
                        if User.objects.filter(username=usuario_nombre).exists():
                            return bad_json(mensaje=u"Ya existe ese nombre de usuario en el sistema.")

                        cliente = Cliente(tipo=tipo,
                                          identificacion=identificacion,
                                          nombre=f.cleaned_data['nombre'],
                                          domicilio=f.cleaned_data['domicilio'],
                                          fecha_nacimiento=f.cleaned_data['fecha_nacimiento'],
                                          email=f.cleaned_data['email'],
                                          telefono=f.cleaned_data['telefono'],
                                          celular=f.cleaned_data['celular'],
                                          # corporativos
                                          ruc=f.cleaned_data['ruc'],
                                          razon_social=f.cleaned_data['razon_social'],
                                          representante_legal=f.cleaned_data['representante_legal'],
                                          # especificos
                                          alergias=f.cleaned_data['alergias'],
                                          caracteristicas_fisicas=f.cleaned_data['caracteristicas_fisicas'],
                                          tipo_cabello=f.cleaned_data['tipo_cabello'],
                                          tipo_piel=f.cleaned_data['tipo_piel'],
                                          oportunidades_servicios=f.cleaned_data['oportunidades_servicios'])
                        cliente.save()

                        if 'foto' in request.FILES:
                            newfile = request.FILES['foto']
                            newfile._name = generar_nombre("foto_", newfile._name)
                            cliente.foto = newfile
                            cliente.save()

                        user = User.objects.create_user(usuario_nombre, cliente.email, DEFAULT_PASSWORD)
                        user.username = user.username.lower()
                        user.save()
                        cliente.usuario = user
                        cliente.save()
                        g = Group.objects.get(pk=CLIENTES_GROUP_ID)
                        g.user_set.add(user)
                        g.save()
                        salva_auditoria(request, cliente, ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'edit':
            cliente = Cliente.objects.get(pk=request.POST['id'])
            f = ClienteForm(request.POST, request.FILES)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        tipo = int(f.cleaned_data['tipo'])
                        ruc = f.cleaned_data['ruc']
                        identificacion = f.cleaned_data['identificacion']
                        usuario_nombre = f.cleaned_data['usuario']
                        if identificacion and Cliente.objects.filter(identificacion=identificacion).exclude(id=cliente.id).exists():
                            return bad_json(mensaje=u"Ya existe un cliente con ese número de identificación.")
                        if ruc and Cliente.objects.filter(ruc=ruc).exclude(id=cliente.id).exists():
                            return bad_json(mensaje=u"Ya existe un cliente con ese número de RUC.")
                        if User.objects.filter(username=usuario_nombre).exclude(cliente__id=cliente.id).exists():
                            return bad_json(mensaje=u"Ya existe ese nombre de usuario en el sistema.")

                        if not cliente.usuario:
                            user = User.objects.create_user(usuario_nombre, cliente.email, DEFAULT_PASSWORD)
                            user.username = user.username.lower()
                            user.save()
                            cliente.usuario = user
                            cliente.save()
                            g = Group.objects.get(pk=CLIENTES_GROUP_ID)
                            g.user_set.add(user)
                            g.save()
                        else:
                            cliente.usuario.username = usuario_nombre
                            cliente.usuario.save()

                        cliente.tipo = tipo
                        cliente.nombre = f.cleaned_data['nombre']
                        cliente.identificacion = f.cleaned_data['identificacion']
                        cliente.domicilio = f.cleaned_data['domicilio']
                        cliente.fecha_nacimiento = f.cleaned_data['fecha_nacimiento']
                        cliente.email = f.cleaned_data['email']
                        cliente.telefono = f.cleaned_data['telefono']
                        cliente.celular = f.cleaned_data['celular']
                        # corporativos
                        cliente.ruc = f.cleaned_data['ruc']
                        cliente.razon_social = f.cleaned_data['razon_social']
                        cliente.representante_legal = f.cleaned_data['representante_legal']
                        # especificos
                        cliente.alergias = f.cleaned_data['alergias']
                        cliente.caracteristicas_fisicas = f.cleaned_data['caracteristicas_fisicas']
                        cliente.tipo_cabello = f.cleaned_data['tipo_cabello']
                        cliente.tipo_piel = f.cleaned_data['tipo_piel']
                        cliente.oportunidades_servicios = f.cleaned_data['oportunidades_servicios']

                        cliente.save()
                        if 'foto' in request.FILES:
                            newfile = request.FILES['foto']
                            newfile._name = generar_nombre("foto_", newfile._name)
                            cliente.foto = newfile
                            cliente.save()
                        salva_auditoria(request, cliente, ACCION_MODIFICAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=2)
            else:
                return bad_json(error=2)

        elif action == 'delete':
            try:
                cliente = Cliente.objects.get(pk=request.POST['id'])
                with transaction.atomic():
                    salva_auditoria(request, cliente, ACCION_ELIMINAR)
                    cliente.delete()
                    return ok_json()
            except Exception:
                return bad_json(error=3)

        elif action == 'resetear':
            try:
                cliente = Cliente.objects.get(pk=request.POST['id'])
                with transaction.atomic():
                    user = cliente.usuario
                    user.set_password(DEFAULT_PASSWORD)
                    user.save()
                    salva_auditoria(request, cliente, ACCION_MODIFICAR)
                    return ok_json()
            except Exception:
                return bad_json(error=3)

        return bad_json(error=0)

    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'add':
                try:
                    data['title'] = u'Crear Cliente'
                    data['form'] = ClienteForm(initial={'fecha_nacimiento': datetime.now().date()})
                    return render_to_response("clientes/add.html", data)
                except Exception as ex:
                    pass

            elif action == 'edit':
                try:
                    data['title'] = 'Editar Cliente'
                    data['cliente'] = cliente = Cliente.objects.get(pk=request.GET['id'])
                    data['form'] = ClienteForm(initial={'tipo': cliente.tipo,
                                                        'identificacion': cliente.identificacion,
                                                        'nombre': cliente.nombre,
                                                        'domicilio': cliente.domicilio,
                                                        'fecha_nacimiento': cliente.fecha_nacimiento,
                                                        'email': cliente.email,
                                                        'telefono': cliente.telefono,
                                                        'celular': cliente.celular,
                                                        'usuario': cliente.usuario.username,
                                                        'ruc': cliente.ruc,
                                                        'razon_social': cliente.razon_social,
                                                        'representante_legal': cliente.representante_legal,
                                                        'tipo_cabello': cliente.tipo_cabello,
                                                        'tipo_piel': cliente.tipo_piel,
                                                        'caracteristicas_fisicas': cliente.caracteristicas_fisicas,
                                                        'alergias': cliente.alergias,
                                                        'oportunidades_servicios': cliente.oportunidades_servicios,
                                                        'foto': cliente.foto})
                    return render_to_response("clientes/edit.html", data)
                except Exception as ex:
                    pass

            elif action == 'delete':
                try:
                    data['title'] = 'Borrar Cliente'
                    data['cliente'] = Cliente.objects.get(pk=request.GET['id'])
                    return render_to_response("clientes/delete.html", data)
                except Exception as ex:
                    pass

            elif action == 'resetear':
                try:
                    data['title'] = u'Resetear clave del usuario'
                    data['cliente'] = Cliente.objects.get(pk=request.GET['id'])
                    return render_to_response("clientes/resetear.html", data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(url_back(request, mensaje_excepcion(ex.args[0])))

        else:
            search = None
            tipo = None

            if 't' in request.GET and int(request.GET['t']) > 0:
                tipo = request.GET['t']

            if 's' in request.GET:
                search = request.GET['s']

            clientes = Cliente.objects.all().select_related('tipo_cabello', 'tipo_piel')
            if search:
                clientes = clientes.filter(Q(nombre__icontains=search) |
                                           Q(ruc__icontains=search) |
                                           Q(identificacion__icontains=search) |
                                           Q(email__icontains=search) |
                                           Q(usuario__username__icontains=search))
            if tipo:
                clientes = clientes.filter(tipo=tipo)

            paging = MiPaginador(clientes, 30)
            p = 1
            try:
                if 'page' in request.GET:
                    p = int(request.GET['page'])
                page = paging.page(p)
            except:
                page = paging.page(1)
            data['paging'] = paging
            data['rangospaging'] = paging.rangos_paginado(p)
            data['page'] = page
            data['search'] = search if search else ""
            data['clientes'] = page.object_list
            data['tipoid'] = int(tipo) if tipo else ""
            return render_to_response("clientes/clientes.html", data)
예제 #6
0
def view(request):
    ex = None
    data = {'title': 'Paquetes'}
    addUserData(request, data)
    if request.method == 'POST':
        action = request.POST['action']
        if action == 'add':
            f = PaqueteForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        codigo = f.cleaned_data['codigo']
                        tipo = int(f.cleaned_data['tipo'])
                        sesiones = int(f.cleaned_data['sesiones'])
                        if Paquete.objects.filter(codigo=codigo).exists():
                            return bad_json(
                                mensaje=u"Ya existe un paquete con ese código."
                            )
                        if (tipo == PAQUETE_PROMOCIONAL or tipo
                                == PAQUETE_MULTISESION) and sesiones < 2:
                            return bad_json(
                                mensaje=
                                u"La cantidad de sesión no puede ser menor a 2 "
                                u"por el tipo de paquete seleccionado")
                        paquete = Paquete(
                            codigo=codigo,
                            descripcion=f.cleaned_data['descripcion'],
                            alias=f.cleaned_data['alias'],
                            tipo=tipo,
                            sesiones=sesiones)
                        paquete.save()
                        salva_auditoria(request, paquete, ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'edit':
            paquete = Paquete.objects.get(pk=request.POST['id'])
            f = PaqueteForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        codigo = f.cleaned_data['codigo']
                        tipo = int(f.cleaned_data['tipo'])
                        sesiones = int(f.cleaned_data['sesiones'])
                        if Paquete.objects.filter(codigo=codigo).exclude(
                                id=paquete.id).exists():
                            return bad_json(
                                mensaje=u"Ya existe un paquete con ese código."
                            )
                        if (tipo == PAQUETE_PROMOCIONAL or tipo
                                == PAQUETE_MULTISESION) and sesiones < 2:
                            return bad_json(
                                mensaje=
                                u"La cantidad de sesión no puede ser menor a 2 "
                                u"por el tipo de paquete seleccionado")
                        paquete.codigo = f.cleaned_data['codigo']
                        paquete.descripcion = f.cleaned_data['descripcion']
                        paquete.alias = f.cleaned_data['alias']
                        paquete.tipo = tipo
                        paquete.sesiones = sesiones
                        paquete.save()
                        salva_auditoria(request, paquete, ACCION_MODIFICAR)
                    return ok_json()

                except Exception:
                    return bad_json(error=2)
            else:
                return bad_json(error=2)

        elif action == 'delete':
            paquete = Paquete.objects.get(pk=request.POST['id'])
            try:
                with transaction.atomic():
                    salva_auditoria(request, paquete, ACCION_ELIMINAR)
                    paquete.delete()
                return ok_json()
            except Exception:
                return bad_json(error=3)

        elif action == 'get_next_codigo':
            categoria = TipoServicio.objects.get(pk=request.POST['cid'])
            try:
                with transaction.atomic():
                    codigo = "SV-{}-0001".format(categoria.codigo)
                    ultimo_servicio = categoria.get_ultimo_servicio()
                    if ultimo_servicio:
                        codigo = "SV-{}-{}".format(
                            categoria.codigo,
                            str(ultimo_servicio.secuencia_codigo() +
                                1).zfill(4))
                    return ok_json(data={"codigo": codigo})

            except Exception:
                return bad_json(error=1)

        elif action == 'favorito':
            try:
                servicio = Servicio.objects.get(pk=request.POST['idprod'])
                try:
                    with transaction.atomic():
                        servicio.favorito = False if servicio.favorito else True
                        servicio.save()
                        return ok_json()
                except Exception:
                    return bad_json(error=1)

            except:
                return bad_json(error=1)

        if action == 'addelementoproducto':
            paquete = Paquete.objects.get(pk=request.POST['id'])
            f = PaqueteProductoForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        pp = PaqueteProducto(
                            paquete=paquete,
                            producto=f.cleaned_data['producto'])
                        pp.save()
                        pp.paquete.save()  # actualizar precios
                        salva_auditoria(request, pp, ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        if action == 'addelementoservicio':
            paquete = Paquete.objects.get(pk=request.POST['id'])
            f = PaqueteServicioForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        ps = PaqueteServicio(
                            paquete=paquete,
                            servicio=f.cleaned_data['servicio'])
                        ps.save()
                        ps.paquete.save()  # actualizar precios
                        salva_auditoria(request, ps, ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'deleteelementoproducto':
            pp = PaqueteProducto.objects.get(pk=request.POST['id'])
            paquete = pp.paquete
            try:
                with transaction.atomic():
                    salva_auditoria(request, pp, ACCION_ELIMINAR)
                    pp.delete()
                    paquete.save()
                return ok_json()

            except Exception:
                return bad_json(error=1)

        elif action == 'deleteelementoservicio':
            ps = PaqueteServicio.objects.get(pk=request.POST['id'])
            paquete = ps.paquete
            try:
                with transaction.atomic():
                    salva_auditoria(request, ps, ACCION_ELIMINAR)
                    ps.delete()
                    paquete.save()
                return ok_json()

            except Exception:
                return bad_json(error=1)

        elif action == 'valor_precios_clientes':
            paquete = Paquete.objects.get(pk=request.POST['pid'])
            try:
                porciento_cliente_normal = float(
                    request.POST['porciento_cliente_normal'])
                porciento_cliente_corporativo = float(
                    request.POST['porciento_cliente_corporativo'])
                porciento_cliente_vip = float(
                    request.POST['porciento_cliente_vip'])

                paquete.porciento_cliente_normal = porciento_cliente_normal
                paquete.porciento_cliente_corporativo = porciento_cliente_corporativo
                paquete.porciento_cliente_vip = porciento_cliente_vip
                paquete.save()

                return ok_json(
                    data={
                        "valor_cliente_normal": paquete.valor_cliente_normal,
                        "valor_cliente_corporativo":
                        paquete.valor_cliente_corporativo,
                        "valor_cliente_vip": paquete.valor_cliente_vip
                    })
            except Exception:
                return bad_json(error=1)

        return bad_json(error=0)

    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'add':
                try:
                    data['title'] = u'Crear Paquete'
                    data['form'] = PaqueteForm()
                    return render_to_response('paquetes/add.html', data)
                except Exception as ex:
                    pass

            elif action == 'edit':
                try:
                    data['title'] = u'Modificar Paquete'
                    data['paquete'] = paquete = Paquete.objects.get(
                        pk=request.GET['id'])
                    data['form'] = PaqueteForm(initial=model_to_dict(paquete))
                    return render_to_response('paquetes/edit.html', data)
                except Exception as ex:
                    pass

            elif action == 'delete':
                try:
                    data['title'] = u'Eliminar Paquete'
                    data['paquete'] = Paquete.objects.get(pk=request.GET['id'])
                    return render_to_response('paquetes/delete.html', data)
                except Exception as ex:
                    pass

            elif action == 'elementos':
                try:
                    data['title'] = u'Elementos del Paquete'
                    data['paquete'] = Paquete.objects.get(pk=request.GET['id'])
                    return render_to_response('paquetes/elementos.html', data)
                except Exception as ex:
                    pass

            if action == 'addelementoproducto':
                try:
                    data['title'] = u'Adicionar producto al paquete'
                    data['paquete'] = paquete = Paquete.objects.get(
                        pk=request.GET['id'])
                    form = PaqueteProductoForm()
                    form.for_paquete(paquete)
                    data['form'] = form
                    return render_to_response(
                        'paquetes/addelementoproducto.html', data)
                except Exception as ex:
                    pass

            if action == 'addelementoservicio':
                try:
                    data['title'] = u'Adicionar servicio al paquete'
                    data['paquete'] = paquete = Paquete.objects.get(
                        pk=request.GET['id'])
                    form = PaqueteServicioForm()
                    form.for_paquete(paquete)
                    data['form'] = form
                    return render_to_response(
                        'paquetes/addelementoservicio.html', data)
                except Exception as ex:
                    pass

            elif action == 'deleteelementoproducto':
                try:
                    data['title'] = u'Eliminar producto del paquete'
                    data['paqueteproducto'] = pp = PaqueteProducto.objects.get(
                        pk=request.GET['id'])
                    data['paquete'] = pp.paquete
                    return render_to_response(
                        'paquetes/deleteelementoproducto.html', data)
                except Exception as ex:
                    pass

            elif action == 'deleteelementoservicio':
                try:
                    data['title'] = u'Eliminar servicio del paquete'
                    data['paqueteservicio'] = ps = PaqueteServicio.objects.get(
                        pk=request.GET['id'])
                    data['paquete'] = ps.paquete
                    return render_to_response(
                        'paquetes/deleteelementoservicio.html', data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(
                url_back(request, mensaje_excepcion(ex.args[0])))

        else:
            search = None

            if 's' in request.GET:
                search = request.GET['s']

            paquetes = Paquete.objects.filter(activo=True)
            if search:
                paquetes = paquetes.filter(
                    Q(codigo__icontains=search)
                    | Q(descripcion__icontains=search))

            data['search'] = search if search else ""
            data['paquetes'] = paquetes
            return render_to_response("paquetes/paquetes.html", data)
예제 #7
0
def view(request):
    ex = None
    data = {'title': u'Panel del Colaborador'}
    addUserData(request, data)
    es_colaborador = data['es_colaborador']
    if not es_colaborador:
        return HttpResponseRedirect('/?info=Ud no es colaborador.')

    colaborador = Colaborador.objects.filter(usuario=request.user)[0]
    if request.method == 'POST':
        action = request.POST['action']
        if action == 'addsesion':
            f = MisSesionesForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        sesion = Sesion(cliente=f.cleaned_data['cliente'],
                                        paquete=f.cleaned_data['paquete'],
                                        colaborador=colaborador,
                                        fecha=f.cleaned_data['fecha'],
                                        proxima_cita=f.cleaned_data['proxima_cita'],
                                        observaciones=f.cleaned_data['observaciones'],
                                        cerrada=f.cleaned_data['cerrada'])
                        sesion.save()
                        salva_auditoria(request, sesion, ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'editsesion':
            sesion = Sesion.objects.get(pk=request.POST['id'])
            f = MisSesionesForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        sesion.paquete = f.cleaned_data['paquete']
                        sesion.cliente = f.cleaned_data['cliente']
                        sesion.fecha = f.cleaned_data['fecha']
                        sesion.proxima_cita = f.cleaned_data['proxima_cita']
                        sesion.observaciones = f.cleaned_data['observaciones']
                        sesion.cerrada = f.cleaned_data['cerrada']
                        sesion.save()
                        salva_auditoria(request, sesion, ACCION_MODIFICAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=2)
            else:
                return bad_json(error=2)

        elif action == 'deletesesion':
            try:
                sesion = Sesion.objects.get(pk=request.POST['id'])
                with transaction.atomic():
                    salva_auditoria(request, sesion, ACCION_ELIMINAR)
                    sesion.delete()
                    return ok_json()
            except Exception:
                return bad_json(error=3)

        return bad_json(error=0)

    else:

        if 'action' in request.GET:
            action = request.GET['action']

            if action == 'missesiones':
                try:
                    data['mis_sesiones'] = colaborador.sesion_set.all()
                    return render_to_response("panelcolaborador/missesiones.html", data)
                except Exception:
                    pass

            elif action == 'addsesion':
                try:
                    data['title'] = u'Crear Sesión'
                    data['form'] = MisSesionesForm(initial={'fecha': datetime.now().date()})
                    return render_to_response("panelcolaborador/add.html", data)
                except Exception as ex:
                    pass

            elif action == 'editsesion':
                try:
                    data['title'] = u'Editar Sesión'
                    data['sesion'] = sesion = Sesion.objects.get(pk=request.GET['id'])
                    data['form'] = MisSesionesForm(initial={'paquete': sesion.paquete,
                                                            'cliente': sesion.cliente,
                                                            'colaborador': sesion.colaborador,
                                                            'fecha': sesion.fecha,
                                                            'observaciones': sesion.observaciones,
                                                            'proxima_cita': sesion.proxima_cita})
                    return render_to_response("panelcolaborador/edit.html", data)
                except Exception as ex:
                    pass

            elif action == 'deletesesion':
                try:
                    data['title'] = u'Borrar Sesión'
                    data['sesion'] = Sesion.objects.get(pk=request.GET['id'])
                    return render_to_response("panelcolaborador/delete.html", data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(url_back(request, mensaje_excepcion(ex.args[0])))

        else:
            return render_to_response("panelcolaborador/view.html", data)
예제 #8
0
def view(request):
    ex = None
    data = {'title': u'Control de Sesiones de Paquetes'}
    addUserData(request, data)
    if request.method == 'POST':
        action = request.POST['action']
        if action == 'add':
            f = SesionesForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        sesion = Sesion(
                            factura=f.cleaned_data['factura'],
                            cliente=f.cleaned_data['cliente'],
                            paquete=f.cleaned_data['paquete'],
                            colaborador=f.cleaned_data['colaborador'],
                            fecha=f.cleaned_data['fecha'],
                            proxima_cita=f.cleaned_data['proxima_cita'],
                            observaciones=f.cleaned_data['observaciones'],
                            cerrada=False)
                        sesion.save()
                        salva_auditoria(request, sesion, ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'edit':
            sesion = Sesion.objects.get(pk=request.POST['id'])
            f = SesionesForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        sesion.factura = f.cleaned_data['factura']
                        sesion.paquete = f.cleaned_data['paquete']
                        sesion.cliente = f.cleaned_data['cliente']
                        sesion.colaborador = f.cleaned_data['colaborador']
                        sesion.fecha = f.cleaned_data['fecha']
                        sesion.proxima_cita = f.cleaned_data['proxima_cita']
                        sesion.observaciones = f.cleaned_data['observaciones']
                        sesion.save()
                        salva_auditoria(request, sesion, ACCION_MODIFICAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=2)
            else:
                return bad_json(error=2)

        elif action == 'delete':
            try:
                sesion = Sesion.objects.get(pk=request.POST['id'])
                with transaction.atomic():
                    salva_auditoria(request, sesion, ACCION_ELIMINAR)
                    sesion.delete()
                    return ok_json()

            except Exception:
                return bad_json(error=3)

        elif action == 'get_factura_data':
            try:
                factura = Factura.objects.get(pk=request.POST['idfact'])
                cliente = factura.cliente
                colaborador = factura.mis_colaboradores(
                )[0] if factura.mis_colaboradores() else None
                paquete = factura.detallefactura_set.filter(
                    paquete__isnull=False)[0].paquete
                return ok_json(
                    data={
                        'cliente': cliente.id if cliente else "",
                        'paquete': paquete.id if paquete else "",
                        'fecha': factura.fecha.strftime('%d-%m-%Y'),
                        'colaborador': colaborador.id if colaborador else ""
                    })
            except Exception:
                return bad_json(error=1)

        return bad_json(error=0)

    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'add':
                try:
                    data['title'] = u'Crear Sesión'
                    form = SesionesForm(
                        initial={'fecha': datetime.now().date()})
                    form.solo_facturas_con_paquetes()
                    data['form'] = form
                    return render_to_response("sesiones/add.html", data)
                except Exception as ex:
                    pass

            elif action == 'edit':
                try:
                    data['title'] = u'Editar Sesión'
                    data['sesion'] = sesion = Sesion.objects.get(
                        pk=request.GET['id'])
                    form = SesionesForm(
                        initial={
                            'factura': sesion.factura,
                            'paquete': sesion.paquete,
                            'cliente': sesion.cliente,
                            'colaborador': sesion.colaborador,
                            'fecha': sesion.fecha,
                            'observaciones': sesion.observaciones,
                            'proxima_cita': sesion.proxima_cita
                        })
                    form.solo_facturas_con_paquetes()
                    data['form'] = form
                    return render_to_response("sesiones/edit.html", data)
                except Exception as ex:
                    pass

            elif action == 'delete':
                try:
                    data['title'] = u'Borrar Sesión'
                    data['sesion'] = Sesion.objects.get(pk=request.GET['id'])
                    return render_to_response("sesiones/delete.html", data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(
                url_back(request, mensaje_excepcion(ex.args[0])))

        else:
            search = None

            if 's' in request.GET:
                search = request.GET['s']

            sesiones = Sesion.objects.all().select_related(
                'paquete', 'cliente', 'colaborador')
            if search:
                sesiones = sesiones.filter(
                    Q(cliente__nombre__icontains=search)
                    | Q(cliente__ruc__icontains=search)
                    | Q(cliente__identificacion__icontains=search))

            paging = MiPaginador(sesiones, 30)
            p = 1
            try:
                if 'page' in request.GET:
                    p = int(request.GET['page'])
                page = paging.page(p)
            except:
                page = paging.page(1)
            data['paging'] = paging
            data['rangospaging'] = paging.rangos_paginado(p)
            data['page'] = page
            data['search'] = search if search else ""
            data['sesiones'] = page.object_list
            return render_to_response("sesiones/view.html", data)
예제 #9
0
def view(request):
    ex = None
    data = {'title': u'Servicios'}
    addUserData(request, data)
    if request.method == 'POST':
        action = request.POST['action']
        if action == 'add':
            f = ServicioForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        servicio = Servicio(
                            codigo=f.cleaned_data['codigo'],
                            descripcion=f.cleaned_data['descripcion'],
                            unidadmedida=f.cleaned_data['unidadmedida'],
                            tiposervicio=f.cleaned_data['tiposervicio'],
                            alias=f.cleaned_data['alias'],
                            con_iva=f.cleaned_data['con_iva'],
                            costo_estandar=f.cleaned_data['costo_estandar'],
                            precio=f.cleaned_data['precio'],
                            precio_cliente_normal=f.
                            cleaned_data['precio_cliente_normal'],
                            precio_cliente_corporativo=f.
                            cleaned_data['precio_cliente_corporativo'],
                            precio_cliente_vip=f.
                            cleaned_data['precio_cliente_vip'])
                        servicio.save()

                        # Guardar Historial de cambios de precios
                        historialprecio = HistorialPrecioServicio(
                            servicio=servicio,
                            precio=servicio.precio,
                            precio_cliente_normal=servicio.
                            precio_cliente_normal,
                            precio_cliente_corporativo=servicio.
                            precio_cliente_corporativo,
                            precio_cliente_vip=servicio.precio_cliente_vip,
                            usuario=request.user,
                            modulo='S',  # C - Compra, S - Servicios
                            accion=ACCION_ADICIONAR)
                        historialprecio.save()

                        salva_auditoria(request, servicio, ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'edit':
            servicio = Servicio.objects.get(pk=request.POST['id'])
            f = ServicioForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        flag1 = servicio.precio != f.cleaned_data['precio']
                        flag2 = servicio.precio_cliente_normal != f.cleaned_data[
                            'precio_cliente_normal']
                        flag3 = servicio.precio_cliente_corporativo != f.cleaned_data[
                            'precio_cliente_corporativo']
                        flag4 = servicio.precio_cliente_vip != f.cleaned_data[
                            'precio_cliente_vip']
                        servicio.codigo = f.cleaned_data['codigo']
                        servicio.descripcion = f.cleaned_data['descripcion']
                        servicio.tiposervicio = f.cleaned_data['tiposervicio']
                        servicio.unidadmedida = f.cleaned_data['unidadmedida']
                        servicio.alias = f.cleaned_data['alias']
                        servicio.con_iva = f.cleaned_data['con_iva']
                        servicio.costo_estandar = f.cleaned_data[
                            'costo_estandar']
                        servicio.precio = f.cleaned_data['precio']
                        servicio.precio_cliente_normal = f.cleaned_data[
                            'precio_cliente_normal']
                        servicio.precio_cliente_corporativo = f.cleaned_data[
                            'precio_cliente_corporativo']
                        servicio.precio_cliente_vip = f.cleaned_data[
                            'precio_cliente_vip']
                        servicio.save()

                        # Guardar Historial si hubo cambios de precios
                        if flag1 or flag2 or flag3 or flag4:
                            historialprecio = HistorialPrecioServicio(
                                servicio=servicio,
                                precio=servicio.precio,
                                precio_cliente_normal=servicio.
                                precio_cliente_normal,
                                precio_cliente_corporativo=servicio.
                                precio_cliente_corporativo,
                                precio_cliente_vip=servicio.precio_cliente_vip,
                                fecha=datetime.now().date(),
                                usuario=request.user,
                                modulo='S',
                                accion=ACCION_MODIFICAR)
                            historialprecio.save()

                        for ps in servicio.paqueteservicio_set.all():
                            ps.paquete.save()

                        salva_auditoria(request, servicio, ACCION_MODIFICAR)
                    return ok_json()

                except Exception:
                    return bad_json(error=2)
            else:
                return bad_json(error=2)

        elif action == 'delete':
            servicio = Servicio.objects.get(pk=request.POST['id'])
            try:
                with transaction.atomic():
                    salva_auditoria(request, servicio, ACCION_ELIMINAR)
                    servicio.delete()
                return ok_json()

            except Exception:
                return bad_json(error=3)

        elif action == 'get_next_codigo':
            categoria = TipoServicio.objects.get(pk=request.POST['cid'])
            try:
                with transaction.atomic():
                    codigo = "SV-{}-0001".format(categoria.codigo)
                    ultimo_servicio = categoria.get_ultimo_servicio()
                    if ultimo_servicio:
                        codigo = "SV-{}-{}".format(
                            categoria.codigo,
                            str(ultimo_servicio.secuencia_codigo() +
                                1).zfill(4))
                    return ok_json(data={"codigo": codigo})

            except Exception:
                return bad_json(error=1)

        elif action == 'favorito':
            try:
                servicio = Servicio.objects.get(pk=request.POST['idprod'])
                try:
                    with transaction.atomic():
                        servicio.favorito = False if servicio.favorito else True
                        servicio.save()
                        return ok_json()
                except Exception:
                    return bad_json(error=1)
            except:
                return bad_json(error=1)

        if action == 'addreceta':
            servicio = Servicio.objects.get(pk=request.POST['id'])
            f = RecetaForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        receta = Receta(servicio=servicio,
                                        producto=f.cleaned_data['producto'])
                        receta.save()

                        salva_auditoria(request, receta, ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'deletereceta':
            receta = Receta.objects.get(pk=request.POST['id'])
            try:
                with transaction.atomic():
                    salva_auditoria(request, receta, ACCION_ELIMINAR)
                    receta.delete()
                return ok_json()

            except Exception:
                return bad_json(error=1)

        return bad_json(error=0)

    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'add':
                try:
                    data['title'] = u'Crear Servicio'
                    data['form'] = ServicioForm()
                    return render_to_response('servicios/add.html', data)
                except Exception as ex:
                    pass

            elif action == 'edit':
                try:
                    data['title'] = u'Modificar Servicio'
                    data['servicio'] = servicio = Servicio.objects.get(
                        pk=request.GET['id'])
                    form = ServicioForm(initial=model_to_dict(servicio))
                    form.for_edit()
                    data['form'] = form
                    return render_to_response('servicios/edit.html', data)
                except Exception as ex:
                    pass

            elif action == 'delete':
                try:
                    data['title'] = u'Eliminar Producto'
                    data['servicio'] = Servicio.objects.get(
                        pk=request.GET['id'])
                    return render_to_response('servicios/delete.html', data)
                except Exception as ex:
                    pass

            elif action == 'receta':
                try:
                    data['title'] = u'Receta del Servicio'
                    data['servicio'] = servicio = Servicio.objects.get(
                        pk=request.GET['id'])
                    data['receta'] = servicio.mi_receta()
                    return render_to_response('servicios/receta.html', data)
                except Exception as ex:
                    pass

            if action == 'addreceta':
                try:
                    data[
                        'title'] = u'Adicionar producto a la receta del servicio'
                    data['servicio'] = servicio = Servicio.objects.get(
                        pk=request.GET['id'])
                    form = RecetaForm()
                    form.for_receta(servicio)
                    data['form'] = form
                    return render_to_response('servicios/addreceta.html', data)
                except Exception as ex:
                    pass

            elif action == 'deletereceta':
                try:
                    data['title'] = u'Eliminar producto de la receta'
                    data['receta'] = Receta.objects.get(pk=request.GET['id'])
                    return render_to_response('servicios/deletereceta.html',
                                              data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(
                url_back(request, mensaje_excepcion(ex.args[0])))

        else:
            search = None
            tipo = None

            if 't' in request.GET and int(request.GET['t']) > 0:
                tipo = int(request.GET['t'])

            if 's' in request.GET:
                search = request.GET['s']

            servicios = Servicio.objects.filter(activo=True).select_related(
                'unidadmedida', 'tiposervicio')
            if search:
                servicios = servicios.filter(
                    Q(codigo__icontains=search)
                    | Q(descripcion__icontains=search))

            if tipo:
                servicios = servicios.filter(tiposervicio__id=tipo)

            paging = MiPaginador(servicios, 30)
            p = 1
            try:
                if 'page' in request.GET:
                    p = int(request.GET['page'])
                page = paging.page(p)
            except:
                page = paging.page(p)

            data['paging'] = paging
            data['rangospaging'] = paging.rangos_paginado(p)
            data['page'] = page
            data['search'] = search if search else ""
            data['servicios'] = page.object_list
            data['categoriaid'] = int(tipo) if tipo else ""
            data['tipos_servicios'] = TipoServicio.objects.all()
            return render_to_response("servicios/servicios.html", data)
예제 #10
0
def view(request):
    ex = None
    data = {'title': u'Ventas'}
    addUserData(request, data)

    empresaid = request.session['empresa'].id
    usuario = request.user

    if not data['es_cajero']:
        return HttpResponseRedirect(
            "/?info=El usuario no tiene permisos como cajero")
    data['cajero'] = cajero = usuario.cajero_set.all()[0]

    if not cajero.tiene_sesioncaja_abierta():
        return HttpResponseRedirect("/?info=NO TIENE SESION DE CAJA ABIERTA")

    data['sesioncaja'] = sesioncaja = cajero.get_sesion_caja_abierta()

    if request.method == 'POST':
        action = request.POST['action']

        if action == 'guardar':
            try:
                with transaction.atomic():

                    # Para comprobar si se generara la venta a partir de una orden de servicio
                    orden = None
                    if 'oid' in request.POST and request.POST['oid'] != '':
                        orden = OrdenServicio.objects.get(
                            pk=int(request.POST['oid']))

                    # JSON con los datos generales y productos
                    datos = json.loads(request.POST['items'])

                    formadepago_efectivo = False
                    if int(datos['formadepago']) == 1:
                        formadepago_efectivo = True

                    if Cliente.objects.filter(
                            identificacion=datos['ruccliente']).exists():
                        cliente = Cliente.objects.filter(
                            identificacion=datos['ruccliente'])[0]
                        cliente.nombre = datos['nombrecliente']
                        cliente.domicilio = datos['direccioncliente']
                        cliente.tipo = int(datos['tipoclienteid'])
                        cliente.telefono = datos['telefonocliente']
                        cliente.email = datos['emailcliente']
                        # cliente.save()
                    else:
                        cliente = Cliente(identificacion=datos['ruccliente'],
                                          nombre=datos['nombrecliente'],
                                          domicilio=datos['direccioncliente'],
                                          tipo=int(datos['tipoclienteid']),
                                          telefono=datos['telefonocliente'],
                                          email=datos['emailcliente'])
                        cliente.save()
                        if cliente.tipo == TIPO_CLIENTE_CORPORATIVO:
                            cliente.ruc = cliente.identificacion
                            cliente.save()

                    # Crear Factura
                    factura = Factura(
                        sesioncaja=sesioncaja,
                        cliente=cliente,
                        cajero=cajero,
                        numero=datos['numerofactura'],
                        fecha_vencimiento=convertir_fecha(
                            datos['fechafactura']).date(),
                        bruto=float(datos['bruto']),
                        descuento=float(datos['descuento']),
                        subtotal=float(datos['subtotal']),
                        iva=float(datos['iva']),
                        total=float(datos['total']),
                        notaventa=True
                        if cliente.identificacion == "9999999999" else False,
                        valida=True,
                        pagado=0,
                        valorpagado=float(datos['pagado']),
                        cambio=float(datos['cambio']),
                        observaciones=datos['observacionesfactura'])
                    factura.save()
                    # si es en efectivo, generar pago al instante
                    if formadepago_efectivo:
                        pago = Pago(factura=factura,
                                    fecha=datetime.now().date(),
                                    valor=factura.total,
                                    observaciones='')
                        pago.save()
                        pagoefectivo = PagoEfectivo(pago=pago)
                        pagoefectivo.save()
                        factura.save()  # recalcula campo pagado y cancelada

                    # Actualizar Inventario Real
                    if Area.objects.exists():
                        if Area.objects.filter(es_principal=True):
                            area = Area.objects.filter(es_principal=True)[0]
                        else:
                            area = Area.objects.all()[0]
                    else:
                        area = Area(nombre='Matriz', es_principal=True)
                        area.save()

                    for item in datos['productos']:
                        if int(item['id']):
                            producto = None
                            servicio = None
                            paquete = None

                            if item['tipoproducto'] == 'PRODUCTO':
                                producto = Producto.objects.get(
                                    pk=int(item['id']))

                            elif item['tipoproducto'] == 'SERVICIO':
                                servicio = Servicio.objects.get(
                                    pk=int(item['id']))

                            else:
                                paquete = Paquete.objects.get(
                                    pk=int(item['id']))

                            colaborador = None
                            if item['colaborador_id']:
                                colaborador = Colaborador.objects.get(
                                    pk=int(item['colaborador_id']))

                            detallefactura = DetalleFactura(
                                factura=factura,
                                producto=producto,
                                servicio=servicio,
                                paquete=paquete,
                                colaborador=colaborador,
                                cantidad=float(item['cantidad']),
                                precio=float(item['precio']),
                                valor_bruto=float(item['valorbruto']),
                                porciento_descuento=float(
                                    item['porcientodescuento']),
                                valor_descuento=float(item['valordescuento']),
                                valor=float(item['valorneto']))
                            detallefactura.save()

                            # Actualizar Inventario si es producto
                            if producto:
                                producto.actualizar_inventario_salida(
                                    detallefactura, area)

                            # Actualizar Inventario si el paquete contiene productos a consumir
                            if paquete:
                                for pp in paquete.mis_productos():
                                    pp.producto.actualizar_inventario_salida(
                                        detallefactura, area)

                    # Asignacion de la factura a la solicitud q la origino
                    if orden:
                        orden.factura_asignada = factura
                        orden.fecha_asignada = datetime.now().date()
                        orden.save()

                    salva_auditoria(request, factura, ACCION_ADICIONAR)

                    # FPDF Factura
                    pdfname = get_pdf_factura(factura, empresaid,
                                              request.user.username)
                    return ok_json(
                        data={
                            'es_efectivo':
                            '1' if formadepago_efectivo else '0',
                            'cliente_id':
                            cliente.id,
                            'urlimpresion':
                            '/'.join([
                                MEDIA_URL, 'documentos', 'userreports',
                                request.user.username, pdfname
                            ])
                        })

            except ErrorVentas as ex:
                return bad_json(mensaje=str(ex))
            except Exception as ex:
                return bad_json(mensaje=str(ex))

        if action == 'datoscliente':
            cliente = None

            if 'idc' in request.POST and int(request.POST['idc']) > 0:
                cliente = Cliente.objects.get(pk=int(request.POST['idc']))
                if not cliente.identificacion:
                    diff_lenght_clienteid = 10 - len(str(cliente.id))
                    cliente.identificacion = str(
                        cliente.id) + '1'.zfill(diff_lenght_clienteid)
                    cliente.save()

            if 'identificacion' in request.POST[
                    'identificacion'] and request.POST['identificacion']:
                if Cliente.objects.filter(identificacion=request.
                                          POST['identificacion']).exists():
                    cliente = Cliente.objects.filter(
                        identificacion=request.POST['identificacion'])[0]

            if cliente:

                if cliente.tipo == TIPO_CLIENTE_NORMAL:
                    tipo = 1
                    ruc = cliente.identificacion
                elif cliente.tipo == TIPO_CLIENTE_CORPORATIVO:
                    tipo = 2
                    if not cliente.ruc and cliente.identificacion:
                        cliente.ruc = cliente.identificacion
                        cliente.save()
                    ruc = cliente.ruc
                else:
                    tipo = 3
                    ruc = cliente.identificacion

                return ok_json(
                    data={
                        "identificacion": ruc,
                        "nombre": cliente.nombre,
                        "tipo": tipo,
                        "telefono": cliente.mi_telefono(),
                        "email": cliente.email,
                        "facturas_vencidas":
                        cliente.cantidad_facturas_vencidas(),
                        "direccion": cliente.domicilio
                    })
            else:
                return bad_json(error=1)

        if action == 'rangoprecio_producto':
            try:
                producto = Producto.objects.get(pk=request.POST['pid'])
                cantidad = float(request.POST['cantidad'])
                precioprod = producto.get_precio_by_rangoprecio(cantidad)
                return ok_json(data={"precio": precioprod})
            except:
                return bad_json(error=1)

        return bad_json(error=0)

    else:
        if 'action' in request.GET:
            action = request.GET['action']

            if action == 'ultimonumerofactura':
                try:
                    numero = 1
                    sc = SesionCaja.objects.get(pk=request.GET['scid'])
                    if sc.factura_set.exists():
                        ultimafactura = sc.factura_set.latest('id')
                        numero = int(ultimafactura.numero) + 1
                    return ok_json(data={"numero": numero})
                except Exception:
                    return bad_json(error=1)

            if action == 'ordenes':
                try:
                    clienteid = None
                    if 'c' in request.GET and int(request.GET['c']) > 0:
                        clienteid = int(request.GET['c'])
                    ordenes = OrdenServicio.objects.filter(
                        factura_asignada=None)
                    if clienteid:
                        ordenes = ordenes.filter(cliente__id=clienteid)
                    data['ordenes'] = ordenes
                    data['clientes'] = Cliente.objects.filter(
                        ordenservicio__isnull=False).distinct()
                    return render_to_response("ventas/ordenes.html", data)
                except Exception as ex:
                    pass

            if action == 'detalle_orden':
                try:
                    data['orden'] = orden = OrdenServicio.objects.get(
                        pk=request.GET['ordenid'])
                    data['detalles'] = orden.ordenserviciodetalle_set.all()
                    return render_to_response('ordenes/detalles.html', data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(
                url_back(request, mensaje_excepcion(ex.args[0])))

        else:

            if 'oid' in request.GET:
                data['orden'] = orden = OrdenServicio.objects.get(
                    pk=int(request.GET['oid']))
                data['orden_detalles'] = orden.ordenserviciodetalle_set.all()

            data['colaboradores'] = Colaborador.objects.all()
            data['lista_items_ventas'] = [x for x in range(10)]

            productos = Producto.objects.filter(
                activo=True,
                precio__gt=0,
                inventarioreal__isnull=False,
                inventarioreal__cantidad__gt=0).distinct()[:10]

            servicios = Servicio.objects.filter(activo=True, precio__gt=0)[:10]

            paquetes = Paquete.objects.filter(activo=True)

            data['lista_items'] = list(chain(productos, servicios, paquetes))

            return render_to_response("ventas/view.html", data)
예제 #11
0
def view(request):
    ex = None
    data = {'title': u'Sesiones de Caja'}
    addUserData(request, data)

    usuario = request.user
    if not data['es_cajero']:
        return HttpResponseRedirect("/?info=El usuario no tiene permisos como cajero")
    data['cajero'] = cajero = usuario.cajero_set.all()[0]

    if request.method == 'POST':
        action = request.POST['action']

        if action == 'abrirsesion':
            f = SesionCajaForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        sc = SesionCaja(cajero=cajero,
                                        fecha=datetime.now(),
                                        fondo=f.cleaned_data['fondo'],
                                        abierta=True)
                        sc.save()
                        salva_auditoria(request, sc, ACCION_MODIFICAR, 'Abierta sesion de caja: ' + sc.__str__())
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'closesesion':
            sc = SesionCaja.objects.get(pk=request.POST['id'])
            f = CierreSesionCajaForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        sc.bill100 = f.cleaned_data['bill100']
                        sc.bill50 = f.cleaned_data['bill50']
                        sc.bill20 = f.cleaned_data['bill20']
                        sc.bill10 = f.cleaned_data['bill10']
                        sc.bill5 = f.cleaned_data['bill5']
                        sc.bill2 = f.cleaned_data['bill2']
                        sc.bill1 = f.cleaned_data['bill1']
                        sc.enmonedas = f.cleaned_data['enmonedas']
                        sc.cheque = f.cleaned_data['cheque']
                        sc.deposito = f.cleaned_data['deposito']
                        sc.transferencia = f.cleaned_data['transferencia']
                        sc.abierta = False
                        sc.fechacierre = datetime.now()
                        sc.horacierre = datetime.now().time()
                        sc.save()
                        salva_auditoria(request, sc, ACCION_MODIFICAR, 'Cerrada sesion de caja: {}'.format(sc))
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        return bad_json(error=0)

    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'addsesion':
                try:
                    data['title'] = u'Abrir Sesión de Caja'
                    data['form'] = SesionCajaForm(initial={'fondo': '0.00'})
                    return render_to_response("caja/adicionarbs.html", data)
                except Exception as ex:
                    pass

            elif action == 'closesesion':
                try:
                    data['title'] = u'Cierre Sesión de Caja'
                    data['sesion'] = SesionCaja.objects.get(pk=request.GET['id'])
                    data['form'] = CierreSesionCajaForm(initial={'bill100': 0,
                                                                 'bill50': 0,
                                                                 'bill20': 0,
                                                                 'bill10': 0,
                                                                 'bill5': 0,
                                                                 'bill2': 0,
                                                                 'bill1': 0,
                                                                 'enmonedas': 0.00,
                                                                 'cheque': 0.00,
                                                                 'deposito': 0.00,
                                                                 'transferencia': 0.00,
                                                                 'total': 0.00})
                    return render_to_response("caja/cerrarsesionbs.html", data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(url_back(request, mensaje_excepcion(ex.args[0])))

        else:
            sesiones = cajero.sesiones_caja()
            paging = MiPaginador(sesiones, 30)
            p = 1
            try:
                if 'page' in request.GET:
                    p = int(request.GET['page'])
                sesionespagina = paging.page(p)
            except:
                sesionespagina = paging.page(1)
            data['paging'] = paging
            data['rangospaging'] = paging.rangos_paginado(p)
            data['page'] = sesionespagina
            data['sesiones'] = sesionespagina.object_list
            return render_to_response("caja/sesionesbs.html", data)
예제 #12
0
def view(request):
    ex = None
    data = {'title': u'Gestión de Cajeros'}
    addUserData(request, data)

    if request.method == 'POST':
        action = request.POST['action']
        if action == 'add':
            f = CajeroForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        cedula = f.cleaned_data['cedula']
                        usuario_nombre = f.cleaned_data['usuario']
                        if Cajero.objects.filter(cedula=cedula).exists():
                            return bad_json(
                                mensaje=
                                u"Ya existe un cajero registrado con ese número de cedula."
                            )
                        if User.objects.filter(
                                username=usuario_nombre).exists():
                            return bad_json(
                                mensaje=
                                u"Ya existe ese nombre de usuario en el sistema favor de corregir."
                            )

                        cajero = Cajero(cedula=cedula,
                                        nombre=f.cleaned_data['nombre'],
                                        direccion=f.cleaned_data['direccion'],
                                        telefono=f.cleaned_data['telefono'],
                                        email=f.cleaned_data['email'])
                        cajero.save()

                        user = User.objects.create_user(
                            usuario_nombre, cajero.email, DEFAULT_PASSWORD)
                        user.username = user.username.lower()
                        user.save()
                        cajero.usuario = user
                        cajero.save()
                        g = Group.objects.get(pk=CAJAS_GROUP_ID)
                        g.user_set.add(user)
                        g.save()
                        salva_auditoria(request, cajero, ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        elif action == 'edit':
            cajero = Cajero.objects.get(pk=request.POST['id'])
            f = CajeroForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        cedula = f.cleaned_data['cedula']
                        usuario_nombre = f.cleaned_data['usuario']
                        if Cajero.objects.filter(cedula=cedula).exclude(
                                id=cajero.id).exists():
                            return bad_json(
                                mensaje=
                                u"Ya existe un cajero registrado con ese número de cedula."
                            )
                        if User.objects.filter(
                                username=usuario_nombre).exclude(
                                    cajero__id=cajero.id).exists():
                            return bad_json(
                                mensaje=
                                u"Ya existe ese nombre de usuario en el sistema favor de corregir."
                            )

                        cajero.cedula = cedula
                        cajero.nombre = f.cleaned_data['nombre']
                        cajero.direccion = f.cleaned_data['direccion']
                        cajero.telefono = f.cleaned_data['telefono']
                        cajero.email = f.cleaned_data['email']
                        cajero.save()
                        cajero.usuario.username = usuario_nombre
                        cajero.usuario.save()
                        salva_auditoria(request, cajero, ACCION_MODIFICAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=2)
            else:
                return bad_json(error=2)

        elif action == 'delete':
            try:
                cajero = Cajero.objects.get(pk=request.POST['id'])
                with transaction.atomic():
                    salva_auditoria(request, cajero, ACCION_ELIMINAR)
                    cajero.delete()
                    return ok_json()

            except Exception:
                return bad_json(error=3)

        elif action == 'resetear':
            try:
                cajero = Cajero.objects.get(pk=request.POST['id'])
                with transaction.atomic():
                    user = cajero.usuario
                    user.set_password(DEFAULT_PASSWORD)
                    user.save()
                    salva_auditoria(request, cajero, ACCION_MODIFICAR)
                    return ok_json()

            except Exception:
                return bad_json(error=2)

        return bad_json(error=0)
    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'add':
                try:
                    data['title'] = u'Crear Cajero'
                    data['form'] = CajeroForm()
                    return render_to_response("cajeros/add.html", data)
                except Exception as ex:
                    pass

            elif action == 'edit':
                try:
                    data['title'] = u'Editar Cajero'
                    data['cajero'] = cajero = Cajero.objects.get(
                        pk=request.GET['id'])
                    data['form'] = CajeroForm(
                        initial={
                            'cedula': cajero.cedula,
                            'nombre': cajero.nombre,
                            'direccion': cajero.direccion,
                            'telefono': cajero.telefono,
                            'email': cajero.email,
                            'usuario': cajero.usuario.username
                        })
                    return render_to_response("cajeros/edit.html", data)
                except Exception as ex:
                    pass

            elif action == 'delete':
                try:
                    data['title'] = u'Borrar cajero'
                    data['cajero'] = Cajero.objects.get(pk=request.GET['id'])
                    return render_to_response("cajeros/delete.html", data)
                except Exception as ex:
                    pass

            elif action == 'resetear':
                try:
                    data['title'] = u'Resetear clave del cajero'
                    data['cajero'] = Cajero.objects.get(pk=request.GET['id'])
                    return render_to_response("cajeros/resetear.html", data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(
                url_back(request, mensaje_excepcion(ex.args[0])))

        else:
            search = None

            if 's' in request.GET:
                search = request.GET['s']
            if search:
                cajeros = Cajero.objects.filter(
                    Q(nombre__icontains=search) | Q(cedula__icontains=search)
                    | Q(usuario__username__icontains=search))
            else:
                cajeros = Cajero.objects.all()

            paging = MiPaginador(cajeros, 30)
            p = 1
            try:
                if 'page' in request.GET:
                    p = int(request.GET['page'])
                page = paging.page(p)
            except:
                page = paging.page(1)
            data['paging'] = paging
            data['rangospaging'] = paging.rangos_paginado(p)
            data['page'] = page
            data['search'] = search if search else ""
            data['cajeros'] = page.object_list
            return render_to_response("cajeros/view.html", data)
예제 #13
0
def view(request):
    ex = None
    data = {'title': u'Ordenes de Servicio'}
    addUserData(request, data)
    if not data['es_colaborador']:
        return bad_json(
            mensaje=u"El usuario no pertenece al grupo de colaboradores")
    if not Colaborador.objects.filter(usuario__username=request.user).exists():
        return bad_json(mensaje=u"El usuario no es colaborador")
    colaborador = Colaborador.objects.filter(usuario__username=request.user)[0]

    if request.method == 'POST':
        action = request.POST['action']
        if action == 'delete':
            orden = OrdenServicio.objects.get(pk=request.POST['id'])
            try:
                with transaction.atomic():
                    salva_auditoria(request, orden, ACCION_ELIMINAR)
                    orden.delete()
                    return ok_json()

            except Exception:
                return bad_json(error=3)

        elif action == 'datoscliente':
            cliente = None

            if 'idc' in request.POST and int(request.POST['idc']) > 0:
                cliente = Cliente.objects.get(pk=int(request.POST['idc']))
                if not cliente.identificacion:
                    diff_lenght_clienteid = 10 - len(str(cliente.id))
                    cliente.identificacion = str(
                        cliente.id) + '1'.zfill(diff_lenght_clienteid)
                    cliente.save()

            if 'identificacion' in request.POST[
                    'identificacion'] and request.POST['identificacion']:
                if Cliente.objects.filter(identificacion=request.
                                          POST['identificacion']).exists():
                    cliente = Cliente.objects.filter(
                        identificacion=request.POST['identificacion'])[0]

            if cliente:

                if cliente.tipo == TIPO_CLIENTE_NORMAL:
                    tipo = 1
                    ruc = cliente.identificacion
                elif cliente.tipo == TIPO_CLIENTE_CORPORATIVO:
                    tipo = 2
                    if not cliente.ruc and cliente.identificacion:
                        cliente.ruc = cliente.identificacion
                        cliente.save()
                    ruc = cliente.ruc
                else:
                    tipo = 3
                    ruc = cliente.identificacion

                return ok_json(
                    data={
                        "identificacion": ruc,
                        "nombre": cliente.nombre,
                        "tipo": tipo,
                        "telefono": cliente.mi_telefono(),
                        "email": cliente.email,
                        "direccion": cliente.domicilio
                    })
            else:
                return bad_json(error=1)

        elif action == 'generar':
            try:
                with transaction.atomic():

                    datos = json.loads(request.POST['items'])
                    items = json.loads(request.POST['productos'])

                    if Cliente.objects.filter(
                            identificacion=datos['ruccliente']).exists():
                        cliente = Cliente.objects.filter(
                            identificacion=datos['ruccliente'])[0]
                        cliente.nombre = datos['nombrecliente']
                        cliente.domicilio = datos['direccioncliente']
                        cliente.tipo = int(datos['tipoclienteid'])
                        cliente.telefono = datos['telefonocliente']
                        cliente.email = datos['emailcliente']
                        cliente.save()
                    else:
                        cliente = Cliente(identificacion=datos['ruccliente'],
                                          nombre=datos['nombrecliente'],
                                          domicilio=datos['direccioncliente'],
                                          tipo=int(datos['tipoclienteid']),
                                          telefono=datos['telefonocliente'],
                                          email=datos['emailcliente'])
                        cliente.save()
                        if cliente.tipo == TIPO_CLIENTE_CORPORATIVO:
                            cliente.ruc = cliente.identificacion
                            cliente.save()

                    # Crear Orden de Servicio
                    orden = OrdenServicio(
                        cliente=cliente,
                        colaborador=colaborador,
                        fecha=fechaactual,
                        subtotal=float(datos['subtotal']),
                        iva=float(datos['iva']),
                        total=float(datos['total']),
                        observaciones=datos['observacionesfactura'])
                    orden.save()

                    for item in items:
                        producto = None
                        servicio = None
                        if item['tipoproducto'] == 'PRODUCTO':
                            producto = Producto.objects.filter(
                                codigo=item['codproducto'])[0]
                        else:
                            servicio = Servicio.objects.filter(
                                codigo=item['codproducto'])[0]
                        detalleorden = OrdenServicioDetalle(
                            orden=orden,
                            servicio=servicio,
                            producto=producto,
                            cantidad=float(item['cantidad']),
                            precio=float(item['pvpproducto']),
                            valor=float(item['valor']))
                        detalleorden.save()

                    salva_auditoria(request, orden, ACCION_ADICIONAR)
                    return ok_json(data={
                        "orden": orden.repr_id(),
                        "cliente": orden.cliente.nombre
                    })

            except ErrorOrdenServicio:
                return bad_json(error=2)
            except Exception:
                return bad_json(error=1)

        elif action == 'add_serviciofuturo':
            orden = OrdenServicio.objects.get(pk=request.POST['id'])
            f = ServicioFuturoForm(request.POST)
            if f.is_valid():
                try:
                    with transaction.atomic():
                        if f.cleaned_data['fecha'] < datetime.now().date():
                            return bad_json(
                                mensaje=
                                "La fecha no puede ser menor al dia de hoy")
                        serviciofuturo = ServicioFuturo(
                            orden=orden,
                            cliente=orden.cliente,
                            servicio=f.cleaned_data['servicio'],
                            fecha=f.cleaned_data['fecha'])
                        serviciofuturo.save()
                        salva_auditoria(request, serviciofuturo,
                                        ACCION_ADICIONAR)
                        return ok_json()

                except Exception:
                    return bad_json(error=1)
            else:
                return bad_json(error=1)

        if action == 'delete_serviciofuturo':
            serviciofuturo = ServicioFuturo.objects.get(pk=request.POST['id'])
            try:
                with transaction.atomic():
                    salva_auditoria(request, serviciofuturo, ACCION_ELIMINAR)
                    serviciofuturo.delete()
                    return ok_json()
            except Exception:
                return bad_json(error=1)

        return bad_json(error=0)

    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'add':
                try:
                    data['title'] = u'Crear Orden de Servicio'
                    data['tipos_productos'] = TipoProducto.objects.all()
                    data['tipos_servicios'] = TipoServicio.objects.all()
                    data['tipos_documentos'] = TipoDocumento.objects.all()
                    return render_to_response("ordenes/add.html", data)
                except Exception as ex:
                    pass

            elif action == 'delete':
                try:
                    data['title'] = u'Eliminar orden de servicio'
                    data['orden'] = OrdenServicio.objects.get(
                        pk=request.GET['id'])
                    return render_to_response("ordenes/delete.html", data)
                except Exception as ex:
                    pass

            elif action == 'detalle_orden':
                try:
                    data['orden'] = orden = OrdenServicio.objects.get(
                        pk=request.GET['id'])
                    data['detalles'] = orden.ordenserviciodetalle_set.all()
                    return render_to_response('ordenes/detalles.html', data)
                except Exception as ex:
                    pass

            if action == 'buscaproductos':
                try:
                    inventarios = None
                    tipoprod = None
                    if 'tipoid' in request.GET and request.GET['tipoid'] != '':
                        tipoprod = TipoProducto.objects.get(
                            pk=request.GET['tipoid'])
                        inventarios = tipoprod.productos_con_existencias()
                    data['productos'] = inventarios
                    data['tipoprod'] = tipoprod
                    data['tipocliente'] = int(request.GET['tipoclienteid'])
                    return render_to_response("ordenes/buscaproductos.html",
                                              data)
                except Exception as ex:
                    pass

            if action == 'buscaservicios':
                try:
                    servicios = None
                    tiposerv = None
                    if 'tipoid' in request.GET and request.GET['tipoid'] != '':
                        tiposerv = TipoServicio.objects.get(
                            pk=request.GET['tipoid'])
                        servicios = tiposerv.servicio_set.filter(activo=True)
                    data['servicios'] = servicios
                    data['tiposerv'] = tiposerv
                    data['tipocliente'] = int(request.GET['tipoclienteid'])
                    return render_to_response("ordenes/buscaproductos.html",
                                              data)
                except Exception as ex:
                    pass

            if action == 'serviciosfuturos':
                try:
                    data['orden'] = orden = OrdenServicio.objects.get(
                        pk=request.GET['id'])
                    data['servicios_futuros'] = orden.serviciofuturo_set.all()
                    data[
                        'cantidad_servicios_futuros'] = orden.serviciofuturo_set.count(
                        )
                    return render_to_response("ordenes/serviciosfuturos.html",
                                              data)
                except Exception as ex:
                    pass

            if action == 'add_serviciofuturo':
                try:
                    data['title'] = u'Adicionar Servicio Futuro'
                    data['orden'] = orden = OrdenServicio.objects.get(
                        pk=request.GET['id'])
                    form = ServicioFuturoForm()
                    form.for_serviciofuturo(orden)
                    data['form'] = form
                    return render_to_response(
                        'ordenes/add_serviciofuturo.html', data)
                except Exception as ex:
                    pass

            elif action == 'delete_serviciofuturo':
                try:
                    data['title'] = u'Eliminar servicio futuro'
                    data[
                        'servicio_futuro'] = servicio_futuro = ServicioFuturo.objects.get(
                            pk=request.GET['id'])
                    data['orden'] = servicio_futuro.orden
                    return render_to_response(
                        "ordenes/delete_serviciofuturo.html", data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(
                url_back(request, mensaje_excepcion(ex.args[0])))

        else:

            search = None
            clienteid = None

            if 's' in request.GET:
                search = request.GET['s']

            if 'c' in request.GET and int(request.GET['c']) > 0:
                clienteid = int(request.GET['c'])

            if search:
                ordenes = OrdenServicio.objects.filter(
                    Q(cliente__nombre__icontains=search),
                    Q(factura__numero__icontains=search),
                    colaborador=colaborador).distinct()
            elif clienteid:
                ordenes = OrdenServicio.objects.filter(cliente__id=clienteid,
                                                       colaborador=colaborador)
            else:
                ordenes = OrdenServicio.objects.filter(colaborador=colaborador)

            paging = MiPaginador(ordenes, 30)
            p = 1
            try:
                if 'page' in request.GET:
                    p = int(request.GET['page'])
                page = paging.page(p)
            except:
                page = paging.page(1)
            data['paging'] = paging
            data['rangospaging'] = paging.rangos_paginado(p)
            data['page'] = page
            data['search'] = search if search else ""
            data['ordenes'] = page.object_list
            data['clienteid'] = clienteid if clienteid else ""
            data['clientes'] = Cliente.objects.filter(
                ordenservicio__colaborador__usuario=request.user).distinct()
            return render_to_response("ordenes/view.html", data)
예제 #14
0
def view(request):
    data = {'title': u'Cobros'}
    addUserData(request, data)
    data['empresa'] = request.session['empresa']

    if request.method == 'POST':
        action = request.POST['action']

        if action == 'pendientes':
            cliente = Cliente.objects.get(pk=request.POST['cid'])
            ventas = cliente.factura_set.filter(total__gt=F('pagado'),
                                                valida=True).order_by(
                                                    '-fecha_vencimiento',
                                                    'numero')
            totalpendiente = 0
            totalpagado = 0
            lista = []
            for a in ventas:
                d = model_to_dict_safe(
                    a, exclude=['fecha', 'fecha_vencimiento', 'detalles'])
                d['fecha'] = a.fecha_vencimiento.strftime("%d-%m-%Y")
                d['cantidad_productos'] = a.cantidad_productos()
                totalpendiente += (a.total - a.pagado)
                totalpagado += a.pagado
                lista.append(d)

            return ok_json(
                data={
                    "datos": lista,
                    "totalpendiente": totalpendiente,
                    "totalpagado": totalpagado
                })

        elif action == 'pago':
            datos = json.loads(request.POST['datos'])
            total = 0
            try:
                with transaction.atomic():
                    # Facturas seleccionadas
                    for documento in datos['ingresosapagar']:
                        factura = Factura.objects.get(pk=documento['id'])
                        # Pagos asociados
                        for p in datos['pagos']:
                            if p['formapago'] == str(FORMA_PAGO_EFECTIVO):
                                pago = Pago(factura=factura,
                                            fecha=convertir_fecha(
                                                p['fechaefectivo']),
                                            valor=float(p['valor']),
                                            observaciones=p['observaciones'])
                                pago.save()
                                pagoefectivo = PagoEfectivo(pago=pago)
                                pagoefectivo.save()
                                total += pagoefectivo.pago.valor

                            elif p['formapago'] == str(FORMA_PAGO_CHEQUE):
                                pago = Pago(factura=factura,
                                            fecha=convertir_fecha(
                                                p['fechacheque']),
                                            valor=float(p['valor']),
                                            observaciones=p['observaciones'])
                                pago.save()
                                pagocheque = PagoCheque(
                                    pago=pago,
                                    numero=p['numerocheque'],
                                    banco_id=p['bancocheque'],
                                    postfechado=True
                                    if int(p['postfechado']) == 1 else False,
                                    depositado=True
                                    if int(p['depositado']) == 1 else False,
                                    fechadepositado=convertir_fecha(
                                        p['fechadepositado']),
                                    emite=p['emite'])
                                pagocheque.save()
                                total += pagocheque.pago.valor

                            elif p['formapago'] == str(FORMA_PAGO_DEPOSITO):
                                pago = Pago(factura=factura,
                                            fecha=convertir_fecha(
                                                p['fechadeposito']),
                                            valor=float(p['valor']),
                                            observaciones=p['observaciones'])
                                pago.save()
                                pagodeposito = PagoDeposito(
                                    pago=pago,
                                    numero=p['numerodeposito'],
                                    efectuadopor=p['efectuadopor'])
                                pagodeposito.save()
                                total += pagodeposito.pago.valor

                            elif p['formapago'] == str(
                                    FORMA_PAGO_TRANSFERENCIA):
                                pago = Pago(factura=factura,
                                            fecha=convertir_fecha(
                                                p['fechatransferencia']),
                                            valor=float(p['valor']),
                                            observaciones=p['observaciones'])
                                pago.save()
                                pagotransferencia = PagoTransferencia(
                                    pago=pago,
                                    numero=p['numerotransferencia'],
                                    efectuadopor=p['efectuadopor'])
                                pagotransferencia.save()
                                total += pagotransferencia.pago.valor

                            elif p['formapago'] == str(FORMA_PAGO_TARJETA):
                                if PagoTarjeta.objects.filter(
                                        referencia=p['referencia'],
                                        lote=p['lote']).exists():
                                    return bad_json(
                                        extradata={'result': 'repeat'})
                                pago = Pago(factura=factura,
                                            fecha=convertir_fecha(
                                                p['fechatarjeta']),
                                            valor=float(p['valor']),
                                            observaciones=p['observaciones'])
                                pago.save()
                                pagotarjeta = PagoTarjeta(
                                    pago=pago,
                                    banco_id=p['bancotarjeta'],
                                    tipotarjeta_id=p['tipotarjeta'],
                                    poseedor=p['poseedor'],
                                    procesadorpago_id=p['procesadorpago'],
                                    referencia=p['referencia'],
                                    lote=p['lote'])
                                pagotarjeta.save()
                                total += pagotarjeta.pago.valor

                            elif p['formapago'] == str(FORMA_PAGO_RETENCION):
                                pago = Pago(factura=factura,
                                            fecha=convertir_fecha(
                                                p['fecharetencion']),
                                            valor=float(p['valor']),
                                            observaciones=p['observaciones'])
                                pago.save()
                                pagoretencion = PagoRetencion(
                                    pago=pago, numero=p['numeroretencion'])
                                pagoretencion.save()
                                total += pagoretencion.pago.valor

                        factura.pagado += total
                        factura.save()

                    return ok_json()

            except Exception:
                return bad_json(error=1)

        return bad_json(error=0)

    else:
        try:
            cliente = None
            if 'cid' in request.GET and int(
                    request.GET['cid']) > 0 and Cliente.objects.filter(
                        pk=int(request.GET['cid'])).exists():
                cliente = Cliente.objects.filter(pk=int(request.GET['cid']))[0]

            data['hoy'] = hoy = datetime.now().date()
            data['form'] = PagoForm()
            data['form3'] = TransaccionPagoForm(
                initial={
                    'valor': 0,
                    'fechacheque': hoy,
                    'fechaefectivo': hoy,
                    'fechadeposito': hoy,
                    'fechatransferencia': hoy,
                    'fechatarjeta': hoy,
                    'fechadepositado': hoy
                })
            data['formasdepago'] = FormaDePago.objects.all()
            data['forma_pago_efectivo'] = FORMA_PAGO_EFECTIVO
            data['forma_pago_cheque'] = FORMA_PAGO_CHEQUE
            data['forma_pago_deposito'] = FORMA_PAGO_DEPOSITO
            data['forma_pago_transferencia'] = FORMA_PAGO_TRANSFERENCIA
            data['forma_pago_tarjeta'] = FORMA_PAGO_TARJETA
            data['forma_pago_retencion'] = FORMA_PAGO_RETENCION
            data['procesadorespago'] = ProcesadorPagoTarjeta.objects.all()
            data['tipostarjeta'] = TipoTarjetaBanco.objects.all()
            data['cliente'] = cliente
            return render_to_response("pagos/view.html", data)

        except Exception:
            pass
예제 #15
0
def index(request):
    global ex
    data = {'title': 'Bienvenidos - ' + NOMBRE_INSTITUCION}
    addUserData(request, data)
    data['hoy'] = datetime.now().date()
    es_cliente = data['es_cliente']
    es_colaborador = data['es_colaborador']
    if es_colaborador:
        return HttpResponseRedirect('/panelcolaborador')
    if es_cliente:
        return HttpResponseRedirect('/panelclientes')
    if request.method == 'POST':
        if 'action' in request.POST:
            return bad_json(error=0)

    else:
        if 'action' in request.GET:
            action = request.GET['action']
            if action == 'buscaproductos':
                try:
                    inventarios = None
                    if request.GET['tipoid'] != '':
                        data['tipoprod'] = tipoprod = TipoProducto.objects.get(pk=request.GET['tipoid'])
                        inventarios = tipoprod.productos_con_existencias()
                    data['productos_existencias'] = inventarios
                    data['iva'] = IVA
                    return render_to_response("solicitudes/buscaproductos.html", data)
                except Exception as ex:
                    pass

            return HttpResponseRedirect(url_back(request, mensaje_excepcion(ex.args[0])))

        else:
            if 'info' in request.GET:
                data['info'] = request.GET['info']

            # Dashboard estadistico (Para los administradores del sistema)
            # ventas
            data['valores_ventas_total'] = valores_ventas_total()
            data['cantidad_facturas_total'] = cantidad_facturas_total()
            # compras
            data['valor_total_cif_compras'] = valor_total_cif_compras()
            data['cantidad_compras_total'] = cantidad_compras_total()
            # pagos
            data['pagos_total'] = pagos_total()
            data['cantidad_pagos_total'] = cantidad_pagos_total()
            # inventarios
            data['valor_inventario_con_existencia'] = valor_inventario_con_existencia()
            data['cantidad_inventario_con_existencia'] = cantidad_inventario_con_existencia()
            # cobros pendientes
            data['valor_facturas_por_cancelar'] = valor_facturas_por_cancelar()
            data['cantidad_facturas_por_cancelar'] = cantidad_facturas_por_cancelar()
            # 2da Tabla estadistica
            data['cantidad_clientes'] = cantidad_clientes()
            data['cantidad_vendedores'] = cantidad_vendedores()
            data['cantidad_proveedores'] = cantidad_proveedores()
            data['cantidad_inventario_agotado'] = cantidad_inventario_agotado()
            data['cantidad_inventario_bajo_minimo'] = cantidad_inventario_bajo_minimo()
            # Graficos
            data['clientes_mas_compran'] = Cliente.objects.filter(factura__isnull=False,
                                                                  factura__valida=True).distinct().annotate(
                cantidadventas=Count('factura__id')).distinct().order_by('-cantidadventas')[:5]
            data['productos_mas_vendidos'] = Producto.objects.filter(detallefactura__isnull=False).annotate(
                cantidadventas=Count('detallefactura__id')).distinct().order_by('-cantidadventas')[:5]
            # Tablas - Ultimas ventas y compras
            data['ultimas_ventas'] = Factura.objects.filter(valida=True)[:5]
            data['ultimas_compras'] = IngresoProducto.objects.all()[:5]
            # Otras Tablas - Resumen y Ultimas auditorias
            data['cantidad_productos'] = cantidad_productos()
            data['cantidad_categorias'] = cantidad_categorias()
            data['cantidad_usuarios'] = cantidad_usuarios()
            data['cantidad_facturas_anuladas'] = cantidad_facturas_anuladas()
            data['cantidad_formas_pago'] = cantidad_formas_pago()
            data['ultimas_auditorias'] = AudiUsuarioTabla.objects.all()[:5]
            # Solicitudes de compras (usuarios Clientes o Vendedores)
            data['cantidad_solicitudes_pendientes_clientes'] = cantidad_solicitudes_pendientes_clientes()
            data['cantidad_solicitudes_pendientes_vendedores'] = cantidad_solicitudes_pendientes_vendedores()
            data['cantidad_solicitudes_asignadas'] = cantidad_solicitudes_asignadas()
            data['tipos_productos'] = TipoProducto.objects.all().order_by('orden')
            data['tipos_documentos'] = TipoDocumento.objects.all()
            return render_to_response("panelbs.html", data)
예제 #16
0
def view(request):
    data = {'title': 'Compras'}
    addUserData(request, data)
    usuario = request.user

    if request.method == 'POST':
        action = request.POST['action']
        if action == 'ingresoinv':
            try:
                datos = json.loads(request.POST['datos'])
                with transaction.atomic():
                    ingresoprod = IngresoProducto(
                        proveedor_id=int(datos['proveedor']),
                        tipodocumento_id=int(datos['tipodocumento']),
                        numerodocumento=datos['numerodocumento'],
                        fechadocumento=convertir_fecha(
                            datos['fechadocumento']),
                        descripcion=datos['descripcion'],
                        fecha=datetime.now().date(),
                        usuario=usuario)
                    ingresoprod.save()
                    # items
                    items = datos['items']
                    for d in items:
                        codigo = d['codigo']
                        if Producto.objects.filter(codigo=codigo).exists():
                            producto = Producto.objects.filter(
                                codigo=codigo)[0]
                        else:
                            return HttpResponse(
                                json.dumps({
                                    "result": "bad",
                                    "mensaje": "El producto no existe"
                                }),
                                content_type="application/json")

                        detalleingprod = DetalleIngresoProducto(
                            compra=ingresoprod,
                            producto=producto,
                            cantidad=float(d['cantidad']),
                            costo=float(d['costo']),
                            valor=float(d['valor']))
                        detalleingprod.save()

                        # Guardar Historial de costos CIF
                        historialcif = HistorialCifProducto(
                            producto=producto,
                            compra=ingresoprod,
                            cif=detalleingprod.costo,
                            usuario=request.user)
                        historialcif.save()

                        # Actualizar Inventario Real
                        if Area.objects.exists():
                            if Area.objects.filter(es_principal=True):
                                area = Area.objects.filter(
                                    es_principal=True)[0]
                            else:
                                area = Area.objects.all()[0]
                        else:
                            area = Area(nombre='Matriz', es_principal=True)
                            area.save()

                        # COSTO Y SALDO ANTES DEL MOVIMIENTO
                        saldoinicialvalor = detalleingprod.producto.valor_inventario(
                            area)
                        saldoinicialcantidad = detalleingprod.producto.stock_inventario(
                            area)

                        # ACTUALIZAR INVENTARIO REAL
                        costoproducto = round(
                            (detalleingprod.valor / detalleingprod.cantidad),
                            2) if detalleingprod.cantidad else 0
                        producto.actualizar_inventario_ingreso(
                            costoproducto, detalleingprod.cantidad, area)
                        inventario = producto.mi_inventario(area)

                        # ACTUALIZAR KARDEX
                        kardex = KardexInventario(
                            producto=detalleingprod.producto,
                            inventario=inventario,
                            tipomovimiento=TIPO_MOVIMIENTO_ENTRADA,
                            dcompra=detalleingprod,
                            saldoinicialvalor=saldoinicialvalor,
                            saldoinicialcantidad=saldoinicialcantidad,
                            cantidad=detalleingprod.cantidad,
                            costo=costoproducto,
                            valor=round(
                                (costoproducto * detalleingprod.cantidad), 2))
                        kardex.save()

                        # COSTO Y SALDO DESPUES DEL MOVIMIENTO
                        saldofinalvalor = detalleingprod.producto.valor_inventario(
                            area)
                        saldofinalcantidad = detalleingprod.producto.stock_inventario(
                            area)
                        kardex.saldofinalcantidad = saldofinalcantidad
                        kardex.saldofinalvalor = saldofinalvalor
                        kardex.save()

                    # Actualizar valore total de la compra
                    ingresoprod.valor = ingresoprod.valor_compra()
                    ingresoprod.save()
                    salva_auditoria(request, ingresoprod, ACCION_ADICIONAR)
                    return ok_json()

            except Exception:
                return bad_json(error=1)

        elif action == 'chequeacodigos':
            cod_existen = [
                x.codigo for x in Producto.objects.filter(
                    codigo__in=request.POST['codigos'].split(","))
            ]
            if cod_existen:
                return ok_json(data={"codigosexisten": cod_existen})
            return bad_json(error=1)

        elif action == 'comprobarnumero':
            proveedor = Proveedor.objects.get(pk=request.POST['pid'])
            numero = request.POST['numero']
            tipodoc = TipoDocumento.objects.get(pk=request.POST['tipodoc'])
            if proveedor.ingresoproducto_set.filter(
                    numerodocumento=numero, tipodocumento=tipodoc).exists():
                return bad_json(error=1)
            return ok_json()

        elif action == 'importar':
            form = ImportarArchivoXLSForm(request.POST, request.FILES)
            if form.is_valid():
                try:
                    nfile = request.FILES['archivo']
                    nfile._name = generar_nombre("importacion_", nfile._name)
                    archivo = Archivo(nombre='IMPORTACION DE PRODUCTOS',
                                      fecha=datetime.now(),
                                      archivo=nfile)
                    archivo.save()

                    ingresoprod = IngresoProducto(
                        proveedor=Proveedor.objects.get(
                            pk=request.POST['proveedor']),
                        tipodocumento_id=1,  # factura
                        numerodocumento='111-111-111111',
                        fechadocumento=datetime.today(),
                        descripcion='MIGRACION',
                        fecha=datetime.today(),
                        usuario=usuario)
                    ingresoprod.save()

                    # 0 - Codigo
                    # 1 - Descripcion
                    # 2 - Categoria producto
                    # 3 - Codigo barra
                    # 4 - Cantidad minima
                    # 5 - Precio referencial
                    # 6 - Precio cliente normal
                    # 7 - Precio cliente corporativo
                    # 8 - Precio cliente vip
                    # 9 - Cantidad Existencia
                    # 10 - Costo unitario
                    workbook = xlrd.open_workbook(archivo.archivo.file.name)
                    sheet = workbook.sheet_by_index(0)
                    linea = 1
                    for rowx in range(sheet.nrows):
                        try:
                            cols = sheet.row_values(rowx)

                            codigo = cols[0]
                            descripcion = cols[1]
                            categoria = TipoProducto.objects.filter(
                                codigo=cols[2])[0] if cols[2] else ""
                            codigobarra = cols[3]
                            cantidadminima = cols[4]
                            precio_referencial = cols[5]
                            precio_cliente_normal = cols[6]
                            precio_cliente_corporativo = cols[7]
                            precio_cliente_vip = cols[8]
                            cantidad = float(cols[9])
                            costo = float(cols[10])
                            valor = round(cantidad * costo, 2)

                            if codigo and Producto.objects.filter(
                                    codigo=codigo).exists():
                                producto = Producto.objects.filter(
                                    codigo=codigo)[0]
                            else:
                                codigo = "PV-{}-0001".format(categoria.codigo)
                                ultimo_producto = categoria.get_ultimo_producto(
                                )
                                if ultimo_producto:
                                    codigo = "PV-{}-{}".format(
                                        categoria.codigo,
                                        str(ultimo_producto.secuencia_codigo()
                                            + 1).zfill(4))
                                producto = Producto(
                                    codigo=codigo,
                                    descripcion=descripcion,
                                    unidadmedida_id=1,
                                    tipoproducto=categoria,
                                    alias=descripcion[:25],
                                    codigobarra=codigobarra,
                                    minimo=cantidadminima,
                                    precio=precio_referencial,
                                    precio_cliente_normal=precio_cliente_normal,
                                    precio_cliente_corporativo=
                                    precio_cliente_corporativo,
                                    precio_cliente_vip=precio_cliente_vip)
                                producto.save()

                            detalleingprod = DetalleIngresoProducto(
                                compra=ingresoprod,
                                producto=producto,
                                cantidad=cantidad,
                                costo=costo,
                                valor=valor)
                            detalleingprod.save()

                            # Guardar Historial de costos CIF
                            historialcif = HistorialCifProducto(
                                producto=producto,
                                compra=ingresoprod,
                                cif=detalleingprod.costo,
                                usuario=request.user)
                            historialcif.save()

                            # Actualizar Inventario Real
                            if Area.objects.exists():
                                if Area.objects.filter(es_principal=True):
                                    area = Area.objects.filter(
                                        es_principal=True)[0]
                                else:
                                    area = Area.objects.all()[0]
                            else:
                                area = Area(nombre='Matriz', es_principal=True)
                                area.save()

                            # COSTO Y SALDO ANTES DEL MOVIMIENTO
                            saldoinicialvalor = detalleingprod.producto.valor_inventario(
                                area)
                            saldoinicialcantidad = detalleingprod.producto.stock_inventario(
                                area)

                            # ACTUALIZAR INVENTARIO REAL
                            costoproducto = round(
                                (detalleingprod.valor /
                                 detalleingprod.cantidad),
                                2) if detalleingprod.cantidad else 0
                            producto.actualizar_inventario_ingreso(
                                costoproducto, detalleingprod.cantidad, area)
                            inventario = producto.mi_inventario(area)

                            # ACTUALIZAR KARDEX
                            kardex = KardexInventario(
                                producto=detalleingprod.producto,
                                inventario=inventario,
                                tipomovimiento=TIPO_MOVIMIENTO_ENTRADA,
                                dcompra=detalleingprod,
                                saldoinicialvalor=saldoinicialvalor,
                                saldoinicialcantidad=saldoinicialcantidad,
                                cantidad=detalleingprod.cantidad,
                                costo=costoproducto,
                                valor=round(
                                    costoproducto * detalleingprod.cantidad,
                                    2))
                            kardex.save()

                            # COSTO Y SALDO DESPUES DEL MOVIMIENTO
                            saldofinalvalor = detalleingprod.producto.valor_inventario(
                                area)
                            saldofinalcantidad = detalleingprod.producto.stock_inventario(
                                area)
                            kardex.saldofinalcantidad = saldofinalcantidad
                            kardex.saldofinalvalor = saldofinalvalor
                            kardex.save()

                            # Actualizar valore total de la compra
                            ingresoprod.valor = ingresoprod.valor_compra()
                            ingresoprod.save()
                            salva_auditoria(request, ingresoprod,
                                            ACCION_ADICIONAR)

                            linea += 1
                        except Exception:
                            return bad_json(
                                mensaje=u'Error al ingresar la linea: %s' %
                                linea)

                    return ok_json()
                except Exception:
                    return bad_json(error=1)

        return bad_json(error=0)
    else:
        if 'action' in request.GET:
            action = request.GET['action']

            if action == 'importar':
                try:
                    data['title'] = u'Importación de inventario'
                    data['form'] = ImportarArchivoXLSForm()
                    return render_to_response("compras/importar.html", data)

                except Exception:
                    pass

        else:
            data['form'] = IngresoProductoForm(
                initial={'fechadocumento': datetime.now().date()})
            data['form2'] = DetalleIngresoProductoForm()
            data['form_entidad'] = ProveedorForm(prefix='proveedor')
            data['valor_iva'] = data['iva']
            return render_to_response("compras/view.html", data)