Esempio n. 1
0
    def update(self, table, set_fields, where_part = None, where_arguments = tuple([])):
        """executes update on all `set_fields` where `where_part`
        \param table 
        \param set_fields hash like {"id" : value}
        \param where_part string
        \param where_arguments tuple with arguments or list with tuples with arguments
        """
        assert(isinstance(set_fields, dict))
        assert(isinstance(where_arguments, (tuple, list)))
        if is_null_or_empty(set_fields):
            return
        
        names = []
        data = []
        for k in set_fields.keys():
            names.append(k)
            data.append(set_fields[k])

        q = 'update {0} set {1}'.format(table, reduce_by_string(', ', map(lambda a: '{0} = ?'.format(a), names)))
        if not is_null_or_empty(where_part):
            q += ' where {0}'.format(where_part)
            wargs = (isinstance(where_arguments, tuple) and [where_arguments] or where_arguments)
            exargs = map(lambda warg: tuple(list(data) + list(warg)), wargs)
            self.executemany(q, exargs)
        else:
            self.execute(q, data)
 def check_entry_ready(self, ):
     """\brief return true if all fields completely selected
     """
     if is_null_or_empty(self.account.get_value()):
         return False
     if is_null_or_empty(self.datetime.get_datetime()):
         return False
     if abs(self.amount.get_value()) < 0.001:
         return False
     return True
Esempio n. 3
0
    def __init__(self, ):
        """initialize gtk view
        """
        self.model = None
        self.settings = settings()
        self.window = main_window_controller(self)
        if self.settings.get_key('behavior.load_last_database'):
            dbpath = self.settings.get_key('database.path')
            if not (is_null_or_empty(dbpath) or dbpath == ':memory:'):
                try:
                    self.open_existing_sqlite(dbpath)
                except sqlite3.OperationalError as e:
                    show_and_print_error(e, self.window.builder.get_object('main_window'))
            else:
                self.settings.set_key('database.path', '')
        self.currency = currency_edit_control(self)
        self.account_edit = account_edit_control(self)
        self.accounts = accounts_tab_controller(self)
        self.deals_tab = deals_tab_controller(self)
        self.deal_adder = deal_adder_control(self)
        self.deal_editor = deal_editor_control(self)
        self.deals_filter = deals_filter(self)
        self.paper_adder = paper_adder(self)
        self.positions_tab = positions_tab_controller(self)
        self.positions_filter = positions_filter(self)
        self.position_adder = position_adder_control(self)
        self.points = points_control(self)
        self.report_importer = report_importer_control(self)
        self.chart_tab = chart_tab_controller(self)
        self.settings_dialog = settings_dialog_controller(self)
        self.account_in_out = account_in_out_controller(self)
        self.history_dialog = history_dialog_controller(self)

        self.call_update_callback()
 def update_accounts(self, ):
     """\brief update accounts box
     """
     accs = self._parent.model.list_accounts(['name'])
     self.account.update_answers(map(lambda a: (a['id'], a['name']), accs))
     got = self.account.get_value()
     if is_null_or_empty(got):
         cacc = self._parent.model.get_current_account()
         if cacc <> None:
             self.account.set_value(cacc['id'])
 def check_correctness(self):
     errs = []
     if not self.price.get_lower_value() > 0:
         errs.append(u'Необходимо указать цену открытия')
     if not self.price.get_upper_value() > 0:
         errs.append(u'Необходимо указать цену закрытия')
     if is_null_or_empty(self.instrument.get_value()):
         errs.append(u'Необходимо выбрать инструмент')
     if is_null_or_empty(self.account.get_value()):
         errs.append(u'Необходимо выбрать класс инструмента')
     if not self.count.get_value() > 0:
         errs.append(u'Неоходимо указать количество бумаг в позиции')
     if len(errs) > 0:
         show_error(reduce(lambda a, b:u'{0}\n{1}'.format(a, b),
                           errs),
                    self.builder.get_object("padder"))
         return False
     else:
         return True
 def check_correctness(self):
     errs = []
     if is_blank(self.name.get_text()):
         errs.append(u'Необходимо указать имя счета')
     vv = self.currency_combo.get_value()
     if is_null_or_empty(vv):
         errs.append(u'Нужно указать название валюты')
     if len(errs) > 0:
         show_error(reduce(lambda a, b:u'{0}\n{1}'.format(a, b), errs), self.window)
         return False
     return True
 def change_multiple_deals(self):
     if not self._parent.connected():
         return
     selected = self.deals_view.get_selected_rows()
     self._parent.deal_editor.update_editor()
     ret = self._parent.deal_editor.run()
     if ret == gtk.RESPONSE_ACCEPT:
         dhash = self._parent.deal_editor.get_data()
         if is_null_or_empty(dhash):
             return
         self._parent.model.tachange_deals(map(lambda dl: dl[0], selected), dhash)
         self._parent.call_update_callback()
 def change_one_deal(self):
     if not self._parent.connected():
         return
     row = self.deals_view.get_selected_rows()
     if not is_null_or_empty(row) and len(row) == 1:
         self._parent.deal_adder.update_adder()
         self._parent.deal_adder.load_from_deal(row[0][0])
         ret = self._parent.deal_adder.run()
         if ret == gtk.RESPONSE_ACCEPT:
             data = self._parent.deal_adder.get_data()
             self._parent.model.tachange_deals(row[0][0], data)
             self._parent.call_update_callback()
 def quit(self, ): #@ReservedAssignment
     """\brief quit procedure activate
     """
     if self._parent.connected():
         cs = self._parent.model.get_connection_string()
         self._parent.settings.set_key('database.path', ('' if is_null_or_empty(cs) or cs == ':memory:' else cs))
     else:
         self._parent.settings.set_key('database.path', '')
     if self._parent.disconnect():
         self._parent.quit()
         return False
     else:
         return True
Esempio n. 10
0
 def __init__(self, ):
     """\brief constructor
     """
     self._config_data = None
     self._default_cinfig_data = {'database' : {'path' : ''},
                                  'behavior' : {'load_last_database' : True},
                                  'interface' : {'odd_color' : '#FFFFFF',
                                                 'even_color' : '#FFFFFF'},
                                  'chart' : {'legend': {'position' : 'bottom',
                                                        'font' : 'Sans 14',
                                                        'color' : '#FFFFFF'},
                                             'mesh' : {'line_width' : 1.5,
                                                       'color' : '#FFFFFF',
                                                       'font' : {'name' : 'Sans 14'}},
                                             'background' : {'color' : '#FFFFFF'},
                                             'top_indent' : 5,
                                             'bottom_indent' : 5}}
     
     if os.name in ['posix', 'nt']: # there is HOME environment under windoze in 2.7 python at least
         if os.name == 'nt':
             os.environ['HOME'] = os.path.join(os.environ['HOMEDRIVE'], os.environ['HOMEPATH'])
         config_dir = None
         if not is_null_or_empty(gethash(os.environ, 'TD_CONFIG_DIR')):
             config_dir = os.environ['TD_CONFIG_DIR']
         else:
             if not is_null_or_empty(gethash(os.environ, 'HOME')):
                 config_dir = os.path.join(os.environ['HOME'], '.track-deals') # this is default config directory
             else:
                 raise EnvironmentError('There is not HOME environment specified')
     else:
         raise NotImplementedError('There is no code for windoze yet')
     self.config_file = os.path.join(config_dir, 'gtk-view.cfg')
     if not os.path.exists(config_dir):
         os.makedirs(config_dir)
     if not os.path.exists(self.config_file):
         self.make_default_config()
     else:
         self.read_config()
Esempio n. 11
0
    def autoset_x_min_max(self, data_charts):
        """\brief automatically set lower_x_limit and upper_x_limit to display data from data_charts
        \param data_charts - list of \ref data_chart.data_chart instances
        """
        if is_null_or_empty(data_charts):
            return
        lower, upper = 0, 1
        for chart in data_charts:
            x = map(lambda a: a[0], chart.get_data_list())
            lower = min(lower, min(x))
            upper = max(upper, max(x))

        self.set_lower_x_limit(lower)
        self.set_upper_x_limit(upper)
Esempio n. 12
0
 def update_adder(self,):
     """\brief update posible values for account and instrument widget
     """
     if not self._parent.connected():
         return
     papers = self._parent.model.list_papers(["name"]).fetchall()
     pps = map(lambda p: (p["id"], p["name"]), papers)
     self.instrument.update_answers(pps)
     accs = self._parent.model.list_accounts(["name"]).fetchall()
     acs = map(lambda ac: (ac["id"], ac["name"]), accs)
     self.account.update_answers(acs)
     if is_null_or_empty(self.account.get_value()):
         cacc = self._parent.model.get_current_account()
         if cacc <> None:
             self.account.set_value(cacc["id"])
Esempio n. 13
0
    def autoset_y_min_max(self, data_charts):
        """\brief automatically set lower_y_limit and upper_y_limit for printing the data
        \param data_charts - the list of \ref data_chart.data_chart instances
        \note if length of data_charts is 0 then do nothing
        """
        if is_null_or_empty(data_charts):
            return
        lower = 0
        upper = 1
        for chart in data_charts:
            y = map(lambda a: a[1], chart.get_data_list())
            lower = min(lower, min(y))
            upper = max(upper, max(y))

        self.set_lower_y_limit(lower)
        self.set_upper_y_limit(upper)
Esempio n. 14
0
 def execute_select_cond(self, tablename, selects = ["*"], wheres = [], order_by = []):
     """\breif generates query for execute_select pass it to
     \param tablename  string with table name
     \param selects  [* | field name | expression | (field name | expression, alias)]
     \param wheres  [(= | < | > | ... | 'between', exp1, exp2, exp3 ...)]
     \param order_by  [field name]
     """
     q = u"select {0} from {1}".format(format_select_part(selects), tablename)
     (whpart, adarg) = format_where_part(wheres)
     if not is_null_or_empty(whpart):
         q += " where {0}".format(whpart)
     q += order_by_print(order_by)
     if len(adarg) > 0:
         return self.execute_select(q, adarg)
     else:
         return self.execute_select(q)
Esempio n. 15
0
 def autoset_rectangle(self, data_charts):
     """\brief automatically set all rectangle attributes
     \param data_charts - list of \ref data_chart.data_chart instances
     """
     if is_null_or_empty(data_charts):
         return
     rectangles = map(lambda a: a.get_drawing_rectangle(), data_charts)
     xx = map(lambda a: a[0], rectangles) + map(lambda a: a[1], rectangles)
     yy = map(lambda a: a[2], rectangles) + map(lambda a: a[3], rectangles)
     x_lower = min(xx)
     x_upper = max(xx)
     y_lower = min(yy)
     y_upper = max(yy)
     self.set_lower_x_limit(x_lower)
     self.set_upper_x_limit(x_upper)
     self.set_lower_y_limit(y_lower)
     self.set_upper_y_limit(y_upper)
Esempio n. 16
0
    def fill_fields_from_selected(self, ):
        """\brief fill fields in the window from the selected row
        """
        if not self._parent.connected():
            return

        row = self.list.get_selected_row()
        if row <> None:
            paper = self._parent.model.get_paper(row[0])
            for set_meth, keyval in [(self.name.set_text, 'name'),
                                     (self.type.set_value, 'type'),
                                     (self.full_name.set_text, 'full_name'),
                                     (self.stock.set_value, 'stock'),
                                     (self.class_field.set_value, 'class')]:
                if is_null_or_empty(paper[keyval]):
                    set_meth('')
                else:
                    set_meth(paper[keyval])
Esempio n. 17
0
 def check_fields_before_add(self, ):
     """\brief check if fields like "name", "full_name" and so on entered correctly
     """
     tt = self.type.get_value()
     nn = self.name.get_text()
     return tt <> None and not is_null_or_empty(nn) and not is_blank(nn)