예제 #1
0
    def Formatea_Valor(self):
        valor = self.__cttext.GetValue()
        fmt = self._fmt
        lmax = self._lmax
        #
        punto = False
        if self._pb != None:
            try:
                if self._pb._idx == self._name and valor == '' or valor == '.':
                    valor = '.'
                    punto = True
            except:
                pass  # Si no tiene _idx daría fallo

        if not punto:
            if fmt == '%':
                if valor != '': valor = valor.zfill(lmax)
            elif fmt == 'd':
                fecha = Fecha_aNum(valor)
                if fecha == None:
                    mes = str(Fecha(fmt='m')).zfill(2)
                    anio = str(Fecha(fmt='y'))
                    if 0 < len(valor) <= 2:
                        valor = valor + '/' + mes + '/' + anio
                    elif len(valor) < 5:
                        dia = valor[:2]
                        mes = valor[2:]
                        valor = dia + '/' + mes + '/' + anio
                    elif len(valor) >= 6:
                        dia = valor[:2]
                        mes = valor[2:4]
                        anio = valor[4:]
                        if len(anio) == 2: anio = '20' + anio
                        elif len(anio) == 3: anio = '2' + anio
                        valor = dia + '/' + mes + '/' + anio
                    #
                    valor = Num_aFecha(Fecha_aNum(valor))
            elif fmt in ('1', '2', '3', '4', '5', '6', '7', '8', '9'):
                if valor == '': valor = '0'
                if valor.find('.') == -1: valor = valor + '.'
                ent, dec = valor.split('.')
                while len(dec) < int(fmt):
                    dec = dec + '0'
                valor = ent + '.' + dec

        self.__cttext.SetValue(valor)
        #
        return valor  # Se Utiliza en el grid.
예제 #2
0
 def SetValue(self, value, acc='s'):
     """ Asigna valor en su formato al campo de texto (convierte a cadena)"""
     fmt = self._fmt
     lmax = self._lmax
     #
     if value == None:
         value = ''
     elif fmt == 'd':
         value = Num_aFecha(value)
     elif fmt in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):
         if value == '': value = 0.0
         else: value = float(value)
         value = str(round(value, int(fmt)))
     elif fmt == 'i':
         if value == '': value = 0
         value = str(value)
     #
     vant = self.GetValue()
     if vant != value and self._name != self._pb._idx:
         self._pb.Modifica = 1
     #
     self.__cttext.SetValue(value)
     #
     #
     if acc != 'n' and self._ade != '':
         ls_ade = self._ade.split('|')
         for ade in ls_ade:
             res = self._pb.Ejecuta_Accion(ade, self)
             if res[0] < 0:
                 print(res)
                 return  # La ejecución falló
예제 #3
0
    def SetValue(self,data,acc='s'):
        """ Asigna a la lista los valores seleccionados """
        lis = self.__ctlis
        fmtlis = self.__fmtlis
        self.__data = data
        lis.DeleteAllItems()

        for lnd in data:
            if isinstance(lnd,str): lnd=[lnd]
            nfila = lis.InsertItem(MAXINT,lnd[0])
            ncol=0
            for fmt in fmtlis:
                try:
                    valor = lnd[ncol]
                except:
                    valor = ''
                #
                if fmt == 'd':
                    valor = Num_aFecha(valor)
                elif fmt =='i':
                    valor = str(valor)
                elif fmt in ('0','1','2','3','4','5','6','7','8','9'):
                    try:
                        valor = str(round(valor,int(fmt)))
                    except:
                        valor = '0.0'
                
                lis.SetItem(nfila,ncol,valor)
                #
                ncol += 1
        #-
        #- Reasignamos el ancho de la columna
        anchos = self.__anchos
        if anchos==[]:
            anchos = [0]*len(self.__fmtlis)
            for i in range(lis.GetColumnCount()):
                col = lis.GetColumn(i)
                anchos[i] = len(col.Text)

            if data!=[]:    # Ajustamos al ancho maximo de todas las filas
                for fdata in data:
                    if isinstance(fdata,str): fdata=[fdata]
                    i=0
                    for cdata in fdata:
                        if i>=len(fmtlis): continue
                        if fmtlis[i]=='d':  # Fechas siempre mismo ancho
                            anchos[i]=10
                            continue
                        if isinstance(cdata,float) or isinstance(cdata,int):
                            cdata=str(cdata)
                        if len(cdata) > anchos[i]: anchos[i] = len(cdata)
                        i+=1
        #
        for i in range(len(anchos)):
            tam = anchos[i]*10
            lis.SetColumnWidth(i,tam)
예제 #4
0
    def Ejecuta_Accion(self, accion, obj=None, args=None):
        """ Acciones a ejecutar """
        # Probamos primero si es una accion estandar
        std = OC.ui.Ventana.Ejecuta_Accion(self, accion, obj)
        ok, val = std

        # Comprobar el valor devuelto por si hay que hacer algo
        # Ya se ejecutó la accion. No continuar con la accion normal
        if ok > 0:
            return val

        if accion == 'a_carga_rg':
            cod = self._ct['LS'].GetValue()
            if cod != None: self._ct[self._idx].SetValue(cod)

        elif accion == 'a_pon_histo':
            cdcl = self._ct['IDX'].GetValue()
            if not cdcl in ('', '.', None):
                tablaVentas = OC.db.Table('alb-venta')
                histo = tablaVentas.select('0 AV_FEC AV_TN AV_TTT',
                                           [['AV_CL', '=', cdcl]])
                self._ct['L1'].SetValue(histo)
            return (1, accion + ': ok')

        elif accion == 'a_pon_detalle':
            resul = []
            cdav = self._ct['L1'].GetValue()
            tablaVentas = OC.db.Table('alb-venta')
            av = tablaVentas.get(cdav)
            for ln in av['AV_LNA']:
                cdar, uds = ln[:2]
                tablaArticulos = OC.db.Table('articulos')
                ar = tablaArticulos.get(cdar)
                ardeno = 'undefined'
                if ar != 1: ardeno = ar['AR_DENO']
                resul.append([cdar, ardeno, uds])
            self._ct['L2'].SetValue(resul)
            return (1, accion + ': ok')

        elif accion == 'a_inf1':  # Cumpleaños
            res, preguntas = args

            mes = 0
            for ln in preguntas:
                if ln[0] == 'MES': mes = ln[2]

            rs = []
            for lna in res:
                fnac = lna[2]
                if mes != 0 and mes != Num_aFecha(fnac, 'm'): continue
                rs.append(lna)

            return rs

        elif accion == 'a_inf2':  # Importe pendiente
            res, preguntas = args
            ls_cl = [ln[0] for ln in res]

            prg = [['AV_PTE', '>', 0]]
            for ln in preguntas:
                if ln[0] == 'DFEC': prg.append(['AV_FEC', '>=', ln[2]])
                if ln[0] == 'HFEC': prg.append(['AV_FEC', '<=', ln[2]])
            #
            rs = []
            tablaVentas = OC.db.Table('alb-venta')
            tablaClientes = OC.db.Table('clientes')

            vtas = tablaVentas.select('0 AV_CL AV_TTT AV_COB AV_FEC', prg)
            for ln in vtas:
                cdav, cdcl, ttt, cob, av_fec = ln[:5]
                if not cdcl in ls_cl: continue  # Cliente no preguntado
                if ttt != cob:
                    cli = tablaClientes.get(cdcl)
                    if cli == 1: denocli = 'NO DEFINIDO'
                    else: denocli = cli['CL_DENO']
                    rs.append(
                        [cdcl, denocli, cdav, av_fec, ttt, cob, ttt - cob])

            rs.sort()
            return rs

        return (0, 'No se ejecutó ninguna accion')
예제 #5
0
    def Ejecuta_Accion(self,accion,obj=None):
        pb = self

        """ Acciones a ejecutar """
        # Probamos primero si es una accion estandar
        std = OC.ui.Ventana.Ejecuta_Accion(self, accion,obj)
        ok,val = std

        # Comprobar el valor devuelto por si hay que hacer algo
        # Ya se ejecut� la accion. No continuar con la accion normal
        if ok>0:
            return val

        if accion=='a_ini_var':
            pb._ct['IDX'].SetValue(Fecha())
            self.Modifica=0

        elif accion=='a_actu_resumen':
            dfec=pb._ct['DFEC'].GetValue()
            hfec=pb._ct['HFEC'].GetValue()
            porcen = pb._ct['RATIO'].GetValue()

            if hfec==None: hfec=Fecha()

            if dfec==None or hfec==None:
                Men('Debe indicar el rango de fechas.')
                return -1
            if porcen==0: porcen = 100.

            resul = []
            dc={}

            #
            ## NO COGEMOS COBROS PQ NO TENEMOS FORMA DE SABER A QUE ARTICULO PERTENECE EL IMPORTE !!!!!!
            #
            tablaVentas = OC.db.Table('alb-venta')
            tablaArticulos = OC.db.Table('articulos')
            #
            avList = tablaVentas.select('0 AV_FEC AV_PTJ AV_LNA',[['AV_FEC','>=',dfec],['AV_FEC','<=',hfec]])
            for av in avList:
                fec = av[1]
                estj = av[2]
                lnas = av[3]
                if not fec in dc.keys(): dc[fec]=[0,0,0,0,0]
                for ln in lnas:
                    cdar,uds,pvp = ln[:3]
                    ar = tablaArticulos.get(cdar)
                    if ar==1: tipo='P'
                    else: tipo = ar['AR_TIPO']
                    if tipo=='S':
                        if not estj: dc[fec][0]+=uds*pvp    # Servicio Efectivo
                        else: dc[fec][1]+= uds*pvp      # Servicio Tarjeta
                    else:
                        if not estj: dc[fec][2]+=uds*pvp    # Producto Efectivo
                        else: dc[fec][3]+= uds*pvp      # Producto Tarjera

            tablaGastos = OC.db.Table('gastos')
            ls_ga = tablaGastos.select('0 GA_IMPO GA_FEC',[['GA_FEC','>=',dfec],['GA_FEC','<=',hfec]])
            for ln in ls_ga:
                cod,impo,fec = ln
                if not fec in dc.keys(): dc[fec]=[0,0,0,0,0]
                dc[fec][4]+= impo

            #
            tt1,tt2,tt3 = 0,0,0
            hoja=[]
            for fec in dc:
                ttsrve,ttsrvj,ttvtse,ttvtsj,ttgas = dc[fec]
                ttsrv = round(ttsrvj + ttsrve*porcen/100.,2)
                ttvts = round(ttvtsj + ttvtse*porcen/100.,2)
                hoja.append([fec,ttsrv,ttvts,ttsrv+ttvts,ttgas,ttsrv+ttvts-ttgas])
                tt1+=ttsrv
                tt2+=ttvts
                tt3+=ttgas

            #
            hoja.sort()
            ##hoja.append([None,tt1,tt2,tt1+tt2,tt3,tt1+tt2-tt3])
            pb._ct['G_DIAS'].SetValue(hoja)
            pb._ct['TT1'].SetValue(tt1)
            pb._ct['TT2'].SetValue(tt2)
            pb._ct['TT3'].SetValue(tt1+tt2)
            pb._ct['TT4'].SetValue(tt3)
            pb._ct['TT5'].SetValue(tt1+tt2-tt3)


        #
        #--
        #
        elif accion=='a_guarda_resumen':
            hoja = pb._ct['G_DIAS'].GetValue()
            titus = ['Fecha','Servicios','Productos','Total','Gastos','Beneficio']

            SEP = '\t'
            aux = []
            for ln in hoja:
                ln[0] = Num_aFecha(ln[0])
                ln[1],ln[2],ln[3] = str(ln[1]),str(ln[2]),str(ln[3])
                ln[4],ln[5] = str(ln[4]),str(ln[5])
                for i in range(len(ln)): ln[i] = ln[i].replace('.',',')
                aux.append(SEP.join(ln))
            hoja= '\n'.join(aux)
            titus = '\t'.join(titus)
            hoja = titus + '\n' + hoja

            ## Seleccionar Directorio
            dlg = wx.DirDialog(self,"Elija Directorio",
                defaultPath=os.environ['HOME'],
                style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON)
            ruta = ''
            if dlg.ShowModal()==wx.ID_OK:
                ruta = dlg.GetPath()
            dlg.Destroy()
            ##
            if ruta=='':
                Men('Proceso Cancelado. No ha indicado donde guardar.')
                return -1

            dfec=pb._ct['DFEC'].GetValue()
            hfec=pb._ct['HFEC'].GetValue()
            dfec = Num_aFecha(dfec).replace('/','_')
            hfec = Num_aFecha(hfec).replace('/','_')
            ruta += '/resumen_'+dfec+'-'+hfec+'.xls'
            f = open(ruta,"wb")
            f.write(hoja)
            f.close()
            Men('Resumen creado correctamente.')


        return 0 # No se ejecut� ninguna accion !!!!
예제 #6
0
    def Ejecuta_Accion(self, accion, obj=None, args=None):
        """ Acciones Estandar para las ventanas """
        valor = accion
        aux = accion.split(':')
        accion = aux[0]
        arg = []
        if args != None:
            arg = args
        else:
            if len(aux) > 1: arg = aux[1].split(',')

        cta = self._cta
        if obj != None: cta = obj

        if accion == 'a_SALIR':
            if self.Modifica == 1:
                dlg = Men(
                    'Ha realizado cambios en la ficha\n¿Desea Continuar sin grabar?',
                    'sn', 'q')
                if dlg == 'n':
                    return (1, 'a_SALIR: accion cancelada por usuario'
                            )  # Accion Ejecutada
            #-
            self.Close()
            self.Destroy()
            return (1, 'ok')

        elif accion == 'a_CPAN':
            import sys

            ventana = arg[0]
            win = wx.FindWindowByName(ventana)
            # print('Ventana','a_CPAN',ventana,win)
            if win:
                win.Hide()
                win.Show()
                #win.RequestUserAttention() --> La marca y parpadea...
                return

            code = 'import ' + ventana + '\n'
            code += 'dlg = ' + ventana + '.' + ventana + '(self)\n'
            exec(code)
            return (1, 'ok')

        else:
            # Abrir el fichero de datos y asociar a la ventana
            file = self._filedb
            # ruta_datos = DIR_DATA +'/'+ file + '.db'
            try:
                idx = self._ct[self._idx].GetValue()
                idx = str(idx)
                if idx == '': idx = '.'
            except:
                idx = ''
            #
            if file != '' and self._dbTable == None:
                self._dbTable = OC.db.Table(file)

        res = None  # Si es igual a None, no se ejecutó accion
        if accion == 'a_LEE_RG':
            if self.Modifica == 1 and cta._vant != '':
                dlg = Men(
                    'Ha realizado cambios en la ficha\n¿Desea Continuar sin grabar?',
                    'sn', 'q')
                if dlg == 'n':
                    return (1, 'Accion cancelada por el usuario'
                            )  # Accion Ejecutada
            #-
            self.Modifica = 0
            self.__hash = 0
            cod = str(cta.GetValue())
            if cod != '' and cod != '.':
                fich = self._dbTable
                rg = fich.get(cod)
                if rg == 1:
                    avisa = 1
                    if len(arg) > 0:
                        if arg[0] == 'n': avisa = 0
                    if avisa:
                        Men('No existe el registro ' + cod + ' en ' +
                            self._filedb)
                    self.Limpia_Pantalla('n')
                    self.__hash = 0
                else:
                    self.Reg_aPan(rg)
                    self.__hash = fich.getHash(cod)

            self.Modifica = 0
            res = (1, 'ok')

        elif accion == 'a_GRABA':
            #
            if len(arg) > 0:
                if arg[0] != '':  # Accion antes de grabar
                    ok = self.Ejecuta_Accion(arg[0])
                    if ok == -1:
                        return (-1, '')  # Operacion cancelada

                # Volver a leer despues de grabar?
                voleer = 1
                if len(arg) > 1:
                    if arg[1] == 'n': voleer = 0
            #
            if file == '':
                Men('No ha definido tabla sobre la que grabar.')
                return (-1, 'a_GRABA: no hay tabla')
            if idx == '':
                Men('No se ha definido correctamente el campo codigo de registro'
                    )
                return (-1, 'a_GRABA: No hay campo IDX')
            #
            if self.Modifica == 0:
                msj = 'No ha realizado cambios.\12¿Desea guardar el registro?'
                dlg = Men(msj, 'sN', 'q')
                if dlg == 'n':
                    return (1, 'a_GRABA: Accion cancelada por el usuario')

            rg_new = self.Pan_aReg()
            if rg_new == None: return (0, 'No se pudo leer datos de pantalla.')

            #- Está definida la tabla en los diccionarios de aplicacion??
            midicc = self._dbTable.getTableDef()
            #---
            accion = midicc[4]  # Acción al grabar
            ndig = midicc[1]  # Nº de digitos de la clave del dicc
            if ndig < 1: ndig = 1

            f = self._dbTable
            fkeys = f.keys()
            # Se ha anticipado alguien?
            if idx in fkeys:
                if self.__hash != f.getHash(idx):
                    Men('No es posible grabar. Alguien se anticipó')
                    return (-1, 'a_GRABA: Alguien se anticipó')

            # Busqueda del ultimo codigo libre
            if idx == '.':
                claves = fkeys
                claves.sort()
                if claves == []:
                    idx = '0' * ndig
                else:
                    idx = claves[-1]
                    idx = str(int(idx) + 1).zfill(ndig)

            if accion != '':  # Hay accion al grabar... la ejecutamos
                if idx in fkeys:  # El registro ya existe, desactualizamos
                    self._signo = -1
                    rg_old = f.get(idx)
                    self._rg = copy.deepcopy(rg_old)  # Registro antiguo
                    self.Ejecuta_Accion(accion)

                # Actualizamos con el valor nuevo del registro
                self._signo = 1
                self._rg = copy.deepcopy(rg_new)
                self.Ejecuta_Accion(accion)
                rg = self._rg  # Cogemos los valores nuevos

            else:  # No hay accion al grabar... simplemente grabamos
                rg = rg_new
            #-
            f.save(idx, rg)
            Men('Registro ' + idx + ' guardado', img='i')

            # Recargar el registro
            if self._ct[self._idx].GetFmt() == 'd': idx = int(idx)
            try:
                if voleer: self._ct[self._idx].SetValue(idx)
                else: self._ct[self._idx].SetValue(idx, 'n')
            except:
                self._ct[self._idx].SetValue(idx, 'n')
            self.__hash = f.getHash(idx)
            self.Modifica = 0
            res = (1, 'ok')

        elif accion == 'a_NEXT':
            if self.Modifica == 1:
                dlg = Men(
                    'Ha realizado cambios en la ficha\n¿Desea Continuar sin grabar?',
                    'sn', 'q')
                if dlg == 'n': return (1, 'Accion cancelada por el usuario')

            self.Modifica = 0
            f = self._dbTable
            lsk = f.keys()
            lsk.sort()

            if lsk == []:
                Men('No hay registros en la tabla ' + file)
                return (1, 'No hay registros en la tabla')
            nidx = lsk[0]
            if idx in lsk:
                pos = lsk.index(idx)
                if pos == len(lsk) - 1:
                    Men('No hay registro siguiente a ' + idx)
                    return (1, 'No hay registro siguiente')
                nidx = lsk[pos + 1]

            self._ct[self._idx].SetValue(nidx)
            self.Modifica = 0
            res = (1, 'ok')

        elif accion == 'a_PREV':
            if self.Modifica == 1:
                dlg = Men(
                    'Ha realizado cambios en la ficha\n¿Desea Continuar sin grabar?',
                    'sn', 'q')
                if dlg == 'n':
                    return (1, 'A_PREV: Accion cancelada por el usuario')

            self.Modifica = 0
            f = self._dbTable
            lsk = f.keys()
            lsk.sort()

            if lsk == []:
                Men('No hay registros en la tabla ' + file)
                return (1, 'a_PREV: No hay registros')
            nidx = lsk[-1]
            if idx in lsk:
                pos = lsk.index(idx)
                if pos == 0:
                    Men('No hay registro anterior a ' + idx)
                    return (1, 'a_PREV: No hay registro anterior')
                nidx = lsk[pos - 1]

            self._ct[self._idx].SetValue(nidx)
            self.Modifica = 0
            res = (1, 'ok')

        elif accion == 'a_NUEVO':
            if self.Modifica == 1:
                dlg = Men(
                    'Ha realizado cambios en la ficha\n¿Desea Continuar sin grabar?',
                    'sn', 'q')
                if dlg == 'n':
                    return (1, 'a_NUEVO: Accion cancelada por el usuario')
            self.Limpia_Pantalla(otros=arg)
            self._ct[self._ctord[0]].SetFocus()
            self.Modifica = 0
            res = (1, 'ok')

        elif accion == 'a_BORRA':
            tipo = self._ct[self._idx]._fmt
            cod = self._ct[self._idx].GetValue()
            if cod == '' or cod == '.':
                Men('No ha indicado el código de registro a borrar')
                return (-1, 'a_BORRA: No hay codigo para borrar')
            if tipo == 'd': cod = Num_aFecha(cod)
            else: cod = str(cod)
            #
            #- Accion antes de borrar
            if len(arg) > 0:
                if arg[0] != '':
                    ok = self.Ejecuta_Accion(arg[0])
                    if ok == -1:
                        return (-1, 'a_BORRA: ' + str(ok)
                                )  # Operacion cancelada
            #
            dlg = Men(u'¿Está seguro de borrar el registro ' + cod + '?', 'sn',
                      'q')
            if dlg == 'n':
                return (1, 'a_BORRA: Accion cancelada por el usuario')

            midicc = self._dbTable.getTableDef()

            # Acción para grabar (desactualizar)
            f = self._dbTable
            accion = midicc[4]
            if accion != '':
                self._signo = -1
                self._rg = f.get(idx)
                self.Ejecuta_Accion(accion)
            # Borrar el registro
            f.delete(idx)

            Men('Registro ' + idx + ' borrado.', img='i')
            self.Limpia_Pantalla()
            self._ct[self._ctord[0]].SetFocus()
            self.Modifica = 0
            res = (1, 'ok')

        elif accion == 'a_SELE':
            valor = cta.GetValue()
            opciones = arg[0].split('+')
            if not valor in opciones:
                Men('Valor ' + str(valor) + ' no válido. Solo admite ' +
                    ','.join(opciones))
                res = (-1, 'a_SELE: valor no valido')  # Se ejecutó pero mal.
            else:
                res = (1, 'ok')

        elif accion == 'a_INFO':
            if len(arg) > 0: fichero = arg[0]
            else: fichero = self._filedb
            informe, destino = '', ''
            if len(arg) > 1: informe = arg[1]
            if len(arg) > 2: destino = arg[2]
            if informe == '':
                dlg = OC.ui.dl_sel_inf(self, fichero)
                informe = dlg.res()
            #
            if informe == '':
                return (-1, 'a_INFO: No se ha indicado nombre de informe')
            OC.utils.Funciones.Crea_Info(self, fichero, informe, destino)
            res = (1, 'ok')

        elif accion == 'c_CAMPOS':
            lscampos = arg[0]
            lscampos = lscampos.split(' ')
            for campo in lscampos:
                fcal = self._ct[campo]._fcal
                if fcal != '':
                    val = self.Ejecuta_Accion(fcal, self._ct[campo])
                    self._ct[campo].SetValue(val)
            res = (1, 'ok')

        elif accion == 'a_CREA_INFO':
            res = (1, 'ok')

        if res == None:
            res = (0, u'No se ejecutó ninguna accion: ' + accion
                   )  # NO SE EJECUTÓ NINGUNA ACCION
        else:
            res = (1, res)  # SE EJECUTÓ LA ACCION, CON ESTE RESULTADO

        return res
예제 #7
0
    def Ejecuta_Accion(self, accion, obj=None):
        """ Acciones a ejecutar """
        # Probamos primero si es una accion estandar
        std = OC.ui.Ventana.Ejecuta_Accion(self, accion, obj)
        ok, val = std

        # Comprobar el valor devuelto por si hay que hacer algo
        # Ya se ejecut� la accion. No continuar con la accion normal
        if ok > 0:
            return val

        pb = self
        ct = pb._ct

        try:
            if accion == 'a_ini_var':
                pb._ct['IDX'].SetValue(Fecha())

            elif accion == 'a_actu_resumen':
                inicio = ct['DC_CINI'].GetValue()
                fin = ct['DC_CFIN'].GetValue()
                hoy = 0
                for ln in ct['DC_SRV'].GetValue():
                    if not ln[2] in ('s', 'S'):
                        if ln[1] == '': ln[1] = '0'
                        impo = float(ln[1])
                        hoy += impo
                for ln in ct['DC_VTS'].GetValue():
                    if not ln[2] in ('s', 'S'):
                        if ln[1] == '': ln[1] = '0'
                        impo = float(ln[1])
                        hoy += impo
                for ln in ct['DC_GAS'].GetValue():
                    if ln[1] == '': ln[1] = '0'
                    impo = float(ln[1])
                    hoy -= impo

                ct['DC_CHOY'].SetValue(hoy)
                descuadre = inicio + hoy - fin
                descuadre = -1 * descuadre
                ct['DC_CDES'].SetValue(descuadre)

            elif accion == 'a_genera_archivo':
                ## DIALOGO CON PREGUNTAS DE SELECCIÓN
                lsc = []
                p1 = ['PANEL', 'P1', 0, 0, -1, -1, '', '', '', []]
                enf = ['ENTRYS', 'FECS', '25', '50', '', '', []]
                #enf[-1].append(['ID','Etq','X','Y','Ancho','Fmt','lmax','edi','FC','Sobre','ADE','Dlg','Tip','CPAN','Style'])
                enf[-1].append([
                    'DFEC', 'Desde Fecha', '5', '20', '9', 'd', '10', '', '',
                    '', '', '', '', '', ''
                ])
                enf[-1].append([
                    'HFEC', 'Hasta Fecha', '105', '20', '9', 'd', '10', '', '',
                    '', '', '', '', '', ''
                ])
                enf[-1].append([
                    'PORCEN', ']%', '65', '55', '5', '2', '5', '', '', '', '',
                    '', '', '', ''
                ])
                p1[-1].append(enf)

                btn = []
                btn.append([
                    'B1', 5, 95, 90, 'ok.gif', 'Aceptar', 'a_ACEPTAR', '', ''
                ])
                btn.append([
                    'B2', 105, 95, 90, 'cancel.gif', 'Cancelar', 'a_SALIR:n',
                    '', ''
                ])
                p1[-1].append(['BUTTONS', 'BID', 40, '', '', btn])

                lsc.append(p1)
                ## ######################################

                dl = OC.ui.Dialogo(self,
                                   titulo='Exportar',
                                   campos=lsc,
                                   tam=(200, 150))
                dl.ShowModal()
                res = dl.res()
                if not res is None:
                    dfec, hfec, porcen = res
                    if dfec == None or hfec == None:
                        Men('Debe indicar el rango de fechas.')
                        return -1
                    tablaDiario = OC.db.Table('diario')
                    diarioList = tablaDiario.select(
                        '0 DC_SRV DC_VTS DC_GAS',
                        [['0', '>=', dfec], ['0', '<=', hfec]])
                    #
                    resul = []
                    for rg in diarioList:
                        cod = int(rg[0])
                        srv = rg[1]
                        vta = rg[2]
                        gas = rg[3]
                        #
                        ttsrve, ttsrvj = 0, 0  # Total Servicios Efectivo, Tarjeta
                        ttvtse, ttvtsj = 0, 0  # Total Ventas Efectivo, Tarjeta
                        ttgas = 0  # Total Gastos
                        for ln in srv:
                            if ln[1] == '': continue  # Sin importe??
                            impo = float(ln[1])
                            if ln[2] in ('s', 'S'): ttsrvj += impo
                            else: ttsrve += impo
                        for ln in vta:
                            if ln[1] == '': continue  # Sin importe??
                            impo = float(ln[1])
                            if ln[2] in ('s', 'S'): ttvtsj += impo
                            else: ttvtse += impo
                        for ln in gas:
                            if ln[1] == '': continue  # Sin importe??
                            impo = float(ln[1])
                            ttgas += impo
                        #
                        fec = Num_aFecha(cod)
                        resul.append(
                            [fec, ttsrve, ttsrvj, ttvtse, ttvtsj, ttgas])
                    #
                    hoja = [['Fecha', 'Servicios', 'Productos', 'Gastos']]
                    for ln in resul:
                        fec, ttsrve, ttsrvj, ttvtse, ttvtsj, ttgas = ln
                        ttsrv = ttsrvj + ttsrve * porcen / 100.
                        ttvts = ttvtsj + ttvtse * porcen / 100.
                        hoja.append([fec, str(ttsrv), str(ttvts), str(ttgas)])
                    #
                    SEP = ','
                    aux = []
                    for ln in hoja:
                        aux.append(SEP.join(ln))
                    hoja = '\n'.join(aux)

                    ## Seleccionar Directorio
                    dlg = wx.DirDialog(self,
                                       "Elija Directorio",
                                       defaultPath=os.environ['HOME'],
                                       style=wx.DD_DEFAULT_STYLE
                                       | wx.DD_NEW_DIR_BUTTON)
                    ruta = ''
                    if dlg.ShowModal() == wx.ID_OK:
                        ruta = dlg.GetPath()
                    dlg.Destroy()
                    ##
                    if ruta == '':
                        Men('Proceso Cancelado. No ha indicado donde guardar.')
                        return -1
                    dfec = Num_aFecha(dfec).replace('/', '_')
                    hfec = Num_aFecha(hfec).replace('/', '_')
                    ruta += '/resumen_' + dfec + '-' + hfec + '.csv'
                    f = open(ruta, "wb")
                    f.write(hoja)
                    f.close()
                    Men('Resumen creado correctamente.')

        except:
            Men(Busca_Error())

        return 0  # No se ejecutó ninguna accion !!!!