Example #1
0
    def salvaFile(self):
        data_inizio = stringToDate(self.data_inizio_entry.get_text())
        nome_file = 'ESTRATTO_RIBA_' + data_inizio.strftime('%m_%y') + ".txt"
        fileDialog = gtk.FileChooserDialog(title='Salvare il file',
                                           parent=self.getTopLevel(),
                                           action= GTK_FILE_CHOOSER_ACTION_SAVE,
                                           buttons=(gtk.STOCK_CANCEL,
                                                    GTK_RESPONSE_CANCEL,
                                                    gtk.STOCK_SAVE,
                                                    GTK_RESPONSE_OK),
                                           backend=None)
        fileDialog.set_current_name(nome_file)
        fileDialog.set_current_folder(Environment.documentsDir)

        response = fileDialog.run()

        if ( (response == GTK_RESPONSE_CANCEL) or ( response == GTK_RESPONSE_DELETE_EVENT)) :
            fileDialog.destroy()
        elif response == GTK_RESPONSE_OK:
            filename = fileDialog.get_filename()
            if not filename:
                messageInfo(msg="Nessun nome scelto per il file")
            else:
                fileDialog.destroy()
                self.generatore.write(filename)
Example #2
0
 def on_seriale_menu_activate(self, widget):
     from promogest.dao.Setconf import SetConf
     try:
         data = SetConf().select(key="install_code",section="Master")
         codice = data[0].value
         msg = _('Codice installazione:\n\n') + str(codice)
     except:
         msg = _('Impossibile generare il codice !!!')
     messageInfo(msg= msg, transient=self.getTopLevel())
Example #3
0
    def refresh(self):
        # Aggiornamento TreeView
        idArticolo = self.id_articolo_filter_customcombobox1.getId()
        if idArticolo is None:
            self._treeViewModel.clear()
            messageInfo(transient=self._visualizzazione.getTopLevel(), msg='Selezionare un articolo !')
            return

        idListino = findIdFromCombobox(self.id_listino_filter_combobox1)
        daDataListino = stringToDate(self.da_data_listino_filter_entry.get_text())
        aDataListino = stringToDate(self.a_data_listino_filter_entry.get_text())

        self.numRecords = ListinoArticolo().count(idArticolo=idArticolo,
                                                            idListino=idListino,
                                                            listinoAttuale=None,
#                                                            daDataListino =daDataListino,
#                                                            aDataListino=aDataListino
                                                            )

        self._refreshPageCount()

        liss = ListinoArticolo().select(orderBy=self.orderBy,
                                                    idArticolo=idArticolo,
                                                    idListino=idListino,
                                                    listinoAttuale=None,
#                                                    daDataListino=daDataListino,
#                                                    aDataListino=aDataListino,
                                                    offset = self.offset,
                                                    batchSize = self.batchSize)


        self._treeViewModel.clear()

        for l in liss:
            przDet = mN(l.prezzo_dettaglio or 0)
            przIngr = mN(l.prezzo_ingrosso or 0)
            ricDett = '%-6.3f' % calcolaRicarico(float(l.ultimo_costo or 0),
                                                 float(l.prezzo_dettaglio or 0),
                                                 float(l.percentuale_iva or 0))
            margDett = '%-6.3f' % calcolaMargine(float(l.ultimo_costo or 0),
                                                 float(l.prezzo_dettaglio or 0),
                                                 float(l.percentuale_iva or 0))
            ricIngr = '%-6.3f' % calcolaRicarico(float(l.ultimo_costo or 0),
                                                 float(l.prezzo_ingrosso or 0))
            margIngr = '%-6.3f' % calcolaMargine(float(l.ultimo_costo or 0),
                                                 float(l.prezzo_ingrosso or 0))

            self._treeViewModel.append((l,
                                        (l.denominazione or ''),
                                        dateToString(l.data_listino),
                                        przDet, ricDett, margDett,
                                        przIngr, ricIngr, margIngr,
                                        (l.ultimo_costo or 0)))
Example #4
0
def getconn():
    import psycopg2
    a=None
    try:
        from promogest.preEnv import *
        a = psycopg2.connect(user=user, host=host, port=port,
                            password=password, database=database)
        cursor = a.cursor()
        cursor.execute("SELECT * FROM pg_stat_activity")
        records = cursor.fetchall()
        st = "CI SONO  ----- {0} ------- CONNESSIONI ATTIVE AL MOMENTO".format(len(records))
            #print st
    except Exception, e:
        from promogest.lib.utils import messageInfo
        a = "CONNESSIONE AL DATABASE PRO NON RIUSCITA.\n DETTAGLIO ERRORE: [%s]" % str(e)
        messageInfo(msg=a)
        sys.exit()
Example #5
0
 def on_acquista_button_clicked(self, button):
     if self.main.pp.lite_radio.get_active():
         url ="http://www.promogest.me/promoGest/preventivo_lite"
         webbrowser.open_new_tab(url)
     elif self.main.pp.pro_radio.get_active():
         url ="http://www.promogest.me/promoGest/preventivo_pro"
         webbrowser.open_new_tab(url)
     elif self.main.pp.promowear_radio.get_active():
         messageInfo(msg="NON ancora disponibile")
         return
         url ="http://www.promogest.me/promoGest/preventivo_promowear"
         webbrowser.open_new_tab(url)
     elif self.main.pp.promoshop_radio.get_active():
         messageInfo(msg="NON ancora disponibile")
         return
         url ="http://www.promogest.met/promoGest/preventivo_promoshop"
         webbrowser.open_new_tab(url)
Example #6
0
    def on_Back_up_Database_activate(self, widget):
        """ Si prepara un file zip con il dump del DB """

        if Environment.tipodb == "sqlite":
            msg = _("""NELLA VERSIONE ONE IL BACKUP SI
EFFETTUA COPIANDO IL FILE db CHE SI TROVA NELLA CARTELLA
promogest2 IN /HOME/NOMEUTENTE/ O IN C:/UTENTI/NOMEUTENTE""")
            messageInfo(msg= msg)
        else:
            st = Environment.startdir()
            nameDump = "promoGest3_bkp_"+self.aziendaStr+"_"+ datetime.now().strftime('%d_%m_%Y_%H_%M')+".zip"
            msgg = _("""Il "dump" del database verrà salvato in

    %s
    ed avrà il nome

    %s

    ATTENZIONE!!!! la procedura potrebbe richiedere diversi minuti.""") %(st, nameDump)
            messageInfo(msg= msgg, transient=self.getTopLevel())
            #if response == gtk.RESPONSE_OK:
            st = Environment.startdir()
            stname = st+nameDump
            os.environ["PGPASSWORD"] = Environment.password
            if os.name == "nt":
                PG_DUMP_ESEC = os.path.split(os.path.dirname(__file__))[0]+"\lib\pg_dump_dir\pg_dump.exe"
            elif os.name =="posix":
                PG_DUMP_ESEC = "pg_dump"
            else:
                messageInfo(msg="SU QUESTO SISTEMA OPERATIVO NON SI PUò FARE IL BACKUP DA QUI")
            retcode = call([PG_DUMP_ESEC,
                            "-h",Environment.host,
                            "-p",Environment.port,
                            "-U",Environment.user,
                            "-Z","7",
                            "-f",stname,
                            Environment.database])

            Environment.pg2log.info("STO EFFETTUANDO UN BACKUP DEL FILE %s" %stname)
            if not retcode:
                Environment.pg2log.info("DUMP EFFETTUATO CON SUCCESSO")
                messageInfo(msg="BACKUP EFFETTUATO CON SUCCESSO")
            else:
                messageInfo(msg="BACKUP NON RIUSCITO")
                Environment.pg2log.info("ATTENZIONE DUMP NON RIUSCITO")
Example #7
0
 def on_test_promowear_button_clicked(self, button):
     msg = _( """PROVIAMO IL MODULO DI TAGLIA E COLORE o PROMOWEAR, Procedo? """ )
     if not YesNoDialog(msg=msg, transient=self.getTopLevel()):
         return
     from data.createSchemaDb import orderedInstallPromoWear
     if orderedInstallPromoWear():
         if not setconf("PromoWear","mod_enable",value="yes"):
             a = SetConf()
             a.section = "PromoWear"
             a.tipo_section ="Modulo"
             a.description = "Modulo Taglia e colore"
             a.tipo = "bool"
             a.key = "mod_enable"
             a.value = "yes"
             a.persist()
     messageInfo(msg=_("RIAVVIA IL PROMOGEST"))
     Environment.delete_pickle()
     Environment.restart_program()
Example #8
0
    def on_test_promoshop_button_clicked(self, button):
        from promogest.dao.Setconf import SetConf
        msg = _(""" PROVIAMO IL MODULO VENDITA DETTAGLIO o PROMOSHOP, Procedo? """)
        if not YesNoDialog(msg=msg, transient=self.getTopLevel()):
            return
        if not setconf("VenditaDettaglio","mod_enable",value="yes"):
            a = SetConf()
            a.section = "VenditaDettaglio"
            a.tipo_section ="Modulo"
            a.description = "Modulo Vendita Dettaglio"
            a.tipo = "bool"
            a.key = "mod_enable"
            a.value = "yes"
            a.persist()

            a = SetConf()
            a.section = "VenditaDettaglio"
            a.tipo_section ="Modulo"
            a.description = "Nome del movimento generato"
            a.tipo = "str"
            a.key = "operazione"
            a.value = "Scarico venduto da cassa"
            a.persist()

            a = SetConf()
            a.section = "VenditaDettaglio"
            a.tipo_section ="Modulo"
            a.description = "disabilita_stampa"
            a.tipo = "bool"
            a.key = "disabilita_stampa"
            a.value = "True"
            a.active = True
            a.persist()
            from data.createSchemaDb import orderedInstallVenditaDettaglio
            orderedInstallVenditaDettaglio()
            messageInfo(msg=_("RIAVVIA IL PROMOGEST"))
            Environment.delete_pickle()
            Environment.restart_program()

        else:
            messageInfo(msg=_("RISULTA GIA' ATTIVATO"))
Example #9
0
    def salvaFile(self):
        fileDialog = gtk.FileChooserDialog(title='Salva il file',
                                           parent=self.getTopLevel(),
                                           action=GTK_FILE_CHOOSER_ACTION_SAVE,
                                           buttons=(gtk.STOCK_CANCEL,
                                                    GTK_RESPONSE_CANCEL,
                                                    gtk.STOCK_SAVE,
                                                    GTK_RESPONSE_OK),
                                           )
        fileDialog.set_current_name(self.dao.__class__.__name__+".csv")
        fileDialog.set_current_folder(Environment.documentsDir)

        response = fileDialog.run()
        # FIXME: handle errors here
        if ( (response == GTK_RESPONSE_CANCEL) or ( response == GTK_RESPONSE_DELETE_EVENT)) :
            fileDialog.destroy()
        elif response == GTK_RESPONSE_OK:
            filename = fileDialog.get_filename()
            if not filename:
                messageInfo(msg="Nessun nome scelto per il file")
            else:
                fileDialog.destroy()
                copy2(Environment.tempDir+"tempCSV", filename)
Example #10
0
 def cursor_execute(self, execute, cursor, statement, parameters, context, executemany):
     try:
         from promogest.lib.utils import messageInfo
     except:
         pass
     from promogest.preEnv import session
     try:
         return execute(cursor, statement, parameters, context)
     except OperationalError as e:
         messageInfo(msg="UN ERRORE È STATO INTERCETTATO E SEGNALATO: "+ str(e) )
     except IntegrityError as e:
         messageInfo(msg="IntegrityError UN ERRORE È STATO INTERCETTATO E SEGNALATO: "+ str(e))
         session.rollback()
     except ProgrammingError as e:
         messageInfo(msg="UN ERRORE È STATO INTERCETTATO E SEGNALATO: "+str(e))
         session.rollback()
         delete_pickle()
     except InvalidRequestError as e:
         messageInfo(msg="UN ERRORE È STATO INTERCETTATO E SEGNALATO: "+str(e))
         session.rollback()
     except AssertionError as e:
         messageInfo(msg="UN ERRORE È STATO INTERCETTATO E SEGNALATO\n Possibile tentativo di cancellazione di un dato\n collegato ad altri dati fondamentali: "+str(e))
         session.rollback()
     except ValueError as e:
         messageInfo(msg="Risulta inserito un Valore non corretto. Ricontrolla: "+str(e))
         session.rollback()
Example #11
0
    def analizza(self, data_inizio=None, data_fine=None, pageData=None):
        if not data_inizio:
            messageError(msg='Inserire una data d\'inizio periodo.')
            return 0
        if not data_fine:
            data_inizio_, data_fine = dataInizioFineMese(data_inizio)

        documenti = TestataDocumento().select(complexFilter=(and_(or_(TestataDocumento.operazione=='Fattura differita vendita', TestataDocumento.operazione=='Fattura accompagnatoria'), TestataDocumento.data_documento.between(data_inizio, data_fine))), batchSize=None)

        if not documenti:
            messageInfo(msg="Nessun risultato.")
            return 0

        righe = []

        buff = self.recordIB()

        i = 0
        totale_importi = Decimal(0)

        for documento in documenti:

            if self.progressbar:
                pbar(self.progressbar, parziale=i, totale=len(documenti))

            ope = leggiOperazione(documento.operazione)
            if ope:
                if ope['tipoPersonaGiuridica'] != 'cliente':
                    continue

            banca = None
            if documento.id_banca:
                banca = leggiBanca(documento.id_banca)
            else:
                continue

            cli = leggiCliente(documento.id_cliente)
            cli_ente = Cliente().getRecord(id=documento.id_cliente)
            cod_fisc_piva = ''
            if cli_ente:
                cod_fisc_piva = cli_ente.codice_fiscale or cli_ente.partita_iva
            else:
                cod_fisc_piva = documento.codice_fiscale_cliente
            debitore = Debitore(cod_fisc_piva, banca['abi'], banca['cab'])
            debitore.descrizione[0] = ''
            if cli['ragioneSociale']:
                debitore.descrizione[0] = cli['ragioneSociale']
            else:
                debitore.descrizione[0] = cli['cognome'] + ' ' + cli['nome']
            debitore.indirizzo = documento.indirizzo_cliente
            debitore.CAP = documento.cap_cliente
            debitore.provincia = documento.provincia_cliente
            debitore.comune = documento.localita_cliente

            for scadenza in documento.scadenze:
                if pagamentoLookup(scadenza.pagamento):

                    row = "%s N. %s a %s del %s \nImporto: %s data scadenza: %s" % (documento.operazione,
                                                     documento.numero,
                                                     documento.intestatario,
                                                     dateToString(documento.data_documento),
                                                     # scadenza.pagamento,
                                                     mN(scadenza.importo, 2),
                                                     dateToString(scadenza.data)
                                                     )

                    progressivo = i + 1
                    totale_importi += scadenza.importo
                    buff += self.record14(progressivo, scadenza.data, scadenza.importo, debitore)
                    buff += self.record20(progressivo)
                    buff += self.record30(progressivo, debitore)
                    buff += self.record40(progressivo, debitore)
                    buff += self.record50(progressivo, debitore, row.replace('\n', ''))
                    buff += self.record51(progressivo, progressivo)
                    buff += self.record70(progressivo)

                    riga = {
                        'destinatario': debitore.descrizione[0],
                        'indirizzo': debitore.indirizzo,
                        'CAP': debitore.CAP,
                        'comune': debitore.comune,
                        'provincia': debitore.provincia,
                        'cod_fisc_piva': cod_fisc_piva,
                        'banca_abi': banca['abi'],
                        'banca_cab': banca['cab'],
                        'importo': scadenza.importo,
                        'data_scadenza': scadenza.data,
                        'rif_debito': row
                    }
                    righe.append(riga)

                    i = i + 1

        buff += self.recordEF(i, totale_importi)

        pageData['righe'] = righe
        pageData['totale_importi'] = totale_importi
        pageData['disposizioni'] = i

        if self.progressbar:
            pbar(self.progressbar, stop=True)

        self._buffer = buff
Example #12
0
    def on_button_login_clicked(self, button=None):
        """
        """
        #username = self.username_comboxentry.child.get_text()
        username = self.username_entry.get_text()
        password = self.password_entry.get_text()

        if username == '' or password == '':
            messageInfo(msg=_('Inserire nome utente e password'))
            return
        elif Environment.engine.name != "sqlite" and \
                findStrFromCombobox(self.azienda_combobox, 0) == '':
            messageInfo(msg=_("Occorre selezionare un'azienda"))
            return
        else:
            #if hasattr(self,"azienda_combobox"):
            self.azienda = findStrFromCombobox(self.azienda_combobox, 0)
            findComboboxRowFromStr(self.azienda_combobox, self.azienda, 0)
            self.azienda_combobox.get_active() != -1
            #if not self.azienda:
                #self.azienda = "AziendaPromo"

        #superati i check di login
        users = User().select(username=username,
                    password=hashlib.md5(username + password).hexdigest())
        if not users:
            users = User().select(username=str(username).strip())
            if users:
                try:
                    from promogest.lib.utils import AESCipher, ops
                    r = AESCipher(ops).decrypt(
                        users[0].password)
                    if r != password:
                        messageInfo(msg=_('Password errata'))

                except:
                    rows = []
        if len(users) == 1:
            if users[0].active == False:
                messageInfo(msg=_('Utente Presente Ma non ATTIVO'))
                return
            else:
                Environment.workingYear = str(self.anno_lavoro_spinbutton.get_value_as_int())
                oldSchema = Environment.params["schema"]
                Environment.azienda = self.azienda
                for a in self.azs:
                    if a.schemaa == self.azienda:
                        a.tipo_schemaa = "last"
                    else:
                        a.tipo_schemaa = ""
                    Environment.session.add(a)
                Environment.session.commit()
                if Environment.tipodb == "postgresql":
                    Environment.params["schema"] = self.azienda
                    Environment.fk_prefix = Environment.params["schema"] + '.'
                    if self.azienda not in Environment.meta._schemas:
                        print(" PICKLE NON VA BENE")
                        #Environment.azienda = oldSchema
                        Environment.delete_pickle()
                    # import pickle
                    # cachefile = 'orm.p'
                    # Environment.meta.create_all()
                    # with open(cachefile, 'w') as cache:
                    #     pickle.dump(Environment.meta, cache)
                    #     cache.close()
                # Lancio la funzione di generazione della dir di configurazione
                from promogest.buildEnv import set_configuration
                Environment.conf = set_configuration(Environment.azienda,
                                                     Environment.workingYear)
#                    if setconf("Feed","feed"):
#                    if True == True:
#                        thread = threading.Thread(target=self.feddretreive)
#                        thread.start()
#                        thread.join(2.3)

                files = glob.glob(Environment.tempDir+"/*")
                for f in files:
                    os.remove(f)
                Environment.params['usernameLoggedList'][0] = users[0].id
                Environment.params['usernameLoggedList'][1] =\
                                                 users[0].username
                try:
                    Environment.params['usernameLoggedList'][2] =\
                                                 users[0].id_role
                except:
                    Environment.params['usernameLoggedList'][2] = 1
                if hasAction(actionID=1):
                    self.login_window.hide()
                    Environment.windowGroup.remove(self.getTopLevel())
                    installId()
                    Environment.pg2log.info(
                        "LOGIN  id, user, role azienda: %s, %s" % (
                            repr(Environment.params['usernameLoggedList']),
                                 self.azienda))
                    checkInstallation()
                    from promogest.dao.Setconf import SetConf
                    avv = SetConf().select(key="avvii")
                    if avv:
                        avv[0].value = int(avv[0].value)+1
                        Environment.avvii = int(avv[0].value)+1
                        avv[0].persist()
                    Environment.settaggi = Environment.session.query(
                        SetConf.key,
                        SetConf.value).all()
                    Environment.pg2log.info(
                        "SETAGGI: %s" % (str(Environment.settaggi)))

                    self.importModulesFromDir('promogest/modules')
                    # ATTENZIONE!!! RIATTIVARE!!!
                    from promogest.dao.DaoOrderedImport import orderedImport
                    orderedImport()
                    def mainmain():
                        from Main import Main
                        main = Main(self.azienda,
                                    self.anagrafiche_modules,
                                    self.parametri_modules,
                                    self.anagrafiche_dirette_modules,
                                    self.frame_modules,
                                    self.permanent_frames)
                        main.getTopLevel().connect("destroy",
                                                   on_main_window_closed,
                                                   self.login_window)
                        main.show()
                    glib.idle_add(mainmain)

        else:
            messageInfo(msg=_('Nome utente o password errati, Riprova'))
Example #13
0
 def on_master_sincro_db_activate(self, widget):
     msg = _("SERVER NON ANCORA IMPLEMENTATO")
     messageInfo(msg= msg, transient=self.getTopLevel())
Example #14
0
    def on_inserimento_codice_activate(self,widget):
        from promogest.dao.Setconf import SetConf
        dialog = gtk.MessageDialog(self.getTopLevel(),
                                   GTK_DIALOG_MODAL
                                   | GTK_DIALOG_DESTROY_WITH_PARENT,
                                   GTK_DIALOG_MESSAGE_INFO, GTK_BUTTON_OK)
        dialog.set_markup(_("""<b>                CODICE ATTIVAZIONE PACCHETTO               </b>"""))
        hbox = gtk.HBox()
        entry___ = gtk.Entry()

        label = gtk.Label()
        label.set_markup(_("<b>   Inserisci codice   </b>"))
        hbox.pack_start(label, True, True, 0)
        hbox.pack_start(entry___, True, True, 0)
        dialog.get_content_area().pack_start(hbox, True, True, 0)
        dialog.show_all()
        dialog.run()
        codice = entry___.get_text()
#        hascode = str(hashlib.sha224(codice+orda(codice)).hexdigest())
        if "cl" and "|" in codice :
            d = codice.split("|")
            if d[1] == "azienda":
                if Environment.tipodb == "sqlite":
                    from promogest.dao.Azienda import Azienda
                    oldnomeazienda = d[2]
                    newnameazienda = d[3]
                    aa = Azienda().select(schemaa = oldnomeazienda)
                    if aa:
                        aa[0].schemaa = newnameazienda.strip()
                        aa[0].persist()
                        messageInfo(msg=_("NOME AZIENDA MODIFICATO"))
                        dialog.destroy()
                        return
                    else:
                        messageInfo(msg=_("VECCHIO NOME AZIENDA NON TROVATO"))
                        dialog.destroy()
                        return
                    return
                else:
                    messageInfo(msg=_("POSSIBILE SOLO CON LA VERSIONE ONE"))
                    dialog.destroy()
                    return
            elif d[1] == "modulo":
                tipo_section = d[2]  # Modulo
                section = d[3]  # Inventario
                description = str(d[4]) or ""  # Gestione inventario
                tipo = d[5] or None  # Niente o BOOLEAN o colore
                active = bool(d[6]) or True  # bool
                visible = bool(d[7]) or True  # bool
                key = d[8]  # mod_enable
                value = d[9]  # yes or no
                if section not in Environment.modules_folders:
                    messageInfo(msg=_("ERRORE ATTIVAZIONE MODULO"))
                    return
                dao = SetConf().select(key=key, section=section)
                if dao:
                    d = dao[0]
                else:
                    d = SetConf()
                d.key = key
                d.value =value
                d.section = section
                d.description = description
                d.tipo_section = tipo_section
                d.tipo = tipo
                d.active = active
                d.visible = visible
                d.date = datetime.now()
                d.persist()
                messageInfo(msg=_("MODULO O OPZIONE MODIFICATO attivato o disattivato"))
                dialog.destroy()
                return
            elif d[1] == "registro":
                operazione = d[2].strip()+".registro"
                registro_da_assegnare = d[3]
                from promogest.dao.Setting import Setting
                a = Setting().getRecord(id=operazione)
                if a:
                    b = Setting().select(value=registro_da_assegnare)
                    if b:
                        a.value = registro_da_assegnare
                        a.persist()
                        messageInfo(msg=_("REGISTRO NUMERAZIONE MODIFICATO\n\nRIAVVIARE"))
                        dialog.destroy()
                        return True
                    else:
                        messageInfo(msg=_("REGISTRO DA ASSEGNARE NON TROVATO O CORRETTO\n\n RIPROVARE"))
                        return False
                else:
                    messageInfo(msg=_("OPERAZIONE NON CORRETTA E NON TROVATA\n\nRIPROVARE"))
                    return False
        else:
            sets = SetConf().select(key="install_code",section="Master")
            if sets:
                sets[0].delete()
            if codice:
                k = SetConf()
                k.key = "install_code"
                k.value =str(hashlib.sha224(codice+orda(codice)).hexdigest())
                k.section = "Master"
                k.description = "codice identificativo della propria installazione"
                k.tipo_section = "General"
                k.tipo = "ONE"
                k.active = True
                k.date = datetime.now()
                k.persist()
                messageInfo(msg=_("ATTIVAZIONE EFFETTUATA, RIAVVIARE IL PROMOGEST"))
        dialog.destroy()