<commit_before>#!/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Name:         cfg/azisetup.py
# Author:       <NAME> <<EMAIL>>
# Copyright:    (C) 2011 <NAME>.l. <NAME>, 122 18038 Sanremo (IM)
# ------------------------------------------------------------------------------
# This file is part of X4GA
# 
# X4GA is free software: you can redistribute it and/or modify
# it under the terms of the Affero GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# X4GA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with X4GA.  If not, see <http://www.gnu.org/licenses/>.
# ------------------------------------------------------------------------------

import wx
import Env
bt = Env.Azienda.BaseTab

import awc.controls.windows as aw
import awc.controls.radiobox as awradio
import awc.controls.checkbox as awcheck
import awc.controls.linktable as lt
from awc.controls.numctrl import NumCtrl
from awc.controls.datectrl import DateCtrl

import cfg.azisetup_wdr as wdr
import stormdb as adb

from cfg.cfgcontab import CfgContab

import os
import lib


FRAME_TITLE = "Setup azienda"


class _SetupPanel(aw.Panel):
    
    def __init__(self, *args, **kwargs):
        aw.Panel.__init__(self, *args, **kwargs)
        self.dbsetup = adb.DbTable(bt.TABNAME_CFGSETUP, 'setup')
    
    def EncodeValue(self, value, name):
        return value
    
    def DecodeValue(self, value, name):
        return value
    
    def SetupRead(self):
        db = self.dbsetup
        cn = self.FindWindowByName
        for ctr in aw.awu.GetAllChildrens(self):
            if ctr.GetName()[:6] == 'setup_':
                name = ctr.GetName()[6:]
                if db.Retrieve('setup.chiave=%s', name) and db.RowsCount() == 1:
                    if isinstance(ctr, (awradio.RadioBox, awcheck.CheckBox)):
                        val = db.flag
                    elif isinstance(ctr, (int, long, lt.LinkTable, NumCtrl)):
                        val = db.importo
                    elif isinstance(ctr, DateCtrl):
                        val = db.data
                    else:
                        val = self.DecodeValue(db.descriz, name)
                    ctr.SetValue(val)
    
    def SetupWrite(self):
        
        out = True
        db = self.dbsetup
        cn = self.FindWindowByName
        
        for ctr in aw.awu.GetAllChildrens(self):
            name = ctr.GetName()
            if name[:6] == 'setup_':
                val = cn(name).GetValue()
                name = ctr.GetName()[6:]
                if db.Retrieve('setup.chiave=%s', name):
                    if db.RowsCount() == 0:
                        db.CreateNewRow()
                        db.chiave = name
                    if isinstance(ctr, (awradio.RadioBox, awcheck.CheckBox)):
                        db.flag = val
                    elif isinstance(ctr, (int, long, lt.LinkTable, NumCtrl)):
                        db.importo = val
                    elif isinstance(ctr, DateCtrl):
                        db.data = val
                    else:
                        db.descriz = self.EncodeValue(val, name)
                    if not db.Save():
                        aw.awu.MsgDialog(self, message="Problema in aggiornamento setup:\n%s" % repr(db.GetError()))
                        out = False
                        break
                else:
                    aw.awu.MsgDialog(self, message="Problema in lettura setup:\n%s" % db.GetError())
                    out = False
                    break
        
        import lib
        evt = wx.PyCommandEvent(lib._evtCHANGEMENU)
        wx.GetApp().GetTopWindow().AddPendingEvent(evt)
        
        return out
    
    def OnConfirm(self, event):
        if self.Validate():
            if self.SetupWrite():
                event.Skip()
    
    def Validate(self):
        raise Exception, 'Classe non istanziabile'


# ------------------------------------------------------------------------------


class AziendaSetupPanel(_SetupPanel):
    """
    Impostazione setup azienda.
    """
    
    def __init__(self, *args, **kwargs):
        
        _SetupPanel.__init__(self, *args, **kwargs)
        wdr.AziendaSetup(self)
        cn = lambda x: self.FindWindowByName(x)
        for name, vals in (('tipo_contab',     'OS'),
                           ('liqiva_periodic', 'MT')):
            name = 'setup_'+name
            cn(name).SetDataLink(name, list(vals))
        tf = {True: '1', False: '0'}
        for name, vals in (('setup_conbilricl',   tf),
                           ('setup_conbilrcee',   tf),
                           ('setup_conattritacc', tf),
                           ('setup_magscocat',    tf),
                           ('setup_gesfidicli',   tf),
                           ('setup_magimgprod',   tf),
                           ('setup_magdigsearch', tf),
                           ('setup_optdigsearch', tf),
                           ('setup_opttabsearch', tf),
                           ('setup_optlnkcrdpdc', tf),
                           ('setup_optlnkgrdpdc', tf),
                           ('setup_optlnkcrdcli', tf),
                           ('setup_optlnkgrdcli', tf),
                           ('setup_optlnkcrdfor', tf),
                           ('setup_optlnkgrdfor', tf),
                           ('setup_optnotifiche', tf),
                           ('setup_magpzconf',    tf),
                           ('setup_magpzgrip',    tf),
                           ('setup_magppromo',    tf),
                           ('setup_magprovatt',   tf),
                           ('setup_magprovcli',   tf),
                           ('setup_magprovpro',   tf),
                           ('setup_magvisgia',    tf),
                           ('setup_magvispre',    tf),
                           ('setup_magviscos',    tf),
                           ('setup_magviscpf',    tf),
                           ('setup_magvisbcd',    tf),
                           ('setup_maggesacc',    tf),
                           ):
            try:
                cn(name).SetDataLink(name, vals)
            except:
                pass
        self.SetupRead()
        self.Bind(wx.EVT_BUTTON, self.OnConfirm, id=wdr.ID_BTNOK)
    
    def SetupRead(self):
        out = _SetupPanel.SetupRead(self)
        cn = self.FindWindowByName
        cn('setup_consovges').SetValue(bt.CONSOVGES) #il flag è numerico, ma memorizzato in setup.flag che è carattere
        logo = os.path.join(self.GetLogoPath(), self.GetLogoFileName())
        if os.path.isfile(logo):
            cn('azienda_logo').display_image(logo)
        return out
    
    def SetupWrite(self):
        
        cn = self.FindWindowByName
        out = _SetupPanel.SetupWrite(self)
        
        if out:
            #aggiornamento ragione sociale su db aziende
            out = False
            cod = Env.Azienda.codice
            host = Env.Azienda.DB.servername
            user = Env.Azienda.DB.username
            pswd = Env.Azienda.DB.password
            dba = adb.db.DB(dbType=adb.db.__database__._dbType, globalConnection=False)
            if dba.Connect(host=host, user=user, passwd=<PASSWORD>, db='x4'):
                dbz = adb.DbTable('aziende', 'azi', db=dba)
                if dbz.Retrieve('azi.codice=%s', cod):
                    if dbz.RowsCount() == 1:
                        dbz.codice = Env.Azienda.codice = cn('setup_azienda_codice').GetValue()
                        dbz.azienda = Env.Azienda.descrizione = cn('setup_azienda_ragsoc').GetValue()
                        if dbz.Save():
                            out = True
                        else:
                            aw.awu.MsgDialog(self, message="Problema in fase di aggiornamento della tabella aziende:\n%s" % repr(dbz.GetError()))
                    else:
                        aw.awu.MsgDialog(self, message="Codice '%s' non trovato su tabella aziende" % cod)
                else:
                    aw.awu.MsgDialog(self, message="Problema in fase di aggiornamento della tabella aziende:\n%s" % repr(dbz.GetError()))
            else:
                aw.awu.MsgDialog(self, message="Problema di connessione al database delle aziende:\n%s" % dba._Error_MySQLdb)
            dba.Close()
            
            if out:
                
                img = cn('azienda_logo')
                if img.is_changed():
                    fns = img.get_image_filename()
                    if fns:
                        d = self.GetLogoPath(azienda_codice=cn('setup_azienda_codice').GetValue())
                        if d:
                            if not os.path.isdir(d):
                                os.makedirs(d)
                            try:
                                fnt = os.path.join(d, self.GetLogoFileName())
                                hs = open(fns, 'rb')
                                buf = hs.read()
                                hs.close()
                                ht = open(fnt, 'wb')
                                ht.write(buf)
                                ht.close()
                                p = Env.Azienda.config.get('Site', 'folder')
                                if os.path.isdir(p):
                                    if aw.awu.MsgDialog(self, 'Aggiorno anche il logo aziendale su X4?', style=wx.ICON_QUESTION|wx.YES_NO|wx.NO_DEFAULT) == wx.ID_YES:
                                        fnt = os.path.join(p, self.GetLogoFileName())
                                        hs = open(fns, 'rb')
                                        buf = hs.read()
                                        hs.close()
                                        ht = open(fnt, 'wb')
                                        ht.write(buf)
                                        ht.close()
                            except Exception, e:
                                aw.awu.MsgDialog(self, repr(e.args))
            
                bt.ReadAziendaSetup()
            
        return out
    
    def GetLogoPath(self, azienda_codice=None):
        import report
        d = report.pathsub
        if d:
            d = os.path.join(d, 'immagini')
        return d
    
    def GetLogoFileName(self):
        return 'logo_aziendale.jpg'
    
    def Validate(self):<commit_msg>Rimozione riferimenti non riconosciuti nell'analisi del codice con Eclipse<commit_after>#!/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Name:         cfg/azisetup.py
# Author:       <NAME> <<EMAIL>>
# Copyright:    (C) 2011 <NAME>.r.l. <NAME>, 122 18038 Sanremo (IM)
# ------------------------------------------------------------------------------
# This file is part of X4GA
# 
# X4GA is free software: you can redistribute it and/or modify
# it under the terms of the Affero GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# X4GA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with X4GA.  If not, see <http://www.gnu.org/licenses/>.
# ------------------------------------------------------------------------------

import wx
import Env
bt = Env.Azienda.BaseTab

import awc.controls.windows as aw
import awc.controls.radiobox as awradio
import awc.controls.checkbox as awcheck
import awc.controls.linktable as lt
from awc.controls.numctrl import NumCtrl
from awc.controls.datectrl import DateCtrl

import cfg.azisetup_wdr as wdr
import stormdb as adb

from cfg.cfgcontab import CfgContab

import os
import lib


FRAME_TITLE = "Setup azienda"


class _SetupPanel(aw.Panel):
    
    def __init__(self, *args, **kwargs):
        aw.Panel.__init__(self, *args, **kwargs)
        self.dbsetup = adb.DbTable(bt.TABNAME_CFGSETUP, 'setup')
    
    def EncodeValue(self, value, name):
        return value
    
    def DecodeValue(self, value, name):
        return value
    
    def SetupRead(self):
        db = self.dbsetup
        cn = self.FindWindowByName
        for ctr in aw.awu.GetAllChildrens(self):
            if ctr.GetName()[:6] == 'setup_':
                name = ctr.GetName()[6:]
                if db.Retrieve('setup.chiave=%s', name) and db.RowsCount() == 1:
                    if isinstance(ctr, (awradio.RadioBox, awcheck.CheckBox)):
                        val = db.flag
                    elif isinstance(ctr, (int, long, lt.LinkTable, NumCtrl)):
                        val = db.importo
                    elif isinstance(ctr, DateCtrl):
                        val = db.data
                    else:
                        val = self.DecodeValue(db.descriz, name)
                    ctr.SetValue(val)
    
    def SetupWrite(self):
        
        out = True
        db = self.dbsetup
        cn = self.FindWindowByName
        
        for ctr in aw.awu.GetAllChildrens(self):
            name = ctr.GetName()
            if name[:6] == 'setup_':
                val = cn(name).GetValue()
                name = ctr.GetName()[6:]
                if db.Retrieve('setup.chiave=%s', name):
                    if db.RowsCount() == 0:
                        db.CreateNewRow()
                        db.chiave = name
                    if isinstance(ctr, (awradio.RadioBox, awcheck.CheckBox)):
                        db.flag = val
                    elif isinstance(ctr, (int, long, lt.LinkTable, NumCtrl)):
                        db.importo = val
                    elif isinstance(ctr, DateCtrl):
                        db.data = val
                    else:
                        db.descriz = self.EncodeValue(val, name)
                    if not db.Save():
                        aw.awu.MsgDialog(self, message="Problema in aggiornamento setup:\n%s" % repr(db.GetError()))
                        out = False
                        break
                else:
                    aw.awu.MsgDialog(self, message="Problema in lettura setup:\n%s" % db.GetError())
                    out = False
                    break
        
        import lib
        evt = wx.PyCommandEvent(lib._evtCHANGEMENU)
        wx.GetApp().GetTopWindow().AddPendingEvent(evt)
        
        return out
    
    def OnConfirm(self, event):
        if self.Validate():
            if self.SetupWrite():
                event.Skip()
    
    def Validate(self):
        raise Exception, 'Classe non istanziabile'


# ------------------------------------------------------------------------------


class AziendaSetupPanel(_SetupPanel):
    """
    Impostazione setup azienda.
    """
    
    def __init__(self, *args, **kwargs):
        
        _SetupPanel.__init__(self, *args, **kwargs)
        wdr.AziendaSetup(self)
        cn = lambda x: self.FindWindowByName(x)
        for name, vals in (('tipo_contab',     'OS'),
                           ('liqiva_periodic', 'MT')):
            name = 'setup_'+name
            cn(name).SetDataLink(name, list(vals))
        tf = {True: '1', False: '0'}
        for name, vals in (('setup_conbilricl',   tf),
                           ('setup_conbilrcee',   tf),
                           ('setup_conattritacc', tf),
                           ('setup_magscocat',    tf),
                           ('setup_gesfidicli',   tf),
                           ('setup_magimgprod',   tf),
                           ('setup_magdigsearch', tf),
                           ('setup_optdigsearch', tf),
                           ('setup_opttabsearch', tf),
                           ('setup_optlnkcrdpdc', tf),
                           ('setup_optlnkgrdpdc', tf),
                           ('setup_optlnkcrdcli', tf),
                           ('setup_optlnkgrdcli', tf),
                           ('setup_optlnkcrdfor', tf),
                           ('setup_optlnkgrdfor', tf),
                           ('setup_optnotifiche', tf),
                           ('setup_magpzconf',    tf),
                           ('setup_magpzgrip',    tf),
                           ('setup_magppromo',    tf),
                           ('setup_magprovatt',   tf),
                           ('setup_magprovcli',   tf),
                           ('setup_magprovpro',   tf),
                           ('setup_magvisgia',    tf),
                           ('setup_magvispre',    tf),
                           ('setup_magviscos',    tf),
                           ('setup_magviscpf',    tf),
                           ('setup_magvisbcd',    tf),
                           ('setup_maggesacc',    tf),
                           ):
            try:
                cn(name).SetDataLink(name, vals)
            except:
                pass
        self.SetupRead()
        self.Bind(wx.EVT_BUTTON, self.OnConfirm, id=wdr.ID_BTNOK)
    
    def SetupRead(self):
        out = _SetupPanel.SetupRead(self)
        cn = self.FindWindowByName
        cn('setup_consovges').SetValue(bt.CONSOVGES) #il flag è numerico, ma memorizzato in setup.flag che è carattere
        logo = os.path.join(self.GetLogoPath(), self.GetLogoFileName())
        if os.path.isfile(logo):
            cn('azienda_logo').display_image(logo)
        return out
    
    def SetupWrite(self):
        
        cn = self.FindWindowByName
        out = _SetupPanel.SetupWrite(self)
        
        if out:
            #aggiornamento ragione sociale su db aziende
            out = False
            cod = Env.Azienda.codice
            host = Env.Azienda.DB.servername
            user = Env.Azienda.DB.username
            pswd = Env.Azienda.DB.password
            dba = adb.db.DB(dbType=getattr(adb.db.__database__, '_dbType'), globalConnection=False)
            if dba.Connect(host=host, user=user, passwd=<PASSWORD>, db='x4'):
                dbz = adb.DbTable('aziende', 'azi', db=dba)
                if dbz.Retrieve('azi.codice=%s', cod):
                    if dbz.RowsCount() == 1:
                        dbz.codice = Env.Azienda.codice = cn('setup_azienda_codice').GetValue()
                        dbz.azienda = Env.Azienda.descrizione = cn('setup_azienda_ragsoc').GetValue()
                        if dbz.Save():
                            out = True
                        else:
                            aw.awu.MsgDialog(self, message="Problema in fase di aggiornamento della tabella aziende:\n%s" % repr(dbz.GetError()))
                    else:
                        aw.awu.MsgDialog(self, message="Codice '%s' non trovato su tabella aziende" % cod)
                else:
                    aw.awu.MsgDialog(self, message="Problema in fase di aggiornamento della tabella aziende:\n%s" % repr(dbz.GetError()))
            else:
                aw.awu.MsgDialog(self, message="Problema di connessione al database delle aziende:\n%s" % dba._Error_MySQLdb)
            dba.Close()
            
            if out:
                
                img = cn('azienda_logo')
                if img.is_changed():
                    fns = img.get_image_filename()
                    if fns:
                        d = self.GetLogoPath(azienda_codice=cn('setup_azienda_codice').GetValue())
                        if d:
                            if not os.path.isdir(d):
                                os.makedirs(d)
                            try:
                                fnt = os.path.join(d, self.GetLogoFileName())
                                hs = open(fns, 'rb')
                                buf = hs.read()
                                hs.close()
                                ht = open(fnt, 'wb')
                                ht.write(buf)
                                ht.close()
                                cfg = Env.Azienda.config
                                p = cfg.get('Site', 'folder')
                                if os.path.isdir(p):
                                    if aw.awu.MsgDialog(self, 'Aggiorno anche il logo aziendale su X4?', style=wx.ICON_QUESTION|wx.YES_NO|wx.NO_DEFAULT) == wx.ID_YES:
                                        fnt = os.path.join(p, self.GetLogoFileName())
                                        hs = open(fns, 'rb')
                                        buf = hs.read()
                                        hs.close()
                                        ht = open(fnt, 'wb')
                                        ht.write(buf)
                                        ht.close()
                            except Exception, e:
                                aw.awu.MsgDialog(self, repr(e.args))
            
                bt.ReadAziendaSetup()
            
        return out
    
    def GetLogoPath(self, azienda_codice=None):
        import report
        d = report.pathsub
        if d:
            d = os.path.join(d, 'immagini')
        return d
    
    def GetLogoFileName(self):
        return 'logo_aziendale.jpg'
    
    def Validate(self):
{'fraction_non_alphanumeric': 0.12746325404553252, 'fraction_numerical': 0.002689293828534335, 'mean_word_length': 1.1983487921720517, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 39, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '455688', 'n_tokens_mistral': 6036, 'n_tokens_neox': 5824, 'n_words': 1312}