p_fb.py :  » Business-Application » hylaPEx » hylapex » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Business Application » hylaPEx 
hylaPEx » hylapex » p_fb.py
# -*- coding: utf-8 -*-

import wx, wx.grid
import os, string, time, sys
import wx_util, string
from library.ftp import read_conf
import db_lib

from library import log,utils

from library.constants import *
from library import i18n

_ = None

from twisted.internet import reactor,threads

class wxPanel1(wx.Panel):
    def __init__(self, parent, paths, use = 'send', fax2add = '', observable=None):
        wx.Panel.__init__(self, parent, style=wx.WANTS_CHARS)
        
        self.__doc = observable
        
        global _
        _ = i18n.i18n(default=paths.language)

        sz_contacts = self._create_ctrls(self)

        sz = wx.BoxSizer(wx.HORIZONTAL)
        sz.Add(sz_contacts, 1, wx.EXPAND)
        self.SetSizerAndFit(sz)

        self.parent = parent
        self.paths = paths
        self.fax2add = fax2add
        self.opt_cls = parent.opt_cls

        self.cbox_method.Select(2)
        self.use = use

        self.tctrl_value.SetFocus()
        
        self.gr_contacts.Bind(wx.EVT_CHAR, self.OnWxPanel1Char)

        wx.CallAfter(self.my_init)
        
        self.Bind(wx.EVT_CHAR, self.OnWxPanel1Char)
        
    #
    # Graphic methods
    #
    def _create_ctrls(self, parent):
        """ returns the sizer containing the ctrls for the contacts search
        """

        # sizer components
        sz_north = self._createContactsNorthSizer(parent)
        sz_south = self._createContactsSouthSizer(parent)

        # sizer adding
        sbx_contacts = wx.StaticBox(parent, -1, " "+_("sb_contacts")+" ")
        sz_contacts = wx.StaticBoxSizer(sbx_contacts, wx.VERTICAL)
        flag = wx.ALIGN_CENTER | wx.EXPAND | wx.ALL
        sz_contacts.Add(sz_north, 1, flag, 0)
        sz_contacts.Add(sz_south, 0, flag, 0)

        return sz_contacts
    
    def _createContactsNorthSizer(self, parent):
        """ returns the part of the contacts sizer containing the contacts list
        """        
        lbl_faxBookList = wx.StaticText(parent, -1, _("lbl_list_fb"))
        self.trCtrl_faxBookList = wx.TreeCtrl(parent, style=wx.TR_HAS_BUTTONS,
            size=wx.Size(120, 120))
        self.trCtrl_faxBookList.Bind(wx.EVT_LEFT_DOWN, self.OnTree_fbLeftDown)
        btn_config = wx.Button(parent, -1, _("bt_configure_fb"))
        btn_config.Bind(wx.EVT_BUTTON, self._onContactsFaxBookConfigBtn)

        # grid creation and setting
        lbl_contactsList = wx.StaticText(parent, -1, _("lbl_fb_rows"))
        self.gr_contacts = wx_util.sortGrid(parent, size=wx.Size(150, 150))
        self.gr_contacts.CreateGrid(0,0)
        self.gr_contacts.SetColMinimalAcceptableWidth(0)

        self.gr_contacts.Bind(wx.grid.EVT_GRID_EDITOR_SHOWN,
              self.OnGr_fbGridEditorShown)
        self.gr_contacts.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK,
              self.OnGr_fbGridCellLeftDclick)
        self.gr_contacts.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK,
              self.OnGr_fbGridCellRightclick)
        self.gr_contacts.Bind(wx.EVT_KEY_DOWN, self.OnGr_fbGridKeyDown)

        colLblExtentH = self.gr_contacts.GetTextExtent(_("grid_col_company"))[1]
        rowLblExtentH = self.gr_contacts.GetTextExtent("0000")[0]
        self.gr_contacts.SetColLabelSize(colLblExtentH + 10)
        self.gr_contacts.SetRowLabelSize(rowLblExtentH + 10)
        self.gr_contacts.SetDefaultColSize(100)
        
        # buttons creation
        btn_new = wx.Button(parent, -1, _("bt_new"))
        btn_delete = wx.Button(parent, -1, _("bt_delete"))
        btn_save = wx.Button(parent, -1, _("bt_save"))
        btn_addAll = wx.Button(parent, -1, _("bt_add_all"))

        btn_new.Bind(wx.EVT_BUTTON, self._onContactsNewButton)
        btn_delete.Bind(wx.EVT_BUTTON, self._onContactsDelButton)
        btn_save.Bind(wx.EVT_BUTTON, self._onContactsSaveButton)
        btn_addAll.Bind(wx.EVT_BUTTON, self._onAttachAddAllBtn)
        
        self._bt_new = btn_new
        self._bt_del = btn_delete
        self._bt_sav = btn_save
        
        fl_cent_all = wx.ALIGN_CENTER | wx.ALL
        fl_cent_all_exp = fl_cent_all | wx.EXPAND
        
        # buttons sizer
        sz_contactsBtns = wx.BoxSizer(wx.HORIZONTAL)
        sz_contactsBtns.Add(btn_new, 0, fl_cent_all, 5)
        sz_contactsBtns.Add(btn_delete, 0, fl_cent_all, 5)
        sz_contactsBtns.Add(btn_save, 0, fl_cent_all, 5)
        sz_contactsBtns.Add(btn_addAll, 0, fl_cent_all, 5)

        if not self.__doc:
            btn_addAll.Disable()

        sz_north = wx.GridBagSizer(3, 2)
        sz_north.AddGrowableCol(1)
        sz_north.AddGrowableRow(1)
        sz_north.Add(lbl_faxBookList, (0,0), (1,1), wx.ALIGN_LEFT | wx.ALL, 2)
        sz_north.Add(lbl_contactsList, (0,1), (1,1), wx.ALIGN_LEFT | wx.ALL, 2)
        sz_north.Add(self.trCtrl_faxBookList, (1,0), (1,1), fl_cent_all_exp, 2)
        sz_north.Add(self.gr_contacts, (1,1), (1,1), fl_cent_all_exp, 2)
        sz_north.Add(btn_config, (2,0), (1,1), fl_cent_all, 2)
        sz_north.Add(sz_contactsBtns, (2,1), (1,1), fl_cent_all, 2)

        return sz_north

    def _createContactsSouthSizer(self, parent):
        """ returns the part of the contacts sizer containing the search ctrls
        """
        # ctrls creation
        lbl_value = wx.StaticText(parent, -1, _("lbl_value"))
        lbl_field = wx.StaticText(parent, -1, _("lbl_field"))
        lbl_method = wx.StaticText(parent, -1, _("lbl_method_search"))
        
        # ctrl for search value
        self.tctrl_value = wx.TextCtrl(parent, size=wx.Size(100, -1))
        # ctrl for search field
        self.cbox_field = wx.ComboBox(parent, style=wx.CB_READONLY)

        # ctrl for search method
        methodChoices = [x.strip() for x in _("cho_method_search").split(",")]

        self.cbox_method = wx.ComboBox(parent, -1, choices=methodChoices,
            value=methodChoices[2], style=wx.CB_READONLY)
        # button for search
        btn_search = wx.Button(parent, -1, _("bt_search"))
        btn_search.Bind(wx.EVT_BUTTON, self._onContactsSearchBtn)
        
        # sizer creation and adding
        sz_search = wx.GridBagSizer(2, 4)
        sz_search.Add(lbl_value, (0,0), (1,1), wx.ALIGN_CENTER | wx.ALL, 2)
        sz_search.Add(lbl_field, (0,1), (1,1), wx.ALIGN_CENTER | wx.ALL, 2)
        sz_search.Add(lbl_method, (0,2), (1,1), wx.ALIGN_CENTER | wx.ALL, 2)
        sz_search.Add(self.tctrl_value, (1,0), (1,1),
            wx.ALIGN_CENTER | wx.ALL, 2)
        sz_search.Add(self.cbox_field, (1,1), (1,1),
            wx.ALIGN_CENTER | wx.ALL, 2)
        sz_search.Add(self.cbox_method, (1,2), (1,1),
            wx.ALIGN_CENTER | wx.ALL, 2)
        sz_search.Add(btn_search, (1,3), (1,1),
            wx.ALIGN_CENTER | wx.ALL, 2)

        # static box  for search
        sbx_search = wx.StaticBox(parent, -1, " "+_("sb_search")+" ")
        sz_searchBox = wx.StaticBoxSizer(sbx_search, wx.HORIZONTAL)
        sz_searchBox.Add(sz_search, 0, wx.ALIGN_CENTER | wx.EXPAND | wx.ALL, 5)

        return sz_searchBox

    #
    # Functional methods
    #
    def my_init(self):
        table_list = ["CREATE TABLE fb (name text not null unique,\
            fb_order int, fb_db_name text, fb_type text not null, fb_fields text,\
            fb_other text, id integer primary key unique)"]

        self.db = db_lib.Sqlite(self.paths.file_db_fb, 
                                debug=utils.do_debug,
                                tables=table_list)
        self.db.conn()
        
        #Test to add
        #self.db.queryReturn('INSERT INTO fb (name, fb_type, fb_db_name, fb_order, fb_fields, fb_db_name) VALUES ("cdss","local", 2, "aa,bb,cc")')
       
        self.init_tree()
        
        self.pop_gr_send_fax = wx.NewId()
        self.Bind(wx.EVT_MENU, self.pop_gr_send_fax_evt, id=self.pop_gr_send_fax)

        #self.gr_contacts.enableOrd()

    def init_tree(self):
        """ Load the phone books on the tree
        """
        self.trCtrl_faxBookList.DeleteAllItems()
        self.root_inst = self.trCtrl_faxBookList.AddRoot(_("_faxbook_hylapex"))
        status, val_ret = self.db.queryReturn('SELECT name FROM fb ORDER BY fb_order')
        if status:
            self.send_error(str(val_ret), title = _('_faxbook_list_err'))
            return
        
        if val_ret:
            for fb in val_ret:
                self.trCtrl_faxBookList.AppendItem(self.root_inst, fb[0])
            fb_first = val_ret[0][0]
            self.set_grid_fields(fb_first)
        else:
            self.trCtrl_faxBookList.AppendItem(self.root_inst, _('_no_faxbook'))
        
        self.trCtrl_faxBookList.Expand(self.root_inst)
        self.paths.log4write.write('Tree list: %s' % str(val_ret))

    def set_grid_fields(self, db_name):
        """Used for update grid when start or when tree are pressed
        """
        #Delete the preview values, if any
        self.tctrl_value.SetValue("")
        self.cbox_field.SetValue("")
        
        status, val_ret = self.db.queryReturn('SELECT fb_fields, fb_type FROM fb WHERE name = ?', (db_name, ))
        if status:
            self.send_error(str(val_ret), title = _('_error_field_type'))
            return
        self.gr_contacts.ClearSelection()
        
        #Db type
        if not val_ret: return
        self.fb_type = val_ret[0][1]
        self.db4w_name = db_name
        
        fields_name = val_ret[0][0].split(',')
        nc = self.gr_contacts.GetNumberCols()
        nc2del = nc - (len(fields_name) +3)
        if nc2del > 0:
            self.gr_contacts.DeleteCols(0, nc2del)
        else:
            self.gr_contacts.AppendCols(-nc2del)
        nc = self.gr_contacts.GetNumberCols()

        #Clear the combo search
        self.cbox_field.Clear()

        for num, i in enumerate(fields_name):
            self.gr_contacts.SetColSize(num, 100)
            self.gr_contacts.SetColLabelValue(num, i.strip())
            self.cbox_field.Append( i.strip() )
        
        if self.cbox_field.GetItems():
            self.cbox_field.SetSelection(0)
        
        self.gr_contacts.ClearGrid()


        self.num_col_id = nc -3
        self.num_col_new = nc -2
        self.num_col_mod = nc -1

        self.gr_contacts.SetColSize(self.num_col_id, 0)          # Id
        self.gr_contacts.SetColSize(self.num_col_new , 0)        # Modified
        self.gr_contacts.SetColSize(self.num_col_mod , 0)        # new
        self.load_db()
        
        self.gr_contacts.ForceRefresh()

    def load_db(self):
        """ Load the phonebook in a thread or not
        """
        if self.opt_cls.getint("chk_pb_thread"):
            d = threads.deferToThread(self._load_db)
            d.addErrback(self.__err)
        else:
            reactor.callLater(0.4, self._load_db)

    def get_db_args(self, vals):
        """ Translate the vales that come from db to a dict
        """
        db_args = string.split(vals, ',')
        args = {}
        for val in db_args:
            tmp_val = string.split(val, '=')
            if len(tmp_val) > 1: args[tmp_val[0].strip()] = tmp_val[1].strip()
            else:                args[tmp_val[0].strip()] = ""
        return args

    #
    # New events
    #

    def _onContactsDelButton(self, evt):
        """ button "Delete contact event management
        """
        sel = self.gr_contacts.GetSelectedRows()
        if not sel:
            return
        #Id's list
        id2del = [self.gr_contacts.GetCellValue(col, self.num_col_id) for col in sel]
        ctrl_id = 0
        for i in id2del:
            #Control if the field that we want to delete are without an id
            if i == '':
                ctrl_id = 1
        if ctrl_id == 0:
            for id in id2del:
                status, val_ret = self.db4w.queryNoReturn('DELETE FROM %s WHERE id = "%s"'\
                    % (self.db_table4w, id))
                if status:
                    self.send_error(str(val_ret), title = _('_error_delete'))
                    return
        else:
            for row in sel:
                status, val_ret = self.db4w.queryNoReturn('DELETE FROM %s WHERE %s'\
                    % (self.db_table4w, self.GetValsAndFields(row)))
                if status:
                    self.send_error(str(val_ret), title = _('_error_delete'))
                    return
        sel.sort()
        sel.reverse()
        for id in sel:
            self.gr_contacts.DeleteRows(id)

    def _onContactsFaxBookConfigBtn(self, evt):
        """ button "Configure" event management
        """
        import configure_fb
        configure_fb.create(self, self.db, self.paths).Show()

    def _onContactsNewButton(self, evt):
        """ button "New contact event management
        """
        self.gr_contacts.AppendRows()
        nr = self.gr_contacts.GetNumberRows() -1 
        self.gr_contacts.SetCellValue(nr, self.num_col_new, '1')
        self.gr_contacts.MakeCellVisible(nr, 0)
        self.gr_contacts.ShowCellEditControl()
        
    def _onContactsSaveButton(self, evt):
        """ button "Save contact event management
        """
        row_num = self.gr_contacts.GetNumberRows()
        if row_num == 0:
            return
        q = 'SELECT fb_db_name, fb_fields FROM fb WHERE name = ?', (self.db4w_name, )
        status, table_name = self.db.queryReturn(*q)
        
        table_name, table_fields = table_name[0]
        #Global query
        q = ""
        lstWC = []
        lstCV = []
        
        for row in range(row_num):
            #If the row exist
            if self.gr_contacts.GetCellValue(row, self.num_col_new) != '1':
                #If the row is modified, update. Else continue
                if self.gr_contacts.GetCellValue(row, self.num_col_mod) != '':
                    id = self.gr_contacts.GetCellValue(row, self.num_col_id)
                    for col in range(self.num_col_id):
                        lstWC.append( (row, col) )
                        col_val = self.gr_contacts.GetCellValue(row, col)
                        colANDval = "%s='%s'" % ( self.gr_contacts.GetColLabelValue(col),
                                    self.gr_contacts.GetCellValue(row, col))

                        if id != '':
                            q += "UPDATE %s SET %s WHERE id = %s" % (table_name, colANDval, id )
                        else:
                            q += 'UPDATE %s SET %s WHERE %s' % (table_name, colANDval, self.GetValsAndFields(row))

                        q += ";\n"

                    lstCV.append( (row, self.num_col_mod, '') )

                else:
                    continue
            else:
                tmp_list = []
                tmp_list2 = []
                tmp_list3 = []
                
                for tmp_col in range(self.num_col_id):
                    lstWC.append( (row, tmp_col) )

                    #Cell value
                    cv = self.gr_contacts.GetCellValue(row, tmp_col)
                    tmp_list.append(cv)
                    tmp_list2.append( "'%s'" % cv.decode("latin-1") )
                
                for l1 in range(len(tmp_list)):
                    tmp_list3.append(""+ self.gr_contacts.GetColLabelValue(l1) +"")

                for tmp_1 in range(len(tmp_list2)):
                    tmp_str2 = string.join(tmp_list2, ',')
                    tmp_str3 = string.join(tmp_list3, ',')

                q += 'INSERT INTO %s (%s) VALUES (%s)' % (table_name, table_fields, tmp_str2)
                q += ";\n"

                lstCV.append( (row,self.num_col_mod, '') )
                lstCV.append( (row,self.num_col_new, '') )


        status, val_ret = self.db4w.queryNoReturn(q)
        if status:
            self.send_error(str(val_ret), title = _('_error_update'))
            return
        
        #Set the data on the hide columns and redraw the white background
        self.gr_contacts.Freeze()
        for row, col, datain in lstCV:
            self.gr_contacts.SetCellValue(row,col, datain)
        for row, col in lstWC:
            self.gr_contacts.SetCellBackgroundColour(row,col,wx.WHITE)
        
        #Reload data
        wx.CallAfter(self.load_db)
        self.gr_contacts.Thaw()

    
    def _onContactsSearchBtn(self, evt):
        """ button "Search" event management
        """
        self.load_db()
    
    def _onAttachAddAllBtn(self, evt):
        """ button "Add all" event management
        """
        self.update_send_grid(range(0, self.gr_contacts.GetNumberRows()))

    #
    # Old events
    #
    def OnGr_fbGridCellRightclick(self,event):
        if self.use == 'fb':
            event.Skip()
            return
        pos_h, pos_l = self.gr_contacts.GetPosition()
        pos_r_h, pos_r_l = event.GetPosition()
        self._popup_pos = event.GetRow()
        
        menu = wx.Menu()
        menu.Append(self.pop_gr_send_fax, _('_send_fax'))
        real_x, real_y = pos_r_h + pos_h, pos_r_l + pos_l
        self.PopupMenu(menu, (real_x, real_y))
        event.Skip()

    def pop_gr_send_fax_evt(self, event):
        
        rows = self.gr_contacts.GetSelectedRows()
        if rows:
            self.update_send_grid(rows)
        else:
            self.update_send_grid(self._popup_pos)
        
        del self._popup_pos
        
    def OnBt_searchButton(self, event):
        """ Respond to the search button
        """
        self.load_db()
        
    def OnBt_newButton(self, event):
        """ Create the empty line
        """
        self.gr_contacts.AppendRows()
        nr = self.gr_contacts.GetNumberRows() -1 
        self.gr_contacts.SetCellValue(nr, self.num_col_new, '1')
        self.gr_contacts.MakeCellVisible(nr, 0)
        self.gr_contacts.ShowCellEditControl()


    def OnBt_deleteButton(self, event):
        sel = self.gr_contacts.GetSelectedRows()
        if not sel:
            return
        #Id's list
        id2del = [self.gr_contacts.GetCellValue(col, self.num_col_id) for col in sel]
        ctrl_id = 0
        for i in id2del:
            #Control if the field that we want to delete are without an id
            if i == '':
                ctrl_id = 1
        if ctrl_id == 0:
            for id in id2del:
                status, val_ret = self.db4w.queryNoReturn('DELETE FROM %s WHERE id = "%s"'\
                    % (self.db_table4w, id))
                if status:
                    self.send_error(str(val_ret), title = _('_error_delete'))
                    return
        else:
            for row in sel:
                status, val_ret = self.db4w.queryNoReturn('DELETE FROM %s WHERE %s'\
                    % (self.db_table4w, self.GetValsAndFields(row)))
                if status:
                    self.send_error(str(val_ret), title = _('_error_delete'))
                    return
        sel.sort()
        sel.reverse()
        for id in sel:
            self.gr_contacts.DeleteRows(id)

    def GetValsAndFields(self, row):
        valsANDfields = []
        val_col_mod = self.gr_contacts.GetCellValue(row, self.num_col_mod)
        colToJump = val_col_mod.split(',')
        for col in range(self.num_col_id):
            if str(col) in colToJump: continue
            val = self.gr_contacts.GetCellValue(row, col)
            if val == '':
                valsANDfields.append("%s=''" % self.gr_contacts.GetColLabelValue(col))
            else:
                valsANDfields.append("%s='%s'" % (self.gr_contacts.GetColLabelValue(col), val))
        return string.join(valsANDfields, ' AND ')

    def OnTree_fbLeftDown(self, event):
        pt = event.GetPosition()
        item, flags = self.trCtrl_faxBookList.HitTest(pt)
        if flags == wx.TREE_HITTEST_NOWHERE: return
        val = self.trCtrl_faxBookList.GetItemText(item)       # Get code
        self.trCtrl_faxBookList.SelectItem(item)              # Select code
        if val == _("_faxbook_hylapex"): return
        self.set_grid_fields(val)

    def OnGr_fbGridEditorShown(self, event):
        row = event.GetRow()
        col = event.GetCol()
        self.gr_contacts.SetCellBackgroundColour(row,col,wx.Color(200,200,200))
        new_val = self.gr_contacts.GetCellValue(row, self.num_col_mod) + ',' + str(col)
        self.gr_contacts.SetCellValue(row, self.num_col_mod, new_val)

    def OnGr_fbGridCellLeftDclick(self, event):
        if self.use == 'fb':
            event.Skip()
            return
        self.update_send_grid(event.GetRow())
    
    def selectAllAndSend(self):
        """ Help method for select all the current phone book record and send
            the fax to them
        """
        self.update_send_grid(range(0, self.gr_contacts.GetNumberRows()))
        
    def update_send_grid(self, rows):
        """
        """
        if not isinstance(rows, (list, tuple)):
            rows = (rows, )
            
        for row in rows:
            #This list MUST be like wiz_link
            field_list = ['company', 'fax number']
            field_link = read_conf.conf_parser(self.paths.file_db_fb_link, self.db4w_name)
            field_link.exist()

            status, val_ret = self.db.queryReturn('SELECT fb_fields FROM fb WHERE name = "%s"' % self.db4w_name)

            if status:
                self.send_error(str(val_ret))
                return

            fields_db = [x.strip() for x in string.split(val_ret[0][0], ',')]
            link_dict = {}
            link_dict1 = {}
            for f in field_list:
                if field_link.get(f) in fields_db:
                    link_dict[field_link.get(f)] = f
                    link_dict1[f] = field_link.get(f)
            vals_dict = {}

            for col in xrange(self.gr_contacts.GetNumberCols()):
                if self.gr_contacts.GetColLabelValue(col) in link_dict:
                    vals_dict[self.gr_contacts.GetColLabelValue(col)] = self.gr_contacts.GetCellValue(row, col)

            try:
                fax = vals_dict[link_dict1[field_list[1]]]
                comp = vals_dict[link_dict1[field_list[0]]]
            except KeyError:
                return
            self.__doc.set(OBS_ADD_ALL_FILES, fax, comp)

    def send_error(self, err, title = 'Errore', dim = 2):
        if title == '_sql':
            title = _('_error_mysql')
        elif title == '_odbc':
            title = _('_error_odbc')

        utils.do_debug(err)
        
        dlg = wx.MessageDialog(self, err, title, wx.ICON_ERROR)
        dlg.ShowModal()
        dlg.Destroy()
        
    def OnBt_configure_fbButton(self, event):
        import configure_fb
        configure_fb.create(self, self.db, self.paths).Show()

    def OnGr_fbGridKeyDown(self, event):
        key_press = event.GetKeyCode()
        rows = self.gr_contacts.GetSelectedRows()
        if not rows:
            event.Skip()
            return
        if key_press == 13:
            self.update_send_grid(rows)

    def OnWxPanel1Close(self, event):
        self.close()
        event.Skip()

    def close(self):
        try:    self.db4w.close()
        except: pass
        try:    self.db.close()
        except: pass
        self.Destroy()
    
    # --------------- #
    # Private methods #
    # --------------- #
    
    def _createFilterQuery(self):
        """ Return the current filter query
        """
        select = self.cbox_field.GetValue().strip()
        if not select: return ""
        txt_val = self.tctrl_value.GetValue()
        method = self.cbox_method.GetSelection()

        if " " in select.strip():
            select = '"%s"' % select

        strQuery = "WHERE %s " % select
        if   method == 0: strQuery += "= '%s'" % txt_val
        elif method == 1: strQuery += "LIKE '%s%%'" % txt_val
        elif method == 2: strQuery += "LIKE '%%%s%%'" % txt_val
        return " %s " % strQuery

    def _add_line(self, fax2add_lst=''):
        """ Add the row into the grid
        """
    
        if not isinstance(fax2add_lst, (tuple, list)):
            fax2add_lst = (fax2add_lst, )
        
        for fax2add in fax2add_lst:
            self.gr_contacts.InsertRows()
            self.gr_contacts.SetCellValue(0, self.num_col_new, '1')
            fax_col = self.opt_cls.get('fax_col')
            comp_col = self.opt_cls.get('comp_col')
            
            cols = [self.gr_contacts.GetColLabelValue(c).strip()
                    for c in range(self.num_col_id)]
            
            #If the value are not (more) present
            if not fax_col in cols:
                fax_col = self._dialogPosFax(cols, 0)            
            
            if not fax_col: return
            
            fax2add = fax2add or self.fax2add
            
            #Now for the company, if need
            companyname = ''
            if not isinstance(fax2add, basestring):
                companyname, fax2add = fax2add
                
                #Control for the cols if it is present
                if not comp_col in cols:
                    comp_col = self._dialogPosFax(cols, 1)
                
                if not comp_col: return
            
            #The number of fax to add
            if not fax2add: return
            self.gr_contacts.SetCellValue(0, cols.index(fax_col), 
                    str(fax2add).replace(self.opt_cls.get('txt_prefix'), '') )
            
            if companyname: 
                self.gr_contacts.SetCellValue(0, cols.index(comp_col), str(companyname))

    def _dialogPosFax(self, cols, fax_or_company):
        """ Ask for the right column where I can find the fax number
            @arg fax_or_company: True if you want company, false otherwise
        """
        
        if fax_or_company: 
            quest = _("select_comp_col")
            k = "comp_col"
        else: 
            quest = _("select_fax_col")
            k = "fax_col"
        
        dlg = wx.SingleChoiceDialog( self, quest, 
                    _("select_fax"), cols, wx.CHOICEDLG_STYLE )
        
        if dlg.ShowModal() == wx.ID_OK:
            str_col = dlg.GetStringSelection()
            dlg.Destroy()
        else:
            return None
        
        self.opt_cls.set(k, str_col)
        return str_col

    def __err(self, *msg):
        """ Error method for twisted thread
        """
        myMsg = "Error on phone book therad:"
        self.paths.log4write.write(myMsg)
        self.paths.log4write.write(msg)
        print myMsg, msg
        
    def _load_db(self):
        """ Load data into grid and close previous opened db
        """
        try:
            if hasattr(self, 'db4w'):
                self.db4w.close()
        except:
            pass
        status, val_ret = self.db.queryReturn("SELECT fb_db_name, fb_other FROM fb WHERE name = '%s'" %  self.db4w_name)
        if status:
            self.send_error(str(val_ret), title = _('_error_db_other'))
            return
        
        if not val_ret: return
        
        db_table = val_ret[0][0]
        self.db_table4w = db_table
        
        strQuery = self._createFilterQuery()
        
        filter_field, filter_val = "", ""
        
        #Go with the db
        if self.fb_type in ('local', 'file'):
            #Local db
            if self.fb_type == 'local':
                dbpath = os.path.join(self.paths.conf_dir, 'local_' + self.db4w_name + '.db')
            else:
                dbpath = val_ret[0][1].split(",")[0]
            
            self.db4w = db_lib.Sqlite(dbpath, debug=utils.do_debug)
            self.db4w.conn()
            
            first_col = self.gr_contacts.GetColLabelValue(0)
            q = 'SELECT * FROM %s %s ORDER BY "%s"' % (db_table, strQuery, first_col)

            self.paths.log4write.write('Send local query: %s' % q)
            status, val_ret = self.db4w.queryReturn(q)
            if status:
                self.send_error(str(val_ret))
                return
            self._del_cols(len(val_ret))
            self.__append_row_local(val_ret)
            
        elif self.fb_type == 'mysql':
            #Mysql db
            args = self.get_db_args(val_ret[0][1])
            args['table'] = db_table
            ULQ = 'use_table_like_query'
            ULQV = 0
            if args.has_key(ULQ) and args[ULQ] == 'True':
                ULQV = 1
            self.db4w = db_lib.Mysql(debug=utils.do_debug)
            status, err = self.db4w.conn(args)
            if status:
                self.send_error(str(err), title = '_sql')
                return
            first_col = self.gr_contacts.GetColLabelValue(0)
            
            if ULQV: q = db_table
            else:    q = ('SELECT * FROM %s ' % db_table)
            q += ' %s ORDER BY "%s"' % (strQuery, first_col)
            
            self.paths.log4write.write('Send mysql query: %s' % q)
            status, ret_my = self.db4w.queryReturn(q)
            
            if status:
                self.send_error(str(ret_my))
                return
            status, ret_tmp = self.db.queryReturn('SELECT fb_fields FROM fb WHERE name = "' + self.db4w_name + '"')
            ret_tmp = ret_tmp[0][0]
            if status:
                self.send_error(str(ret_tmp))
                return
            ret_f = string.split(ret_tmp, ',')
            if len(ret_my) > 0 and ret_my[0].has_key('id'):
                ret_f.append('id')
            self._del_cols(len(ret_my))
            self.__append_row_sql(ret_my, ret_f)
            
        elif self.fb_type == 'odbc':
            #Odbc db
            args = self.get_db_args(val_ret[0][1])
            args['table'] = db_table
            
            ULQ = 'use_table_like_query'
            ULQV = 0
            if args.has_key(ULQ) and args[ULQ] == 'True':
                ULQV = 1
            
            first_col = self.gr_contacts.GetColLabelValue(0)
            status, value = self.db.queryReturn('SELECT fb_fields FROM fb WHERE name = "' + self.db4w_name + '"')
            if status:
                self.send_error(str(value), title = '_odbc')
                return

            field_select = []
            for x in value[0][0].split(","):
                x = x.strip()
                if " " in x:
                    field_select.append('"%s"' % x )
                else:
                    field_select.append(x)

            field_select = ",".join( field_select )

            self.db4w = db_lib.Odbc(debug=utils.do_debug)

            #Force the db to not use mx.ODBC because it use a lot of memory...
            #I have to understand why!
            try:
                self.db4w.conn(args['dsn'].strip(),
                                  args['user'].strip(),
                                  args['pass'].strip())
            except Exception, ex:
                self.send_error('Error on connect %s' % ex, title = '_odbc')
                return
            
            if ULQV: q = db_table
            else:    q = ("SELECT %s FROM %s " % (field_select, db_table))
            q += ' %s ORDER BY "%s" ' % (strQuery, first_col)
            
            status, val_ret = self.db4w.queryReturn(str(q))

            if status:
                self.send_error('Error %s \nQuery: %s' % (val_ret, q), title = '_odbc')
                return
        
            nc = len(string.split(field_select, ','))
            self._del_cols(len(val_ret))
            self.__append_row_odbc(val_ret, nc)

        #control for odbc readonly
        if (self.fb_type == 'odbc' and 
                self.opt_cls.has_option("chk_db_odbc_readonly") and 
                self.opt_cls.getint("chk_db_odbc_readonly") ):
            
            to_enable_modify = False
        else:
            to_enable_modify = True
        
        for c in (self._bt_del, self._bt_new, self._bt_sav):
            c.Enable(to_enable_modify)
        
        
        if self.fax2add: 
            self._add_line(self.fax2add)
            self.fax2add = ''
            
    def _del_cols(self, val):
        """ Delete and recreate the grid cols
        """
        num_row_pr = self.gr_contacts.GetNumberRows()
        num_row_del = num_row_pr - val
        if num_row_del > 0:
            self.gr_contacts.DeleteRows(0, num_row_del)
        else:
            self.gr_contacts.AppendRows(-num_row_del)

    def __append_row_local(self, ret):
        """ Set the values to the grid from local db
        """
        num_col = self.gr_contacts.GetNumberRows()
        tmpLst = list()
        for row, val in enumerate(ret):
            tmpLst_Col = list()
            for col in range(self.num_col_id +1):
                value = val[col] or ""
                
                if not isinstance(value, basestring):
                    value = str(value)

                if wx.USE_UNICODE:
                    if not isinstance(value, unicode):
                        value = unicode(value, "latin-1")
                else:
                    try:
                        value = str(value)
                    except Exception, ex:
                        value = "Error!" + repr(ex)
                
                tmpLst_Col.append(value)
            tmpLst.append(tmpLst_Col)
        self.gr_contacts.setData(tmpLst)
        #print tmpLst
    
    def __append_row_sql(self, ret_my, ret_f):
        """
        """
        tmpLst = list()
        for row, val in enumerate(ret_my):
            tmpLst_Col = [ val[f] for f in ret_f ]
            tmpLst.append(tmpLst_Col)
        self.gr_contacts.setData(tmpLst)
        
    def __append_row_odbc(self, val_ret, nc):
        """
        """
        self.gr_contacts.setData(val_ret)
        #print val_ret
        return
        num_col = self.gr_contacts.GetNumberRows()
        for row, val in enumerate(val_ret):
            for col in range(nc):
                self.gr_contacts.SetCellValue(row, col, str(val[col]))

    def OnWxPanel1Char(self, evt):
        if evt.GetKeyCode() == 14 and evt.ControlDown():
            #Control new pressed
            self.OnBt_newButton(None)
        else:
            evt.Skip()
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.