예제 #1
0
    def __Pon_Grid(self,padre,datos):
        """ Añade un grid en la ventana/panel padre
            ['GRID',id,titulo,posx,posy,ancho,alto_fila,nfilas,columnas
              ancho_titulo_fila, lista_titus_fila,prop_generales ]

            columnas = [[Titulo, ancho, fmt, lmax, edi, grab, fcal, sobre
                        ade, dlsel, totales, tip, cpan, style]
                        ,
                        ...]
        """
        tipo,nombre,titulo,posx,posy,ancho,hfila,nfilas,cols = datos[:9]
        wfilat,filast,props = datos[9:]

        if tipo!='GRID':
            return -1

        posx,posy = int(posx),int(posy)
        ancho,hfila=int(ancho),int(hfila)
        nfilas,wfilat = int(nfilas),int(wfilat)

        grid = OC.ui.Grid(self,padre,nombre,(posx,posy),ancho,hfila,nfilas,cols)

        #- Ponemos en el diccionario de campos
        self._ctord.append(grid)
        if not nombre in self._ct:
            self._ct[nombre]=grid
            self._ctord.append(nombre)
        else:
            Men('El control '+nombre+' se encuentra repetido.')
예제 #2
0
    def __Pon_Lista(self,padre,datos):
        """ Añade una lista a la ventana/panel padre
             ['LISTA',id, xini, yini, tamanox, tamanoy, cols,
                anchos_fijos_cols, style, multisel?, borrar?
                acc_click, acc_dclick, acc_borra]
        """
        tipo,nombre,xini,yini,tamx,tamy,cols,wcols,style = datos[:9]
        multisel,borrar,acc,acd,acb=datos[9:14]

        xini,yini = int(xini),int(yini)
        tamx,tamy = int(tamx),int(tamy)

        if tipo!='LIST':
            return -1

        posic = wx.Point(xini,yini)
        size = (tamx,tamy)
        elem = OC.ui.List(self,padre,nombre,posic,size,cols,[],acc,acd)

        #- Ponemos en el diccionario de campos
        self._ctord.append(elem)
        if not nombre in self._ct:
            self._ct[nombre]=elem
        else:
            Men('El control '+nombre+' se encuentra repetido.')
예제 #3
0
    def OnCalSelected(self, evt):
        if self.Modifica == 1:
            dlg = Men(
                'Ha realizado cambios en la ficha\n¿Desea Continuar sin grabar?',
                'sn', 'q')
            if dlg == 'n': return 0

        sele = evt.Date
        text = "%02d/%02d/%d" % (sele.GetDay(), sele.GetMonth() + 1,
                                 sele.GetYear())
        self._ct['IDX'].SetValue(Fecha_aNum(text))
예제 #4
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_actualiza':
            fec = pb._ct['IDX'].GetValue()
            #
            ttini = pb._ct['CJ_INI'].GetValue()
            ttfin = pb._ct['CJ_CIE'].GetValue()
            #
            tablaCobros = OC.db.Table('cobros')
            cobros = tablaCobros.select('0 CB_TARJ CB_IMPO',
                                        [['CB_FEC', '=', fec]])
            #
            ttvtas = 0
            for cod, esTarj, importe in cobros:
                if esTarj == 1: continue  #Pago tarjeta, no influye saldo
                ttvtas += importe
            pb._ct['CJ_VTAS'].SetValue(ttvtas)
            #
            tablaGastos = OC.db.Table('gastos')
            gastos = tablaGastos.select('0 GA_IMPO', [['GA_FEC', '=', fec]])
            ttgas = 0
            for cod, importe in gastos:
                ttgas += importe
            pb._ct['CJ_GAS'].SetValue(ttgas)
            #
            resto = ttini + ttvtas - ttgas
            descuadre = ttfin - resto
            pb._ct['CJ_DES'].SetValue(descuadre)
            #
            tablaCobros.close()
            tablaGastos.close()
            #
            Men('Datos Actualizados')

        return 0  # No se ejecutó ninguna accion !!!!
예제 #5
0
 def Borra_Cobro(self,cdav,cdcb):
     tablaCobros = OC.db.Table('cobros')
     rg = tablaCobros.get(cdcb)
     if rg==1:
         Men('No se pudo leer el cobro '+cdcb)
         return None
     importe = rg['CB_IMPO']
     
     ok = tablaCobros.delete(cdcb)
     tablaCobros.close()
     if ok==None: return None
     
     av = self._tablaVentas.get(cdav)
     if av==1: return 1
     av['AV_COB']-=importe
     av['AV_PTE']+=importe
     
     self._tablaVentas.save(cdav, av)
     return 1
예제 #6
0
    def __Pon_Checks(self, padre, datos):
        """ Añade un check en la ventana/panel padre
        """
        tipo, id, posx, posy, alto, ancho, texto, valor, accion, tip, style = datos
        if tipo != 'CHECK':
            return -1

        alto, ancho = int(alto), int(ancho)
        posic = (int(posx), int(posy))
        tam = (ancho, alto)
        #
        elem = OC.ui.CheckButton(self, padre, id, posic, tam, texto, accion)
        ##if tip != '': ....
        ##if style != '': ...

        #- Ponemos en el diccionario de campos
        if not id in self._ct:
            self._ct[id] = elem
        else:
            Men('El control ' + id + ' se encuentra repetido.')
예제 #7
0
    def Crea_Cobro(self,cdav,importe,tarj):
        tablaCobros = OC.db.Table('cobros')
        rg = tablaCobros.get(None) # rg_vacio
        idx = tablaCobros.getNextId()
        rg['CB_DENO']='Cobro de la venta '+cdav
        rg['CB_FEC']=Fecha()
        rg['CB_IMPO']=importe
        rg['CB_CDAV']=cdav
        rg['CB_TARJ']=tarj
       
        av = self._tablaVentas.get(cdav)
        if av==1: 
            Men('No se pudo obtener venta '+cdav)
            return 1
        av['AV_COB']+=importe
        av['AV_PTE']-=importe
        if tarj: av['AV_PTJ']=1  # Si uno de los cobros es con tarjerta, ponemos la venta con tarjeta
        
        tablaCobros.save(idx, rg)
        tablaCobros.close()

        self._tablaVentas.save(cdav, av)
        
        return idx
예제 #8
0
    def __Pon_Entradas(self,padre,datos):
        """ Inserta una/varias entradas en la ventana o panel padre.
          datos:
            ['ENTRYS', Id, alto_control, salto_a_-1, style_etiq,
                style_txt, LS_ENT]

            LS_ENT = [Id,etiq,xini,yini,ancho,formato,lmax,edi,
                               fcal,sobre,ade,dlsel,tip,cpan,style]
        """
        tipo,id,alto,salto,stylelabel,styletext,entradas = datos[:7]
        alto,salto = int(alto),int(salto)
        if tipo!='ENTRYS':
            return -1

        ultx,ulty = 0,0     # Ultimas posiciones X e Y de un campo
        sumax = 0   # Distancia a sumar para poner la proxima entrada si -1
        for lne in entradas:
            nombre,etiq,xini,yini,ancho,fmt,max = lne[:7]
            edi,fcal,sobre,ade,dlsel,tip,cpan,style = lne[7:15]
            #-
            xini,yini = int(xini),int(yini)
            ancho,max = int(ancho),int(max)

            #-- Asignar Posicion cuando se indica pos -1
            auto = 0
            if xini==-1:
                auto=1
                xini,yini = ultx+sumax, ulty
            elif yini==-1:
                yini = ulty + salto
            elif yini==0:
                yini = ulty

            posic = wx.Point(xini,yini)
            #-- Crear el elemento
            elem = OC.ui.Entry(self,padre,nombre,posic,etiq,fmt,max,ancho,alto,dlsel)

            #- Comprobamos que no salga fuera de la ventana
            fin = elem.GetPosition()[0] + elem.GetSize()[0]
            xmax = padre.GetSize()[0]
            if fin > xmax and auto:
                xini,yini = 1, ulty + salto
                posic = wx.Point(xini,yini)
                elem.SetPosition(posic)

            # Posicion del ultimo campo
            ultx,ulty = xini, yini
            sumax = elem.GetSize()[0]+10


            #- Editable
            if edi in ['n','i']:
                elem.SetEditable(False)
                elem.Disable()
                if edi=='i': elem.Show(0)
            else:
                self._ctord.append(nombre)

            #- Formula Calculo
            if fcal!='':
                elem._fcal = fcal
                elem._sobre = sobre

            #- Accion Despues Editar
            if ade!='':
                elem._ade = ade

            #- Tip de Ayuda
            if tip!='':
                elem.SetToolTipString(tip)

            #- CPAN
            if cpan!='':
                elem._cpan = cpan

            #- Estilos
            if styletext!='':
                stl = styletext.split('/')
                cttext = elem.GetTextCtrl()
                for ln in stl:
                    if ln[:2]=='B-':
                        rgb = ln[2:].split(':')
                        cttext.SetBackgroundColour(wx.Colour(int(rgb[0]), int(rgb[1]), int(rgb[2])))
                    elif ln[:2]=='F-':
                        rgb = ln[2:].split(':')
                        cttext.SetForegroundColour(wx.Colour(int(rgb[0]), int(rgb[1]), int(rgb[2])))
                    else:
                        pass    # Tener en cuenta otros tipos de estilo ???
            if stylelabel!='':
                stl = stylelabel.split('/')
                ctlabel = elem.GetLabelCtrl()
                for ln in stl:
                    if ln[:2]=='B-':
                        rgb = ln[2:].split(':')
                        ctlabel.SetBackgroundColour(wx.Colour(int(rgb[0]), int(rgb[1]), int(rgb[2])))
                    elif ln[:2]=='F-':
                        rgb = ln[2:].split(':')
                        ctlabel.SetForegroundColour(wx.Colour(int(rgb[0]), int(rgb[1]), int(rgb[2])))
                    else:
                        pass    # Tener en cuenta otros tipos de estilo ???

            # Si hay estilo especifico, lo ponemos
            if style!='':
                stl = style.split('/')
                cttext = elem.GetTextCtrl()
                for ln in stl:
                    if ln[:2]=='B-':
                        rgb = ln[2:].split(':')
                        cttext.SetBackgroundColour(wx.Colour(int(rgb[0]), int(rgb[1]), int(rgb[2])))
                    elif ln[:2]=='F-':
                        rgb = ln[2:].split(':')
                        cttext.SetForegroundColour(wx.Colour(int(rgb[0]), int(rgb[1]), int(rgb[2])))
                    else:
                        pass    # Tener en cuenta otros tipos de estilo ???

            #- Ponemos en el diccionario de campos
            if not nombre in self._ct:
                self._ct[nombre]=elem
            else:
                Men('El control '+nombre+' se encuentra repetido.')
예제 #9
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 !!!!
예제 #10
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 !!!!
예제 #11
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':
            modelDicc = OC.manage.DiccsManager()
            lista_files = list(x[0] for x in modelDicc.getDiccList())
            lista_files.insert(0, '')

            wx.StaticText(self._ct['P1'], -1, "Archivo:", (10, 5))
            sele = wx.Choice(self._ct['P1'],
                             -1, (10, 20), (150, 25),
                             choices=lista_files)
            sele.Bind(wx.EVT_CHOICE, self.onChangeFile)
            self._FILE = sele

        #
        #-- Rellenar la lista de informes de un fichero
        #
        elif accion == 'a_lista_inf':
            items = self._FILE.GetItems()
            sele = self._FILE.GetSelection()
            tabla = items[sele]
            #
            ls_inf = []
            if (tabla != ''):
                ls_inf = self._formManager.getFormsForTable(tabla)
            #
            linf = []
            for inf in ls_inf:
                linf.append([inf])
            self._ct['LINF'].SetValue(linf)
            self._ct['DESCRIP'].SetValue('')
            self._ct['ANTES'].SetValue('')
            self._ct['ACCION'].SetValue('')
            self._ct['DESPUES'].SetValue('')
            self._ct['GRIDC'].SetValue([])
            self._ct['GRIDP'].SetValue([])
        #
        #-- Cargar los datos de un informe
        #
        elif accion == 'a_carga_inf':
            items = self._FILE.GetItems()
            sele = self._FILE.GetSelection()
            tabla = items[sele]
            inf = self._ct['LINF'].GetValue()
            #
            ls_inf = {}
            if (tabla != ''):
                ls_inf = self._formManager.getFormsForTable(tabla)
            #
            if not inf in ls_inf.keys():
                # Le ha dado a informe nuevo y se ha seleccionado
                deno,antes,accion,despues,gridc,gridp='','','','',[],[]
            else:
                deno, antes, accion, despues, gridc, gridp = ls_inf[inf]
            self._ct['DESCRIP'].SetValue(deno)
            self._ct['ANTES'].SetValue(antes)
            self._ct['ACCION'].SetValue(accion)
            self._ct['DESPUES'].SetValue(despues)
            self._ct['GRIDC'].SetValue(gridc)
            self._ct['GRIDP'].SetValue(gridp)
            Foco(self, 'DESCRIP')

        #
        #-- Crear un nuevo informe
        #
        elif accion == 'a_nuevo':
            items = self._FILE.GetItems()
            sele = self._FILE.GetSelection()
            tabla = items[sele]
            if tabla == '':
                Men('Debe rellenar el fichero al que pertenece el informe')
                return 1
            id = Entra_dlg(self,
                           titu='Nuevo Informe ' + tabla,
                           text='Id Informe ' + tabla,
                           value='')
            if id == None: return 1
            lsinf = self._ct['LINF'].GetValue(fmt='L')
            if id in lsinf:
                Men('Ya existe un informe con ese id')
                return 1
            lsinf.append([id])

            self._ct['LINF'].SetValue(lsinf)
            self._ct['LINF'].Sel_Item(len(lsinf) - 1)  # último
            self._ct['DESCRIP'].SetValue('')
            self._ct['ANTES'].SetValue('')
            self._ct['ACCION'].SetValue('')
            self._ct['DESPUES'].SetValue('')
            self._ct['GRIDC'].SetValue([])
            self._ct['GRIDP'].SetValue([])

            rs = self._formManager.createForm(tabla, id, '')
            if (rs != 0):
                Men('No se pudo guardar el informe')

        #
        #-- Grabar un informe
        #
        elif accion == 'a_graba':
            ls_inf = self._FILE.GetItems()
            selinf = self._FILE.GetSelection()
            tabla = ls_inf[selinf]
            info = self._ct['LINF'].GetValue()
            #
            if tabla == '' or info == None:
                Men('No tiene seleccionado ningún informe.')
                return -1
            #
            deno = self._ct['DESCRIP'].GetValue()
            antes = self._ct['ANTES'].GetValue()
            accion = self._ct['ACCION'].GetValue()
            despues = self._ct['DESPUES'].GetValue()
            gridc = self._ct['GRIDC'].GetValue()
            gridp = self._ct['GRIDP'].GetValue()
            #
            rs = self._formManager.updateForm(tabla, info,
                                              [deno, antes, accion, despues],
                                              gridc, gridp)
            if rs == 0:
                Men('Listado Guardado', img='i')
                self.Ejecuta_Accion('a_carga_dicc')
            else:
                Men('Error al grabar')
                return -1

        #
        #-- Borrar un informe
        #
        elif accion == 'a_borra':
            ls_inf = self._FILE.GetItems()
            selinf = self._FILE.GetSelection()
            tabla = ls_inf[selinf]
            info = self._ct['LINF'].GetValue()
            #
            if tabla == '' or info == None:
                Men('No tiene seleccionado ningún informe para borrar')
                return -1
            #
            dl = Men('¿Está seguro de borrar el listado ' + info + '?', 'sN')
            if dl == 'n': return -1
            #
            rs = self._formManager.deleteForm(tabla, info)
            if (rs == 0):
                Men('Listado Borrado', img='i')
                self.Ejecuta_Accion('a_lista_inf')

        return 0  # No se ejecutó ninguna accion !!!!
예제 #12
0
    def Ejecuta_Accion(self, accion, argumentos=''):
        if accion == 'a_salir':
            if self.Modifica == 1:
                dlg = Men(
                    'Hay cambios en la ventana y no ha guardado.\n¿Desea Continuar?',
                    'sn',
                    img='q')
                if dlg == 'n': return
            self.Modifica = 0
            self.Close()
            self.Destroy()
            #
        elif accion == 'a_carga_wins':
            if self.Modifica == 1:
                dlg = Men(
                    'Hay cambios en la ventana y no ha guardado.\n¿Desea Continuar?',
                    'sn',
                    img='q')
                if dlg == 'n': return
            self.Modifica = 0
            """ Leer la lista de ventanas actuales """
            lis = []
            wins = db.btopen(self.fileName)
            for nm in wins.keys():
                datos = pickle.loads(wins[nm])
                lis.append([nm, datos[0]])  # Ventana, Descripcion
            wins.close()
            #
            self._ct['G1'].SetValue([])
            self.arbol.DeleteAllItems()

            self._ct['L1'].SetValue(lis)
            #
        elif accion == 'a_sele_win':
            #
            if self.Modifica == 1:
                dlg = Men(
                    'Hay cambios en la ventana y no ha guardado.\n¿Desea Continuar?',
                    'sn',
                    img='q')
                if dlg == 'n': return
            self.Modifica = 0
            #
            sele = self._ct['L1'].GetValue()
            if sele == None:
                Men('No hay seleccionada ventana')
                return -1
            #
            wins = db.btopen(self.fileName)
            datos = pickle.loads(wins[sele])
            wins.close()
            #
            self.Datos_a_Arbol(datos)
            #
            self.wsele = sele
            self.titu.SetLabel(sele.upper())
            self.arbol.SelectItem(self.arbol.RootItem)

        elif accion == 'a_nuevo':
            if self.Modifica == 1:
                dlg = Men(
                    'Hay cambios en la ventana y no ha guardado.\n¿Desea Continuar?',
                    'sn',
                    img='q')
                if dlg == 'n': return
            self.Modifica = 0
            #
            nombre = Entra_dlg(self, '', 'Nombre de la ventana nueva:')
            if nombre == -1: return

            propgen = []  # Propiedades Generales de la ventana
            propgen.append('Ventana ' + nombre)  # Descripción
            propgen.append('')  # Nombre Ventana Padre
            propgen.append('')  # Icono Ventana
            propgen.append('')  # Titulo de la ventana
            propgen.append('800')  # Tamaño X
            propgen.append('600')  # Tamaño Y
            propgen.append('c')  # Pos X inicial (c=Centro)
            propgen.append('c')  # Pos Y inicial (c=Centro)
            propgen.append('')  # Nombre de la tabla Asociada
            propgen.append('')  # Campo que contiene Clave Tabla
            propgen.append('')  # Acción Cargar Ventana
            propgen.append('')  # Acción Despues de Leer
            propgen.append('')  # Boton a Ejecutar con FIN
            data = {}
            data[self.NOMBRE_ROOT] = propgen
            self.arbol.AddRoot(self.NOMBRE_ROOT)
            #
            dicc = db.btopen(self.fileName)
            datoswin = copy.deepcopy(propgen)
            datoswin.append([])  # Ningun elemento Hijo al empezar
            dicc[nombre] = pickle.dumps(datoswin)
            dicc.close()
            #
            self.Ejecuta_Accion('a_carga_wins')
            self._ct['L1'].Sel_Item(nombre)

        elif accion == 'a_borra':
            """ Borrar una tabla """
            sele = self._ct['L1'].GetValue()
            if sele == None:
                Men('Debe seleccionar la ventana a borrar')
                return -1
            dlg = Men('¿Está seguro de borrar la ventana ' + sele + '?',
                      'sn',
                      img='q')
            if dlg == 'n': return -1
            dicc = db.btopen(self.fileName)
            del dicc[sele]
            dicc.close()
            Men('Ventana Borrada')
            self.Ejecuta_Accion('a_carga_wins')

        elif accion == 'a_graba_cambio':
            arbol = self.arbol
            data = self.data
            grid = self._ct['G1']
            fila = grid.GetNRow() - 1
            nodo = arbol.GetSelection()
            if nodo.IsOk():
                idnodo = arbol.GetItemText(nodo)
                self.data[idnodo][fila] = grid.GetValue(fila, 1)
                self.Modifica = 1

        elif accion == 'a_graba':
            """ Grabar los datos de la ventana actual """

            win = self._ct['L1'].GetValue()
            if win == None:
                Men('No hay seleccionada ventana')
                return -1
            datos = self.Arbol_a_Datos()
            #
            dicc = db.btopen(self.fileName)
            dicc[win] = pickle.dumps(datos)
            dicc.close()
            #
            self.Modifica = 0
            Men('Ventana Guardada', img='i')
            #self.Ejecuta_Accion('a_carga_wins')
        elif accion == 'a_ejecuta':
            sele = self._ct['L1'].GetValue()
            if sele == None:
                Men('Debe seleccionar la ventana a ejecutar')
                return -1
            wins = db.btopen(self.fileName)
            datos = pickle.loads(wins[sele])
            wins.close()

            codigo = "#!/usr/bin/env python    " + "\n"
            codigo += "# -*- coding: iso-8859-1 -*-" + "\n"
            codigo += "import wx" + "\n"
            codigo += "import OC" + "\n"
            codigo += "# from OC.ui.Funciones import *" + "\n"

            codigo += "class " + sele + "(OC.ui.Ventana):" + "\n"
            codigo += "    def __init__(self):" + "\n"
            codigo += "        OC.ui.Ventana.__init__(self, None,'" + datos[
                3] + "',tam=(" + datos[4] + "," + datos[5] + "))" + "\n"
            ##
            codigo += "        ls_campos = " + str(datos[-1]) + "\n"
            #
            codigo += "        self.init_ctrls(ls_campos)" + "\n"

            codigo += "win = " + sele + "()"
            debug(codigo)
            exec(codigo)
            return 0

        elif accion == 'a_detalle_entradas':
            import dl_entrys
            dlg = dl_entrys.Detalle_Entrys(self)
            #dlg.ShowModal()
            print dlg.GetValue()
            dlg.Destroy()
            return 0

        else:
            return -999
예제 #13
0
    def onPopupSele(self, evt):
        id = evt.GetId()  # Id del menú popup
        #item = self.popup.FindItemById(id)
        #text = item.GetText()
        #ventana = self.wsele
        arbol = self.arbol
        data = self.data

        nodo = arbol.GetSelection()
        txtnodo = arbol.GetItemText(nodo)
        raiz = arbol.RootItem

        if id == 100:  # Añadir Elemento
            if nodo != raiz:
                tipo = data[txtnodo][0]
                if tipo in ('LIST', 'GRID'):
                    Men('No puede añadir hijos a este elemento')
                    return

            ops = ['Panel', 'Texto', 'Entrada', 'Lista', 'Grid', 'Botones']
            res = List_dlg(self, choices=ops)
            if res == -1: return
            sele = ops[res]

            idnodo = Entra_dlg(self, 'Id Elemento',
                               'Introduce el ID del elemento')
            if idnodo == -1: return
            if idnodo == '':
                Men('Debe introducir un nombre para identificar el elemento.')
                return
            if idnodo in data.keys():
                Men('Ya existe un nodo con ese identificador.')
                return
            idnodo = idnodo.upper()
            if sele == 'Panel':
                data[idnodo] = [
                    'PANEL', idnodo, '0', '0', '-1', '-1', '', '', ''
                ]
            elif sele == 'Tabbox':
                data[idnodo] = [
                    'TABBOX', idnodo, '0', '0', '-1', '-1', '', '', ''
                ]
            elif sele == 'Texto':
                data[idnodo] = [
                    'TEXT', idnodo, '0', '0', '10', '22', '', '', '', '', ''
                ]
            elif sele == 'Entrada':
                data[idnodo] = ['ENTRYS', idnodo, '22', '50', '', '', []]
            elif sele == 'Lista':
                cols = []
                data[idnodo] = [
                    'LIST', idnodo, '0', '0', '100', '100', cols, [], '', 'n',
                    'n', '', '', ''
                ]
            elif sele == 'Grid':
                cols = []
                data[idnodo] = [
                    'GRID', idnodo, 'Titulo', '0', '0', '100', '22', '5', cols,
                    '1', [], ''
                ]
            elif sele == 'Botones':
                data[idnodo] = ['BUTTONS', idnodo, '40', '', '', []]
            else:
                Men('Ha elegido un elemento no válido.')
                return
            #
            arbol.AppendItem(nodo, idnodo)
            arbol.Expand(nodo)

        elif id == 101:  # Eliminar Elemento
            if nodo == raiz:
                Men('No puede borrar el elemento raiz')
                return
            dlg = Men('¿Está seguro de borrar el elemento?', 'sn', img='q')
            if dlg == 'n': return
            del data[txtnodo]  # No borra los hijos,pero no es necesario
            arbol.Delete(nodo)
        else:
            Men('No se encontró accion para opcion seleccionada.')

        self.arbol.Expand(self.arbol.RootItem)
예제 #14
0
    def onSeleTree(self, evt):
        ventana = self.wsele
        if ventana == None:
            Men('No ha seleccionado ninguna ventana')
            return -1

        item = evt.GetItem()
        raiz = self.arbol.RootItem
        #
        titus = []
        sele_cell = {}  # Dialogo de selección por celda
        if item == raiz:
            datos = self.data[self.NOMBRE_ROOT]
            titus = ['Descripción', 'Ventana Padre', 'Icono', 'Título Ventana']
            titus.extend(['Tamaño X', 'Tamaño Y', 'PosX', 'PosY'])
            titus.extend(['Tabla Asociada', 'Campo IDX'])
            titus.extend(
                ['Accion Al Cargar', 'Accion Despues Leer', 'Boton al FIN'])
        else:
            id = self.arbol.GetItemText(item)
            datos = self.data[id]

            tipo = datos[0]
            if tipo == 'PANEL':
                titus = ['Tipo', 'ID', 'X inicio', 'Y inicio', 'Ancho', 'Alto']
                titus.extend(['Color+Font', 'Borde', 'Titulo (Si Tabbox)'])
            elif tipo == 'TABBOX':
                titus = ['Tipo', 'ID', 'X inicio', 'Y inicio', 'Ancho', 'Alto']
                titus.extend(['Color+Font', 'Borde', 'Accion al Cambio'])
            elif tipo == 'ENTRYS':
                titus = ['Tipo', 'ID', 'Alto', 'Salto Y cuando -1']
                titus.extend(['Estilo Etiqueta', 'Estilo Entrada'])
                titus.extend(['Lista Entradas'])
                ## LISTA ENTRADAS:
                #    ID, Etiq X, Y, Ancho, Fmt, LMax, Edi, FC, Sobre, ADE
                #    Dialogo, Tip, CPAN, Estilo
                sele_cell[(6, 1)] = 'a_detalle_entradas'
            elif tipo == 'LIST':
                titus = ['Tipo', 'ID', 'X inicio', 'Y inicio', 'Ancho', 'Alto']
                titus.extend(['Columnas', 'Anchos Fijos Columnas'])
                titus.extend(['Estilo', 'Seleccion Multiple?', 'Borrado?'])
                titus.extend(['Acción al Seleccionar', 'Accion Doble Click'])
                titus.extend(['Acción al Borrar'])
                ## COLUMNAS: [['Titulo','Formato']]
            elif tipo == 'GRID':
                titus = ['Tipo', 'ID', 'Titulo', 'X inicio', 'Y inicio']
                titus.extend(['Ancho', 'Alto Fila', 'Nº Filas', 'Columnas'])
                titus.extend(['Ancho Titulo Fila', 'Titulos Filas'])
                titus.extend(['Propiedades Generales'])
                ## COLUMNAS:
                #    Nombre, Ancho, Fmt, lmax, Edit, Grabab,
                #    FC, Sobre, ADE, dl-sel, Totales, Tip, CPan, Style
            elif tipo == 'BUTTONS':
                titus = [
                    'Tipo', 'ID', 'Alto', 'Estilo', 'Arco', 'Lista Botones'
                ]
                # LISTA BOTONES:
                #    ID, X, Y, Ancho, Imagen, Texto, Accion, Tip, Tecla
            elif tipo == 'CHECK':
                titus = ['Tipo', 'ID', 'X', 'Y', 'Ancho', 'Alto', 'Titulo']
                titus.extend(['Valor Inicial', 'Accion al cambiar'])
            elif tipo == 'RADIO':
                titus = ['Tipo', 'ID', 'X', 'Y', 'Ancho', 'Alto', 'Titulo']
                titus.extend(['Direccion', 'Valores (SEP = |)'])
                titus.extend(['Valor Inicial', 'Accion al Cambiar'])
            elif tipo == 'TABBOX':
                titus = ['Tipo', 'ID', 'X inicio', 'Y inicio', 'Ancho', 'Alto']
                titus.extend(['Color+Font', 'Borde', 'Accion al Cambio'])
            elif tipo == 'TEXT':
                titus = ['Tipo', 'ID', 'X inicio', 'Y inicio', 'Ancho', 'Alto']
                titus.extend(['Color+Font', 'Color+Font con Ratón', 'Borde'])
                titus.extend(['Alineamiento', 'Acción al Click'])
        #
        i = 0
        g1 = []
        ntitus, ndatos = len(titus), len(datos)
        maxf = max(ntitus, ndatos)
        for i in range(maxf):
            titu, valor = '????', ''
            if ntitus > i: titu = titus[i]
            if ndatos > i: valor = datos[i]
            g1.append([titu, valor])
        #
        self._ct['G1'].SetValue(g1)
        self._ct['G1']._seleCell = sele_cell
예제 #15
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
예제 #16
0
    def Ejecuta_Accion(self, accion):
        """ Acciones a ejecutar """

        if accion == 'a_salir':
            self.Close()
            self.Destroy()

        elif accion == 'a_nuevo':
            self._ct['DENO'].SetValue('')
            self._ct['DESC'].SetValue('')
            self._ct['LCOD'].SetValue('')
            self._ct['RELS'].SetValue('')
            self._ct['INDICES'].SetValue('')
            self._ct['ACCGRAB'].SetValue('')
            self._ct['G1'].SetValue([])

        elif accion == 'a_carga_dicc':
            """ Leer la lista de tablas actuales """
            lis = self._engine.getDiccList()
            self._ct['L1'].SetValue(lis)

        elif accion == 'a_pon_dic':
            """ Pone los datos del diccionario selecionado"""
            if self.Modifica == 1:
                dlg = Men(
                    'Ha modificado los datos.¿Desea Continuar sin grabar?',
                    'sn',
                    img='q')
                if dlg == 'n': return -1
            tabla = self._ct['L1'].GetValue()
            datos = self._engine.getDicc(tabla)
            #
            self._ct['DENO'].SetValue(tabla)
            self._ct['DESC'].SetValue(datos[0])
            self._ct['LCOD'].SetValue(datos[1])
            self._ct['RELS'].SetValue(datos[2])
            self._ct['INDICES'].SetValue(datos[3])
            self._ct['ACCGRAB'].SetValue(datos[4])
            self._ct['G1'].SetValue(datos[-1])
            self.Modifica = 0

        elif accion == 'a_borra':
            """ Borrar una tabla """
            sele = self._ct['L1'].GetValue()
            if sele == '':
                Men('Debe seleccionar el fichero a borrar')
                return -1
            dlg = Men('¿Está seguro de borrar la tabla ' + sele + '?',
                      'sn',
                      img='q')
            if dlg == 'n': return -1

            self._engine.deleteDicc(sele)
            Men('Tabla Borrada')
            self.Ejecuta_Accion('a_carga_dicc')

        elif accion == 'a_graba':
            """ Grabar los datos de la tabla actual """
            tabla = self._ct['DENO'].GetValue().lower()
            desc = self._ct['DESC'].GetValue()
            lcod = self._ct['LCOD'].GetValue()
            rels = self._ct['RELS'].GetValue()
            indx = self._ct['INDICES'].GetValue()
            accg = self._ct['ACCGRAB'].GetValue()
            campos = self._ct['G1'].GetValue()

            if tabla == '':
                Men('No hay nombre de tabla a grabar.')
                return -1  # No ha indicado nada que grabar
            if campos == []:
                Men('No ha indicado los campos del diccionario')
                return -1
            # datos del fichero => "dicc". dicc[tabla] = ...
            # 0 - Descripción de la tabla
            # 1 - Longitud del codigo (Si fija)
            # 2 - Tablas Relacionadas
            # 3 - Indices Secundarios
            # 4 - Accion de grabación
            # 5 - Lista de Campos
            datos = [desc, lcod, rels, indx, accg, campos]

            self._engine.updateDicc(tabla, datos[:-1], datos[-1])
            #
            Men('Registro Guardado', img='i')
            self.Ejecuta_Accion('a_carga_dicc')
예제 #17
0
    def Ejecuta_Accion(self,accion,obj=None):
        try:
            """ 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 std

            pb = self
            ct = pb._ct
            cta = pb._cta
            if obj!=None: cta=obj

            global ls_articulos

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

            if accion=='a_cambia_tipo':
                tipo = self._radio.GetSelection()
                preg = []
                if tipo==0: preg.append(['AR_TIPO','=','S'])
                elif tipo==1: preg.append(['AR_TIPO','=','A'])
                tablaArticulos = OC.db.Table('articulos')
                lsar = tablaArticulos.select('0 AR_DENO AR_PVP',preg,'AR_DENO')
                tablaArticulos.close()
                ls_articulos = lsar
                ct['L1'].SetValue(lsar)
                ct['BUSCA'].SetValue('')
                ct['BUSCA'].SetFocus()

            elif accion=='a_pon_cliente':
                cdcl = cta.GetValue()
                if cdcl=='':
                    ct['CL_DENO'].SetValue('')
                else:
                    tablaClientes = OC.db.Table('clientes')
                    cli = tablaClientes.get(cdcl)
                    tablaClientes.close()
                    cldeno = 'Undefined'
                    if cli==1:
                        Men('No se pudo leer el cliente '+cdcl)
                    else:
                        cldeno = cli['CL_DENO']
                    ct['CL_DENO'].SetValue(cldeno)

                pb.Ejecuta_Accion('a_pon_datos_cliente',ct['AV_CL'])

                ptes = ct['LP'].GetValue(fmt='L')
                #if ptes!=[]: Men('El cliente tiene pagos pendientes.')
                    
            elif accion=='a_pon_datos_cliente':
                cdcl = cta.GetValue()
                cdav = ct['IDX'].GetValue()
                #- Vemos si tiene ventas pendientes
                ls = []
                if cdcl!='':
                    rs = self._tablaVentas.select('0 AV_PTE AV_FEC AV_TTT',[['AV_CL','=',cdcl],['AV_PTE','>','0']])
                    if rs != []:
                        for ln in rs:
                            ls.append([ln[0],ln[2],ln[3],ln[1]])
                ct['LP'].SetValue(ls)
                
                if cdav!='':
                    #- Mostramos la lista de cobros de la venta
                    ls = []
                    idx = ct['IDX'].GetValue()
                    tablaCobros = OC.db.Table('cobros')
                    rs = tablaCobros.select('0 CB_FEC CB_IMPO',[['CB_CDAV','=',idx]])
                    tablaCobros.close()
                    if rs != []:
                        for ln in rs:
                            ls.append([ln[0],ln[1],ln[2]])
                    ct['LC'].SetValue(ls)
                    

            elif accion=='a_pon_arti':
                sele = ct['L1'].GetValue(fmt='l')
                if (sele == None): return (0,'No hay nada seleccionado')
                venta = ct['AV_LNA'].GetData()
                sele = sele[:]
                sele.insert(2,'1')
                venta.append(sele)
                ct['AV_LNA'].SetData(venta)
                self.Ejecuta_Accion('a_pon_ttt')

            elif accion=='a_completa_linea':
                venta = ct['AV_LNA'].GetData()
                fila,col = ct['AV_LNA'].GetCursor()
                #fila = fila-1   # -1 pq desp. editar está en la siguiente
                #       ... esto era pq solo había una columna editable ...
                if (fila >= len(venta)):
                    Men('Para añadir articulos, haz doble click en la lista de arriba')
                    return (1,'Haz click para añadir')

                cdar=''
                if fila>=0 and venta!=[]: cdar = venta[fila][0]
                if cdar!='':
                    tablaArticulos = OC.db.Table('articulos')
                    ar = tablaArticulos.get(cdar)
                    tablaArticulos.close()
                    if ar!=1:
                        venta[fila][1]=ar['AR_DENO']
                        venta[fila][2]='1'
                        venta[fila][3]=ar['AR_PVP']
                    else:
                        Men('No existe el artículo '+cdar)
                        ##venta = venta[:-1]
                        ##ct['AV_LNA'].SetCursor(0,0)

                    ct['AV_LNA'].SetData(venta)
                    self.Ejecuta_Accion('a_pon_ttt')

            elif accion=='a_suma_arti':
                venta = ct['AV_LNA'].GetData()
                fl = ct['AV_LNA'].GetNRow()
                if fl>=len(venta): return (0,'error')
                venta[fl][2] += 1
                ct['AV_LNA'].SetData(venta)
                self.Ejecuta_Accion('a_pon_ttt')


            elif accion=='a_resta_arti':
                venta = ct['AV_LNA'].GetData()
                fl = ct['AV_LNA'].GetNRow()
                if fl>=len(venta): return (0,'error')
                venta[fl][2] -= 1
                if venta[fl][2]<=0:
                    if fl < len(venta):
                        del venta[fl]
                ct['AV_LNA'].SetData(venta)
                self.Ejecuta_Accion('a_pon_ttt')

            elif accion=='a_pon_ttt':
                venta = ct['AV_LNA'].GetData()
                ttt=0
                for ln in venta:
                    ttt += ln[2]*ln[3]
                ct['AV_TTT'].SetValue(ttt)

            elif accion=='a_filtra_ar':
                lsar = ls_articulos
                busca = ct['BUSCA'].GetValue()
                busca = busca.upper()
                resul=[]
                for ln in lsar:
                    deno = ln[1].upper()
                    if busca in deno: resul.append(ln)
                ct['L1'].SetValue(resul)

            elif accion=='a_antes_grabar':
                fec = ct['AV_FEC'].GetValue()
                if fec==None: ct['AV_FEC'].SetValue(Fecha())
                #-
                if ct['AV_LNA'].GetValue() == []:
                    Men('No ha indicado ningún artículo')
                    return (-1, 'antes_de_grabar: no articulos')
                #
                if ct['AV_CL'].GetValue() == '':
                    Men('Debe indicar cliente')
                    return (-1,'antes_de_grabar: no cliente')
                #
                ttt=ct['AV_TTT'].GetValue()
                cob=ct['AV_COB'].GetValue()
                ct['AV_PTE'].SetValue(ttt-cob)
                #
                
            elif accion=='a_antes_borrar':
                lscb = ct['LC'].GetValue('L')
                if lscb!=[]:
                    Men('La venta tiene cobros asignados.\nDebe borrarlos antes de borrar la venta.')
                    return (-1,'antes_de_borrar: Borra cobros primero')

            elif accion=='a_graba_venta':
                signo = self._signo
                rg = self._rg       # Se quedarán las modificaciones en rg
                #
                for ln in rg['AV_LNA']:
                    cdar,uds = ln[:2]
                    tablaArticulos = OC.db.Table('articulos')
                    ar = tablaArticulos.get(cdar)
                    if ar==1: continue
                    ar['AR_STK'] -= uds*signo
                    tablaArticulos.save(cdar, ar)
                    tablaArticulos.close()
                #
                self._rg = rg  

            elif accion=='a_desp_grabar':
                cob = self._ct['AV_COB'].GetValue()
                if cob==0:  # Si es una venta nueva, mostramos el dialogo de cobro
                    self._tablaVentas.close()  ## Si no refresco, no toma el nuevo idx. TODO: mejorar
                    self._tablaVentas = OC.db.Table(self._filedb)
                    pb.Ejecuta_Accion('a_cobra_pte')
                    ##ct['IDX'].SetValue(ct['IDX'].GetValue()) => Lo ejecuta la accion anterior
                

            elif accion=='a_cobra_pte':
                cdav = self._ct['IDX'].GetValue()
                if cdav=='' or cdav=='.' or self.Modifica==1: 
                    Men('Debe guardar la venta antes de cobrar')
                    return (-1,'a_cobra_pte: graba la venta primero')
                #
                pte = self._ct['AV_PTE'].GetValue()
                cob = self._ct['AV_COB'].GetValue()
                ttt = self._ct['AV_TTT'].GetValue()
                if pte==0 and cob==ttt:
                    Men('Esta venta no tiene importe pendiente.')
                    return (-1,'a_cobra_pte: Nada que cobrar')
                #
                res = self.Muestra_Dlg_Pago()
                if res==-1: return (-1,'a_cobra_pte: Cancelado')
                importe,tarj = res
                
                if tarj: importe = pte
                if importe==0:
                    Men('No se puede generar cobro con importe cero')
                    return (-1,'a_cobra_pendiente: Importe zero incorrecto')
                else:
                    cod = self.Crea_Cobro(cdav,importe,tarj)
                    if cod==1:  Men('No se pudo crear el cobro.')

                ct['IDX'].SetValue(ct['IDX'].GetValue())
                    
            #
            #-- Borra el cobro seleccionado de la venta actual
            #
            elif accion=='a_borra_cobro':
                cdav = self._ct['IDX'].GetValue()
                cdcb = ct['LC'].GetValue()
                if cdcb==None:
                    Men('No ha seleccionado ningún cobro para borrar')
                else:
                    dlg=Men(u'¿Está seguro de borrar el cobro '+cdcb+'?','sn','q')
                    if dlg=='n': return (0, 'aborra_cobro: cancelado por usuario')
                    
                    ok = self.Borra_Cobro(cdav,cdcb)
                    if ok!=None:
                        #Men('Cobro '+cdcb+' borrado')
                        ct['IDX'].SetValue(ct['IDX'].GetValue())  
                    else:
                        Men('No se pudo borrar el cobro.')

            #
            #-- Borra el registro de venta pendiente seleccionado
            #
            elif accion=='a_borra_ventap':
                cdav = ct['LP'].GetValue()
                if cdav==None:
                    Men('No ha seleccionado ninguna venta pendiente para borrar')
                else:
                    dlg=Men(u'¿Está seguro de borrar la venta '+cdav+'?','sn','q')
                    if dlg=='n': return (0,'a_borra_ventap: cancelado por usuario')
                    
                    self._tablaVentas.delete(cdav)
                    if ok!=None:
                        Men('Venta '+cdav+' borrada')
                        pb.Ejecuta_Accion('a_pon_datos_cliente',ct['AV_CL'])
            
            
        except:
            Men(accion+'\n'+Busca_Error())


        return (1,'ok') # No se ejecutó ninguna accion o todo correcto