def view(request): global ex data = informacionusuario(request) data['persona'] = persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Acciones de usuarios' search = None ids = None data['acciones'] = LogEntry.objects.all().order_by( '-action_time') return render_to_response( "auditoria/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'add': try: form = PresupuestoForm(request.POST) if form.is_valid(): if PresupuestoCompra.objects.filter( anio=datetime.now().date().year).exists(): return bad_json( transaction, mensaje= u'Ya existe un presupuesto para este periodo') personaadmin = PresupuestoCompra( anio=datetime.now().date().year, fechai=datetime.now().date(), mes=datetime.now().month, fechaf=datetime.now().date(), valor=form.cleaned_data['valor']) personaadmin.save(request) log(u'Adiciono presupuesto: %s' % personaadmin, request, "add") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'edit': try: form = PresupuestoForm(request.POST) if form.is_valid(): personaadmin = PresupuestoCompra.objects.get( id=int(request.POST['id'])) if form.cleaned_data['valor'] < personaadmin.total_compras( ): return bad_json( transaction, mensaje= u'No se puede poner un presupuesto menor a las compras realizadas' ) personaadmin.valor = form.cleaned_data['valor'] personaadmin.save() log(u'Modifico presupuesto: %s' % personaadmin, request, "edit") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'delete': try: administrativo = PresupuestoCompra.objects.get( id=int(request.POST['id'])) administrativo.delete() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'cerrar': try: administrativo = PresupuestoCompra.objects.get( id=int(request.POST['id'])) administrativo.activo = False administrativo.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Adicionar Presupuesto' form = PresupuestoForm() data['form'] = form return render_to_response( "presupuestos/add.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'edit': try: data['title'] = u'Editar Presupuesto' data[ 'administrativo'] = administrativo = PresupuestoCompra.objects.get( id=int(request.GET['id'])) form = PresupuestoForm( initial={'valor': administrativo.valor}) data['form'] = form return render_to_response( "presupuestos/edit.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'delete': try: data['title'] = u'Eliminar Presupuesto' data['prov'] = PresupuestoCompra.objects.get( id=int(request.GET['id'])) return render_to_response( "presupuestos/delete.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'cerrar': try: data['title'] = u'Cerrar Presupuesto' data['prov'] = PresupuestoCompra.objects.get( id=int(request.GET['id'])) return render_to_response( "presupuestos/cerrar.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Presupuestos para compras' search = None ids = None administrativos = PresupuestoCompra.objects.all() data['administrativos'] = administrativos return render_to_response( "presupuestos/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'nueva': try: form = DevolucionForm(request.POST) if form.is_valid(): datos = json.loads(request.POST['lista_items1']) if not datos: return bad_json( transaction, mensaje=u'Debe especificar valores a devolver') factura = form.cleaned_data['factura'] dev = DevolucionCompraProducto( compra=factura, usuario=request.user, motivo=form.cleaned_data['motivo'], fecha=datetime.now().date()) dev.save() for dato in datos: detalle = Detallecompra.objects.get(id=int(dato['id'])) if detalle.articulo.mi_inventario().cantidad < float( dato['valor']): return bad_json( transaction, mensaje= u'No se puede completar la devolucion porque el inventario de este producto es menor' ) detdev = DetalleDevolucion(devolucion=dev, detalle=detalle, cantidad=float( dato['valor'])) detdev.save() detalle.cantidad -= float(dato['valor']) detalle.valor = detalle.calcular_valor() detalle.save() p = detalle.articulo inv = p.mi_inventario() inv.cantidad -= float(dato['valor']) inv.valor = inv.costo * inv.cantidad inv.save() factura.actualiza_valor() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'datosprod': try: c = CompraProducto.objects.get(id=int(request.POST['id'])) detalles = c.productos.all() data['detalles'] = detalles template = get_template("devoluciones/segmento.html") json_content = template.render(Context(data)) return ok_json(transaction, {'data': json_content}) except Exception as ex: return bad_json(transaction, error=3) if action == 'confirmar': try: c = DevolucionCompraProducto.objects.get( id=int(request.POST['id'])) for d in c.detalledevolucion_set.all(): det = d.detalle det.cantidad += d.cantidad det.valor = det.calcular_valor() det.save() p = det.articulo inv = p.mi_inventario() inv.cantidad += d.cantidad inv.valor = inv.costo * inv.cantidad inv.save() c.compra.actualiza_valor() c.delete() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Nueva Devolucion' data['form'] = DevolucionForm() return render_to_response("devoluciones/nueva.html", data) except Exception as ex: pass if action == 'revertir': try: data['title'] = u'Revertir devolucion' data['c'] = c = DevolucionCompraProducto.objects.get( id=int(request.GET['id'])) return render_to_response( "devoluciones/confirmar.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'detalle': try: data['title'] = u'Detalle Devolucion' data['c'] = c = DevolucionCompraProducto.objects.get( id=int(request.GET['id'])) data['detalles'] = c.detalledevolucion_set.all() form = InfoCompraProductoForm( initial={'numero': c.compra.numerodocumento}) data['form'] = form data['permite_modificar'] = False return render_to_response( "devoluciones/detalles.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Devoluciones realizadas' search = None ids = None if 'c' in request.GET: request.session['c'] = c = int(request.GET['c']) elif 'c' in request.session: c = int(request.session['c']) else: request.session['c'] = c = 10 if 's' in request.GET: search = request.GET['s'].strip() ventas = DevolucionCompraProducto.objects.filter( Q(compra__proveedor__razonsocial__icontains=search) | Q(motivo__icontains=search) | Q(compra__numero__icontains=search)).distinct() elif 'id' in request.GET: ids = request.GET['id'] ventas = DevolucionCompraProducto.objects.filter( id=ids).distinct() else: ventas = DevolucionCompraProducto.objects.all() paging = MiPaginador(ventas, c) p = 1 try: paginasesion = 1 if 'paginador' in request.session and 'paginador_url' in request.session: if request.session['paginador_url'] == 'ventas': paginasesion = int(request.session['paginador']) if 'page' in request.GET: p = int(request.GET['page']) else: p = paginasesion page = paging.page(p) except: p = 1 page = paging.page(p) request.session['paginador'] = p request.session['paginador_url'] = 'ventas' data['paging'] = paging data['rangospaging'] = paging.rangos_paginado(p) data['page'] = page data['search'] = search if search else "" data['ids'] = ids if ids else "" data['ventas'] = page.object_list data['c'] = c data['totales'] = DevolucionCompraProducto.objects.all().count( ) return render_to_response( "devoluciones/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'add': try: form = GastoForm(request.POST) if form.is_valid(): g = Gastos(descripcion=form.cleaned_data['descripcion'], fecha=convertir_fecha_invertida(form.cleaned_data['fecha']), total=form.cleaned_data['costo'], sueldo=False, finalizado=True) g.save(request) log(u'Adiciono gasto: %s' % g, request, "add") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) elif action == 'act_adicional': try: pago = DetalleGastos.objects.get(pk=request.POST['id']) pago.adicional = float(request.POST['valor']) pago.save() pago.gasto.actualiza_total() valor = round(pago.total, 2) return ok_json(transaction, data={ "final": str(valor)}) except Exception as ex: return bad_json(transaction, error=1) elif action == 'act_descuento': try: pago = DetalleGastos.objects.get(pk=request.POST['id']) pago.descuento = float(request.POST['valor']) pago.save() pago.gasto.actualiza_total() valor = round(pago.total, 2) return ok_json(transaction, data={"final": str(valor)}) except Exception as ex: return bad_json(transaction, error=1) elif action == 'cerrar': try: pago = Gastos.objects.get(pk=request.POST['id']) pago.finalizado = True pago.save() pago.actualiza_total() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) elif action == 'generar': try: anio = int(request.POST['anio']) mes = int(request.POST['mes']) fecha = date(anio, mes, 1) if Gastos.objects.filter(sueldo=True, fecha__year=anio, fecha__month=mes).exists(): return bad_json(transaction, mensaje=u'Ya existe un Pago en esta fecha') g = Gastos(fecha=fecha, sueldo=True) g.save() for e in Empleado.objects.all(): d = DetalleGastos(gasto=g, empleado=e, adicional=0, descuento=0, total=0) d.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Adicionar Gasto' form = GastoForm() data['form'] = form return render_to_response("gastos/add.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'otros': try: data['title'] = u'Gastos Operativos' data['gastos'] = Gastos.objects.filter(sueldo=False) return render_to_response("gastos/otros.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: anio = datetime.now().year mes = datetime.now().month pago = None if 'anio_otro' in request.session: anio = int(request.session['anio_otro']) if 'anio_otro' in request.GET: request.session['anio_otro'] = anio = int(request.GET['anio_otro']) if 'mes_otro' in request.session: mes = int(request.session['mes_otro']) if 'mes_otro' in request.GET: request.session['mes_otro'] = mes = int(request.GET['mes_otro']) if Gastos.objects.filter(sueldo=True, fecha__year=anio, fecha__month=mes).exists(): pago = Gastos.objects.filter(sueldo=True, fecha__year=anio, fecha__month=mes)[0] data['title'] = u'Gastos por pago de sueldos' data['anios'] = ANIO_LISTADO data['meses'] = MESES_LISTADO data['empresa'] = Institucion.objects.all()[0] data['pago'] = pago data['anio'] = anio data['mes'] = mes return render_to_response("gastos/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] sucursal = request.session['sucursal'] if request.method == 'POST': action = request.POST['action'] if action == 'pagar': try: c = CuotasFacturas.objects.get(id=int(request.POST['id'])) c.pagada = True c.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'cuotas': try: data['title'] = u'Cuotas' data['c'] = c = Factura.objects.get( id=int(request.GET['id'])) data['detalles'] = c.cuotasfacturas_set.all() return render_to_response( "cuentascobrar/detalles.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'pagar': try: data['title'] = u'Pagar' data['c'] = c = CuotasFacturas.objects.get( id=int(request.GET['id'])) return render_to_response( "cuentascobrar/confirmar.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Listado de cuentas por cobrar' search = None ids = None if 's' in request.GET: search = request.GET['s'].strip() compras = Factura.objects.filter( Q(cliente__nombres__icontains=search) | Q(cliente__apellidos__icontains=search) | Q(cliente__identificacion__icontains=search) | Q(numeroreal__icontains=search) | Q(numero__icontains=search), sucursal=sucursal, credito=True).distinct() elif 'id' in request.GET: ids = request.GET['id'] compras = Factura.objects.filter(id=ids, sucursal=sucursal, credito=True).distinct() else: compras = Factura.objects.filter(sucursal=sucursal, credito=True) paging = MiPaginador(compras, 25) p = 1 try: paginasesion = 1 if 'paginador' in request.session and 'paginador_url' in request.session: if request.session['paginador_url'] == 'compras': paginasesion = int(request.session['paginador']) if 'page' in request.GET: p = int(request.GET['page']) else: p = paginasesion page = paging.page(p) except: p = 1 page = paging.page(p) request.session['paginador'] = p request.session['paginador_url'] = 'compras' data['paging'] = paging data['rangospaging'] = paging.rangos_paginado(p) data['page'] = page data['search'] = search if search else "" data['ids'] = ids if ids else "" data['compras'] = page.object_list return render_to_response( "cuentascobrar/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'add': try: form = AdministrativoForm(request.POST) if form.is_valid(): if Persona.objects.filter(identificacion=form.cleaned_data['identificacion']).exists(): return bad_json(transaction, error=18) personaadmin = Persona(nombre1=form.cleaned_data['nombre1'], nombre2=form.cleaned_data['nombre2'], apellido1=form.cleaned_data['apellido1'], apellido2=form.cleaned_data['apellido2'], identificacion=form.cleaned_data['identificacion'], tipoidentificacion=form.cleaned_data['tipoidentificacion'], nacimiento=form.cleaned_data['nacimiento'], provincia=form.cleaned_data['provincia'], canton=form.cleaned_data['canton'], sector=form.cleaned_data['sector'], direccion=form.cleaned_data['direccion'], numero=form.cleaned_data['numero'], referencia=form.cleaned_data['referencia'], telefonomovil=form.cleaned_data['telefonomovil'], telefonofijo=form.cleaned_data['telefonofijo'], email=form.cleaned_data['email']) personaadmin.save(request) administrativo = Empleado(persona=personaadmin, email=form.cleaned_data['email'], sueldo=form.cleaned_data['sueldo']) administrativo.save(request) tipousuario = PerfilUsuario(tipoperfilusuario=form.cleaned_data['tipoempleado'], empleado=administrativo) tipousuario.save() usuario = generar_usuario(form.cleaned_data['identificacion'], form.cleaned_data['identificacion']) personaadmin.usuario = usuario personaadmin.save() log(u'Adiciono personal administrativo: %s' % administrativo, request, "add") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'edit': try: form = TipoAdministrativoForm(request.POST) if form.is_valid(): administrativo = Empleado.objects.get(id=int(request.POST['id'])) perfil = administrativo.mi_perfil() perfil.tipoperfilusuario = form.cleaned_data['tipoempleado'] perfil.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'des': try: administrativo = Empleado.objects.get(id=int(request.POST['id'])) perfil = administrativo.mi_perfil() perfil.activo = False perfil.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'act': try: administrativo = Empleado.objects.get(id=int(request.POST['id'])) perfil = administrativo.mi_perfil() perfil.activo = True perfil.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'addmodulogrupo': try: grupo = PerfilUsuario.objects.get(pk=int(request.POST['id'])) datos = json.loads(request.POST['lista']) for dato in datos: modulo = Modulo.objects.get(pk=int(dato['id'])) if not GrupoModulos.objects.filter(perfil=grupo, modulo=modulo).exists(): grupom = GrupoModulos(perfil=grupo, modulo=modulo) grupom.save(request) return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'delmodulogrupo': try: grupo = PerfilUsuario.objects.get(pk=int(request.POST['id'])) datos = json.loads(request.POST['lista']) for dato in datos: modulo = Modulo.objects.get(pk=int(dato['id'])) if GrupoModulos.objects.filter(perfil=grupo, modulo=modulo).exists(): gm = GrupoModulos.objects.filter(perfil=grupo, modulo=modulo)[0] gm.delete() log(u'Eliminó módulos al grupo: %s' % grupo, request, "add") return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'addsucursal': try: grupo = Empleado.objects.get(pk=int(request.POST['id'])) datos = json.loads(request.POST['lista']) for dato in datos: modulo = Sucursales.objects.get(pk=int(dato['id'])) if not EmpleadoSucursal.objects.filter(empleado=grupo, sucursal=modulo).exists(): grupom = EmpleadoSucursal(empleado=grupo, sucursal=modulo) grupom.save(request) return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'delsucursal': try: grupo = Empleado.objects.get(pk=int(request.POST['id'])) datos = json.loads(request.POST['lista']) for dato in datos: modulo = Sucursales.objects.get(pk=int(dato['id'])) if EmpleadoSucursal.objects.filter(empleado=grupo, sucursal=modulo).exists(): gm = EmpleadoSucursal.objects.filter(empleado=grupo, sucursal=modulo)[0] gm.delete() log(u'Eliminó sucursal al empleado: %s' % grupo, request, "add") return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Adicionar Administrativo' form = AdministrativoForm() data['form'] = form data['tipo_cedula'] = TipoIdentificacion.objects.filter(cedula=True)[0].id return render_to_response("adm_administrativos/add.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'edit': try: data['title'] = u'Editar Tipo' data['administrativo'] = administrativo = Empleado.objects.get(id=int(request.GET['id'])) form = TipoAdministrativoForm(initial={'tipoempleado': administrativo.mi_perfil().tipoperfilusuario}) data['form'] = form return render_to_response("usuarios/edit.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'info': try: data['title'] = u'Información del usuario' data['empleado'] = empleado = Empleado.objects.get(pk=request.GET['id']) data['usuario'] = empleado.persona.usuario return render_to_response("usuarios/info.html", data) except Exception as ex: pass if action == 'permisos': try: data['title'] = u'Permisos' data['empleado'] = empleado = Empleado.objects.get(pk=int(request.GET['id'])) data['grupo'] = perfil = empleado.mi_perfil() data['modulos_grupo'] = modulos = Modulo.objects.filter(grupomodulos__perfil=perfil).distinct() data['modulos'] = Modulo.objects.all().exclude(grupomodulos__perfil=perfil) return render_to_response("usuarios/permisosgrupo.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'sucursales': try: data['title'] = u'Sucursales a las que el usuario tiene acceso' data['empleado'] = empleado = Empleado.objects.get(pk=int(request.GET['id'])) data['modulos_grupo'] = modulos = Sucursales.objects.filter(empleadosucursal__empleado=empleado).distinct() data['modulos'] = Sucursales.objects.all().exclude(empleadosucursal__empleado=empleado) return render_to_response("usuarios/sucursales.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'des': try: data['title'] = u'Desactivar acceso de usuario' data['c'] = c = Empleado.objects.get(id=int(request.GET['id'])) return render_to_response("usuarios/des.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'act': try: data['title'] = u'Activar acceso de usuario' data['c'] = c = Empleado.objects.get(id=int(request.GET['id'])) return render_to_response("usuarios/act.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Usuarios del sistema' search = None ids = None if 's' in request.GET: search = request.GET['s'].strip() ss = search.split(' ') if len(ss) == 1: administrativos = Empleado.objects.filter(Q(persona__nombre1__icontains=search) | Q(persona__nombre2__icontains=search) | Q(persona__apellido1__icontains=search) | Q(persona__apellido2__icontains=search) | Q(persona__identificacion__icontains=search) | Q(perfilusuario__tipoperfilusuario__nombre__icontains=search), persona__usuario__isnull=False).distinct() else: administrativos = Empleado.objects.filter(Q(persona__apellido1__icontains=ss[0]) & Q(persona__apellido2__icontains=ss[1]), persona__usuario__isnull=False).distinct() elif 'id' in request.GET: ids = request.GET['id'] administrativos = Empleado.objects.filter(id=ids, persona__usuario__isnull=False).distinct() else: administrativos = Empleado.objects.filter(persona__usuario__isnull=False) paging = MiPaginador(administrativos, 25) p = 1 try: paginasesion = 1 if 'paginador' in request.session and 'paginador_url' in request.session: if request.session['paginador_url'] == 'adm_administrativos': paginasesion = int(request.session['paginador']) if 'page' in request.GET: p = int(request.GET['page']) else: p = paginasesion page = paging.page(p) except: p = 1 page = paging.page(p) request.session['paginador'] = p request.session['paginador_url'] = 'adm_administrativos' data['paging'] = paging data['rangospaging'] = paging.rangos_paginado(p) data['page'] = page data['search'] = search if search else "" data['ids'] = ids if ids else "" data['administrativos'] = page.object_list return render_to_response("usuarios/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'add': try: form = ManualForm(request.POST, request.FILES) if form.is_valid(): nfile = None if 'archivo' in request.FILES: nfile = request.FILES['archivo'] noticia = ManualProcedimientos(detalles=form.cleaned_data['detalles'], fecha=datetime.now().date(), nombre=form.cleaned_data['nombre'], archivo=nfile) noticia.save() log(u'Adiciono noticia: %s' % noticia, request, "add") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'delete': try: administrativo = ManualProcedimientos.objects.get(id=int(request.POST['id'])) administrativo.delete() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Adicionar Manual' form = ManualForm() data['form'] = form return render_to_response("procedimientos/add.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'delete': try: data['title'] = u'Eliminar Manual' data['prov'] = ManualProcedimientos.objects.get(id=int(request.GET['id'])) return render_to_response("procedimientos/delete.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Manuales de procedimientos' data['manuales'] = ManualProcedimientos.objects.all() return render_to_response("procedimientos/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'add': try: form = ClienteForm(request.POST) if form.is_valid(): if Cliente.objects.filter( identificacion=form.cleaned_data['identificacion'] ).exists(): return bad_json(transaction, error=18) personaadmin = Cliente( nombres=form.cleaned_data['nombres'], apellidos=form.cleaned_data['apellidos'], identificacion=form.cleaned_data['identificacion'], tipoidentificacion=form. cleaned_data['tipoidentificacion'], provincia=form.cleaned_data['provincia'], canton=form.cleaned_data['canton'], sector=form.cleaned_data['sector'], direccion=form.cleaned_data['direccion'], telefonomovil=form.cleaned_data['telefonomovil'], telefonofijo=form.cleaned_data['telefonofijo'], email=form.cleaned_data['email']) personaadmin.save(request) log(u'Adiciono cliente: %s' % personaadmin, request, "add") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'edit': try: form = ClienteForm(request.POST) if form.is_valid(): personaadmin = Cliente.objects.get( id=int(request.POST['id'])) personaadmin.nombres = form.cleaned_data['nombres'] personaadmin.apellidos = form.cleaned_data['apellidos'] personaadmin.provincia = form.cleaned_data['provincia'] personaadmin.canton = form.cleaned_data['canton'] personaadmin.sector = form.cleaned_data['sector'] personaadmin.direccion = form.cleaned_data['direccion'] personaadmin.telefonomovil = form.cleaned_data[ 'telefonomovil'] personaadmin.telefonofijo = form.cleaned_data[ 'telefonofijo'] personaadmin.email = form.cleaned_data['email'] personaadmin.save() log(u'Modifico personal administrativo: %s' % personaadmin, request, "edit") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'delete': try: personaadmin = Cliente.objects.get(id=int(request.POST['id'])) log(u'Elimino personal administrativo: %s' % personaadmin, request, "edit") personaadmin.delete() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Adicionar Cliente' form = ClienteForm() data['form'] = form data['tipo_cedula'] = TipoIdentificacion.objects.filter( cedula=True)[0].id return render_to_response( "clientes/add.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'edit': try: data['title'] = u'Editar Cliente' data['administrativo'] = cliente = Cliente.objects.get( id=int(request.GET['id'])) form = ClienteForm( initial={ 'nombres': cliente.nombres, 'apellidos': cliente.apellidos, 'tipoidentificacion': cliente.tipoidentificacion, 'identificacion': cliente.identificacion, 'provincia': cliente.provincia, 'canton': cliente.canton, 'sector': cliente.sector, 'direccion': cliente.direccion, 'telefonomovil': cliente.telefonomovil, 'telefonofijo': cliente.telefonofijo, 'email': cliente.email }) data['form'] = form data['tipo_cedula'] = TipoIdentificacion.objects.filter( cedula=True)[0].id return render_to_response( "clientes/edit.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'delete': try: data['title'] = u'Eliminar Cliente' data['cliente'] = cliente = Cliente.objects.get( id=int(request.GET['id'])) return render_to_response( "clientes/delete.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Listado de Clientes' search = None ids = None if 's' in request.GET: search = request.GET['s'].strip() administrativos = Cliente.objects.filter( Q(nombres__icontains=search) | Q(apellidos__icontains=search) | Q(identificacion__icontains=search)).distinct() elif 'id' in request.GET: ids = request.GET['id'] administrativos = Cliente.objects.filter(id=ids).distinct() else: administrativos = Cliente.objects.all() paging = MiPaginador(administrativos, 25) p = 1 try: paginasesion = 1 if 'paginador' in request.session and 'paginador_url' in request.session: if request.session['paginador_url'] == 'clientes': paginasesion = int(request.session['paginador']) if 'page' in request.GET: p = int(request.GET['page']) else: p = paginasesion page = paging.page(p) except: p = 1 page = paging.page(p) request.session['paginador'] = p request.session['paginador_url'] = 'clientes' data['paging'] = paging data['rangospaging'] = paging.rangos_paginado(p) data['page'] = page data['search'] = search if search else "" data['ids'] = ids if ids else "" data['administrativos'] = page.object_list return render_to_response( "clientes/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'add': try: form = TraspasoForm(request.POST, request.FILES) if form.is_valid(): p = form.cleaned_data['producto'] inv = p.mi_inventario_sucursal(form.cleaned_data['origen']) if form.cleaned_data['cantidad'] > inv.cantidad: return bad_json( transaction, mensaje= u'La cantidad a traspasar no puede ser mayor al stock %s' % inv.cantidad) noticia = Traspasos(origen=form.cleaned_data['origen'], fecha=datetime.now().date(), destino=form.cleaned_data['destino'], producto=form.cleaned_data['producto'], motivo=form.cleaned_data['motivo'], cantidad=form.cleaned_data['cantidad']) noticia.save() inv.cantidad -= form.cleaned_data['cantidad'] inv.save() inv2 = p.mi_inventario_sucursal( form.cleaned_data['destino']) inv2.cantidad += form.cleaned_data['cantidad'] inv2.save() log(u'Adiciono traspaso: %s' % noticia, request, "add") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'delete': try: t = Traspasos.objects.get(id=int(request.POST['id'])) p = t.producto inv = p.mi_inventario_sucursal(t.destino) if t.cantidad > inv.cantidad: return bad_json( transaction, mensaje= u'No se puede revertir, las unidades se vendieron - stock actual: %s' % inv.cantidad) inv.cantidad -= t.cantidad inv.save() inv2 = p.mi_inventario_sucursal(t.origen) inv2.cantidad += t.cantidad inv2.save() t.delete() log(u'Elimino traspaso: %s' % t, request, "del") return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Adicionar Traspaso' form = TraspasoForm() data['form'] = form return render_to_response( "traspasos/add.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'delete': try: data['title'] = u'Revertir traspaso' data['prov'] = Traspasos.objects.get( id=int(request.GET['id'])) return render_to_response( "traspasos/delete.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Movimientos entre sucursales' data['manuales'] = Traspasos.objects.all() return render_to_response( "traspasos/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'add': try: form = SucursalForm(request.POST) if form.is_valid(): personaadmin = Sucursales( nombre=form.cleaned_data['nombre'], provincia=form.cleaned_data['provincia'], canton=form.cleaned_data['canton'], direccion=form.cleaned_data['direccion']) personaadmin.save(request) log(u'Adiciono sucursal: %s' % personaadmin, request, "add") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'edit': try: form = SucursalForm(request.POST) if form.is_valid(): personaadmin = Sucursales.objects.get( id=int(request.POST['id'])) personaadmin.nombre = form.cleaned_data['nombre'] personaadmin.provincia = form.cleaned_data['provincia'] personaadmin.canton = form.cleaned_data['canton'] personaadmin.direccion = form.cleaned_data['direccion'] personaadmin.save() log(u'Modifico sucursal: %s' % personaadmin, request, "edit") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'delete': try: personaadmin = Sucursales.objects.get( id=int(request.POST['id'])) log(u'Elimino sucursal: %s' % personaadmin, request, "edit") personaadmin.delete() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Adicionar Sucursal' form = SucursalForm() data['form'] = form return render_to_response( "sucursales/add.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'edit': try: data['title'] = u'Editar Sucursal' data['administrativo'] = cliente = Sucursales.objects.get( id=int(request.GET['id'])) form = SucursalForm( initial={ 'nombre': cliente.nombre, 'provincia': cliente.provincia, 'canton': cliente.canton, 'direccion': cliente.direccion }) data['form'] = form return render_to_response( "sucursales/edit.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'delete': try: data['title'] = u'Eliminar Sucursal' data['cliente'] = cliente = Sucursales.objects.get( id=int(request.GET['id'])) return render_to_response( "sucursales/delete.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Listado de Sucursales' search = None ids = None if 's' in request.GET: search = request.GET['s'].strip() administrativos = Sucursales.objects.filter( Q(nombre__icontains=search) | Q(provincia__nombre__icontains=search) | Q(canton__nombre__icontains=search)).distinct() elif 'id' in request.GET: ids = request.GET['id'] administrativos = Sucursales.objects.filter( id=ids).distinct() else: administrativos = Sucursales.objects.all() paging = MiPaginador(administrativos, 25) p = 1 try: paginasesion = 1 if 'paginador' in request.session and 'paginador_url' in request.session: if request.session['paginador_url'] == 'clientes': paginasesion = int(request.session['paginador']) if 'page' in request.GET: p = int(request.GET['page']) else: p = paginasesion page = paging.page(p) except: p = 1 page = paging.page(p) request.session['paginador'] = p request.session['paginador_url'] = 'clientes' data['paging'] = paging data['rangospaging'] = paging.rangos_paginado(p) data['page'] = page data['search'] = search if search else "" data['ids'] = ids if ids else "" data['administrativos'] = page.object_list return render_to_response( "sucursales/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'addmodulogrupo': try: grupo = GrupoInstitucion.objects.get( pk=int(request.POST['id'])) datos = json.loads(request.POST['lista']) for dato in datos: modulo = Modulo.objects.get(pk=int(dato['id'])) if not GrupoModulos.objects.filter(grupoinstitucion=grupo, modulo=modulo).exists(): grupom = GrupoModulos(grupoinstitucion=grupo, modulo=modulo, modificable=True) grupom.save(request) return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'delmodulogrupo': try: grupo = GrupoInstitucion.objects.get( pk=int(request.POST['id'])) datos = json.loads(request.POST['lista']) for dato in datos: modulo = Modulo.objects.get(pk=int(dato['id'])) if GrupoModulos.objects.filter(grupoinstitucion=grupo, modulo=modulo).exists(): gm = GrupoModulos.objects.filter( grupoinstitucion=grupo, modulo=modulo)[0] gm.delete() log(u'Eliminó módulos al grupo: %s' % grupo, request, "add") return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'permisosgrupo': try: data['title'] = u'Permisos' data['grupo'] = grupo = GrupoInstitucion.objects.get( pk=int(request.GET['id'])) # data['pg'] = pg = grupo.mi_permisogrupo() # data['permisos_grupo'] = grupo.mi_permisogrupo().permiso.all() # data['permisos'] = Permiso.objects.all().exclude(id__in=[x.id for x in pg.permiso.all()]) data['modulos_grupo'] = modulos = Modulo.objects.filter( grupomodulos__grupoinstitucion=grupo).distinct() if grupo.administrativo: data['modulos'] = Modulo.objects.filter( administrativo=True).exclude( id__in=modulos.values_list( 'id', flat=True)).order_by('id') elif grupo.empleado: data['modulos'] = Modulo.objects.filter( empleado=True).exclude(id__in=modulos.values_list( 'id', flat=True)).order_by('id') return render_to_response( "grupos_permisos/permisosgrupo.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Tipos de Usuarios del sistema' search = None ids = None if 's' in request.GET: search = request.GET['s'].strip() grupos = GrupoInstitucion.objects.filter( Q(grupo__name__icontains=search) | Q(nombre__icontains=search)).distinct() elif 'id' in request.GET: ids = request.GET['id'] grupos = GrupoInstitucion.objects.filter(id=ids).distinct() else: grupos = GrupoInstitucion.objects.all() paging = MiPaginador(grupos, 25) p = 1 try: paginasesion = 1 if 'paginador' in request.session and 'paginador_url' in request.session: if request.session[ 'paginador_url'] == 'grupos_permisos': paginasesion = int(request.session['paginador']) if 'page' in request.GET: p = int(request.GET['page']) else: p = paginasesion page = paging.page(p) except: p = 1 page = paging.page(p) request.session['paginador'] = p request.session['paginador_url'] = 'grupos_permisos' data['paging'] = paging data['rangospaging'] = paging.rangos_paginado(p) data['page'] = page data['search'] = search if search else "" data['ids'] = ids if ids else "" data['grupos'] = page.object_list return render_to_response( "grupos_permisos/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'clientes': clientes = Cliente.objects.all() tpl = Template("{% include 'reportes/clientes.html' %}") data = { 'e': Institucion.objects.all()[0], 'clientes': clientes } html = tpl.render(Context(data)) result = BytesIO() links = lambda uri, rel: os.path.join( MEDIA_ROOT, uri.replace(MEDIA_URL, '')) pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, encoding='UTF-8', link_callback=links) return HttpResponse(result.getvalue(), content_type='application/pdf') if action == 'proveedores': proveedores = Proveedor.objects.all() tpl = Template("{% include 'reportes/proveedores.html' %}") data = { 'e': Institucion.objects.all()[0], 'proveedores': proveedores } html = tpl.render(Context(data)) result = BytesIO() links = lambda uri, rel: os.path.join( MEDIA_ROOT, uri.replace(MEDIA_URL, '')) pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, encoding='UTF-8', link_callback=links) return HttpResponse(result.getvalue(), content_type='application/pdf') if action == 'inventario': try: productos = Producto.objects.all() tpl = Template("{% include 'reportes/productos.html' %}") data = { 'e': Institucion.objects.all()[0], 'productos': productos } html = tpl.render(Context(data)) result = BytesIO() links = lambda uri, rel: os.path.join( MEDIA_ROOT, uri.replace(MEDIA_URL, '')) pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, encoding='UTF-8', link_callback=links) return HttpResponse(result.getvalue(), content_type='application/pdf') except Exception as ex: pass if action == 'compras': try: fechai = convertir_fecha_invertida(request.GET['fi']) fechaf = convertir_fecha_invertida(request.GET['ff']) compras = CompraProducto.objects.filter( fecha__gte=fechai, fecha__lte=fechaf, finalizada=True).distinct() tpl = Template("{% include 'reportes/compras.html' %}") data = { 'e': Institucion.objects.all()[0], 'compras': compras, 'fi': fechai, 'ff': fechaf } html = tpl.render(Context(data)) result = BytesIO() links = lambda uri, rel: os.path.join( MEDIA_ROOT, uri.replace(MEDIA_URL, '')) pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, encoding='UTF-8', link_callback=links) return HttpResponse(result.getvalue(), content_type='application/pdf') except Exception as ex: pass if action == 'ventas': try: fechai = convertir_fecha_invertida(request.GET['fi']) fechaf = convertir_fecha_invertida(request.GET['ff']) ventas = Factura.objects.filter( fecha__gte=fechai, fecha__lte=fechaf, finalizada=True).distinct() tpl = Template("{% include 'reportes/ventas.html' %}") data = { 'e': Institucion.objects.all()[0], 'ventas': ventas, 'fi': fechai, 'ff': fechaf } html = tpl.render(Context(data)) result = BytesIO() links = lambda uri, rel: os.path.join( MEDIA_ROOT, uri.replace(MEDIA_URL, '')) pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, encoding='UTF-8', link_callback=links) return HttpResponse(result.getvalue(), content_type='application/pdf') except Exception as ex: pass if action == 'gastos': try: fechai = convertir_fecha_invertida(request.GET['fi']) fechaf = convertir_fecha_invertida(request.GET['ff']) gastos = Gastos.objects.filter( fecha__gte=fechai, fecha__lte=fechaf).distinct() tpl = Template("{% include 'reportes/gastos.html' %}") data = { 'e': Institucion.objects.all()[0], 'gastos': gastos, 'fi': fechai, 'ff': fechaf } html = tpl.render(Context(data)) result = BytesIO() links = lambda uri, rel: os.path.join( MEDIA_ROOT, uri.replace(MEDIA_URL, '')) pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, encoding='UTF-8', link_callback=links) return HttpResponse(result.getvalue(), content_type='application/pdf') except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Configuración de parámetros' data['empresa'] = Institucion.objects.all()[0] data['hoy'] = datetime.now().date() return render_to_response( "reportes/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'edit': try: form = EmpresaForm(request.POST) if form.is_valid(): empresa = Institucion.objects.all()[0] dato = empresa.dato_institucion() iva = IvaAplicado.objects.all()[0] empresa.nombre = form.cleaned_data['nombre'] dato.ruc = form.cleaned_data['ruc'] dato.provincia = form.cleaned_data['provincia'] dato.canton = form.cleaned_data['canton'] dato.sector = form.cleaned_data['sector'] dato.direccion = form.cleaned_data['direccion'] dato.telefonofijo = form.cleaned_data['telefonofijo'] dato.email = form.cleaned_data['email'] dato.margenutilidad = form.cleaned_data['utilidad'] iva.porciento = form.cleaned_data['iva'] dato.save() empresa.save() log(u'Modifico dato empresa: %s' % dato, request, "edit") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'edit': try: data['title'] = u'Editar Informacion' data['empresa'] = empresa = Institucion.objects.all()[0] dato = empresa.dato_institucion() data['iva'] = iva = IvaAplicado.objects.all()[0] form = EmpresaForm( initial={ 'nombre': empresa.nombre, 'ruc': dato.ruc, 'provincia': dato.provincia, 'canton': dato.canton, 'sector': dato.sector, 'direccion': dato.direccion, 'telefonofijo': dato.telefonofijo, 'utilidad': dato.margenutilidad, 'iva': iva.porciento, 'email': dato.email }) data['form'] = form return render_to_response( "administracion/edit.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Configuración de parámetros' data['empresa'] = Institucion.objects.all()[0] return render_to_response( "administracion/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] if request.method == 'POST': action = request.POST['action'] if action == 'add': try: form = ProductoForm(request.POST) if form.is_valid(): p = Producto( nombre=form.cleaned_data['nombre'], detalles=form.cleaned_data['detalles'], linea=form.cleaned_data['linea'], color=form.cleaned_data['color'], presentacion=form.cleaned_data['presentacion'], marca=form.cleaned_data['marca']) p.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'adds': try: form = ServicioForm(request.POST) if form.is_valid(): p = Producto(nombre=form.cleaned_data['nombre'], detalles=form.cleaned_data['detalles'], tiposervicio=form.cleaned_data['tipo'], servicio=True, costo=form.cleaned_data['costo']) p.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'edit': try: form = ProductoForm(request.POST) if form.is_valid(): p = Producto.objects.get(id=int(request.POST['id'])) p.nombre = form.cleaned_data['nombre'] p.presentacion = form.cleaned_data['presentacion'] p.detalles = form.cleaned_data['detalles'] p.linea = form.cleaned_data['linea'] p.marca = form.cleaned_data['marca'] p.color = form.cleaned_data['color'] p.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'edits': try: form = ServicioForm(request.POST) if form.is_valid(): p = Producto.objects.get(id=int(request.POST['id'])) p.nombre = form.cleaned_data['nombre'] p.detalles = form.cleaned_data['detalles'] p.tiposervicio = form.cleaned_data['tipo'] p.costo = form.cleaned_data['costo'] p.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'clonar': try: form = ClonarProductoForm(request.POST) if form.is_valid(): p = Producto.objects.get(id=int(request.POST['id'])) if p.talla == form.cleaned_data['talla']: return bad_json( transaction, mensaje= u'No puede clonar un producto con la misma talla') pnuevo = Producto(nombre=p.nombre, detalles=p.detalles, linea=p.linea, proveedor=p.proveedor, marca=p.marca, talla=form.cleaned_data['talla']) pnuevo.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'addlinea': try: form = DatosForm(request.POST) if form.is_valid(): p = LineaProducto(nombre=form.cleaned_data['nombre']) p.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'editlinea': try: form = DatosForm(request.POST) if form.is_valid(): p = LineaProducto.objects.get(id=int(request.POST['id'])) p.nombre = form.cleaned_data['nombre'] p.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'addpres': try: form = DatosForm(request.POST) if form.is_valid(): p = Presentacion(nombre=form.cleaned_data['nombre']) p.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'editpres': try: form = DatosForm(request.POST) if form.is_valid(): p = Presentacion.objects.get(id=int(request.POST['id'])) p.nombre = form.cleaned_data['nombre'] p.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'addmarca': try: form = DatosForm(request.POST) if form.is_valid(): p = Marca(nombre=form.cleaned_data['nombre']) p.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'editmarca': try: form = DatosForm(request.POST) if form.is_valid(): p = Marca.objects.get(id=int(request.POST['id'])) p.nombre = form.cleaned_data['nombre'] p.save() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'delpres': try: p = Presentacion.objects.get(id=int(request.POST['id'])) p.delete() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'dellinea': try: p = LineaProducto.objects.get(id=int(request.POST['id'])) p.delete() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'delmarca': try: p = Marca.objects.get(id=int(request.POST['id'])) p.delete() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Adicionar Artículo' form = ProductoForm() data['form'] = form return render_to_response( "inventario/add.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'adds': try: data['title'] = u'Adicionar Servicio' form = ServicioForm() data['form'] = form return render_to_response( "inventario/adds.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'presentaciones': try: data['title'] = u'Presentaciones de artículos' data['lineas'] = Presentacion.objects.all() return render_to_response("inventario/presentaciones.html", data) except Exception as ex: pass if action == 'lineas': try: data['title'] = u'Líneas de artículos' data['lineas'] = LineaProducto.objects.all() return render_to_response("inventario/lineas.html", data) except Exception as ex: pass if action == 'delpres': try: data['title'] = u'Eliminar Presentación' data['linea'] = linea = Presentacion.objects.get( id=int(request.GET['id'])) return render_to_response( "clientes/delpres.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'dellinea': try: data['title'] = u'Eliminar Linea' data['linea'] = linea = LineaProducto.objects.get( id=int(request.GET['id'])) return render_to_response( "clientes/dellinea.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'delmarca': try: data['title'] = u'Eliminar Marca' data['linea'] = linea = Marca.objects.get( id=int(request.GET['id'])) return render_to_response( "clientes/delmarca.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'delmodelo': try: data['title'] = u'Eliminar Modelo' data['linea'] = linea = TipoServicio.objects.get( id=int(request.GET['id'])) return render_to_response( "clientes/delmodelo.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'addpres': try: data['title'] = u'Adicionar Presentación' form = DatosForm() data['form'] = form return render_to_response( "inventario/addpres.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'addlinea': try: data['title'] = u'Adicionar Linea' form = DatosForm() data['form'] = form return render_to_response( "inventario/addlinea.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'editpres': try: data['title'] = u'Editar Presentación' data['linea'] = linea = Presentacion.objects.get( id=int(request.GET['id'])) form = DatosForm(initial={'nombre': linea.nombre}) data['form'] = form return render_to_response( "inventario/editpres.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'editlinea': try: data['title'] = u'Editar Linea' data['linea'] = linea = LineaProducto.objects.get( id=int(request.GET['id'])) form = DatosForm(initial={'nombre': linea.nombre}) data['form'] = form return render_to_response( "inventario/editlinea.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'modelos': try: data['title'] = u'Modelos de artículos' data['modelos'] = TipoServicio.objects.all() return render_to_response("inventario/modelos.html", data) except Exception as ex: pass if action == 'addmodelo': try: data['title'] = u'Adicionar Modelo' form = DatosForm() data['form'] = form return render_to_response( "inventario/addmodelo.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'editmodelo': try: data['title'] = u'Editar Modelo' data['modelo'] = modelo = TipoServicio.objects.get( id=int(request.GET['id'])) form = DatosForm(initial={'nombre': modelo.nombre}) data['form'] = form return render_to_response( "inventario/editmodelo.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'marcas': try: data['title'] = u'Marcas de artículos' data['marcas'] = Marca.objects.all() return render_to_response("inventario/marcas.html", data) except Exception as ex: pass if action == 'movimientos': try: data['title'] = u'Movimientos del artículo' data['inv'] = inv = Inventario.objects.get( id=int(request.GET['id'])) data['movimientos'] = inv.kardexinventario_set.all( ).order_by('-fechaingreso') return render_to_response("inventario/movimientos.html", data) except Exception as ex: pass if action == 'addmarca': try: data['title'] = u'Adicionar Marca' form = DatosForm() data['form'] = form return render_to_response( "inventario/addmarca.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'editmarca': try: data['title'] = u'Editar Marca' data['marca'] = marca = Marca.objects.get( id=int(request.GET['id'])) form = DatosForm(initial={'nombre': marca.nombre}) data['form'] = form return render_to_response( "inventario/editmarca.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'edit': try: data['title'] = u'Editar Artículo' data['art'] = art = Producto.objects.get( id=int(request.GET['id'])) form = ProductoForm( initial={ 'linea': art.linea, 'nombre': art.nombre, 'detalles': art.detalles, 'color': art.color, 'presentacion': art.presentacion, 'marca': art.marca }) data['form'] = form return render_to_response( "inventario/edit.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'edits': try: data['title'] = u'Editar Servicio' data['art'] = art = Producto.objects.get( id=int(request.GET['id'])) form = ServicioForm( initial={ 'tipo': art.tiposervicio, 'nombre': art.nombre, 'detalles': art.detalles, 'costo': art.costo }) data['form'] = form return render_to_response( "inventario/edits.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'clonar': try: data['title'] = u'Clonar Artículo' data['art'] = art = Producto.objects.get( id=int(request.GET['id'])) form = ClonarProductoForm( initial={ 'linea': art.linea, 'nombre': art.nombre, 'color': art.color, 'detalles': art.detalles, 'modelo': art.modelo, 'marca': art.marca }) data['form'] = form return render_to_response( "inventario/clonar.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Listado de personal administrativo' search = None ids = None if 's' in request.GET: search = request.GET['s'].strip() productos = Producto.objects.filter( Q(nombre__icontains=search) | Q(linea__nombre__icontains=search) | Q(marca__nombre__icontains=search)).distinct() elif 'id' in request.GET: ids = request.GET['id'] productos = Producto.objects.filter(id=ids).distinct() else: productos = Producto.objects.all() paging = MiPaginador(productos, 25) p = 1 try: paginasesion = 1 if 'paginador' in request.session and 'paginador_url' in request.session: if request.session['paginador_url'] == 'inventario': paginasesion = int(request.session['paginador']) if 'page' in request.GET: p = int(request.GET['page']) else: p = paginasesion page = paging.page(p) except: p = 1 page = paging.page(p) request.session['paginador'] = p request.session['paginador_url'] = 'inventario' data['paging'] = paging data['rangospaging'] = paging.rangos_paginado(p) data['page'] = page data['search'] = search if search else "" data['ids'] = ids if ids else "" data['productos'] = page.object_list return render_to_response( "inventario/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] sucursal = request.session['sucursal'] if request.method == 'POST': action = request.POST['action'] if action == 'deldetalle': try: c = DetalleFactura.objects.get(id=int(request.POST['valor'])) compra = c.factura_set.all()[0] c.delete() compra.actualiza_valor() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'addprod': try: form = SalidaProductoForm(request.POST) c = Factura.objects.get(id=int(request.POST['id'])) if form.is_valid(): cantidad = form.cleaned_data['cantidad'] costo = float(request.POST['micosto']) articulo = form.cleaned_data['articulo'] if cantidad > articulo.mi_inventario_sucursal(sucursal).cantidad: return bad_json(transaction, mensaje=u'No existe esa cantidad disponible para ese artículo') desc = form.cleaned_data['descuento'] p = 0.12 subtotal = cantidad * costo iva = subtotal * p total = subtotal + iva - desc detalle = DetalleFactura(producto=articulo, cantidad=cantidad, subtotal=subtotal, descuento=desc, precio=costo, iva=iva, valor=total) detalle.save() c.detalles.add(detalle) c.actualiza_valor() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'updatecli': try: c = Factura.objects.get(id=int(request.POST['id'])) cliente = Cliente.objects.get(id=int(request.POST['cli'])) c.cliente = cliente c.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'datosprod': try: c = Producto.objects.get(id=int(request.POST['id'])) disponible = '0' costo = '0' i = c.mi_inventario_sucursal(sucursal) total = c.stock_total() disponible = i.cantidad costo = i.precioventa otros = total - disponible return ok_json(transaction, data={'disponible': disponible, 'costo': costo, 'otros': otros}) except Exception as ex: return bad_json(transaction, error=1) if action == 'confirmar': try: c = Factura.objects.get(id=int(request.POST['id'])) if not c.cliente: return bad_json(transaction, mensaje=u'No ha seleccionado un cliente') c.finalizada = True c.fecha = datetime.now().date() c.sucursal = sucursal c.save() for d in c.detalles.all(): p = d.producto inv = p.mi_inventario_sucursal(sucursal) movimiento = KardexInventario(ingreso=False, fechaingreso=datetime.now(), inventario=inv, precioventa=d.precio, cantidad=d.cantidad, valor=d.valor) movimiento.save() inv.cantidad -= d.cantidad inv.valor = inv.cantidad * inv.costo inv.save() if c.credito: valor = c.total vc = null_to_numeric(valor / c.meses, 2) fecha = datetime.now().date() fechavence = fecha + timedelta(days=1) for i in range(1, int(c.meses) + 1): cuota = CuotasFacturas(factura=c, cuota=i, valor=vc, fechalimite=fechavence) cuota.save() fechavence = proximafecha(fechavence, 3).date() valorc = null_to_numeric(c.cuotasfacturas_set.aggregate(valor=Sum('valor'))['valor'], 2) ultima = c.cuotasfacturas_set.all().order_by('-cuota')[0] faltante = 0 excddente = 0 if valor > valorc: faltante = valor - valorc ultima.valor += faltante ultima.save() elif valorc > valor: excedente = valorc - valor ultima.valor -= excedente ultima.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'act_credito': try: c = Factura.objects.get(id=int(request.POST['id'])) valor = request.POST['valor'] == 'true' c.credito = valor c.save() if not c.credito: c.meses = 0 c.recargo = 0 c.save() else: if not c.porcentaje: c.porcentaje = 10 c.save() c.actualiza_valor() return ok_json() except Exception as ex: transaction.rollback() return bad_json(error=1) if action == 'act_meses': try: c = Factura.objects.get(id=int(request.POST['id'])) valor = int(request.POST['valor']) c.meses = valor c.save() return ok_json() except Exception as ex: transaction.rollback() return bad_json(error=1) if action == 'act_recargo': try: c = Factura.objects.get(id=int(request.POST['id'])) valor = int(request.POST['valor']) c.porcentaje = valor c.save() valor = null_to_numeric((c.subtotal * c.porcentaje) / 100, 2) c.recargo = valor c.save() c.actualiza_valor() return ok_json() except Exception as ex: transaction.rollback() return bad_json(error=1) if action == 'addcliente': try: form = ClienteForm(request.POST) if form.is_valid(): c = Factura.objects.get(id=int(request.POST['id'])) if Cliente.objects.filter(identificacion=form.cleaned_data['identificacion']).exists(): return bad_json(transaction, error=18) personaadmin = Cliente(nombres=form.cleaned_data['nombres'], apellidos=form.cleaned_data['apellidos'], identificacion=form.cleaned_data['identificacion'], tipoidentificacion=form.cleaned_data['tipoidentificacion'], provincia=form.cleaned_data['provincia'], canton=form.cleaned_data['canton'], sector=form.cleaned_data['sector'], direccion=form.cleaned_data['direccion'], telefonomovil=form.cleaned_data['telefonomovil'], telefonofijo=form.cleaned_data['telefonofijo'], email=form.cleaned_data['email']) personaadmin.save(request) c.cliente = personaadmin c.save() log(u'Adiciono cliente: %s' % personaadmin, request, "add") return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Nueva Venta' i = IvaAplicado.objects.all()[0] data['iva'] = i.nombre data['p'] = i.porciento numero = null_to_numeric(Factura.objects.aggregate(valor=Max('numeroreal'))['valor'], 0) if 'id' in request.GET: c = Factura.objects.get(id=int(request.GET['id'])) else: c = Factura(fecha=datetime.now().date(), numeroreal=int(numero)+1) c.save() c.actualiza_numero() data['c'] = c data['det'] = c.detalles.all() data['clientes'] = Cliente.objects.all() return render_to_response("ventas/nueva.html", data) except Exception as ex: pass if action == 'addcliente': try: data['title'] = u'Adicionar Cliente' form = ClienteForm() data['form'] = form data['venta'] = Factura.objects.get(id=int(request.GET['id'])) data['tipo_cedula'] = TipoIdentificacion.objects.filter(cedula=True)[0].id return render_to_response("ventas/addcliente.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'addprod': try: data['title'] = u'Adicionar Producto' data['iva'] = 12 data['venta'] = c = Factura.objects.get(id=int(request.GET['id'])) data['p'] = 0.12 form = SalidaProductoForm(initial={'porcentaje': 12}) form.editar(sucursal) data['form'] = form return render_to_response("ventas/addproducto.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'detalle': try: data['title'] = u'Productos vendidos' data['c'] = c = Factura.objects.get(id=int(request.GET['id'])) form = InfoCompraProductoForm(initial={'numero': c.numero}) data['form'] = form data['permite_modificar'] = False return render_to_response("ventas/detalles.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'pdf': id = request.GET['id'] compra = Factura.objects.get(id=id) i = IvaAplicado.objects.all()[0] if Factura.objects.filter(id=id): # template = get_template('compras/report.html') tpl = Template("{% include 'ventas/report.html' %}") data = {'e': Institucion.objects.all()[0], 'c': compra, 'details': compra.detalles.all(), 'ivanombre': i.nombre} html = tpl.render(Context(data)) # html = template.render(d) result = BytesIO() links = lambda uri, rel: os.path.join(MEDIA_ROOT, uri.replace(MEDIA_URL, '')) pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, encoding='UTF-8', link_callback=links) return HttpResponse(result.getvalue(), content_type='application/pdf') if action == 'confirmar': try: data['title'] = u'Confirmar venta' data['c'] = c = Factura.objects.get(id=int(request.GET['id'])) return render_to_response("ventas/confirmar.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Factura emitidas' search = None ids = None if 's' in request.GET: search = request.GET['s'].strip() ventas = Factura.objects.filter(Q(cliente__nombres__icontains=search) | Q(cliente__apellidos__icontains=search) | Q(cliente__identificacion__icontains=search) | Q(numeroreal__icontains=search) | Q(numero__icontains=search), sucursal=sucursal).distinct() elif 'id' in request.GET: ids = request.GET['id'] ventas = Factura.objects.filter(id=ids, sucursal=sucursal).distinct() else: ventas = Factura.objects.all() paging = MiPaginador(ventas, 25) p = 1 try: paginasesion = 1 if 'paginador' in request.session and 'paginador_url' in request.session: if request.session['paginador_url'] == 'ventas': paginasesion = int(request.session['paginador']) if 'page' in request.GET: p = int(request.GET['page']) else: p = paginasesion page = paging.page(p) except: p = 1 page = paging.page(p) request.session['paginador'] = p request.session['paginador_url'] = 'ventas' data['paging'] = paging data['rangospaging'] = paging.rangos_paginado(p) data['page'] = page data['search'] = search if search else "" data['ids'] = ids if ids else "" data['ventas'] = page.object_list Factura.objects.filter(finalizada=False).delete() return render_to_response("ventas/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/ventas')
def view(request): global ex data = informacionusuario(request) persona = request.session['persona'] sucursal = request.session['sucursal'] if request.method == 'POST': action = request.POST['action'] if action == 'addprod': try: form = CompraProductoForm(request.POST) c = CompraProducto.objects.get(id=int(request.POST['id'])) if form.is_valid(): cantidad = form.cleaned_data['cantidad'] costo = form.cleaned_data['costo'] porcentaje = 0.12 subtotal = cantidad * costo iva = subtotal * porcentaje total = subtotal + iva detalle = Detallecompra( articulo=form.cleaned_data['articulo'], cantidad=cantidad, subtotal=subtotal, costo=costo, iva=iva, valor=total) detalle.save() c.productos.add(detalle) c.actualiza_valor() return ok_json(transaction) else: return bad_json(transaction, error=6) except Exception as ex: return bad_json(transaction, error=1) if action == 'updateprov': try: c = CompraProducto.objects.get(id=int(request.POST['id'])) prov = Proveedor.objects.get(id=int(request.POST['prov'])) c.proveedor = prov c.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'updatefact': try: c = CompraProducto.objects.get(id=int(request.POST['id'])) numero = request.POST['numero'] c.numerodocumento = numero c.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'act_credito': try: c = CompraProducto.objects.get(id=int(request.POST['id'])) valor = request.POST['valor'] == 'true' c.credito = valor c.save() if not c.credito: c.meses = 0 c.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'act_meses': try: c = CompraProducto.objects.get(id=int(request.POST['id'])) valor = int(request.POST['valor']) c.meses = valor c.save() return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) if action == 'confirmar': try: c = CompraProducto.objects.get(id=int(request.POST['id'])) if not PresupuestoCompra.objects.filter( anio=datetime.now().date().year, activo=True).exists(): return bad_json( transaction, mensaje=u'No existe un presupuesto de compra definido') p = PresupuestoCompra.objects.filter( anio=datetime.now().date().year, activo=True)[0] if not c.proveedor: return bad_json(transaction, mensaje=u'No ha seleccionado un proveedor') if not c.numerodocumento: return bad_json( transaction, mensaje=u'No ha especificado el número de documento') c.finalizada = True c.fecha = datetime.now().date() c.presupuesto = p c.save() empresa = Institucion.objects.all()[0] utilidad = empresa.dato_institucion().margenutilidad / 100.0 for d in c.productos.all(): p = d.articulo inv = p.mi_inventario_sucursal(sucursal) inv.cantidad += d.cantidad inv.valor += d.valor inv.costo = d.valor / d.cantidad inv.precioventa = d.costo + (d.costo * 0.30) inv.save() venta = (d.costo * utilidad) + d.costo movimiento = KardexInventario(inventario=inv, fechaingreso=datetime.now(), cantidad=d.cantidad, costo=d.costo, valor=d.valor, precioventa=venta, disponible=d.cantidad) movimiento.save() if c.credito: valor = c.valor vc = null_to_numeric(valor / c.meses, 2) fecha = datetime.now().date() fechavence = fecha + timedelta(days=1) for i in range(1, int(c.meses) + 1): cuota = CuotasCompras(compra=c, cuota=i, valor=vc, fechalimite=fechavence) cuota.save() fechavence = proximafecha(fechavence, 3).date() valorc = null_to_numeric( c.cuotascompras_set.aggregate( valor=Sum('valor'))['valor'], 2) ultima = c.cuotascompras_set.all().order_by('-cuota')[0] faltante = 0 excddente = 0 if valor > valorc: faltante = valor - valorc ultima.valor += faltante ultima.save() elif valorc > valor: excedente = valorc - valor ultima.valor -= excedente ultima.save() log(u'Confirmo compra: %s' % c, request, "edit") return ok_json(transaction) except Exception as ex: return bad_json(transaction, error=1) return bad_json(transaction, error=0) else: if 'action' in request.GET: action = request.GET['action'] if action == 'add': try: data['title'] = u'Nueva Compra' i = IvaAplicado.objects.all()[0] data['iva'] = i.nombre porcentaje = i.porciento if i.porciento > 1: porcentaje = null_to_numeric(i.porciento / 100.0, 2) data['p'] = porcentaje if 'id' in request.GET: c = CompraProducto.objects.get( id=int(request.GET['id'])) else: c = CompraProducto(fecha=datetime.now().date(), sucursal=sucursal) c.save() data['c'] = c data['det'] = c.productos.all() data['proveedores'] = Proveedor.objects.all() return render_to_response("compras/nueva.html", data) except Exception as ex: pass if action == 'addprod': try: data['title'] = u'Adicionar Producto' data['iva'] = 12 data['compra'] = c = CompraProducto.objects.get( id=int(request.GET['id'])) porcentaje = 0.12 data['p'] = porcentaje form = CompraProductoForm(initial={'porcentaje': 12}) data['form'] = form return render_to_response( "compras/addproducto.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'detalle': try: data['title'] = u'Productos comprados' data['c'] = c = CompraProducto.objects.get( id=int(request.GET['id'])) form = InfoCompraProductoForm( initial={'numero': c.numerodocumento}) data['form'] = form data['permite_modificar'] = False return render_to_response( "compras/detalles.html", data, context_instance=RequestContext(request)) except Exception as ex: pass if action == 'pdf': id = request.GET['id'] compra = CompraProducto.objects.get(id=id) i = IvaAplicado.objects.all()[0] if CompraProducto.objects.filter(id=id): # template = get_template('compras/report.html') tpl = Template("{% include 'compras/report.html' %}") data = { 'e': Institucion.objects.all()[0], 'c': compra, 'details': compra.productos.all(), 'ivanombre': i.nombre } html = tpl.render(Context(data)) # html = template.render(d) result = BytesIO() links = lambda uri, rel: os.path.join( MEDIA_ROOT, uri.replace(MEDIA_URL, '')) pdf = pisa.pisaDocument(BytesIO(html.encode('UTF-8')), result, encoding='UTF-8', link_callback=links) return HttpResponse(result.getvalue(), content_type='application/pdf') if action == 'confirmar': try: data['title'] = u'Confirmar compra' data['c'] = c = CompraProducto.objects.get( id=int(request.GET['id'])) return render_to_response( "compras/confirmar.html", data, context_instance=RequestContext(request)) except Exception as ex: pass return url_back(request, ex=ex if 'ex' in locals() else None) else: try: data['title'] = u'Listado de compras realizadas' search = None ids = None if 's' in request.GET: search = request.GET['s'].strip() compras = CompraProducto.objects.filter( Q(proveedor__razonsocial__icontains=search) | Q(numerodocumento__icontains=search), sucursal=sucursal).distinct() elif 'id' in request.GET: ids = request.GET['id'] compras = CompraProducto.objects.filter( id=ids, sucursal=sucursal).distinct() else: compras = CompraProducto.objects.filter(sucursal=sucursal) paging = MiPaginador(compras, 25) p = 1 try: paginasesion = 1 if 'paginador' in request.session and 'paginador_url' in request.session: if request.session['paginador_url'] == 'compras': paginasesion = int(request.session['paginador']) if 'page' in request.GET: p = int(request.GET['page']) else: p = paginasesion page = paging.page(p) except: p = 1 page = paging.page(p) request.session['paginador'] = p request.session['paginador_url'] = 'compras' data['paging'] = paging data['rangospaging'] = paging.rangos_paginado(p) data['page'] = page data['search'] = search if search else "" data['ids'] = ids if ids else "" data['compras'] = page.object_list CompraProducto.objects.filter(finalizada=False).delete() return render_to_response( "compras/view.html", data, context_instance=RequestContext(request)) except Exception as ex: return HttpResponseRedirect('/')