Exemplo n.º 1
0
 def change_date_session(self, new_value):
     self.date_session = new_value
     self.ui.label_data_session.setText(new_value)
     nd = 'Nueva Fecha: {}'.format(new_value)
     print(nd)
     selfCloseInterface(nd, 3, 1, 'Fecha de trabajo cambiada',
                        '\n\n *Las entradas tendran esa fecha')
     return
Exemplo n.º 2
0
def lock_entry(self):
    self.use_secure_entry = self.ui.actionUsar_verificacion_de_datos.isChecked()
    sem = 'Activado' if self.use_secure_entry else 'Desactivado'
    print('Secure Entry Mode: {}'.format(sem))
    selfCloseInterface('Secure Entry Mode: {}'.format(sem),8,1,'Secure Entry Mode',
                       'Cuando el modo seguro está activo,'+
                       ' se solicita una confirmacion antes de entrar los datos a la base de datos. De esta manera se'
                       +' evitan errores en la entrada de datos.\n\nCuando está desactivado la entrada es directa')
    return
Exemplo n.º 3
0
def export_data_displayed_on_tab1(self):
    try:
        filename_path = export_data(self, self.data_to_display_on_tab1.copy())
        print('data saved on {}'.format(filename_path))
        selfCloseInterface('Diary Table Data Exported ', 6, 1,
                           'Export Success',
                           'Data saved on: {}'.format(filename_path))
        return
    except BaseException as error:
        print('export failed : {}'.format(error))
        selfCloseInterface('Failed on Exporting Data from Diary Table', 4, 2,
                           'Export Failed')
        raise Exception(error)
Exemplo n.º 4
0
def execute_display_table(self, table_name):
    self.table_on_target = table_name
    self.headers_for_tab1 = get_template_fields(table_name)
    if table_name != 'diary':
        self.recalculate_tables_signal.emit()
        # what else??
    self.data_to_display_on_tab1 = crud_driver(self, table_name, 'read',
                                               {'pick_all': True})
    self.display_table_signal.emit()
    self.ui.tabWidget.setCurrentIndex(0)
    selfCloseInterface(
        'tabla: {} ha sido cargada con exito'.format(table_name), 1, 1,
        'Ver {}'.format(table_name))
    return
Exemplo n.º 5
0
def crud_driver(self, table, operation, options):
    type_checker(self, options, dict)
    type_checker(self, table, str)
    data = None
    try:
        if self.cursor is not None:
            close_cursor(self)
        initialize_cursor(self)
        if operation == 'create':
            _insert_on_db(self, table, options)
        if operation == 'read':
            _select_on_db(self, table, options)
        if operation == 'update':
            _update_on_db(self, table, options)
        if operation == 'delete':
            _delete_on_db(self, table, options)
        if operation == 'raw_exec':
            # print('debug: ejecutando raw execution with:')
            # print('debug: query: ',options.get('raw_exec'))
            # print('debug: values: ',options.get('value'))
            if any([
                    isinstance(options.get('value'), list),
                    isinstance(options.get('value'), tuple)
            ]) and len(options.get('value')) > 0:
                self.cursor.execute(options.get('raw_exec'),
                                    options.get('value'))
            else:
                self.cursor.execute(options.get('raw_exec'))
    except sqlite3.Error as error:
        # print('error inside crud driver: ', error)
        selfCloseInterface('error on Database Process',
                           alert_level=3,
                           title='DB Error',
                           info=str(error))
        # raise error

    except ConditionFailedException as error2:
        # print(str(error2))
        # alert_on_error = MessageBox(lambda: # print(str(error)), str(error2), 'e', 'DB error')
        # alert_on_error.show()
        raise error2
    finally:
        if operation in ['raw_exec', 'read']:
            data = self.cursor.fetchall()
            close_cursor(self)
            # print('data from %s operation: ' % operation, data)
            return data

        if self.cursor is not None:
            close_cursor(self)
Exemplo n.º 6
0
def create_connection(self, db_name):
    try:
        self.connection = sqlite3.connect(os.path.join(os.curdir, 'databases', db_name))
        if db_name != statusDB_name:
            self.connection.create_function('REGEXP', 2, regexp)
            self.connection.create_function('total_per_item', 2, total_per_item)
            self.connection.create_function('find_profit', 4, find_profit)
            self.status.update({"connected_to": db_name})
        initialize_cursor(self)
        self.connected_signal.emit(db_name)
        # print('debug: successfully connected to {}'.format(db_name))
    except sqlite3.Error as error:
        print('error while trying to connect to {}  details:\n {}'.format(db_name, error))
        selfCloseInterface('Failed on Connecting To Database {}'.format(db_name), 3, 3, 'Critical Error',
                           'Closing App...')
        QApplication.quit()
Exemplo n.º 7
0
def export_data_from_diary(self):
    # steps:
    # 1- read the diary table
    # 2- export the data using export function.
    try:
        filename_path = export_data(
            self, crud_driver(self, 'diary', 'read', {'pick_all': True}))
        print('data saved on {}'.format(filename_path))
        selfCloseInterface('Diary Table Data Exported ', 6, 1,
                           'Export Success',
                           'Data saved on: {}'.format(filename_path))
        return
    except BaseException as error:
        print('export failed : {}'.format(error))
        selfCloseInterface('Failed on Exporting Data from Diary Table', 4, 2,
                           'Export Failed')
        raise Exception(error)
Exemplo n.º 8
0
 def on_import_button_clicked(self, parent):
     user_is_aware_of_format = {'value': False}
     aware_of_format_dialog = MessageBox(
         lambda: user_is_aware_of_format.update({'value': True}),
         'El formato de la tabla que va a importar debe ser\n'
         'producto_pagado | nombre | total_invertido | cantidad\n'
         'ademas de esto la tabla no debe tener encabezados de campos\n\n'
         'si el formato de la tabla no coincide con lo descrito o usted '
         'no esta seguro, debe cancelar la importacion para evitar errores de datos', 'q',
         'Alerta sobre formato', '\n\ndesea continuar con la importacion?')
     aware_of_format_dialog.exec_()
     if not user_is_aware_of_format.get('value'):
         return
     file_to_import = QFileDialog.getOpenFileName(
         self, 'Seleccione Bloque de Compras', os.pardir, '*.csv'
     )
     data_to_import = list((
         line.replace('\n', '')
             .replace('"', '')
             .split(';')
         for line in open(file_to_import[0]).readlines()
     ))
     total_to_pay = eval(str.join(' + ', list((str(item[2]) for item in data_to_import))))
     cash__ = get_index_in_template('diary', 'cash_')
     last_row_data__ = crud_driver(parent, 'diary', 'read', {})[-1]
     if last_row_data__[cash__] < total_to_pay:
         return selfCloseInterface(
             'la compra que desea realizar no puede ser completada\n'
             'la cantidad de dinero en caja es: $ {:,.2f}\n'
             'el total de la compra es: $ {:,.2f}\n\n'
             'le falta: $ {:,.2f}'.format(
                 float(last_row_data__[cash__]),
                 float(total_to_pay),
                 float(total_to_pay) - float(last_row_data__[cash__])
             ), 20, 2, 'Compra Denegada',
             'Vaya a:\nMenu > Herramientas > Modificar inversion\n'
             'y aumente la cantidad de dinero disponible para cubrir la suma'
         )
     else:
         for index, purchase in enumerate(data_to_import):
             self.accept_routine(parent, True, purchase)
             selfCloseInterface(
                 'procesando datos {} de {} ...'.format(index, len(data_to_import)),
                 0.3,1,'Procesando')
     selfCloseInterface('Operacion de Compra en Bloque realizada con exito', 4, 1, 'Compra Realizada')
     return
Exemplo n.º 9
0
def connect_toDB(self, db_name, create_tables=True, silent=False):
    create_connection(self, db_name)
    print('connected to: %s...' % db_name)
    if create_tables:
        create_tables_onDb(self)
    if not silent:
        selfCloseInterface(
            'Estas conectado a la base de datos: {}'.format(db_name),
            title='Conectado a la Base de Datos')
        # changed by autocloseable alert
        # connection_alert = MessageBox(
        #     lambda: print('ok'),
        #     'Now, you\'re connected to: %s' % db_name,
        #     'i', 'Connection Success')
        # connection_alert.show()
    if db_name != statusDB_name:
        self.recalculate_tables_signal.emit()
    return
Exemplo n.º 10
0
def database_saver_routine(self, silent=False):
    database_name, saving_date, suffix = self.status.get("connected_to").split('.')[0], \
                                         datetime.datetime.now().__str__() \
                                             .replace('-', '') \
                                             .replace(' ', '-') \
                                             .replace('.', '-') \
                                             .replace(':', ''), 'Saved-'
    try:
        saving_dir = os.path.join(os.pardir, 'saved databases')
        os.mkdir(saving_dir)
    except FileExistsError as error:
        print('info: on saving dir: %s' % error)
    try:
        saving_dir = os.path.join(os.pardir, 'saved databases', database_name)
        os.mkdir(saving_dir)
    except FileExistsError as error:
        print('warning on saving dir child: %s' % error)
    try:
        src = os.path.join(os.curdir, 'databases',
                           '{}.db'.format(database_name))
        dst = os.path.join(
            os.pardir, 'saved databases', database_name,
            '{}-{}-{}'.format(suffix, database_name, saving_date))
        shutil.copy(src, dst)
        if not silent:
            selfCloseInterface('Database {} guardada en {}'.format(
                database_name, dst),
                               title='Base de Datos Guardada')
    except FileNotFoundError as fileError:
        print('error: %s' % fileError)
        selfCloseInterface('Fallo a la hora de guardar la base de datos',
                           title='Salva Fallida',
                           alert_level=2)
        # no_db_alert = MessageBox(
        #     lambda: print('error: %s' % fileError),
        #     'the saving process has failed!!',
        #     'e',
        #     'DB Saving Failed',
        #     str(fileError)
        # )
        # no_db_alert.show()
        return
Exemplo n.º 11
0
def import_data_to_diary(self):
    try:
        import_data(
            self,
            False)  # imports the data and writes the array self.imported_data
        transform_imported_data(self, 'diary', 'entry_counter',
                                entry_counter_creator)
        data_to_import = self.imported_data.copy()
        crud_driver(
            self, 'diary', 'create', {
                'fields': get_template_fields('diary'),
                'value_list': data_to_import,
                'multi': True
            })
        self.display_table_signal.emit()
        selfCloseInterface('Data imported to Diary Table', 3, 1,
                           'Import Success')
        return
    except BaseException as error:
        selfCloseInterface('Failed on Importing Data to Diary Table', 3, 2,
                           'Import Failed', str(error))
        print('failed import of data')
        raise error
Exemplo n.º 12
0
def filter_active_table(self):
    # fields = get_template_fields(self.table_on_target)
    # data = crud_driver(self,self.table_on_target,'read',{})

    fields = self.headers_for_tab1.copy()
    data = self.data_to_display_on_tab1.copy()

    if len(data) == 0:
        return selfCloseInterface(
            'No hay datos para filtrar !!', 4, 2, 'Error del Filtro',
            '\n\nVaya a: \nMenu Herramientas > Ver\n y seleccione alguna tabla para aplicarle filtros'
        )
    filter_dialog = FilterDialog(self, fields, data)
    filter_dialog.exec_()
    self.display_table_signal.emit()
    return
Exemplo n.º 13
0
def tool_launcher(self, tool, template=None):
    try:
        # set proper tools
        if template is not None:
            dialog = tool(self, template)
        else:
            dialog = tool(self)
            self.ui.tabWidget.setCurrentIndex(0)
        ph = self.geometry().height()
        pw = self.geometry().width()
        px = self.geometry().x()
        py = self.geometry().y()
        dw = dialog.width()
        dh = dialog.height()
        dialog.setGeometry(pw - dw + px, ph - dh + py, dw, dh)
        dialog.show()
        return
    except IndexError as error:
        return selfCloseInterface(
            'La herramienta que solicita no puede ser mostrada', 8, 3,
            'Error en la herramienta',
            '\n\n si se trata de ventas, es probable que no cuente con articulos en su inventario\nsi se trata de '
            'compras revise el saldo (cash_) antes de hacer alguna compra')
Exemplo n.º 14
0
def ui_init_routine(self):
    self.status = status_loader_routine(self)
    status_saver_routine(self, True)
    if self.status.get('last_date') == current_date:
        self.counter = self.status.get('counter')
    self.status.update({'last_date': current_date})
    # self.data_to_display_on_tab1 = crud_driver(  # on init shows diary on current_date entries
    #     self, 'diary', 'raw_exec', {
    #         'raw_exec': 'SELECT * FROM diary WHERE entry_counter REGEXP ?',
    #         'value': ('{}'.format(current_date).replace('-',''),)
    #     })
    self.data_to_display_on_tab1 = crud_driver(
        self, 'diary', 'read', {
            'pick_all': False,
            'multi': False,
            'pick_cols': ['*'],
            'field': 'entry_counter',
            'operator': 'REGEXP',
            'order_by': ['entry_counter'],
            'order_': ['ASC', 'ASC'],
            'sort': True,
            'value': ('{}'.format(current_date).replace('-', ''), )
        })
    set_menus(self)
    app_clock(self, self.ui.label_app_clock)
    set_calculator(self)
    set_bill_calculator(self)

    # ui initialization
    self.ui.tabWidget.setCurrentIndex(self.status.get('active_tab'))
    self.ui.label_data_session.setText(self.date_session)
    self.ui.label_table_on_display.setText(self.table_on_target)
    self.ui.label_current_database.setText(self.status.get('connected_to'))

    #  signal connections
    self.date_changed_signal.connect(self.change_date_session)
    self.connected_signal.connect(
        lambda db__: self.ui.label_current_database.setText(db__))
    self.resized_signal.connect(self.save_window_size)
    self.counter_updated_signal.connect(lambda: update_counter(self))
    self.display_table_signal.connect(
        lambda: display_active_table_on_data_display(self))
    if self.ui.tabWidget.currentIndex() == 0:
        self.display_table_signal.emit()
    self.recalculate_tables_signal.connect(
        lambda: calculate_auxiliar_tabs(self))
    self.recalculate_tables_signal.connect(
        lambda: display_statistics_on_tab(self))
    if self.ui.tabWidget.currentIndex() == 2:
        self.recalculate_tables_signal.emit()
    self.ui.tabWidget.currentChanged.connect(
        lambda i: tab_index_reaction(self, i))

    # tab1 buttons
    self.ui.pushButton_export_table.clicked.connect(
        lambda: export_data_displayed_on_tab1(self))
    self.ui.toolButton_filter.clicked.connect(
        lambda: filter_active_table(self))

    # statistics tab buttons
    self.ui.pushButton_update_stats_tab.clicked.connect(
        lambda: display_statistics_on_tab(self))
    self.ui.pushButton_update_stats_tab.clicked.connect(
        lambda: selfCloseInterface(
            'Estadisticas Actualizadas', alert_level=1, title='Completado!'))
Exemplo n.º 15
0
    def apply_form(self, parent):
        # props alias...
        data_len__ = get_template_fields('diary')
        date__ = get_index_in_template('diary', 'date')
        comments__ = get_index_in_template('diary', 'comments')
        amount__ = get_index_in_template('diary', 'amount')
        owner__ = get_index_in_template('diary', 'owner')
        invested__ = get_index_in_template('diary', 'invested_')
        cash__ = get_index_in_template('diary', 'cash_')
        total__ = get_index_in_template('diary', 'total_')
        parts__ = [
            get_index_in_template('diary', 'robert_'),
            get_index_in_template('diary', 'ariadna_')
        ]
        sign__ = -1 if self.ui.extraccionDelMontoCheckBox.isChecked() else 1
        last_row_data__ = crud_driver(parent, 'diary', 'read', {})
        last_row_data = build_data_template() if len(
            last_row_data__) == 0 else last_row_data__[-1]
        last_row_data = build_data_template(
        ) if len(data_len__) > len(last_row_data) else last_row_data
        data = build_data_template()

        data[comments__] = self.ui.comentariosDeCapitalLineEdit.text()
        data[date__] = parent.date_session
        data[amount__] = self.ui.cantidadDeDineroDoubleSpinBox.value() * sign__
        data[
            owner__] = self.ui.nombreDelQueInsertaElDineroComboBox.currentText(
            )
        data[parts__[0]] = last_row_data[parts__[0]]
        data[parts__[1]] = last_row_data[parts__[1]]
        data[parts__[self.ui.nombreDelQueInsertaElDineroComboBox.currentIndex()]] = \
            last_row_data[parts__[self.ui.nombreDelQueInsertaElDineroComboBox.currentIndex()]] + data[amount__]

        # this block is for defunding protection:
        amount___ = float(data[parts__[
            self.ui.nombreDelQueInsertaElDineroComboBox.currentIndex()]])
        if amount___ < 0:
            print('capital extraction denied. No enough funds ')
            selfCloseInterface(
                'No puede extraer $ {:,.2f} del saldo de {}.\nFondos Insuficientes'
                .format(
                    self.ui.cantidadDeDineroDoubleSpinBox.value(),
                    self.ui.nombreDelQueInsertaElDineroComboBox.currentText()),
                5, 3, 'Extraccion Denegada',
                'No esta permitido extraer mas dinero que el total de la parte de un socio '
            )
            return self.clean_form()

        data[invested__] = last_row_data[invested__]
        data[total__] = data[parts__[0]] + data[parts__[1]]
        data[cash__] = data[total__] - data[invested__]

        if parent.use_secure_entry:
            confirm = MessageBox(lambda: parent.append_data_to_diary(data),
                                 'Desea confirmar la Entrada?', 'q',
                                 'Confirmar Entrada',
                                 self.ui.notasDeCapital.text())
            confirm.show()
            return
        else:
            parent.append_data_to_diary(data)
            selfCloseInterface(self.ui.notasDeCapital.text(), 4, 1,
                               'Operacion Realizada',
                               'Cambios Insertados en la Base de Datos')
            return
Exemplo n.º 16
0
    def apply_routine(self, parent):

        # props alias...
        data_len__ = get_template_fields('diary')
        date__ = get_index_in_template('diary', 'date')
        is_new__ = get_index_in_template('diary', 'is_new')
        is_sale__ = get_index_in_template('diary', 'is_sale')
        is_consignation__ = get_index_in_template('diary', 'is_consignation')
        quantity__ = get_index_in_template('diary', 'quantity')
        item_name__ = get_index_in_template('diary', 'item_name')
        price__ = get_index_in_template('diary', 'price')
        sell_price__ = get_index_in_template('diary', 'sell_price')
        comments__ = get_index_in_template('diary', 'comments')
        item_code__ = get_index_in_template('diary', 'item_code')
        salary__ = get_index_in_template('diary', 'salary')
        invested__ = get_index_in_template('diary', 'invested_')
        cash__ = get_index_in_template('diary', 'cash_')
        total__ = get_index_in_template('diary', 'total_')
        parts__ = [
            get_index_in_template('diary', 'robert_'),
            get_index_in_template('diary', 'ariadna_')
        ]

        last_row_data__ = crud_driver(parent, 'diary', 'read', {})
        last_row_data = build_data_template() if len(
            last_row_data__) == 0 else last_row_data__[-1]
        last_row_data = build_data_template(
        ) if len(data_len__) > len(last_row_data) else last_row_data
        data = build_data_template()

        # this block  is for preventing sales form to be submitted with  invalid data
        # protect against zero items sale
        if self.ui.cantidadVendidaComboBox.currentIndex() == 0:
            selfCloseInterface(
                'No esta permitido vender "cero" {},defina una cantidad adecuada antes de hacer la operacion'
                .format(self.ui.nombreDelProductoComboBox.currentText()), 8, 3,
                'Venta Denegada: CANTIDAD INCORRECTA',
                'la menor cantidad admitida es 1, si no puede, significa que el producto se ha agotado'
            )
            self.init_ui(parent)  # init ui for clean zero items...
            return
            # protect against low price sales
        minimum_sell_price = self.ui.cantidadVendidaComboBox.currentIndex(
        ) * float(self.combo_data[
            self.ui.codigoDelProductoComboBox.currentIndex()][3])
        if self.ui.precioDeVentaDoubleSpinBox.value() < minimum_sell_price:
            low_price_switch = {'switch': False}
            low_price_warn = MessageBox(
                lambda: low_price_switch.update({'switch': True}),
                'Esta seguro de que desea vender {} {} por ${:,.2f} ??'
                '\nel precio minimo para esta cantidad es ${:,.2f}.'
                '\nSi realiza la venta a este precio ocasiona perdidas !!'.
                format(self.ui.cantidadVendidaComboBox.currentText(),
                       self.ui.nombreDelProductoComboBox.currentText(),
                       self.ui.precioDeVentaDoubleSpinBox.value(),
                       minimum_sell_price), 'w',
                'Advertencia: Venta por debajo del precio de costo',
                '\n\n Esta accion es intencional y desea continuar??')
            low_price_warn.show()
            if not low_price_switch.get('switch'):
                return
                # protect against sale more than on_stock
        on_stock__ = int(
            crud_driver(
                parent, 'stock', 'read', {
                    'field': 'item_code',
                    'operator': '=',
                    'value':
                    (self.ui.codigoDelProductoComboBox.currentText(), )
                })[0][get_index_in_template('stock', 'on_stock')])
        if on_stock__ < 1:
            selfCloseInterface(
                'El producto {} no existe en el inventario en este momento,'
                'revise el nombre del producto antes de hacer la operacion'.
                format(self.ui.nombreDelProductoComboBox.currentText()), 8, 3,
                'Venta Denegada: PRODUCTO NO EXISTE',
                'Es muy probable que el producto se haya agotado en la ultima entrada. Verifique el nombre otra vez'
            )
            self.init_ui(parent)  # init ui for clean zero items...
            return

        data[date__] = parent.date_session
        data[is_new__] = False
        data[is_sale__] = True
        data[
            is_consignation__] = self.ui.codigoDelProductoComboBox.currentText(
            )[0] == 'c'
        data[quantity__] = self.ui.cantidadVendidaComboBox.currentIndex()
        data[item_name__] = self.ui.nombreDelProductoComboBox.currentText()
        data[price__] = minimum_sell_price
        data[sell_price__] = self.ui.precioDeVentaDoubleSpinBox.value()
        data[comments__] = self.ui.comentariosLineEdit.text()
        data[item_code__] = self.ui.codigoDelProductoComboBox.currentText()
        data[salary__] = build_salary(parent, data[sell_price__],
                                      minimum_sell_price)
        # capital cells # touches invested
        data[parts__[0]] = last_row_data[parts__[0]]
        data[parts__[1]] = last_row_data[parts__[1]]
        data[total__] = float(last_row_data[total__])

        data[invested__] = float(last_row_data[invested__]) if \
            data[is_consignation__] else (float(last_row_data[invested__]) - data[price__])

        data[cash__] = data[total__] - data[invested__]

        # this is the secure entry block
        msg_str = 'vender {} {} por ${:,.2f}'.format(data[quantity__],
                                                     data[item_name__],
                                                     data[sell_price__])
        if parent.use_secure_entry:
            confirm = MessageBox(lambda: parent.append_data_to_diary(data),
                                 'Desea confirmar la Entrada?', 'q',
                                 'Confirmar Entrada', msg_str)
            confirm.show()
        else:
            parent.append_data_to_diary(data)
            selfCloseInterface(msg_str, 4, 1, 'Operacion Realizada',
                               'Cambios Insertados en la Base de Datos')

        self.init_ui(parent)
        return
Exemplo n.º 17
0
    def accept_routine(self, parent, is_bulk=False, bulk_data=None):
        # props alias...
        data_len__ = get_template_fields('diary')
        date__ = get_index_in_template('diary', 'date')
        is_new__ = get_index_in_template('diary', 'is_new')
        is_sale__ = get_index_in_template('diary', 'is_sale')
        is_consignation__ = get_index_in_template('diary', 'is_consignation')
        quantity__ = get_index_in_template('diary', 'quantity')
        item_name__ = get_index_in_template('diary', 'item_name')
        price__ = get_index_in_template('diary', 'price')
        sell_price__ = get_index_in_template('diary', 'sell_price')
        comments__ = get_index_in_template('diary', 'comments')
        item_code__ = get_index_in_template('diary', 'item_code')

        # --
        invested__ = get_index_in_template('diary', 'invested_')
        cash__ = get_index_in_template('diary', 'cash_')
        total__ = get_index_in_template('diary', 'total_')
        parts__ = [get_index_in_template('diary', 'robert_'), get_index_in_template('diary', 'ariadna_')]

        last_row_data__ = crud_driver(parent, 'diary', 'read', {})
        last_row_data = build_data_template() if len(last_row_data__) == 0 else last_row_data__[-1]
        last_row_data = build_data_template() if len(data_len__) > len(last_row_data) else last_row_data
        data = build_data_template()

        # this block  is for preventing purchases with no cash
        if last_row_data[cash__] <= 0:
            selfCloseInterface(
                'No esta permitido comprar cuando el saldo de caja es cero, agregue saldo a su caja antes de hacer esta operacion',
                8, 3, 'Compras Denegadas: SIN EFECTIVO',
                'Vaya a:\nMenu Herramientas > Modificar la Inversion\nO presione: CTRL+ALT+M \ny agregue efectivo antes de comprar')
            self.reject()
            parent.ui.actionModificar_la_inversion.trigger()
            return

        data[date__] = parent.date_session
        data[is_new__] = self.ui.nuevoItemPurchaseCheckBox.isChecked() if not is_bulk else True
        data[is_sale__] = False
        data[is_consignation__] = self.ui.itemAConsignacionCheckBox.isChecked() if\
            not is_bulk else not int(bulk_data[0])
        data[quantity__] = self.ui.totalDeItemsCompradosSpinBox.value() if not is_bulk else int(bulk_data[3])
        if not is_bulk:
            data[item_name__] = self.ui.nombreDelItemIncrementadoComboBox.currentText() \
                if not data[is_new__] else self.ui.nombreDelItemCompradoLineEdit.text()
            data[price__] = (self.ui.precioTotalPagadoPorLaCompraDoubleSpinBox.value() / data[quantity__]) \
                if data[is_new__] else self.ui.precioTotalPagadoPorLaCompraDoubleSpinBox.value()
        if is_bulk:
            data[item_name__] = bulk_data[1]
            data[price__] = float(bulk_data[2]) / data[quantity__]

        if any([len(data[item_name__]) < 3, data[price__] == 0]):
            selfCloseInterface(
                'Los datos son incorrectos. Revise la informacion antes de realizar una entrada',
                8, 2, 'Entrada Fallida: DATOS INCORRECTOS',
                'REVISE:\n1- Que el precio no sea cero\n2- Que el articulo tenga un nombre apropiado (mas de 3 letras)'
            )
            return
        data[sell_price__] = 0
        data[comments__] = self.ui.comentariosDeEntradaLineEdit.text()
        data[item_code__] = self.ui.codigoDelItemIncrementadoComboBox.currentText() \
            if not data[is_new__] else build_item_code(data[price__], self.ui.itemAConsignacionCheckBox.isChecked())

        # capital cells # touches invested
        data[parts__[0]] = last_row_data[parts__[0]]
        data[parts__[1]] = last_row_data[parts__[1]]
        data[total__] = float(last_row_data[total__])

        data[invested__] = float(last_row_data[invested__]) if data[is_consignation__] else \
            float(last_row_data[invested__]) + data[quantity__] * data[price__]

        data[cash__] = data[total__] - data[invested__]

        # this block prevents for goes negative funds after purchasing something
        if data[cash__] < 0:
            selfCloseInterface(
                'No esta permitido comprar cuando el monto es mayor que el saldo de caja, agregue saldo a su caja antes de hacer esta operacion',
                8, 3, 'Compras Denegadas: CAPACIDAD EXCEDIDA',
                'Vaya a:\nMenu Herramientas > Modificar la Inversion\nO presione: CTRL+ALT+M \ny agregue efectivo antes de comprar\n\nO reduzca la cantidad de articulos comprados')
            self.reject()
            return

        # this is the secure entry block
        msg_str = 'comprar {} {} por ${:,.2f} cada uno'.format(data[quantity__], data[item_name__], data[price__])
        if parent.use_secure_entry and not is_bulk:
            confirm = MessageBox(
                lambda: parent.append_data_to_diary(data),
                'Desea confirmar la Entrada?', 'q', 'Confirmar Entrada', msg_str
            )
            confirm.show()
        else:
            parent.append_data_to_diary(data)
            if not is_bulk:
                selfCloseInterface(msg_str, 4, 1, 'Operacion Realizada',
                                   'Cambios Insertados en la Base de Datos')

                self.init_ui(parent)
        return