예제 #1
0
 def buscar(self, boton):
     """
     Dadas fecha de inicio y de fin, busca todos los facturas del
     proveedor del combo.
     """
     idproveedor = utils.combo_get_value(self.wids['cmbe_proveedor'])
     str_fini = self.wids['e_fecha_inicio'].get_text()
     criterios = []
     if str_fini:
         self.inicio = utils.parse_fecha(str_fini)
         criterios.append(pclases.FacturaCompra.q.fecha >= self.inicio)
     else:
         self.inicio = None
     try:
         str_ffin = self.wids['e_fecha_fin'].get_text()
         self.fin = utils.parse_fecha(str_ffin)
     except (ValueError, TypeError):
         self.fin = datetime.date.today()
         str_ffin = utils.str_fecha(self.fin)
         self.wids['e_fecha_fin'].set_text(str_ffin)
     criterios.append(pclases.FacturaCompra.q.fecha <= self.fin)
     if idproveedor == None:
         self.proveedor = None
     elif idproveedor == 0:
         self.proveedor = None
     else:
         idproveedor = utils.combo_get_value(self.wids['cmbe_proveedor'])
         self.proveedor = pclases.Proveedor.get(idproveedor)
         criterios.append(
                 pclases.FacturaCompra.q.proveedor == self.proveedor)
     facturas = pclases.FacturaCompra.select(pclases.AND(*criterios))
     self.resultado = facturas
     self.rellenar_tabla(self.resultado)
예제 #2
0
 def cargar_registros_auditoria(self):
     if pclases.DEBUG: print __file__, "cargar_registros_auditoria: 0" 
     try:
         fechaini = utils.parse_fecha(self.wids['e_fechaini'].get_text())
     except ValueError:
         fechaini = None
     try:
         fechafin = (utils.parse_fecha(self.wids['e_fechafin'].get_text())
                     + mx.DateTime.oneDay)
     except ValueError:
         fechafin = None
     if pclases.DEBUG: print __file__, "cargar_registros_auditoria: 1" 
     if fechaini and fechafin:
         res = pclases.Auditoria.select(pclases.AND(
                 pclases.Auditoria.q.fechahora >= fechaini, 
                 pclases.Auditoria.q.fechahora < fechafin), 
             orderBy = "id")
     elif fechaini and not fechafin:
         res = pclases.Auditoria.select(
             pclases.Auditoria.q.fechahora >= fechaini, 
             orderBy = "id")
     elif not fechaini and fechafin:
         res = pclases.Auditoria.select(
             pclases.Auditoria.q.fechahora < fechafin, 
             orderBy = "id")
     else:
         res = pclases.Auditoria.select(orderBy = "id")
     if pclases.DEBUG: print __file__, "cargar_registros_auditoria: 2" 
     return res
예제 #3
0
 def cmp_data(d1, d2):
     f1 = utils.parse_fecha(d1[0].replace("//", "/"))
     f2 = utils.parse_fecha(d2[0].replace("//", "/"))
     if f1 < f2:
         return -1
     else:
         return 1
     return 0
예제 #4
0
 def add(self, w):
     if self.producto != None:
         fecha = self.wids['e_fecha'].get_text()
         if fecha == '':
             utils.dialogo_info(titulo = 'SIN FECHA',
                                texto = 'Debe introducir la fecha del resultado de la prueba.')
             return
         resultado1 = self.wids['e_resultado1'].get_text()
         if resultado1 == '':
             utils.dialogo_info(titulo = 'SIN RESULTADO',
                                texto = 'Debe introducir el resultado de la prueba en resultado1.', 
                                padre = self.wids['ventana'])
             return
         resultado2 = self.wids['e_resultado2'].get_text()
         try:
             mfi = utils._float(self.wids['e_mfi'].get_text())
         except:
             utils.dialogo_info(titulo = "MFI INCORRECTO", 
                 texto = "No ha introducido un valor correcto para el MFI del proveedor.", 
                 padre = self.wids['ventana'])
             return
         try:
             resultado = float(resultado1)
             prueba = pclases.PruebaGranza(fecha = utils.parse_fecha(fecha),
                                                      resultado = resultado,
                                             productoCompra = self.producto, 
                                     fechaEntrada = mx.DateTime.localtime(), 
                                      silo = self.wids['e_silo'].get_text(), 
                                      lote = self.wids['e_lote'].get_text(), 
                                                                  mfi = mfi)
             pclases.Auditoria.nuevo(prueba, self.usuario, __file__)
             if resultado2:
                 try:
                     resultado = float(resultado2)
                     prueba = pclases.PruebaGranza(
                         fecha = utils.parse_fecha(fecha),
                         resultado = resultado,
                         productoCompra = self.producto, 
                         fechaEntrada = mx.DateTime.localtime(), 
                         silo = self.wids['e_silo'].get_text(), 
                         lote = self.wids['e_lote'].get_text(),
                         mfi = mfi)
                     pclases.Auditoria.nuevo(prueba, self.usuario, __file__)
                 except Exception, msg:
                     utils.dialogo_info(titulo = 'ERROR', 
                                        texto = 'Verifique que ha introducido los datos correctamente.\n\n\nInformación de depuración: %s' % (msg), 
                                        padre = self.wids['ventana'])
         except Exception, msg:
             utils.dialogo_info(titulo = 'ERROR', 
                                texto = 'Verifique que ha introducido los datos correctamente.\n\n\nInformación de depuración: %s' % (msg), 
                                padre = self.wids['ventana'])
         self.wids['e_fecha'].set_text(utils.str_fecha(time.localtime()))
         self.wids['e_resultado1'].set_text('')
         self.wids['e_resultado2'].set_text('')
         self.wids['e_lote'].set_text('')
         self.wids['e_silo'].set_text('')
         self.wids['e_mfi'].set_text('0')
         self.rellenar_pruebas()
    def buscar(self, boton):
        """
        A partir de las fechas de inicio y fin de la ventana busca los
        artículos con trazabilidad y los clasifica por A, B y C en metros,
        kilos reales CON embalaje y bultos. También busca los productos de
        compra con las cantidades que salieron o entraron.
        """
        from ventana_progreso import VentanaProgreso

        vpro = VentanaProgreso(padre=self.wids["ventana"])
        vpro.mostrar()
        fini = utils.parse_fecha(self.wids["e_fechainicio"].get_text())
        ffin = utils.parse_fecha(self.wids["e_fechafin"].get_text())
        vpro.set_valor(0.0, "Buscando albaranes de salida...")
        self.albs = pclases.AlbaranSalida.select(
            pclases.AND(pclases.AlbaranSalida.q.fecha >= fini, pclases.AlbaranSalida.q.fecha < ffin), orderBy="fecha"
        )
        fib = {}
        gtx = {}
        cem = {}
        otros = {}
        i = 0.0
        tot = self.albs.count()
        for a in self.albs:
            i += 1
            vpro.set_valor(i / tot, "Analizando albarán %s..." % a.numalbaran)
            if a.es_de_movimiento():
                continue  # No cuento los interalmacenes porque me falsean
                # los totales ya que en realidad la mercancía no se ha movido
                # a ningún sitio todavía. Simplemente se han mandado a otro
                # almacén en espera de ser vendidos definitivamente al cliente.
                # Esa venta, aunque no se facture, es la que debe contar. Da
                # igual que sea venta a cliente o salida por consumo propio.
                # Los interalmacenes no implican salida real de mercancía,
                # solo movimiento.
            extract_data_from_albaran(a, fib, gtx, cem, otros)
        # Abonos
        vpro.set_valor(0.0, "Buscando abonos...")
        self.adedas = pclases.AlbaranDeEntradaDeAbono.select(
            pclases.AND(
                pclases.AlbaranDeEntradaDeAbono.q.fecha >= fini, pclases.AlbaranDeEntradaDeAbono.q.fecha < ffin
            ),
            orderBy="fecha",
        )
        i = 0.0
        tot = self.adedas.count()
        for a in self.adedas:
            i += 1
            vpro.set_valor(i / tot, "Analizando abono %s..." % a.numalbaran)
            extract_data_from_abono(a, fib, gtx, cem, otros)
        vpro.ocultar()
        tot_fib, tot_gtx, tot_cem = self.rellenar_tabla(fib, gtx, cem, otros)
        self.rellenar_totales(tot_fib, "fibra")
        self.rellenar_totales(tot_gtx, "gtx")
        self.rellenar_totales(tot_cem, "cem")
예제 #6
0
 def guardar(self, widget):
     """
     Guarda el contenido de los entry y demás widgets de entrada
     de datos en el objeto y lo sincroniza con la BD.
     """
     albaran = self.objeto
         # Campos del objeto que hay que guardar:
     numalbaran = self.wids['e_numalbaran'].get_text()
     fecha = self.wids['e_fecha'].get_text()
     # Desactivo el notificador momentáneamente
     albaran.notificador.set_func(lambda: None)
     # Actualizo los datos del objeto
     albaran.numalbaran = numalbaran
     albaran.proveedor = utils.combo_get_value(self.wids['cmbe_proveedor'])
     albaran.almacen = utils.combo_get_value(self.wids['cbe_almacenID'])
     try:
         albaran.fecha = utils.parse_fecha(fecha)
     except:
         albaran.fecha = mx.DateTime.localtime()
         utils.dialogo_info(titulo = "ERROR GUARDANDO FECHA", 
                            texto = "La fecha %s no es correcta." % (fecha), 
                            padre = self.wids['ventana'])
     # Fuerzo la actualización de la BD y no espero a que SQLObject lo haga por mí:
     albaran.syncUpdate()
     # Vuelvo a activar el notificador
     albaran.notificador.set_func(self.aviso_actualizacion)
     self.actualizar_ventana()
     self.wids['b_guardar'].set_sensitive(False)
예제 #7
0
 def set_fin(self,boton):
     try:
         temp = utils.mostrar_calendario(utils.parse_fecha(self.wids['e_fechafin'].get_text()), padre = self.wids['ventana'])
     except:
         temp = utils.mostrar_calendario(padre = self.wids['ventana'])
     self.wids['e_fechafin'].set_text(utils.str_fecha(temp))
     self.fin = mx.DateTime.DateTimeFrom(day = temp[0], month = temp[1], year = temp[2])
예제 #8
0
 def set_fecha_fin(self, b):
     try:
         fecha_defecto = utils.parse_fecha(self.wids['e_fecha_fin'].get_text())
     except: 
         fecha_defecto = mx.DateTime.localtime()
     else:
         self.wids['e_fecha_fin'].set_text(utils.str_fecha(utils.mostrar_calendario(fecha_defecto = fecha_defecto, padre = self.wids['ventana'])))
예제 #9
0
파일: adapter.py 프로젝트: Virako/fpinn
def convertir_a_fecha(valor, vdefecto=mx.DateTime.localtime()):
    from formularios.utils import parse_fecha

    try:
        return parse_fecha(valor)
    except:
        return vdefecto
예제 #10
0
 def set_fecha(self, b):
     try:
         fecha_defecto = utils.parse_fecha(self.wids['e_fecha'].get_text())
     except: 
         fecha_defecto = mx.DateTime.localtime()
     else:
         self.wids['e_fecha'].set_text("/".join(["%02d" % i for i in utils.mostrar_calendario(fecha_defecto = fecha_defecto, padre = self.wids['ventana'])]))
 def guardar(self, widget):
     """
     Guarda el contenido de los entry y demás widgets de entrada
     de datos en el objeto y lo sincroniza con la BD.
     """
     albaran = self.objeto
     # Campos del objeto que hay que guardar:
     numalbaran = self.wids['e_numalbaran'].get_text()
     fecha = self.wids['e_fecha'].get_text()
     # Desactivo el notificador momentáneamente
     albaran.notificador.desactivar()
     # Actualizo los datos del objeto
     albaran.numalbaran = numalbaran
     albaran.bloqueado = self.wids['ch_bloqueado'].get_active()
     try:
         albaran.fecha = utils.parse_fecha(fecha)
     except:
         albaran.fecha = mx.DateTime.localtime()
     albaran.almacenOrigenID=utils.combo_get_value(self.wids['cbe_almacen'])
     # Fuerzo la actualización de la BD y no espero a que SQLObject lo 
     # haga por mí:
     albaran.sync()
     # Vuelvo a activar el notificador
     albaran.notificador.activar(self.aviso_actualizacion)
     self.objeto = albaran
     self.modificado = True
     self.actualizar_ventana()
     self.wids['b_guardar'].set_sensitive(False)
예제 #12
0
 def set_fin(self, boton):
     temp = utils.mostrar_calendario(
         fecha_defecto = utils.parse_fecha(
             self.wids["e_fechafin"].get_text()), 
         padre = self.wids['ventana'])
     self.fin = mx.DateTime.DateTimeFrom(*temp[::-1])
     self.wids['e_fechafin'].set_text(utils.str_fecha(self.fin))
예제 #13
0
 def add(self, w):
     if self.lote != None:
         fecha = self.wids['e_fecha'].get_text()
         if fecha == '':
             utils.dialogo_info(titulo = 'SIN FECHA',
                                texto = 'Debe introducir la fecha del resultado de la prueba.')
             return
         resultado = self.wids['e_resultado'].get_text()
         if resultado == '':
             utils.dialogo_info(titulo = 'SIN RESULTADO',
                                texto = 'Debe introducir el resultado de la prueba.')
             return
         try:
             prueba = pclases.PruebaGrasa(fecha = utils.parse_fecha(fecha),
                                                 resultado = resultado,
                                                 lote = self.lote)
             pclases.Auditoria.nuevo(prueba, self.usuario, __file__)
         except:
             utils.dialogo_info(titulo = 'ERROR', 
                                texto = 'Verifique que ha introducido los datos correctamente.')
         self.wids['e_fecha'].set_text(utils.str_fecha(time.localtime()))
         self.wids['e_resultado'].set_text('')
         self.rellenar_pruebas()
     else:
         print "WARNING: Se ha intentano añadir una prueba con lote = None"
예제 #14
0
파일: ausencias.py 프로젝트: pacoqueen/ginn
 def cambiar_fecha_fin_baja(self, cell, path, texto):
     try:
         fecha = utils.parse_fecha(texto)
     except (ValueError, TypeError):
         utils.dialogo_info(titulo = "FECHA INCORRECTA",
                            texto = "La fecha introducida no es válida",
                            padre = self.wids['ventana'])
         return
     model = self.wids['tv_bajas'].get_model()
     baja = pclases.Baja.get(model[path][-1])
     for bajaexistente in self.objeto.bajas:
         if bajaexistente == baja:
             continue
         iniciorango = baja.fechaInicio
         finrango = fecha
         if iniciorango > finrango:
             iniciorango, finrango = finrango, iniciorango
         fechaintermedia = iniciorango
         while fechaintermedia < finrango:
             if bajaexistente.esta_vigente(fechaintermedia):
                 utils.dialogo_info(titulo = "BAJA SOLAPADA",
                                    texto = "Las bajas médicas no pueden solaparse entre sí, elija otra fecha.",
                                    padre = self.wids['ventana'])
                 return
             if isinstance(fechaintermedia, datetime.date):
                 fechaintermedia += datetime.timedelta(1)
             else:
                 fechaintermedia += mx.DateTime.oneDay
     baja.fechaFin = fecha
     if baja.fechaInicio > baja.fechaFin:
         baja.fechaInicio, baja.fechaFin = baja.fechaFin, baja.fechaInicio
     baja.sync()
     model[path][0] = utils.str_fecha(baja.fechaInicio)
     model[path][1] = utils.str_fecha(baja.fechaFin)
예제 #15
0
 def ir_a_fecha(self, boton, fecha = None, comercial = None):
     """
     Desplaza el calendario y contenido de la ventana a la fecha para el
     comercial indicado. Si no se reciben, usa el comercial de la ventana
     y pregunta la fecha en un diálogo modal.
     """
     # 0.- Comprobar fecha recibida o pedir.
     if not fecha:
         fechastr = utils.dialogo_entrada(titulo = "INTRODUZCA FECHA",
                         texto = "Introduzca fecha a la que desplazarse:",
                         padre = self.wids['ventana'])
         if fechastr:
             try:
                 fecha = utils.parse_fecha(fechastr)
             except ValueError, TypeError:
                 utils.dialogo_info(titulo = "ERROR EN FECHA",
                         texto = "Introdujo una fecha no valida: %s" 
                             % fechastr,
                         padre = self.wids['ventana'])
                 return  # Error del usuario al meter fecha
             else:
                 dia = fecha.day
                 mes = fecha.month
                 anno = fecha.year
         else:
             return  # Canceló
예제 #16
0
파일: nominas.py 프로젝트: pacoqueen/ginn
 def crear_nominas_por_defecto(self, boton, mes = None, anno = None, borrar = True, fechaini = None, fechafin = None):
     """
     Si borrar es True, borra todas las nóminas que ya existan para el 
     mes y año indicados.
     Crea las nóminas para todos los empleados activos con la fecha 1 del 
     mes y año recibidos y los cálculos correctos a partir de los partes
     de trabajo, categoría laboral y demás.
     Si fechaini y fechafin son None usará el día 1 o último de mes 
     respectivamente.
     """
     txt = """
                                                                                 
     Al recalcular las nóminas se perderán todos los datos introducidos          
     para las ya existentes.                                                     
                                                                                 
     ¿Está seguro de que desea recalcular todas las nóminas?                     
                                                                                 
     """
     if mes == None:
         mes = self.meses.index(utils.combo_get_value(self.wids['cb_mes'])) + 1
     if anno == None:
         anno = int(self.wids['sp_anno'].get_value())
     nominas = pclases.Nomina.select("""date_part('month', fecha) = %d AND date_part('year', fecha) = %d""" 
                                     % (mes, anno))
     if not fechaini:
         try:
             fechaini = utils.parse_fecha(self.wids['e_fechaini'].get_text())
         except:
             fechaini = mx.DateTime.DateTimeFrom(day = 1, month = mes, year = anno)
     if not fechafin:
         try:
             fechafin = utils.parse_fecha(self.wids['e_fechafin'].get_text())
         except:
             fechafin = mx.DateTime.DateTimeFrom(day = -1, month = mes, year = anno)
     if nominas.count() > 0 and \
        borrar and \
        utils.dialogo(titulo = "¿RECALCULAR NÓMINAS?", texto = txt, padre = self.wids['ventana']):
         # Borrar y crear
         for nomina in nominas:
             nomina.destroy(ventana = __file__)
         self.crear_nominas(mes, anno, fechaini, fechafin)
         self.rellenar_nominas()
     else:
         # Crear sin más
         self.crear_nominas(mes, anno, fechaini, fechafin)
         self.rellenar_nominas()
예제 #17
0
 def cambiar_fecha(self, cell, path, texto):
     model = self.wids["tv_pruebas"].get_model()
     prueba = claseprueba.get(model[path][-1])
     try:
         prueba.fecha = utils.parse_fecha(texto)
     except:
         utils.dialogo_info("FECHA INCORRECTA", "La fecha introducida (%s) no es correcta." % texto)
     self.rellenar_pruebas()
예제 #18
0
 def buscar(self, boton):
     idproducto = utils.combo_get_value(self.wids['cbe_producto'])
     fechaini = utils.parse_fecha(self.wids['e_fechaini'].get_text())
     fechafin = utils.parse_fecha(self.wids['e_fechafin'].get_text())
     if idproducto > 1:
         try:
             producto = pclases.ProductoVenta.get(idproducto)
         except:
             utils.dialogo_info(titulo = "ERROR", 
                 texto = "El producto seleccionado no se encontró.\n"
                         "Probablemente fue eliminado.\nCierre y vuelva "
                         "a abrir esta ventana antes de volver a "
                         "intentarlo.", 
                 padre = self.wids['ventana'])
         else:
             partidas = producto.get_partidas(fechaini = fechaini, 
                                              fechafin = fechafin)
             if pclases.DEBUG:
                 print "consulta_marcado_ce.py::len(partidas", len(partidas)
             if self.wids['ch_gramaje'].get_active():
                 gramaje = producto.camposEspecificosRollo.gramos
                 cers = pclases.CamposEspecificosRollo.select(
                         pclases.CamposEspecificosRollo.q.gramos == gramaje)
                 for cer in cers:
                     try:
                         cerproducto = cer.productosVenta[0]
                     except IndexError, msg:
                         txt = "%sconsulta_marcado_ce::buscar -> "\
                               "El registro CER ID %d no tiene producto "\
                               "asociado. Mensaje de la excepción: %s" % (
                                 self.usuario 
                                     and self.usuario.usuario + ": " or "", 
                                 cer.id, msg)
                         print txt
                         self.logger.error(txt)
                         continue
                     if cerproducto != producto:     # Porque ya lo he 
                                                     # contado antes
                         for partida in cerproducto.get_partidas():
                             if (partida not in partidas 
                                 and fechaini 
                                     <= partida.get_fecha_fabricacion() 
                                     <= fechafin):
                                 partidas.append(partida)
             self.rellenar_tabla(partidas)
예제 #19
0
파일: gastos.py 프로젝트: Virako/fpinn
 def set_fecha(self, boton):
     try:
         fecha_actual = utils.parse_fecha(self.wids['e_fecha'].get_text())
         temp = utils.mostrar_calendario(fecha_actual, 
                                         padre = self.wids['ventana'])
     except:
         temp = utils.mostrar_calendario(padre = self.wids['ventana'])
     self.wids['e_fecha'].set_text(utils.str_fecha(temp))
     self.wids['e_fecha'].grab_focus()
예제 #20
0
 def cambiar_fecha(self, cell, path, texto):
     model = self.wids['tv_pruebas'].get_model()
     prueba = pclases.PruebaGrasa.get(model[path][-1])
     try:
         prueba.fecha = utils.parse_fecha(texto)
     except:
         utils.dialogo_info('FECHA INCORRECTA', 
                            'La fecha introducida (%s) no es correcta.' % texto)
     self.rellenar_pruebas()
예제 #21
0
 def rellenar_tabla(self, items):
     """
     Rellena el model con los items de la consulta
     """
     vpro = VentanaProgreso(padre = self.wids['ventana'])
     vpro.mostrar()
     vpro.set_valor(0.0, "Contando existencias...")
     act = 0.0
     tot = len(items) * len(self.tvs)
     try:
         fecha = utils.parse_fecha(self.wids['e_fecha'].get_text())
     except (TypeError, ValueError, AttributeError):
         fecha = mx.DateTime.today()
         self.wids['e_fecha'].set_text(utils.str_fecha(fecha))
     # XXX: Optimización (cosas de cómo están hechas las funciones de get_*
     #      por dentro en pclases):
     if fecha >= mx.DateTime.today():
         fecha = None
     for tv, kg, bultos, a in self.tvs:
         model = tv.get_model()
         model.clear()
         totalkgs = 0.0
         totalbultos = 0
         for pv in items:
             vpro.set_valor(act/tot, 
                            "Contando existencias...\t[%s]" % pv.get_puid())
             stock = pv.get_stock(hasta = fecha, almacen = a)
             totalkgs += stock
             existencias = pv.get_existencias(hasta=fecha, almacen = a)
             totalbultos += existencias
             stock_A = pv.get_stock_A(hasta = fecha, almacen = a)
             existencias_A = pv.get_existencias_A(hasta=fecha, almacen = a)
             stock_B = pv.get_stock_B(hasta = fecha, almacen = a)
             existencias_B = pv.get_existencias_B(hasta=fecha, almacen = a)
             stock_C = pv.get_stock_C(hasta = fecha, almacen = a)
             existencias_C = pv.get_existencias_C(hasta=fecha, almacen = a)
             model.append((pv.codigo,
                           pv.descripcion,
                           utils.float2str(stock),
                           utils.float2str(existencias, autodec = True),
                           utils.float2str(stock_A!=None and stock_A or 0),
                           utils.float2str(existencias_A != None and 
                                           existencias_A or 0, 
                                           autodec = True),
                           utils.float2str(stock_B!=None and stock_B or 0),
                           utils.float2str(existencias_B != None and 
                                           existencias_B or 0, 
                                           autodec = True),
                           utils.float2str(stock_C!=None and stock_C or 0),
                           utils.float2str(existencias_C != None and 
                                           existencias_C or 0, 
                                           autodec = True),
                           pv.get_puid()))
             act += 1
         kg.set_text(utils.float2str(totalkgs))
         bultos.set_text(utils.float2str(totalbultos, autodec = True))
     vpro.ocultar()
예제 #22
0
def main(fecha):
    """
    Recorre todos los artículos de la base de datos en busca de "gaps" en la
    fecha recibida.
    """
    pivote = utils.parse_fecha(fecha)
    gap1, gap2 = fabricados_fuera_del_parte(pivote)
    dump(gap1, "Artículos en almacén antes de ser fabricados", +1)
    dump(gap2, "Artículos fabricados antes de entrar en almacén", -1)
예제 #23
0
 def __init__(self, objeto = None, usuario = None):
     """
     Constructor. objeto puede ser un objeto de pclases con el que
     comenzar la ventana (en lugar del primero de la tabla, que es
     el que se muestra por defecto).
     """
     self.usuario = usuario
     self.partidas_carga = {}
     Ventana.__init__(self, 'consumo_fibra_por_partida_gtx.glade', objeto,
                      usuario = usuario)
     connections = {'b_salir/clicked': self.salir,
                    'b_buscar/clicked': self.buscar,
                    'b_imprimir/clicked': self.imprimir,
                    'b_fecha_inicio/clicked': self.set_inicio,
                    'b_fecha_fin/clicked': self.set_fin,
                    'e_fechainicio/focus-out-event': act_fecha,
                    'e_fechafin/focus-out-event': act_fecha,
                    'b_exportar/clicked': self.exportar}
     self.add_connections(connections)
     cols = (('Partida', 'gobject.TYPE_STRING', False, True, False, None),
      ('kg consumidos', 'gobject.TYPE_STRING', False, False, False, None),
      ('kg prod. (real)', 'gobject.TYPE_STRING', False, False, False, None),
      ('kg prod. (teórico)', 'gobject.TYPE_STRING', False,False,False,None),
      ('balas cons.', 'gobject.TYPE_STRING', False, False, False, None),
      ('rollos prod.', 'gobject.TYPE_STRING', False, False, False, None),
      ('m² producidos', 'gobject.TYPE_STRING', False, False, False, None),
      ('ID', 'gobject.TYPE_STRING', False, False, False, None))
     utils.preparar_treeview(self.wids['tv_datos'], cols)
     for col in self.wids['tv_datos'].get_columns()[1:]:
         for cell in col.get_cell_renderers():
             cell.set_property("xalign", 1.0)
         col.set_alignment(1.0)
     self.colorear(self.wids['tv_datos'])
     temp = time.localtime()
     self.wids['e_fechafin'].set_text(utils.str_fecha(temp))
     self.wids['e_fechainicio'].set_text(utils.str_fecha(
         mx.DateTime.localtime() - (7 * mx.DateTime.oneDay)))
     self.inicio = utils.parse_fecha(self.wids['e_fechainicio'].get_text())
     self.fin = utils.parse_fecha(self.wids['e_fechafin'].get_text())
     self.wids['rb_pesoreal'].child.set_property("use-markup", True)
     self.wids['rb_teorico'].child.set_property("use-markup", True)
     self.wids['rb_pesosin'].child.set_property("use-markup", True)
     self.wids['rb_pesosin'].set_active(True)
     gtk.main()
예제 #24
0
파일: nominas.py 프로젝트: pacoqueen/ginn
 def buscar_fecha(self, boton):
     """
     Abre el diálogo del calendario.
     """
     e_fecha = boton.name.replace("b_", "e_")
     try:
         valor_anterior = utils.parse_fecha(self.wids[e_fecha].get_text())
     except:
         valor_anterior = None
     self.wids[e_fecha].set_text(utils.str_fecha(utils.mostrar_calendario(valor_anterior, padre = self.wids['ventana'])))
예제 #25
0
 def set_inicio(self, boton):
     try:
         temp = utils.mostrar_calendario(
             fecha_defecto = utils.parse_fecha(
                 self.wids['e_fechainicio'].get_text()), 
             padre = self.wids['ventana'])
     except ValueError:
         temp = datetime.date.today().timetuple()[:3][::-1]
     self.inicio = mx.DateTime.DateTimeFrom(*temp[::-1])
     self.wids['e_fechainicio'].set_text(utils.str_fecha(self.inicio))
예제 #26
0
 def imprimir(self,boton):
     """
     Prepara la vista preliminar para la impresión del informe
     """
     from formularios import reports
     fechastr = self.wids['e_fecha'].get_text()
     fecha = utils.parse_fecha(fechastr)
     reports.abrir_pdf(
         geninformes.existencias(hasta = fecha, 
                                 ventana_padre = self.wids['ventana']))
예제 #27
0
 def set_fin(self, boton):
     try:
         temp = utils.mostrar_calendario(
                 fecha_defecto = utils.parse_fecha(
                     self.wids["e_fechafin"].get_text()), 
                 padre = self.wids['ventana'])
     except (ValueError, TypeError):
         temp = utils.mostrar_calendario(
                 padre = self.wids['ventana'])
     self.wids['e_fechafin'].set_text(utils.str_fecha(temp))
예제 #28
0
   def guardar(self, button):
       """
       Actualiza la información del objeto respecto a la 
       mostrada en pantalla. Guarda todos los datos de
       la ventana en el objeto persistente (y por tanto
       en la base de datos).
       """
       ## NOTAS: A ver, vamos por orden. Campos que tiene una tarifa:
       ## - Nombre -> Se guarda automáticamente con el botón "Cambiar nombre"
       ## - Descripción -> Hay que guardarlo en esta función.
       ## - Identificador -> Es automático y ni lo muestro. No se puede 
       ##                    cambiar.
       ## - Productos asociados -> Se añaden y eliminan con sus botones correspondientes.
       tarifa = self.objeto
 
       # Desactivo notificador:
       tarifa.notificador.set_func(lambda : None)
       
       # Guardo cambios:
       ## Por tanto, sólo hay que guardar los cambios en la descripción:
       buff = self.wids['tv_descripcion_tarifa'].get_buffer()
       texto=buff.get_text(buff.get_bounds()[0], buff.get_bounds()[1])
       tarifa.observaciones=texto
       try:
           periodoValidezIni = utils.parse_fecha(self.wids['e_periodo_validez_ini'].get_text())
       except:
           periodoValidezIni = None
       tarifa.periodoValidezIni = periodoValidezIni
       try:
           periodoValidezFin = utils.parse_fecha(self.wids['e_periodo_validez_fin'].get_text())
       except:
           periodoValidezFin = None
       tarifa.periodoValidezFin = periodoValidezFin
       if tarifa.periodoValidezIni != None and tarifa.periodoValidezFin != None and tarifa.periodoValidezIni > tarifa.periodoValidezFin:
           tarifa.periodoValidezIni, tarifa.periodoValidezFin = tarifa.periodoValidezFin, tarifa.periodoValidezIni
       tarifa.syncUpdate()  # Por probare.
 
       self.actualizar(None)
       # Y vuelvo a activar el notificador:
       tarifa.notificador.set_func(self.act)
       # Y por último deshabilito el botón hasta que el usuario lo vuelva a necesitar
       self.wids['b_guardar'].set_sensitive(False)
예제 #29
0
def act_fecha(entry, event):
    """
    Cambia los mnemotécnicos de fecha por la fecha debidamente formateada
    o la cadena vacía para indicar que no hay límite de fecha.
    """
    txtfecha = entry.get_text()
    try:
        txtfecha = utils.str_fecha(utils.parse_fecha(txtfecha))
    except (ValueError, TypeError):
        txtfecha = ""
    entry.set_text(txtfecha)
예제 #30
0
 def set_inicio(self,boton):
     try:
         datinw = utils.parse_fecha(self.wids['e_fechainicio'].get_text())
         temp = utils.mostrar_calendario(datinw,
                                         padre = self.wids['ventana'])
     except:
         temp = utils.mostrar_calendario(padre = self.wids['ventana'])
     self.wids['e_fechainicio'].set_text(utils.str_fecha(temp))
     self.inicio = mx.DateTime.DateTimeFrom(day = temp[0],
                                            month = temp[1],
                                            year = temp[2])