コード例 #1
0
    def __init__(self, screen_size, parent=None):
        super(ClientDialog, self).__init__(parent)
        self.layout = QtGui.QFormLayout(self)
        self.label = QtGui.QLabel('Buscar Cliente')
        self.line_edit_search = QtGui.QLineEdit()
        header_names = ['ID', 'Nombre', 'Apellido', 'Direccion',
                        'Fecha Nacimiento', 'Telefono']
        self.tablemodel = MyTableModel(Cliente, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setModel(self.tablemodel)
        self.layout.addRow(self.label, self.line_edit_search)

        self.button_new_client = QtGui.QPushButton('Nuevo Cliente')
        self.button_new_client.setMaximumWidth(screen_size.height()/6)
        self.layout.addRow(self.button_new_client)
        self.layout.addRow(self.tableview)
        self.tableview.setMinimumSize(screen_size.width() / 2,
                                      screen_size.height() / 4)
        self.buttons = QtGui.QDialogButtonBox(
            QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel,
            QtCore.Qt.Horizontal, self)

        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.button_new_client.clicked.connect(self.new_client)
        self.line_edit_search.textChanged.connect(self.search_client)

        self.layout.addRow(self.buttons)
        self.setLayout(self.layout)
        self.setWindowTitle('Clientes Administrador')
コード例 #2
0
class Show_Box(QDialog):
    def __init__(self, string, parent=None):
        super(Show_Box, self).__init__(parent)

        self.layout_line_table = QtGui.QVBoxLayout()
        self.layout_line_date = QtGui.QHBoxLayout()

        self.date = QLabel('Fecha')
        self.current_date = string
        self.edit_date = QDateEdit(string)
        self.edit_date.setDisplayFormat(('yyyy-MM-dd'))
        self.edit_date.setDisabled(True)
        self.acceptButton = QPushButton("Aceptar")

        header_names = [
            'ID', 'Salgo Anterior', 'Ingreso', 'Egresos', 'Saldo Actual',
            'Fecha de Caja'
        ]

        self.tablemodel = MyTableModel(Caja, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setAlternatingRowColors(True)
        self.tableview.setModel(self.tablemodel)

        string = string.toString("yyyy-MM-dd")
        self.tablemodel.searchCashDay(string)
        self.tableview.resizeColumnsToContents()

        self.layout_line_table.addWidget(self.tableview)
        self.layout_line_date.addWidget(self.date)
        self.layout_line_date.addWidget(self.edit_date)

        self.grid = QGridLayout()
        self.grid.addLayout(self.layout_line_date, 1, 0)
        self.grid.addLayout(self.layout_line_table, 3, 0)
        self.grid.addWidget(self.acceptButton, 8, 0)
        self.setLayout(self.grid)

        desktopSize = QDesktopWidget().screenGeometry()
        self.setFixedSize(desktopSize.width() / 2, desktopSize.height() / 2)
        size = self.size()
        top = (desktopSize.height() / 2) - (size.height() / 2)
        left = (desktopSize.width() / 2) - (size.width() / 2)

        self.move(left, top)
        self.setWindowTitle('Ver Caja')
        self.acceptButton.clicked.connect(self.close)
コード例 #3
0
ファイル: ServicesTab.py プロジェクト: elias174/LibraryElohim
    def search_client_clicked(self):
        indexes = self.tableview.selectedIndexes()
        if len(indexes) < 1:
            QtGui.QMessageBox.critical(
                self, 'Error', 'No se selecciono ningun cliente',
                QtGui.QMessageBox.Ok)
            self.client_id = None
            return
        else:
            client_id = self.tablemodel.get_id_object_alchemy(indexes[0].row())
        self.client_id = client_id

        self.update_last_query()

        header_names = ['ID', 'Tipo', 'Cancelado', 'Monto Total']
        self.table_model_result = MyTableModel(
            Servicio, header_names, self, self.array_data)
        self.tableview_results.setModel(self.table_model_result)
        self.tableview_results.resizeColumnsToContents()
        self.exist_client = True
コード例 #4
0
    def __init__(self, parent=None):
        super(ClientDialog, self).__init__(parent)
        self.layout = QtGui.QFormLayout(self)
        self.label = QtGui.QLabel('Nombre')
        self.last_name = QtGui.QLabel('Apellido')
        self.layout_line_client = QtGui.QHBoxLayout()
        self.line_edit_search = QtGui.QLineEdit()
        self.line_edit_last_name = QtGui.QLineEdit()
        screen_size = QtGui.QApplication.desktop().availableGeometry()

        header_names = ['ID', 'Nombre', 'Apellido', 'DNI']
        self.tablemodel = MyTableModel(Cliente, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setModel(self.tablemodel)
        self.layout_line_client.addWidget(self.label)
        self.layout_line_client.addWidget(self.line_edit_search)
        self.layout_line_client.addWidget(self.last_name)
        self.layout_line_client.addWidget(self.line_edit_last_name)
        self.layout.addRow(self.layout_line_client)

        self.button_new_client = QtGui.QPushButton('Nuevo Cliente')
        self.button_new_client.setMaximumWidth(screen_size.height() / 6)
        self.layout.addRow(self.button_new_client)
        self.layout.addRow(self.tableview)
        self.tableview.setMinimumSize(screen_size.width() / 2,
                                      screen_size.height() / 4)
        self.buttons = QtGui.QDialogButtonBox(
            QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel,
            QtCore.Qt.Horizontal, self)

        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.button_new_client.clicked.connect(self.new_client)
        self.line_edit_search.textChanged.connect(self.search_client)
        self.line_edit_last_name.textChanged.connect(self.last_name_search)

        self.layout.addRow(self.buttons)
        self.setLayout(self.layout)
        self.setWindowTitle('Clientes Administrador')
コード例 #5
0
class Sale_Tab(QtGui.QWidget):
    change_table = QtCore.pyqtSignal()

    def __init__(self):
        super(Sale_Tab, self).__init__()

        self.screenGeometry = QtGui.QApplication.desktop().availableGeometry()
        # Initialize Layout

        # Signal to check total
        self.last_query = (session.query(Producto).limit(12).all())

        self.central_layout = QtGui.QGridLayout()

        self.sale_group = QtGui.QGroupBox(str("Venta"), self)
        self.search_group = QtGui.QGroupBox(str("Busqueda"), self)

        self.central_layout.addWidget(self.sale_group, 0, 0)
        self.central_layout.addWidget(self.search_group, 0, 1)

        self.initialize_sale_group()
        self.initialize_search_group()

        #QtCore.QObject.connect(self.button_group, QtCore.SIGNAL("buttonClicked(int)"),
        #                      self, QtCore.SLOT("ResultButtonClick(int)"))
        self.change_table.connect(self.update_total)
        self.setLayout(self.central_layout)

    def initialize_sale_group(self):
        self.layout_line = QtGui.QFormLayout()
        # First Line
        # self.label_search = QtGui.QLabel("Buscar Producto:", self)
        # self.edit_search = QtGui.QLineEdit(self)
        # self.edit_search.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, 
        #                                                  QtGui.QSizePolicy.Fixed))
        # Second Line
        self.table_items = QtGui.QTableWidget(self)
        self.table_items.setColumnCount(6)
        self.table_items.setRowCount(0)

        self.table_items.setHorizontalHeaderLabels(["ID", "Cantidad", "Producto",
                                                    "P.Unidad", "P.Total",
                                                    "Eliminar"])

        self.layout_line.addRow(self.table_items)

        self.sale_group.setMaximumWidth(self.screenGeometry.width() / 2)
        self.sale_group.setLayout(self.layout_line)

        # third line, 4th line
        self.edit_search_added = QtGui.QLineEdit(self)
        self.label_search_added = QtGui.QLabel("Buscar en Aniadidos:", self)
        self.total_line = QtGui.QLabel("0.00", self)
        self.pay_line = QtGui.QLabel("0.00", self)
        self.layout_line.addRow(self.label_search_added, self.edit_search_added)
        self.layout_line.addRow("Total: ", self.total_line)
        self.layout_line.addRow("A pagar: ", self.pay_line)

        # Line Client
        self.client_label = QtGui.QLabel('1 Cliente Anonimo')
        self.button_client = QtGui.QPushButton('Aniadir Cliente')
        self.button_client.setMaximumWidth(self.screenGeometry.width() / 8)
        self.layout_line.addRow(self.client_label, self.button_client)

        self.button_client.clicked.connect(self.open_dialog_client)
        self.layout_line.addItem(QtGui.QSpacerItem(1, self.screenGeometry.height() / 4))

        self.button_generate_sale = QtGui.QPushButton('Realizar Venta')
        self.button_generate_sale.clicked.connect(self.realease_sale)
        self.layout_line.addRow(self.button_generate_sale)

    def initialize_search_group(self):
        self.layout_line_search = QtGui.QFormLayout()

        self.label_search = QtGui.QLabel("Buscar Producto:", self)
        self.label_type_view = QtGui.QLabel("Tipo de Vista:", self)
        self.results_group = QtGui.QGroupBox(str("Resultados:"), self)

        self.edit_search = QtGui.QLineEdit(self)
        self.combo_type_search = QtGui.QComboBox()
        self.combo_type_search.addItem("Botones")
        self.combo_type_search.addItem("Tabla")
        self.combo_type_search.setMaximumWidth(100)

        self.layout_line_search.addRow(self.label_search, self.edit_search)
        self.layout_line_search.addRow(self.label_type_view, self.combo_type_search)

        header_names = ['ID', 'Categoria', 'Nombre', 'Precio Compra',
                        'Precio Venta', 'Stock', 'Detalle']
        self.tablemodel = MyTableModel(Producto, header_names, self)
        self.layout_results = QtGui.QGridLayout()
        self.results_group.setLayout(self.layout_results)
        self.results_group.setMinimumHeight(self.screenGeometry.height() -
                                            (self.screenGeometry.height() / 3.5))

        def view_buttons():
            QtGui.QWidget().setLayout(self.layout_results)
            self.layout_results = QtGui.QGridLayout()
            self.results_group.setLayout(self.layout_results)
            self.button_group = ResultsButtonGroup(self, self.last_query,
                                                   self.layout_results)
            QtCore.QObject.connect(self.button_group,
                                   QtCore.SIGNAL("buttonClicked(int)"), self,
                                   QtCore.SLOT("ResultButtonClick(int)"))
            self.edit_search.textChanged.connect(self.on_search_edit_changed)

        def view_table():
            self.tableview = QTableView()
            self.button_add_table = QtGui.QPushButton('Aniadir')
            self.tableview.setModel(self.tablemodel)
            QtGui.QWidget().setLayout(self.layout_results)
            self.layout_results = QtGui.QVBoxLayout()
            self.layout_results.addWidget(self.tableview)
            self.layout_results.addWidget(self.button_add_table)
            self.results_group.setLayout(self.layout_results)
            self.results_group.setMinimumHeight(self.screenGeometry.height() -
                                                (self.screenGeometry.height() / 3.5))
            self.edit_search.textChanged.connect(self.on_search_table_edit_changed)
            self.button_add_table.clicked.connect(self.add_selected_rows)

        def change_results_view(index):
            try:
                self.edit_search.textChanged.disconnect()
            except TypeError:
                pass
            if index is 0:
                view_buttons()
            elif index is 1:
                view_table()

        self.layout_line_search.addRow(self.results_group)

        self.search_group.setLayout(self.layout_line_search)
        self.edit_search_added.textChanged.connect(self.on_search_edit_added_changed)
        self.combo_type_search.activated.connect(change_results_view)
        view_buttons()

    def add_selected_rows(self):
        indexes = self.tableview.selectedIndexes()
        for index in indexes:
            product_id = self.tablemodel.get_id_object_alchemy(index.row())
            self.ResultButtonClick(product_id)

    def open_dialog_client(self):
        if self.client_label.text() != '1 Cliente Anonimo':
            self.button_client.setText('Aniadir Cliente')
            self.client_label.setText('1 Cliente Anonimo')
        else:
            id_client, result = ClientDialog.get_client(self)
            if result and id_client:
                client = session.query(Cliente).get(id_client)
                self.client_label.setText('%s %s %s' % (str(client.id),
                                                        client.nombre,
                                                        client.apellido))
                self.button_client.setText('Eliminar Cliente')

    @QtCore.pyqtSlot(int)
    def ResultButtonClick(self, id):
        product = session.query(Producto).get(id)
        if product.stock < 1:
            QtGui.QMessageBox.critical(self, 'Error',
                                       'No hay stock de este producto',
                                       QtGui.QMessageBox.Ok)
            return
        product_id = str(product.id)
        items = self.table_items.findItems(product_id, QtCore.Qt.MatchExactly)
        if items:
            ok = QtGui.QMessageBox.question(self, u'Doble Producto %s'
                                            % str(product.nombre),
                                            "Desea Agregarlo de nuevo?",
                                            QtGui.QMessageBox.Yes,
                                            QtGui.QMessageBox.No)
            if ok == QtGui.QMessageBox.Yes:
                row_item = items[0].row()
                widget_spin = self.table_items.cellWidget(row_item, 1)
                val = (widget_spin.value() + 1)
                if SaleApi.get_quantity_product(product.id) >= val:
                    widget_spin.setValue(val)
                    qty = float(val)
                    new_value = str(float(self.table_items.item(row_item, 3).text()) * qty)
                    self.table_items.item(row_item, 4).setText(new_value)
                    self.change_table.emit()
                else:
                    QtGui.QMessageBox.critical(self,
                                               'Error',
                                               'No hay mas stock de este producto',
                                               QtGui.QMessageBox.Ok)
            else:
                return
        else:
            self.add_product_table(product)

    def on_search_table_edit_changed(self, string):
        self.tablemodel.setFilter('nombre', string)

    def on_search_edit_changed(self, string):
        text_query = '%'+unicode(string.toUtf8(), encoding="UTF-8")+'%'
        self.last_query = (session.query(Producto)
                           .filter(Producto.nombre.like(text_query)).all())
        for i in reversed(range(self.layout_results.count())):
            self.layout_results.itemAt(i).widget().setParent(None)
        self.button_group.refresh(self.last_query)

    def on_search_edit_added_changed(self, string):
        for row in xrange(self.table_items.rowCount()):
                self.table_items.showRow(row)
        if string != '':
            to_hide = []
            items = [item.row()
                     for item in self.table_items.findItems(string, QtCore.Qt.MatchContains)
                     if item.column() == 2]
            for row in xrange(self.table_items.rowCount()):
                if not (row in items):
                    self.table_items.hideRow(row)

    def delete_row(self):
        button = QtGui.qApp.focusWidget()
        index = self.table_items.indexAt(button.pos())
        self.table_items.removeRow(index.row())
        self.change_table.emit()

    def add_product_table(self, product):
        self.i = self.table_items.rowCount()

        self.table_items.insertRow(self.i)

        button = QtGui.QPushButton()
        button.clicked.connect(self.delete_row)
        button.setStyleSheet("background-color: rgba(255, 255, 255, 0);")
        button.setIcon(QtGui.QIcon('icons/delete-128.png'))

        def quantity_changed(val):
            old_value = spinbox.value()
            spin = QtGui.qApp.focusWidget()
            try:
                row = self.table_items.indexAt(spin.pos()).row()
            except AttributeError:
                return
            qty = float(val)
            new_value = str(float(self.table_items.item(row, 3).text()) * qty)
            self.table_items.setItem(row, 4, QtGui.QTableWidgetItem(new_value))
            self.change_table.emit()

        spinbox = QtGui.QSpinBox()
        spinbox.setValue(1)
        spinbox.setMinimum(1)
        spinbox.setMaximum(SaleApi.get_quantity_product(product.id))

        spinbox.valueChanged.connect(quantity_changed)

        product_item = QtGui.QTableWidgetItem(str(product.id))
        product_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.table_items.setItem(self.i, 0, product_item)

        self.table_items.setCellWidget(self.i, 1, spinbox)

        product_name = QtGui.QTableWidgetItem(str(product.nombre))
        product_name.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.table_items.setItem(self.i, 2, product_name)

        product_price_sale = QtGui.QTableWidgetItem(str(product.precio_venta))
        product_price_sale.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.table_items.setItem(self.i, 3, product_price_sale)

        product_price_sale_total = QtGui.QTableWidgetItem(str(product.precio_venta))
        product_price_sale_total.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
        self.table_items.setItem(self.i, 4, product_price_sale_total)

        self.table_items.setCellWidget(self.i, 5, button)

        self.change_table.emit()

    def update_total(self):
        index_price = 4
        price = 0
        for row in xrange(self.table_items.rowCount()):
            item = self.table_items.item(row, index_price)
            price += float(item.text())
        self.total_line.setText(QtCore.QString(str(price)))

    def clear_table(self):
        while self.table_items.rowCount() > 0:
            self.table_items.removeRow(0)
        self.table_items.setRowCount(0)
        self.change_table.emit()

    def realease_sale(self):
        result = QtGui.QMessageBox.question(self, 'Confirmar',
                                            'Realizar Venta?',
                                            QtGui.QMessageBox.Yes,
                                            QtGui.QMessageBox.No)
        if result == QMessageBox.Yes:
            index_id = 0
            index_quantity = 1
            client_id = int(str(self.client_label.text()).split(' ')[0])
            price_total = float(str(self.total_line.text()))
            if price_total > float(0):
                sale = SaleApi(price_total, client_id)
                sale.generate_factura()
                for row in xrange(self.table_items.rowCount()):
                    item_id = int(self.table_items.item(row, index_id).text())
                    quantity = self.table_items.cellWidget(row, index_quantity).value()
                    try:
                        sale.add_detail(item_id, quantity)
                    except AssertionError:
                        QtGui.QMessageBox.critical(self, 'Error',
                                                   'Algo salio mal, venta anulada',
                                                   QtGui.QMessageBox.Ok)
                        return
                sale.save_sale()
                QtGui.QMessageBox.information(self, 'Finalizado', 'Venta Guardada')
                # sale.print_factura()
                QtGui.QMessageBox.information(self, 'Finalizado', 'Ticket Imprimido')
                self.clear_table()
                QtGui.QMessageBox.information(self, 'Finalizado', 'Venta Finalizada')

            else:
                QtGui.QMessageBox.critical(self, 'Error',
                                           'Venta vacia, no es posible realizar',
                                           QtGui.QMessageBox.Ok)
                return
        else:
            return
コード例 #6
0
    def initialize_search_group(self):
        self.layout_line_search = QtGui.QFormLayout()

        self.label_search = QtGui.QLabel("Buscar Producto:", self)
        self.label_type_view = QtGui.QLabel("Tipo de Vista:", self)
        self.results_group = QtGui.QGroupBox(str("Resultados:"), self)

        self.edit_search = QtGui.QLineEdit(self)
        self.combo_type_search = QtGui.QComboBox()
        self.combo_type_search.addItem("Botones")
        self.combo_type_search.addItem("Tabla")
        self.combo_type_search.setMaximumWidth(100)

        self.layout_line_search.addRow(self.label_search, self.edit_search)
        self.layout_line_search.addRow(self.label_type_view, self.combo_type_search)

        header_names = ['ID', 'Categoria', 'Nombre', 'Precio Compra',
                        'Precio Venta', 'Stock', 'Detalle']
        self.tablemodel = MyTableModel(Producto, header_names, self)
        self.layout_results = QtGui.QGridLayout()
        self.results_group.setLayout(self.layout_results)
        self.results_group.setMinimumHeight(self.screenGeometry.height() -
                                            (self.screenGeometry.height() / 3.5))

        def view_buttons():
            QtGui.QWidget().setLayout(self.layout_results)
            self.layout_results = QtGui.QGridLayout()
            self.results_group.setLayout(self.layout_results)
            self.button_group = ResultsButtonGroup(self, self.last_query,
                                                   self.layout_results)
            QtCore.QObject.connect(self.button_group,
                                   QtCore.SIGNAL("buttonClicked(int)"), self,
                                   QtCore.SLOT("ResultButtonClick(int)"))
            self.edit_search.textChanged.connect(self.on_search_edit_changed)

        def view_table():
            self.tableview = QTableView()
            self.button_add_table = QtGui.QPushButton('Aniadir')
            self.tableview.setModel(self.tablemodel)
            QtGui.QWidget().setLayout(self.layout_results)
            self.layout_results = QtGui.QVBoxLayout()
            self.layout_results.addWidget(self.tableview)
            self.layout_results.addWidget(self.button_add_table)
            self.results_group.setLayout(self.layout_results)
            self.results_group.setMinimumHeight(self.screenGeometry.height() -
                                                (self.screenGeometry.height() / 3.5))
            self.edit_search.textChanged.connect(self.on_search_table_edit_changed)
            self.button_add_table.clicked.connect(self.add_selected_rows)

        def change_results_view(index):
            try:
                self.edit_search.textChanged.disconnect()
            except TypeError:
                pass
            if index is 0:
                view_buttons()
            elif index is 1:
                view_table()

        self.layout_line_search.addRow(self.results_group)

        self.search_group.setLayout(self.layout_line_search)
        self.edit_search_added.textChanged.connect(self.on_search_edit_added_changed)
        self.combo_type_search.activated.connect(change_results_view)
        view_buttons()
コード例 #7
0
    def initialize_search_group(self):
        self.layout_line_main = QtGui.QGridLayout()
        self.layout_line_radio = QtGui.QHBoxLayout()
        self.layout_line_search = QtGui.QHBoxLayout()
        self.layout_line_table = QtGui.QVBoxLayout()
        self.layout_line_gain = QtGui.QHBoxLayout()
        self.layout_line_expenses = QtGui.QHBoxLayout()

        self.search_bill_today = QRadioButton("Ver Facturas de Hoy")
        self.search_bill_today.setToolTip(
            "Buscar en Todas las Facturas que se realizaron hoy")
        self.search_bill_name = QRadioButton("Buscar Factura por ID")
        self.search_bill_name.setToolTip(
            "Buscar en Todas las Facturas pero por su ID")
        self.search_bill_day = QRadioButton("Buscar Factura por Dia")
        self.search_bill_day.setToolTip(
            "Buscar en Todas las Facturas dada una fecha")
        self.searh_name = QtGui.QLabel("Buscador ", self)
        self.edit_search = QtGui.QLineEdit(self)
        self.edit_date = QDateEdit(datetime.now())
        self.edit_date.setCalendarPopup(True)
        self.edit_date.setMaximumWidth(self.screenGeometry.width() / 7)
        self.edit_date.setDisplayFormat(('yyyy-MM-dd'))
        self.edit_search_name = QtGui.QLineEdit(self)
        self.edit_search_name.hide()
        self.edit_date.hide()

        self.search_bill_today.setChecked(True)

        self.search_bill_today.toggled.connect(self.add_searcher)
        self.search_bill_day.toggled.connect(self.add_date_searcher)
        self.search_bill_name.toggled.connect(self.add_searcher_name)

        self.day_gain = QtGui.QLabel("Ganancia del Dia ", self)
        self.day_expenses = QtGui.QLabel("Gastos del Dia ", self)
        self.edit_day_gain = QtGui.QLineEdit(self)
        self.edit_day_gain.setDisabled(True)
        self.edit_day_expenses = QtGui.QLineEdit(self)
        self.edit_day_expenses.setDisabled(True)

        self.button_add_table = QtGui.QPushButton('Ver Detalle de Factura')
        self.button_add_table.setToolTip(
            "Ver ganacia, productos vendidos, servicios de una factura")
        self.button_add_table.clicked.connect(self.view_detail_product)

        self.button_add_gain = QtGui.QPushButton("Agregar Ingreso", self)
        self.button_add_gain.setToolTip(
            "Agregar cualquier tipo de ingreso a la caja")
        self.button_add_gain.clicked.connect(self.add_gain)

        self.button_add_expense = QtGui.QPushButton("Agregar Gasto", self)
        self.button_add_expense.setToolTip(
            "Agregar cualquier tipo de gasto que salga de caja")
        self.button_add_expense.clicked.connect(self.add_expense)

        self.button_detail_gain = QtGui.QPushButton("Detalles de Ingresos",
                                                    self)
        self.button_detail_gain.clicked.connect(self.detail_gain)
        self.button_detail_gain.setToolTip(
            "Ver los ingresos agregados (monto, fecha y detalle)")

        self.button_detail_expense = QtGui.QPushButton("Detalles de Gastos",
                                                       self)
        self.button_detail_expense.clicked.connect(self.detail_expense)
        self.button_detail_expense.setToolTip(
            "Ver los gastos agregados(monto, fecha y detalle)")

        self.button_show_box = QtGui.QPushButton("Estado de Caja del Dia",
                                                 self)
        self.button_show_box.clicked.connect(self.show_box)
        self.button_show_box.hide()
        self.button_show_box.setToolTip("Ver estado de la caja")

        header_names = ['ID', 'Cliente', 'Fecha']
        self.tablemodel = MyTableModel(Factura, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setAlternatingRowColors(True)
        self.tableview.setModel(self.tablemodel)
        self.tableview.horizontalHeader().setResizeMode(
            QtGui.QHeaderView.Stretch)

        self.layout_line_radio.addWidget(self.search_bill_today)
        self.layout_line_radio.addWidget(self.search_bill_day)
        self.layout_line_radio.addWidget(self.search_bill_name)
        self.layout_line_search.addWidget(self.searh_name)
        self.layout_line_search.addWidget(self.edit_search)
        self.layout_line_search.addWidget(self.edit_date)
        self.layout_line_search.addWidget(self.edit_search_name)
        self.layout_line_gain.addWidget(self.day_gain)
        self.layout_line_gain.addWidget(self.edit_day_gain)
        self.layout_line_expenses.addWidget(self.day_expenses)
        self.layout_line_expenses.addWidget(self.edit_day_expenses)
        self.layout_line_expenses.addWidget(self.button_add_gain)
        self.layout_line_expenses.addWidget(self.button_add_expense)
        self.layout_line_expenses.addWidget(self.button_detail_gain)
        self.layout_line_expenses.addWidget(self.button_detail_expense)
        self.layout_line_table.addWidget(self.tableview)
        self.layout_line_main.addLayout(self.layout_line_radio, 1, 1)
        self.layout_line_main.addLayout(self.layout_line_search, 2, 1)
        self.layout_line_main.addLayout(self.layout_line_table, 3, 1)
        self.layout_line_main.addWidget(self.button_add_table, 4, 1)
        self.layout_line_main.addLayout(self.layout_line_gain, 5, 1)
        self.layout_line_main.addLayout(self.layout_line_expenses, 6, 1)
        self.layout_line_main.addWidget(self.button_show_box, 7, 1)

        self.layout_line_search.addStretch()
        self.layout_line_search.setSpacing(20)

        self.refresh_box_today()
        self.update_all_search()
        self.search_group.setLayout(self.layout_line_main)
        self.edit_search.textChanged.connect(self.on_search_table_edit_changed)
        self.edit_search_name.textChanged.connect(
            self.on_search_table_by_name_changed)
        self.edit_date.dateChanged.connect(
            self.on_search_table_by_date_changed)
コード例 #8
0
class Administrator_Tab(QtGui.QWidget):
    change_table = QtCore.pyqtSignal()

    def __init__(self):
        super(Administrator_Tab, self).__init__()

        self.screenGeometry = QtGui.QApplication.desktop().availableGeometry()
        self.last_query = (session.query(Producto).limit(20).all())
        self.central_layout = QtGui.QGridLayout()
        self.search_group = QtGui.QGroupBox(str("Busqueda"), self)
        self.control_singleton = False
        self.toolbar = QtGui.QToolBar('Options', self)
        self.toolbar.setStyleSheet("border: none")
        self.toolbar.setIconSize(QtCore.QSize(51, 51))

        self.icon_gainings = QtGui.QPixmap('icons/gainings')
        self.action_export_excel = self.toolbar.addAction(
            QtGui.QIcon(self.icon_gainings), 'Mostrar Reporte Ganancias',
            self.report_gainings_table)
        self.icon_excel = QtGui.QPixmap('icons/excel')
        self.action_export_excel = self.toolbar.addAction(
            QtGui.QIcon(self.icon_excel), 'Exportar Reporte Ganancias Excel',
            self.export_excel)

        self.central_layout.addWidget(self.toolbar, 0, 0)
        self.central_layout.addWidget(self.search_group, 1, 0)
        self.initialize_search_group()
        self.setLayout(self.central_layout)

    def report_gainings_table(self):
        ReportExportDialog.get_report(screensize=self.screenGeometry,
                                      type_report='table',
                                      parent=self)

    def export_excel(self):
        # ReportExportDialog.get_report(screensize=self.screenGeometry,
        #                               type_report='xlsx', parent=self)
        QtGui.QMessageBox.warning(self, 'En desarrollo',
                                  'Caracteristica aun en desarrollo',
                                  QtGui.QMessageBox.Yes)

    def initialize_search_group(self):
        self.layout_line_main = QtGui.QGridLayout()
        self.layout_line_radio = QtGui.QHBoxLayout()
        self.layout_line_search = QtGui.QHBoxLayout()
        self.layout_line_table = QtGui.QVBoxLayout()
        self.layout_line_gain = QtGui.QHBoxLayout()
        self.layout_line_expenses = QtGui.QHBoxLayout()

        self.search_bill_today = QRadioButton("Ver Facturas de Hoy")
        self.search_bill_today.setToolTip(
            "Buscar en Todas las Facturas que se realizaron hoy")
        self.search_bill_name = QRadioButton("Buscar Factura por ID")
        self.search_bill_name.setToolTip(
            "Buscar en Todas las Facturas pero por su ID")
        self.search_bill_day = QRadioButton("Buscar Factura por Dia")
        self.search_bill_day.setToolTip(
            "Buscar en Todas las Facturas dada una fecha")
        self.searh_name = QtGui.QLabel("Buscador ", self)
        self.edit_search = QtGui.QLineEdit(self)
        self.edit_date = QDateEdit(datetime.now())
        self.edit_date.setCalendarPopup(True)
        self.edit_date.setMaximumWidth(self.screenGeometry.width() / 7)
        self.edit_date.setDisplayFormat(('yyyy-MM-dd'))
        self.edit_search_name = QtGui.QLineEdit(self)
        self.edit_search_name.hide()
        self.edit_date.hide()

        self.search_bill_today.setChecked(True)

        self.search_bill_today.toggled.connect(self.add_searcher)
        self.search_bill_day.toggled.connect(self.add_date_searcher)
        self.search_bill_name.toggled.connect(self.add_searcher_name)

        self.day_gain = QtGui.QLabel("Ganancia del Dia ", self)
        self.day_expenses = QtGui.QLabel("Gastos del Dia ", self)
        self.edit_day_gain = QtGui.QLineEdit(self)
        self.edit_day_gain.setDisabled(True)
        self.edit_day_expenses = QtGui.QLineEdit(self)
        self.edit_day_expenses.setDisabled(True)

        self.button_add_table = QtGui.QPushButton('Ver Detalle de Factura')
        self.button_add_table.setToolTip(
            "Ver ganacia, productos vendidos, servicios de una factura")
        self.button_add_table.clicked.connect(self.view_detail_product)

        self.button_add_gain = QtGui.QPushButton("Agregar Ingreso", self)
        self.button_add_gain.setToolTip(
            "Agregar cualquier tipo de ingreso a la caja")
        self.button_add_gain.clicked.connect(self.add_gain)

        self.button_add_expense = QtGui.QPushButton("Agregar Gasto", self)
        self.button_add_expense.setToolTip(
            "Agregar cualquier tipo de gasto que salga de caja")
        self.button_add_expense.clicked.connect(self.add_expense)

        self.button_detail_gain = QtGui.QPushButton("Detalles de Ingresos",
                                                    self)
        self.button_detail_gain.clicked.connect(self.detail_gain)
        self.button_detail_gain.setToolTip(
            "Ver los ingresos agregados (monto, fecha y detalle)")

        self.button_detail_expense = QtGui.QPushButton("Detalles de Gastos",
                                                       self)
        self.button_detail_expense.clicked.connect(self.detail_expense)
        self.button_detail_expense.setToolTip(
            "Ver los gastos agregados(monto, fecha y detalle)")

        self.button_show_box = QtGui.QPushButton("Estado de Caja del Dia",
                                                 self)
        self.button_show_box.clicked.connect(self.show_box)
        self.button_show_box.hide()
        self.button_show_box.setToolTip("Ver estado de la caja")

        header_names = ['ID', 'Cliente', 'Fecha']
        self.tablemodel = MyTableModel(Factura, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setAlternatingRowColors(True)
        self.tableview.setModel(self.tablemodel)
        self.tableview.horizontalHeader().setResizeMode(
            QtGui.QHeaderView.Stretch)

        self.layout_line_radio.addWidget(self.search_bill_today)
        self.layout_line_radio.addWidget(self.search_bill_day)
        self.layout_line_radio.addWidget(self.search_bill_name)
        self.layout_line_search.addWidget(self.searh_name)
        self.layout_line_search.addWidget(self.edit_search)
        self.layout_line_search.addWidget(self.edit_date)
        self.layout_line_search.addWidget(self.edit_search_name)
        self.layout_line_gain.addWidget(self.day_gain)
        self.layout_line_gain.addWidget(self.edit_day_gain)
        self.layout_line_expenses.addWidget(self.day_expenses)
        self.layout_line_expenses.addWidget(self.edit_day_expenses)
        self.layout_line_expenses.addWidget(self.button_add_gain)
        self.layout_line_expenses.addWidget(self.button_add_expense)
        self.layout_line_expenses.addWidget(self.button_detail_gain)
        self.layout_line_expenses.addWidget(self.button_detail_expense)
        self.layout_line_table.addWidget(self.tableview)
        self.layout_line_main.addLayout(self.layout_line_radio, 1, 1)
        self.layout_line_main.addLayout(self.layout_line_search, 2, 1)
        self.layout_line_main.addLayout(self.layout_line_table, 3, 1)
        self.layout_line_main.addWidget(self.button_add_table, 4, 1)
        self.layout_line_main.addLayout(self.layout_line_gain, 5, 1)
        self.layout_line_main.addLayout(self.layout_line_expenses, 6, 1)
        self.layout_line_main.addWidget(self.button_show_box, 7, 1)

        self.layout_line_search.addStretch()
        self.layout_line_search.setSpacing(20)

        self.refresh_box_today()
        self.update_all_search()
        self.search_group.setLayout(self.layout_line_main)
        self.edit_search.textChanged.connect(self.on_search_table_edit_changed)
        self.edit_search_name.textChanged.connect(
            self.on_search_table_by_name_changed)
        self.edit_date.dateChanged.connect(
            self.on_search_table_by_date_changed)

    def refresh_box_today(self):
        self.day = '%' + str(date.today()) + '%'

        self.query_expenses = (session.query(func.sum(Gasto.monto)).filter(
            Gasto.fecha.like(self.day)).scalar())

        self.query_gain_bill = (session.query(
            Detalle, func.sum(Detalle.precio_total)).join(Factura).filter(
                Factura.fecha.like(self.day)).first())

        self.query_gain = (session.query(func.sum(Ingreso.monto)).filter(
            Ingreso.fecha.like(self.day)).scalar())

        if not self.query_expenses:
            self.edit_day_expenses.setText("0.00")
        else:
            self.edit_day_expenses.setText(str(self.query_expenses))

        if not self.query_gain_bill[1] and not self.query_gain:
            self.edit_day_gain.setText('0.00')
        elif not self.query_gain_bill[1]:
            self.edit_day_gain.setText(str(self.query_gain))
        elif not self.query_gain:
            self.edit_day_gain.setText(str(self.query_gain_bill[1]))
        else:
            self.edit_day_gain.setText(
                str(self.query_gain_bill[1] + self.query_gain))

    def refresh_box_day(self):
        string = self.edit_date.date()

        self.day = ('%' + unicode(string.toString("yyyy-MM-dd").toUtf8(),
                                  encoding="UTF-8") + '%')

        self.query_gain_bill = (session.query(
            Detalle, func.sum(Detalle.precio_total)).join(Factura).filter(
                Factura.fecha.like(self.day)).first())

        self.query_gain = (session.query(func.sum(Ingreso.monto)).filter(
            Ingreso.fecha.like(self.day)).scalar())

        self.query_expenses = (session.query(func.sum(Gasto.monto)).filter(
            Gasto.fecha.like(self.day)).scalar())

        if self.query_expenses is None:
            self.edit_day_expenses.setText("0.00")
        else:
            self.edit_day_expenses.setText(str(self.query_expenses))

        if not self.query_gain_bill[1] and not self.query_gain:
            self.edit_day_gain.setText('0.00')

        elif not self.query_gain_bill[1]:
            self.edit_day_gain.setText(str(self.query_gain))
        elif not self.query_gain:
            self.edit_day_gain.setText(str(self.query_gain_bill[1]))
        else:
            self.edit_day_gain.setText(
                str(self.query_gain_bill[1] + self.query_gain))

    def update_all_search(self):
        if self.search_bill_today.isChecked():
            string = self.edit_search.text()
            self.tablemodel.searchBillToday(string)
            self.refresh_box_today()
        elif self.search_bill_name.isChecked():
            string = self.edit_search_name.text()
            self.tablemodel.setFilter('id', string)
        elif self.search_bill_day.isChecked():
            string = self.edit_date.text()
            self.tablemodel.searchBillDay(string)
            self.refresh_box_day()

    def on_search_table_edit_changed(self, string):
        if self.search_bill_today.isChecked():
            self.tablemodel.searchBillToday(string)
            self.refresh_box_today()

    def on_search_table_by_name_changed(self, string):
        if self.search_bill_name.isChecked():
            self.tablemodel.setFilter('id', string)

    def on_search_table_by_date_changed(self, string):
        if self.search_bill_day.isChecked():
            string = string.toString("yyyy-MM-dd")
            self.tablemodel.searchBillDay(string)
            self.refresh_box_day()

    def add_searcher(self):
        self.edit_date.hide()
        self.edit_search_name.hide()
        self.edit_search.show()
        self.button_show_box.hide()
        self.button_add_expense.show()
        self.button_add_gain.show()
        self.button_detail_expense.show()
        self.button_detail_gain.show()
        self.edit_day_gain.show()
        self.edit_day_expenses.show()
        self.day_expenses.show()
        self.day_gain.show()
        self.refresh_box_today()
        self.update_all_search()

    def add_date_searcher(self):
        self.edit_search.hide()
        self.edit_search_name.hide()
        self.edit_date.show()
        self.button_show_box.show()
        self.button_add_expense.hide()
        self.button_add_gain.hide()
        self.button_detail_expense.show()
        self.button_detail_gain.show()
        self.edit_day_gain.show()
        self.edit_day_expenses.show()
        self.day_expenses.show()
        self.day_gain.show()
        self.update_all_search()

    def add_searcher_name(self):
        self.edit_date.hide()
        self.edit_search_name.show()
        self.edit_search.hide()
        self.button_show_box.hide()
        self.button_add_expense.hide()
        self.button_add_gain.hide()
        self.button_detail_expense.hide()
        self.button_detail_gain.hide()
        self.edit_day_gain.hide()
        self.edit_day_expenses.hide()
        self.day_expenses.hide()
        self.day_gain.hide()
        self.update_all_search()

    def add_expense(self):
        data, window = GenericFormDialog.get_data(Gasto, self)
        if window:
            question = QtGui.QMessageBox.question(self, 'Confirmar',
                                                  'Desea agregar este gasto?',
                                                  QtGui.QMessageBox.Yes,
                                                  QtGui.QMessageBox.No)
            if question == QtGui.QMessageBox.No:
                return
            session.add(Gasto(data['detalle'], data['monto'], data['fecha']))
            session.commit()
            QtGui.QMessageBox.information(self, 'Finalizado', 'Gasto guardado')
            self.close_box(0, data['monto'], data['fecha'])
        self.update_all_search()

    def add_gain(self):
        data, window = GenericFormDialog.get_data(Ingreso, self)
        if window:
            question = QtGui.QMessageBox.question(
                self, 'Confirmar', 'Desea agregar este ingreso?',
                QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            if question == QtGui.QMessageBox.No:
                return
            session.add(Ingreso(data['detalle'], data['monto'], data['fecha']))
            session.commit()
            QtGui.QMessageBox.information(self, 'Finalizado',
                                          'Ingreso guardado')
            self.close_box(1, data['monto'], data['fecha'])
        self.update_all_search()

    def detail_expense(self):
        if self.search_bill_today.isChecked():
            today = str(date.today())
            Detail_Expense(False, today, self).exec_()
        if self.search_bill_day.isChecked():
            string = self.edit_date.date()
            Detail_Expense(True, string, self).exec_()

    def detail_gain(self):
        if self.search_bill_today.isChecked():
            today = str(date.today())
            Detail_Gain(False, today, self).exec_()
        if self.search_bill_day.isChecked():
            string = self.edit_date.date()
            Detail_Gain(True, string, self).exec_()

    def view_detail_product(self):
        try:
            indexes = self.tableview.selectedIndexes()
            for index in indexes:
                factura_id = self.tablemodel.get_id_object_alchemy(index.row())
            Detail_Bill(factura_id, self).exec_()
        except:
            QtGui.QMessageBox.information(self, 'Error',
                                          'Por favor seleccione una Factura')

    def close_box(self, type_action, balance, current_day):
        self.last_query = (session.query(Caja).order_by(desc(Caja.id)).all())
        if (len(self.last_query) == 0):
            previous_balance = 0
            if (type_action):
                current_balance = float(balance) + float(previous_balance)
                today = current_day
                session.add(
                    Caja(previous_balance, balance, 0, current_balance, today))
                session.commit()
            else:
                current_balance = float(previous_balance) - float(balance)
                today = current_day
                session.add(
                    Caja(previous_balance, 0, balance, current_balance, today))
                session.commit()
        else:
            previous_balance = self.last_query[0].saldo_actual
            if (type_action):
                current_balance = float(balance) + float(previous_balance)
                today = current_day
                session.add(
                    Caja(previous_balance, balance, 0, current_balance, today))
                session.commit()
            else:
                current_balance = float(previous_balance) - float(balance)
                today = current_day
                session.add(
                    Caja(previous_balance, 0, balance, current_balance, today))
                session.commit()

    def show_box(self):
        string = self.edit_date.date()
        Show_Box(string, self).exec_()
コード例 #9
0
ファイル: SaleTab.py プロジェクト: elias174/LibraryElohim
class Sale_Tab(QtGui.QWidget):
    change_table = QtCore.pyqtSignal()
    sale_realeased = QtCore.pyqtSignal(float)

    def __init__(self):
        super(Sale_Tab, self).__init__()

        self.screenGeometry = QtGui.QApplication.desktop().availableGeometry()
        # Initialize Layout

        # Signal to check total
        self.last_query = (session.query(Producto).limit(LIMIT_RESULTS).all())

        self.central_layout = QtGui.QGridLayout()

        self.sale_group = QtGui.QGroupBox(str("Venta"), self)
        self.search_group = QtGui.QGroupBox(str("Busqueda"), self)

        self.central_layout.addWidget(self.sale_group, 0, 0)
        self.central_layout.addWidget(self.search_group, 0, 1)

        self.initialize_sale_group()
        self.initialize_search_group()

        #QtCore.QObject.connect(self.button_group, QtCore.SIGNAL("buttonClicked(int)"),
        #                      self, QtCore.SLOT("ResultButtonClick(int)"))
        self.change_table.connect(self.update_total)
        self.setLayout(self.central_layout)

    def update_last_query(self):
        self.last_query = (session.query(Producto).limit(LIMIT_RESULTS).all())

    def initialize_sale_group(self):
        self.layout_line = QtGui.QFormLayout()
        # First Line
        # self.label_search = QtGui.QLabel("Buscar Producto:", self)
        # self.edit_search = QtGui.QLineEdit(self)
        # self.edit_search.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed,
        #                                                  QtGui.QSizePolicy.Fixed))
        # Second Line
        self.table_items = QtGui.QTableWidget(self)
        self.table_items.setColumnCount(6)
        self.table_items.setRowCount(0)
        self.table_items.setMinimumHeight(self.screenGeometry.height() / 2)
        self.layout_line.addRow(self.table_items)
        self.table_items.setHorizontalHeaderLabels(
            ["ID", "Cantidad", "Producto", "P.Unidad", "P.Total", "Eliminar"])

        self.sale_group.setMaximumWidth(self.screenGeometry.width() / 2)
        self.sale_group.setLayout(self.layout_line)

        # third line, 4th line
        self.edit_search_added = QtGui.QLineEdit(self)
        self.label_search_added = QtGui.QLabel("Buscar en Aniadidos:", self)
        self.total_line = QtGui.QLabel("0.00", self)
        self.pay_line = QtGui.QLabel("0.00", self)
        self.layout_line.addRow(self.label_search_added,
                                self.edit_search_added)
        self.layout_line.addRow("Total: ", self.total_line)
        self.layout_line.addRow("A pagar: ", self.pay_line)

        # Line Client
        self.client_label = QtGui.QLabel('1 Cliente Anonimo')
        self.button_client = QtGui.QPushButton('Aniadir Cliente')
        self.button_client.setMaximumWidth(self.screenGeometry.width() / 8)
        self.layout_line.addRow(self.client_label, self.button_client)

        self.button_client.clicked.connect(self.open_dialog_client)

        self.button_generate_sale = QtGui.QPushButton('Realizar Venta')
        self.button_clean_table = QtGui.QPushButton('Limpiar')

        self.label_list = QtGui.QLabel('Administrar Listas:')
        self.button_save_list = QtGui.QPushButton('Guardar como Lista')
        self.button_load_list = QtGui.QPushButton('Cargar Lista')
        self.button_erase_list = QtGui.QPushButton('Eliminar una Lista')

        self.button_load_list.clicked.connect(self.load_list)
        self.button_save_list.clicked.connect(self.save_list)
        self.button_generate_sale.clicked.connect(self.realease_sale)
        self.button_clean_table.clicked.connect(self.clear_table)
        self.button_erase_list.clicked.connect(self.erase_list)

        self.layout_line.addRow(self.table_items)
        self.layout_line.addRow(self.button_generate_sale)
        self.layout_line.addRow(self.button_clean_table)

        self.group_list = QtGui.QGroupBox('Administrar Listas')

        self.layout_lists = QtGui.QHBoxLayout()
        self.layout_lists.addWidget(self.button_save_list)
        self.layout_lists.addWidget(self.button_load_list)
        self.layout_lists.addWidget(self.button_erase_list)
        self.group_list.setLayout(self.layout_lists)

        self.layout_line.addRow(self.group_list)

    def initialize_search_group(self):
        self.layout_line_search = QtGui.QFormLayout()

        self.label_search = QtGui.QLabel("Buscar Producto:", self)
        self.label_type_view = QtGui.QLabel("Tipo de Vista:", self)
        self.results_group = QtGui.QGroupBox(str("Resultados:"), self)

        self.edit_search = QtGui.QLineEdit(self)
        self.combo_type_search = QtGui.QComboBox()
        self.combo_type_search.addItem("Botones")
        self.combo_type_search.addItem("Tabla")
        self.combo_type_search.setMaximumWidth(100)

        self.layout_line_search.addRow(self.label_search, self.edit_search)
        self.layout_line_search.addRow(self.label_type_view,
                                       self.combo_type_search)

        header_names = [
            'ID', 'Categoria', 'Nombre', 'Precio Compra', 'Precio Venta',
            'Stock', 'Detalle'
        ]
        self.tablemodel = MyTableModel(Producto, header_names, self)
        self.layout_results = QtGui.QGridLayout()
        self.results_group.setLayout(self.layout_results)
        self.results_group.setMinimumHeight(self.screenGeometry.height() -
                                            (self.screenGeometry.height() /
                                             3.5))

        def view_buttons():
            QtGui.QWidget().setLayout(self.layout_results)
            self.layout_results = QtGui.QGridLayout()
            self.results_group.setLayout(self.layout_results)
            self.button_group = ResultsButtonGroup(self, self.last_query,
                                                   self.layout_results)
            QtCore.QObject.connect(self.button_group,
                                   QtCore.SIGNAL("buttonClicked(int)"), self,
                                   QtCore.SLOT("ResultButtonClick(int)"))
            self.edit_search.textChanged.connect(self.on_search_edit_changed)

        def view_table():
            self.tableview = QTableView()
            self.button_add_table = QtGui.QPushButton('Aniadir')
            self.tableview.setAlternatingRowColors(True)
            self.tableview.setModel(self.tablemodel)
            self.tableview.resizeColumnsToContents()
            QtGui.QWidget().setLayout(self.layout_results)
            self.layout_results = QtGui.QVBoxLayout()
            self.layout_results.addWidget(self.tableview)
            self.layout_results.addWidget(self.button_add_table)
            self.results_group.setLayout(self.layout_results)
            self.results_group.setMinimumHeight(self.screenGeometry.height() -
                                                (self.screenGeometry.height() /
                                                 3.5))
            self.edit_search.textChanged.connect(
                self.on_search_table_edit_changed)
            self.button_add_table.clicked.connect(self.add_selected_rows)

        def change_results_view(index):
            try:
                self.edit_search.textChanged.disconnect()
            except TypeError:
                pass
            if index is 0:
                view_buttons()
            elif index is 1:
                view_table()

        self.layout_line_search.addRow(self.results_group)

        self.search_group.setLayout(self.layout_line_search)
        self.edit_search_added.textChanged.connect(
            self.on_search_edit_added_changed)
        self.combo_type_search.activated.connect(change_results_view)
        view_buttons()

    def add_selected_rows(self):
        indexes = self.tableview.selectedIndexes()
        for index in indexes:
            product_id = self.tablemodel.get_id_object_alchemy(index.row())
            self.ResultButtonClick(product_id)

    def open_dialog_client(self):
        if self.client_label.text() != '1 Cliente Anonimo':
            self.button_client.setText('Aniadir Cliente')
            self.client_label.setText('1 Cliente Anonimo')
        else:
            id_client, result = ClientDialog.get_client(self)
            if result and id_client:
                client = session.query(Cliente).get(id_client)
                self.client_label.setText(
                    '%s %s %s' %
                    (str(client.id), client.nombre, client.apellido))
                self.button_client.setText('Eliminar Cliente')

    @QtCore.pyqtSlot(int)
    def ResultButtonClick(self, id):
        product = session.query(Producto).get(id)
        if product.stock < 1:
            QtGui.QMessageBox.critical(self, 'Error',
                                       'No hay stock de este producto',
                                       QtGui.QMessageBox.Ok)
            return
        product_id = str(product.id)
        items = self.table_items.findItems(product_id, QtCore.Qt.MatchExactly)
        if items:
            ok = QtGui.QMessageBox.question(
                self, u'Doble Producto %s' % str(product.nombre),
                "Desea Agregarlo de nuevo?", QtGui.QMessageBox.Yes,
                QtGui.QMessageBox.No)
            if ok == QtGui.QMessageBox.Yes:
                row_item = items[0].row()
                widget_spin = self.table_items.cellWidget(row_item, 1)
                val = (widget_spin.value() + 1)
                if SaleApi.get_quantity_product(product.id) >= val:
                    # to avoid that other function tries to change the value
                    widget_spin.blockSignals(True)
                    widget_spin.setValue(val)
                    qty = float(val)
                    new_value = str(
                        float(self.table_items.item(row_item, 3).text()) * qty)
                    self.table_items.item(row_item, 4).setText(new_value)
                    self.change_table.emit()
                    widget_spin.blockSignals(False)
                    return
                else:
                    QtGui.QMessageBox.critical(
                        self, 'Error', 'No hay mas stock de este producto',
                        QtGui.QMessageBox.Ok)
            else:
                return
        else:
            self.add_product_table(product)

    def on_search_table_edit_changed(self, string):
        self.tablemodel.setFilter('nombre', string)

    def on_search_edit_changed(self, string):
        text_query = '%' + unicode(string.toUtf8(), encoding="UTF-8") + '%'
        self.last_query = (session.query(Producto).filter(
            Producto.nombre.like(text_query),
            Producto.stock > MIN_PRODUCTS).limit(LIMIT_RESULTS).all())

        for i in reversed(range(self.layout_results.count())):
            self.layout_results.itemAt(i).widget().setParent(None)
        self.button_group.refresh(self.last_query)

    def on_search_edit_added_changed(self, string):
        for row in xrange(self.table_items.rowCount()):
            self.table_items.showRow(row)
        if string != '':
            to_hide = []
            items = [
                item.row() for item in self.table_items.findItems(
                    string, QtCore.Qt.MatchContains) if item.column() == 2
            ]
            for row in xrange(self.table_items.rowCount()):
                if not (row in items):
                    self.table_items.hideRow(row)

    def delete_row(self):
        button = QtGui.qApp.focusWidget()
        index = self.table_items.indexAt(button.pos())
        self.table_items.removeRow(index.row())
        self.change_table.emit()

    def add_product_table(self, product, quantity=1):
        stock_product = SaleApi.get_quantity_product(product.id)
        if stock_product < quantity:
            QMessageBox.critical(
                self, 'Error',
                'No tenemos Stock para %s no es posible agregarlo' %
                product.nombre, QtGui.QMessageBox.Ok)
            return
        self.i = self.table_items.rowCount()
        self.table_items.insertRow(self.i)

        button = QtGui.QPushButton()
        button.clicked.connect(self.delete_row)
        button.setStyleSheet("background-color: rgba(255, 255, 255, 0);")
        button.setIcon(QtGui.QIcon('icons/delete-128.png'))

        def quantity_changed(val):
            old_value = spinbox.value()
            spin = QtGui.qApp.focusWidget()
            try:
                row = self.table_items.indexAt(spin.pos()).row()
            except AttributeError:
                return
            qty = float(val)
            new_value = str(float(self.table_items.item(row, 3).text()) * qty)
            self.table_items.setItem(row, 4, QtGui.QTableWidgetItem(new_value))
            self.change_table.emit()

        spinbox = QtGui.QSpinBox()
        spinbox.setValue(quantity)
        spinbox.setMinimum(1)
        spinbox.setMaximum(stock_product)

        spinbox.valueChanged.connect(quantity_changed)

        product_item = QtGui.QTableWidgetItem(str(product.id))
        product_item.setFlags(QtCore.Qt.ItemIsSelectable
                              | QtCore.Qt.ItemIsEnabled)
        self.table_items.setItem(self.i, 0, product_item)

        self.table_items.setCellWidget(self.i, 1, spinbox)

        product_name = QtGui.QTableWidgetItem(str(product.nombre))
        product_name.setFlags(QtCore.Qt.ItemIsSelectable
                              | QtCore.Qt.ItemIsEnabled)
        self.table_items.setItem(self.i, 2, product_name)

        product_price_sale = QtGui.QTableWidgetItem(str(product.precio_venta))
        product_price_sale.setFlags(QtCore.Qt.ItemIsSelectable
                                    | QtCore.Qt.ItemIsEnabled)
        self.table_items.setItem(self.i, 3, product_price_sale)

        product_price_sale_total = QtGui.QTableWidgetItem(
            str(product.precio_venta * quantity))
        product_price_sale_total.setFlags(QtCore.Qt.ItemIsSelectable
                                          | QtCore.Qt.ItemIsEnabled)

        self.table_items.setItem(self.i, 4, product_price_sale_total)

        self.table_items.setCellWidget(self.i, 5, button)

        self.table_items.resizeColumnsToContents()
        self.change_table.emit()

    def update_total(self):
        index_price = 4
        price = 0
        for row in xrange(self.table_items.rowCount()):
            item = self.table_items.item(row, index_price)
            price += float(item.text())
        self.total_line.setText(QtCore.QString(str(price)))

    def clear_table(self):
        while self.table_items.rowCount() > 0:
            self.table_items.removeRow(0)
        self.table_items.setRowCount(0)
        self.change_table.emit()

    def save_list(self):

        if self.table_items.rowCount() < 1:
            QtGui.QMessageBox.critical(
                self, 'Error', 'Debe agregar por lo menos un producto',
                QtGui.QMessageBox.Ok)
            return

        message = QtGui.QMessageBox(self)
        message.setText('Como desea guardar la lista?')
        message.setIcon(QtGui.QMessageBox.Question)
        button_update = QtGui.QPushButton('Actualizar')
        message.addButton(button_update, QtGui.QMessageBox.ActionRole)
        button_new = QtGui.QPushButton('Crear Nuevo')
        message.addButton(button_new, QtGui.QMessageBox.ActionRole)
        message.addButton(QtGui.QMessageBox.Cancel)

        message.exec_()

        if message.clickedButton() == button_update:
            lists = [
                '%s %s' % (str(e.id), str(e.nombre))
                for e in session.query(Lista).all()
            ]
            if len(lists) < 1:
                QtGui.QMessageBox.critical(self, 'Error',
                                           'No existen listas guardadas',
                                           QtGui.QMessageBox.Ok)
                return
            combo = AdvComboBox(self)
            combo.addItems(lists)
            data, result = GenericFormDialog.get_data(Lista,
                                                      parent=self,
                                                      fields=[''],
                                                      customs_widgets=[
                                                          ('Lista', combo)
                                                      ],
                                                      title='Actualizar Lista')
            if result:
                question = QtGui.QMessageBox.question(
                    self, 'Confirmar', 'Desea sobreescribir esta lista?',
                    QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
                if question == QtGui.QMessageBox.No:
                    return
                id_list = data['Lista']
                elements = str(self.extract_id_quantity_table())
                current_list = session.query(Lista).get(id_list)
                current_list.elementos = elements
                session.commit()
                QtGui.QMessageBox.information(self, 'Finalizado',
                                              'Lista guardada')

        elif message.clickedButton() == button_new:
            data, result = GenericFormDialog.get_data(Lista,
                                                      parent=self,
                                                      fields=['nombre'])
            if result:
                name_list = data['nombre']
                elements = str(self.extract_id_quantity_table())
                new_list = Lista(name_list, elements)
                session.add(new_list)
                session.commit()
                QtGui.QMessageBox.information(self, 'Finalizado',
                                              'Lista guardada')

    def load_list(self):
        lists = [
            '%s %s' % (str(e.id), str(e.nombre))
            for e in session.query(Lista).all()
        ]
        if len(lists) < 1:
            QtGui.QMessageBox.critical(self, 'Error',
                                       'No existen listas guardadas',
                                       QtGui.QMessageBox.Ok)
            return
        combo = AdvComboBox(self)
        combo.addItems(lists)
        data, result = GenericFormDialog.get_data(Lista,
                                                  parent=self,
                                                  fields=[''],
                                                  customs_widgets=[('Lista',
                                                                    combo)],
                                                  title='Cargar Lista')
        if result:
            question = QtGui.QMessageBox.question(
                self, 'Confirmar', 'Cargar esta lista eliminara los productos '
                'agregados, desea continuar?', QtGui.QMessageBox.Yes,
                QtGui.QMessageBox.No)
            if question == QtGui.QMessageBox.No:
                return
            self.clear_table()
            id_list = data['Lista']
            current_list = session.query(Lista).get(id_list)
            elements = ast.literal_eval(current_list.elementos)
            not_availables = []
            for e in elements:
                self.add_product_table(session.query(Producto).get(e[0]), e[1])

    def erase_list(self):
        lists = [
            '%s %s' % (str(e.id), str(e.nombre))
            for e in session.query(Lista).all()
        ]
        if len(lists) < 1:
            QtGui.QMessageBox.critical(self, 'Error',
                                       'No existen listas guardadas',
                                       QtGui.QMessageBox.Ok)
            return
        combo = AdvComboBox(self)
        combo.addItems(lists)
        data, result = GenericFormDialog.get_data(Lista,
                                                  parent=self,
                                                  fields=[''],
                                                  customs_widgets=[('Lista',
                                                                    combo)],
                                                  title='Borrar una Lista')
        if result:
            id_list = data['Lista']
            current_list = session.query(Lista).get(id_list)
            question = QtGui.QMessageBox.question(
                self, 'Confirmar', 'Eliminar Lista: %s?' % current_list.nombre,
                QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            if question == QtGui.QMessageBox.No:
                return
            session.delete(current_list)
            session.commit()
            QtGui.QMessageBox.information(self, 'Finalizado',
                                          'Lista Eliminada')

    def extract_id_quantity_table(self):
        data = []
        index_id = 0
        index_quantity = 1
        for row in xrange(self.table_items.rowCount()):
            item_id = int(self.table_items.item(row, index_id).text())
            quantity = self.table_items.cellWidget(row, index_quantity).value()
            data.append((item_id, quantity))
        return data

    def realease_sale(self):
        result = QtGui.QMessageBox.question(self, 'Confirmar',
                                            'Realizar Venta?',
                                            QtGui.QMessageBox.Yes,
                                            QtGui.QMessageBox.No)
        if result == QMessageBox.Yes:
            index_id = 0
            index_quantity = 1
            client_id = int(str(self.client_label.text()).split(' ')[0])
            price_total = float(str(self.total_line.text()))
            if price_total > float(0):
                sale = SaleApi(price_total, client_id)
                sale.generate_factura()
                for row in xrange(self.table_items.rowCount()):
                    item_id = int(self.table_items.item(row, index_id).text())
                    quantity = self.table_items.cellWidget(
                        row, index_quantity).value()
                    try:
                        sale.add_detail(item_id, quantity)
                    except AssertionError:
                        QtGui.QMessageBox.critical(
                            self, 'Error', 'Algo salio mal, venta anulada',
                            QtGui.QMessageBox.Ok)
                        return
                sale.save_sale()
                QtGui.QMessageBox.information(self, 'Finalizado',
                                              'Venta Guardada')
                sale.print_factura(self)
                QtGui.QMessageBox.information(self, 'Finalizado',
                                              'Ticket Imprimido')
                self.clear_table()
                QtGui.QMessageBox.information(self, 'Finalizado',
                                              'Venta Finalizada')
                self.sale_realeased.emit(price_total)
                self.update_last_query()
                self.button_group.refresh(self.last_query)

            else:
                QtGui.QMessageBox.critical(
                    self, 'Error', 'Venta vacia, no es posible realizar',
                    QtGui.QMessageBox.Ok)
                return
        else:
            return
コード例 #10
0
ファイル: SaleTab.py プロジェクト: elias174/LibraryElohim
    def initialize_search_group(self):
        self.layout_line_search = QtGui.QFormLayout()

        self.label_search = QtGui.QLabel("Buscar Producto:", self)
        self.label_type_view = QtGui.QLabel("Tipo de Vista:", self)
        self.results_group = QtGui.QGroupBox(str("Resultados:"), self)

        self.edit_search = QtGui.QLineEdit(self)
        self.combo_type_search = QtGui.QComboBox()
        self.combo_type_search.addItem("Botones")
        self.combo_type_search.addItem("Tabla")
        self.combo_type_search.setMaximumWidth(100)

        self.layout_line_search.addRow(self.label_search, self.edit_search)
        self.layout_line_search.addRow(self.label_type_view,
                                       self.combo_type_search)

        header_names = [
            'ID', 'Categoria', 'Nombre', 'Precio Compra', 'Precio Venta',
            'Stock', 'Detalle'
        ]
        self.tablemodel = MyTableModel(Producto, header_names, self)
        self.layout_results = QtGui.QGridLayout()
        self.results_group.setLayout(self.layout_results)
        self.results_group.setMinimumHeight(self.screenGeometry.height() -
                                            (self.screenGeometry.height() /
                                             3.5))

        def view_buttons():
            QtGui.QWidget().setLayout(self.layout_results)
            self.layout_results = QtGui.QGridLayout()
            self.results_group.setLayout(self.layout_results)
            self.button_group = ResultsButtonGroup(self, self.last_query,
                                                   self.layout_results)
            QtCore.QObject.connect(self.button_group,
                                   QtCore.SIGNAL("buttonClicked(int)"), self,
                                   QtCore.SLOT("ResultButtonClick(int)"))
            self.edit_search.textChanged.connect(self.on_search_edit_changed)

        def view_table():
            self.tableview = QTableView()
            self.button_add_table = QtGui.QPushButton('Aniadir')
            self.tableview.setAlternatingRowColors(True)
            self.tableview.setModel(self.tablemodel)
            self.tableview.resizeColumnsToContents()
            QtGui.QWidget().setLayout(self.layout_results)
            self.layout_results = QtGui.QVBoxLayout()
            self.layout_results.addWidget(self.tableview)
            self.layout_results.addWidget(self.button_add_table)
            self.results_group.setLayout(self.layout_results)
            self.results_group.setMinimumHeight(self.screenGeometry.height() -
                                                (self.screenGeometry.height() /
                                                 3.5))
            self.edit_search.textChanged.connect(
                self.on_search_table_edit_changed)
            self.button_add_table.clicked.connect(self.add_selected_rows)

        def change_results_view(index):
            try:
                self.edit_search.textChanged.disconnect()
            except TypeError:
                pass
            if index is 0:
                view_buttons()
            elif index is 1:
                view_table()

        self.layout_line_search.addRow(self.results_group)

        self.search_group.setLayout(self.layout_line_search)
        self.edit_search_added.textChanged.connect(
            self.on_search_edit_added_changed)
        self.combo_type_search.activated.connect(change_results_view)
        view_buttons()
コード例 #11
0
class ClientDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(ClientDialog, self).__init__(parent)
        self.layout = QtGui.QFormLayout(self)
        self.label = QtGui.QLabel('Nombre')
        self.last_name = QtGui.QLabel('Apellido')
        self.layout_line_client = QtGui.QHBoxLayout()
        self.line_edit_search = QtGui.QLineEdit()
        self.line_edit_last_name = QtGui.QLineEdit()
        screen_size = QtGui.QApplication.desktop().availableGeometry()

        header_names = ['ID', 'Nombre', 'Apellido', 'DNI']
        self.tablemodel = MyTableModel(Cliente, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setModel(self.tablemodel)
        self.layout_line_client.addWidget(self.label)
        self.layout_line_client.addWidget(self.line_edit_search)
        self.layout_line_client.addWidget(self.last_name)
        self.layout_line_client.addWidget(self.line_edit_last_name)
        self.layout.addRow(self.layout_line_client)

        self.button_new_client = QtGui.QPushButton('Nuevo Cliente')
        self.button_new_client.setMaximumWidth(screen_size.height() / 6)
        self.layout.addRow(self.button_new_client)
        self.layout.addRow(self.tableview)
        self.tableview.setMinimumSize(screen_size.width() / 2,
                                      screen_size.height() / 4)
        self.buttons = QtGui.QDialogButtonBox(
            QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel,
            QtCore.Qt.Horizontal, self)

        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.button_new_client.clicked.connect(self.new_client)
        self.line_edit_search.textChanged.connect(self.search_client)
        self.line_edit_last_name.textChanged.connect(self.last_name_search)

        self.layout.addRow(self.buttons)
        self.setLayout(self.layout)
        self.setWindowTitle('Clientes Administrador')

    def search_client(self, string):
        self.tablemodel.searchClient(string, self.line_edit_last_name.text())

    def last_name_search(self, string):
        self.tablemodel.searchClient(self.line_edit_search.text(), string)

    def new_client(self):
        data, result = GenericFormDialog.get_data(Cliente, self)
        if result:
            new_client = Cliente(
                data['nombre'],
                data['apellido'],
                data['dni'],
            )
            session.add(new_client)
            session.commit()
            #QtCore.QAbstractTableModel.dataChanged()
            self.tableview.model().refresh_data()

    def get_id_selected_client(self):
        indexes = self.tableview.selectedIndexes()
        if len(indexes) < 1:
            client_id = None
        else:
            client_id = self.tablemodel.get_id_object_alchemy(indexes[0].row())
        return client_id

    @staticmethod
    def get_client(parent=None):
        dialog = ClientDialog(parent)
        result = dialog.exec_()
        id_client = dialog.get_id_selected_client()
        return (id_client, result == QtGui.QDialog.Accepted)
コード例 #12
0
ファイル: ServicesTab.py プロジェクト: elias174/LibraryElohim
    def __init__(self):
        super(ServicesTab, self).__init__()
        self.client_id = None
        self.last_query_services = None
        self.array_data = []
        self.exist_client = False

        self.layout = QtGui.QFormLayout(self)
        self.layout_line_client = QtGui.QHBoxLayout()
        self.screenGeometry = QtGui.QApplication.desktop().availableGeometry()

        self.label = QtGui.QLabel('Nombre')
        self.last_name = QtGui.QLabel('Apellido')

        self.line_edit_search = QtGui.QLineEdit()
        self.line_edit_last_name = QtGui.QLineEdit()

        header_names = ['ID', 'Nombre', 'Apellido', 'DNI']
        self.tablemodel = MyTableModel(Cliente, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setAlternatingRowColors(True)
        self.tableview.setModel(self.tablemodel)
        self.tableview.setMaximumHeight(self.screenGeometry.height() / 6)
        self.tableview.setColumnWidth(1, self.screenGeometry.width() * 0.3)
        self.tableview.setColumnWidth(2, self.screenGeometry.width() * 0.3)
        self.tableview.setColumnWidth(3, self.screenGeometry.width() * 0.15)

        self.button_new_type_service = QtGui.QPushButton('Nuevo Servicio')
        self.button_new_type_service.setMaximumWidth(
            self.screenGeometry.width() / 6)
        self.button_new_type_service.setMinimumWidth(
            self.screenGeometry.width() / 6)

        self.button_search_client = QtGui.QPushButton('Buscar Cliente')
        self.button_search_client.setMaximumWidth(
            self.screenGeometry.width() / 4)
        self.button_new_client = QtGui.QPushButton('Nuevo Cliente')
        self.button_new_client.setMaximumWidth(
            self.screenGeometry.width() / 4)

        self.button_clean = QtGui.QPushButton('Limpiar')

        self.third_contain_layout = QtGui.QHBoxLayout()
        self.third_contain_layout.addWidget(self.button_search_client)
        self.third_contain_layout.addWidget(self.button_new_client)
        self.third_contain_layout.setSpacing(self.screenGeometry.width() / 2)

        self.first_contain_layout = QtGui.QHBoxLayout()
        self.first_contain_layout.addWidget(
            self.button_new_type_service, 0, QtCore.Qt.AlignRight)

        self.line_edit_search.textChanged.connect(
            self.auto_complete_client_search)
        self.line_edit_last_name.textChanged.connect(
            self.auto_complete_last_name_search)
        self.button_search_client.clicked.connect(
            self.search_client_clicked)
        self.button_new_type_service.clicked.connect(
            self.new_service)
        self.button_clean.clicked.connect(
            self.clean_results)
        self.button_new_client.clicked.connect(
            self.new_client)

        self.group_results = QtGui.QGroupBox(str("Resultados Busqueda"))
        self.layout_results = QtGui.QHBoxLayout()
        self.layout_buttons_results = QtGui.QVBoxLayout()
        self.tableview_results = QtGui.QTableView()
        self.button_add_payment = QtGui.QPushButton("Agregar Pago")
        self.button_cancel_payment = QtGui.QPushButton("Cancelar Pago")
        self.button_new_service_payment = QtGui.QPushButton(
            "Nuevo Pago Servicio")

        self.button_add_payment.setMinimumWidth(
            self.screenGeometry.width() / 6)
        self.button_cancel_payment.setMinimumWidth(
            self.screenGeometry.width() / 6)

        self.button_new_service_payment.setMinimumWidth(
            self.screenGeometry.width() / 6)

        self.layout_filter = QtGui.QFormLayout()
        self.label_filter_years = QtGui.QLabel("Mostrar solo del Anio:")
        self.year_filter_results = QtGui.QComboBox()
        self.year_filter_results.addItems(LIST_YEARS)
        self.year_filter_results.setCurrentIndex(INDEX_CURRENT_YEAR)
        self.layout_filter.addRow(self.label_filter_years, self.year_filter_results)

        self.layout_buttons_results.addWidget(self.button_add_payment)
        self.layout_buttons_results.addWidget(self.button_cancel_payment)
        self.layout_buttons_results.addWidget(self.button_new_service_payment)
        self.layout_buttons_results.addLayout(self.layout_filter)

        self.layout_results.addWidget(self.tableview_results)
        self.layout_results.addLayout(self.layout_buttons_results)

        self.group_results.setLayout(self.layout_results)

        self.button_add_payment.clicked.connect(self.add_payment_to_service)
        self.button_cancel_payment.clicked.connect(self.cancel_payment)
        self.button_new_service_payment.clicked.connect(
            self.new_service_payment)

        self.year_filter_results.currentIndexChanged.connect(self.year_filter_changed)

        verticalSpacer = QtGui.QSpacerItem(20, 70, QtGui.QSizePolicy.Minimum,
                                           QSizePolicy.Expanding)
        verticalSpacer_2 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum,
                                             QSizePolicy.Expanding)

        self.layout_line_client.addWidget(self.label)
        self.layout_line_client.addWidget(self.line_edit_search)
        self.layout_line_client.addWidget(self.last_name)
        self.layout_line_client.addWidget(self.line_edit_last_name)
        self.layout.addRow(self.first_contain_layout)
        self.layout.addRow(self.layout_line_client)
        self.layout.addRow(self.tableview)
        self.layout.addRow(self.third_contain_layout)
        self.layout.addItem(verticalSpacer)
        self.layout.addRow(self.group_results)
        self.layout.addItem(verticalSpacer)
        self.layout.addRow(self.button_clean)

        self.setLayout(self.layout)
コード例 #13
0
ファイル: ServicesTab.py プロジェクト: elias174/LibraryElohim
class ServicesTab(QtGui.QWidget):

    service_payment_realeased = QtCore.pyqtSignal(float)

    def __init__(self):
        super(ServicesTab, self).__init__()
        self.client_id = None
        self.last_query_services = None
        self.array_data = []
        self.exist_client = False

        self.layout = QtGui.QFormLayout(self)
        self.layout_line_client = QtGui.QHBoxLayout()
        self.screenGeometry = QtGui.QApplication.desktop().availableGeometry()

        self.label = QtGui.QLabel('Nombre')
        self.last_name = QtGui.QLabel('Apellido')

        self.line_edit_search = QtGui.QLineEdit()
        self.line_edit_last_name = QtGui.QLineEdit()

        header_names = ['ID', 'Nombre', 'Apellido', 'DNI']
        self.tablemodel = MyTableModel(Cliente, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setAlternatingRowColors(True)
        self.tableview.setModel(self.tablemodel)
        self.tableview.setMaximumHeight(self.screenGeometry.height() / 6)
        self.tableview.setColumnWidth(1, self.screenGeometry.width() * 0.3)
        self.tableview.setColumnWidth(2, self.screenGeometry.width() * 0.3)
        self.tableview.setColumnWidth(3, self.screenGeometry.width() * 0.15)

        self.button_new_type_service = QtGui.QPushButton('Nuevo Servicio')
        self.button_new_type_service.setMaximumWidth(
            self.screenGeometry.width() / 6)
        self.button_new_type_service.setMinimumWidth(
            self.screenGeometry.width() / 6)

        self.button_search_client = QtGui.QPushButton('Buscar Cliente')
        self.button_search_client.setMaximumWidth(
            self.screenGeometry.width() / 4)
        self.button_new_client = QtGui.QPushButton('Nuevo Cliente')
        self.button_new_client.setMaximumWidth(
            self.screenGeometry.width() / 4)

        self.button_clean = QtGui.QPushButton('Limpiar')

        self.third_contain_layout = QtGui.QHBoxLayout()
        self.third_contain_layout.addWidget(self.button_search_client)
        self.third_contain_layout.addWidget(self.button_new_client)
        self.third_contain_layout.setSpacing(self.screenGeometry.width() / 2)

        self.first_contain_layout = QtGui.QHBoxLayout()
        self.first_contain_layout.addWidget(
            self.button_new_type_service, 0, QtCore.Qt.AlignRight)

        self.line_edit_search.textChanged.connect(
            self.auto_complete_client_search)
        self.line_edit_last_name.textChanged.connect(
            self.auto_complete_last_name_search)
        self.button_search_client.clicked.connect(
            self.search_client_clicked)
        self.button_new_type_service.clicked.connect(
            self.new_service)
        self.button_clean.clicked.connect(
            self.clean_results)
        self.button_new_client.clicked.connect(
            self.new_client)

        self.group_results = QtGui.QGroupBox(str("Resultados Busqueda"))
        self.layout_results = QtGui.QHBoxLayout()
        self.layout_buttons_results = QtGui.QVBoxLayout()
        self.tableview_results = QtGui.QTableView()
        self.button_add_payment = QtGui.QPushButton("Agregar Pago")
        self.button_cancel_payment = QtGui.QPushButton("Cancelar Pago")
        self.button_new_service_payment = QtGui.QPushButton(
            "Nuevo Pago Servicio")

        self.button_add_payment.setMinimumWidth(
            self.screenGeometry.width() / 6)
        self.button_cancel_payment.setMinimumWidth(
            self.screenGeometry.width() / 6)

        self.button_new_service_payment.setMinimumWidth(
            self.screenGeometry.width() / 6)

        self.layout_filter = QtGui.QFormLayout()
        self.label_filter_years = QtGui.QLabel("Mostrar solo del Anio:")
        self.year_filter_results = QtGui.QComboBox()
        self.year_filter_results.addItems(LIST_YEARS)
        self.year_filter_results.setCurrentIndex(INDEX_CURRENT_YEAR)
        self.layout_filter.addRow(self.label_filter_years, self.year_filter_results)

        self.layout_buttons_results.addWidget(self.button_add_payment)
        self.layout_buttons_results.addWidget(self.button_cancel_payment)
        self.layout_buttons_results.addWidget(self.button_new_service_payment)
        self.layout_buttons_results.addLayout(self.layout_filter)

        self.layout_results.addWidget(self.tableview_results)
        self.layout_results.addLayout(self.layout_buttons_results)

        self.group_results.setLayout(self.layout_results)

        self.button_add_payment.clicked.connect(self.add_payment_to_service)
        self.button_cancel_payment.clicked.connect(self.cancel_payment)
        self.button_new_service_payment.clicked.connect(
            self.new_service_payment)

        self.year_filter_results.currentIndexChanged.connect(self.year_filter_changed)

        verticalSpacer = QtGui.QSpacerItem(20, 70, QtGui.QSizePolicy.Minimum,
                                           QSizePolicy.Expanding)
        verticalSpacer_2 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum,
                                             QSizePolicy.Expanding)

        self.layout_line_client.addWidget(self.label)
        self.layout_line_client.addWidget(self.line_edit_search)
        self.layout_line_client.addWidget(self.last_name)
        self.layout_line_client.addWidget(self.line_edit_last_name)
        self.layout.addRow(self.first_contain_layout)
        self.layout.addRow(self.layout_line_client)
        self.layout.addRow(self.tableview)
        self.layout.addRow(self.third_contain_layout)
        self.layout.addItem(verticalSpacer)
        self.layout.addRow(self.group_results)
        self.layout.addItem(verticalSpacer)
        self.layout.addRow(self.button_clean)

        self.setLayout(self.layout)

    def year_filter_changed(self):
        if not self.exist_client:
            return
        self.search_client_clicked()

    def update_last_query(self):
        current_year_str = str(self.year_filter_results.currentText())

        if current_year_str == 'Todos':
            self.last_query_services = (
                session.query(Detalle.servicio).distinct().join(Factura).
                filter(
                    Detalle.servicio.isnot(None),
                    Factura.cliente == self.client_id
                ).all()
            )

        else:
            current_year = int(current_year_str)
            self.last_query_services = (
                session.query(Detalle.servicio).distinct().join(Factura).
                filter(
                    Detalle.servicio.isnot(None),
                    extract('year', Factura.fecha) == current_year,
                    Factura.cliente == self.client_id
                ).all()
            )

        self.array_data = [session.query(Servicio).get(service)
                           for service in self.last_query_services]

    def search_client_clicked(self):
        indexes = self.tableview.selectedIndexes()
        if len(indexes) < 1:
            QtGui.QMessageBox.critical(
                self, 'Error', 'No se selecciono ningun cliente',
                QtGui.QMessageBox.Ok)
            self.client_id = None
            return
        else:
            client_id = self.tablemodel.get_id_object_alchemy(indexes[0].row())
        self.client_id = client_id

        self.update_last_query()

        header_names = ['ID', 'Tipo', 'Cancelado', 'Monto Total']
        self.table_model_result = MyTableModel(
            Servicio, header_names, self, self.array_data)
        self.tableview_results.setModel(self.table_model_result)
        self.tableview_results.resizeColumnsToContents()
        self.exist_client = True

    def auto_complete_client_search(self, string):
        self.tablemodel.searchClient(string, self.line_edit_last_name.text())

    def auto_complete_last_name_search(self, string):
        self.tablemodel.searchClient(self.line_edit_search.text(), string)

    def new_service(self):
        data, result = GenericFormDialog.get_data(TipoServicio, self)
        if result:
            new_type_service = TipoServicio(
                data['nombre'],
                data['descripcion'],
            )
            session.add(new_type_service)
            session.commit()

    def new_client(self):
        data, result = GenericFormDialog.get_data(Cliente, self)
        if result:
            new_client = Cliente(
                data['nombre'],
                data['apellido'],
                data['dni'],
            )
            session.add(new_client)
            session.commit()
            self.tableview.model().refresh_data()

    def clean_results(self):
        if self.exist_client:
            self.client_id = None
            self.last_query_services = None
            self.array_data = []
            self.exist_client = False
            self.tableview_results.model().clear()
        return

    def cancel_payment(self):
        if not self.exist_client:
            QtGui.QMessageBox.critical(
                self, 'Error', 'Primero Busque un Cliente',
                QtGui.QMessageBox.Ok)
            return

        indexes = self.tableview_results.selectedIndexes()
        if len(indexes) < 1:
            QtGui.QMessageBox.critical(
                self, 'Error', 'No se selecciono ningun servicio',
                QtGui.QMessageBox.Ok)
            return
        row = indexes[0].row()
        service_id = self.table_model_result.get_id_object_alchemy(row)
        service = session.query(Servicio).get(service_id)
        index_type_service = self.table_model_result.index(row, 1)
        type_service = self.table_model_result.data(
            index_type_service, Qt.DisplayRole)
        if service.cancelado:
            QtGui.QMessageBox.information(self, 'Servicio cancelado',
                                          'Este servicio ya esta cancelado')
            return
        cancel_question = (
            QtGui.QMessageBox.question(self, u'Cancelar %s'
                                       % str(type_service),
                                       "Desea Cancelar el pago?",
                                       QtGui.QMessageBox.Yes,
                                       QtGui.QMessageBox.No))
        if cancel_question == QtGui.QMessageBox.Yes:
            service.cancelado = True
            session.add(service)
            session.commit()
            self.update_last_query()
            self.tableview_results.model().refresh_data(self.array_data)

    def add_payment_to_service(self):
        if not self.exist_client:
            QtGui.QMessageBox.critical(
                self, 'Error', 'Primero Busque un Cliente',
                QtGui.QMessageBox.Ok)
            return

        indexes = self.tableview_results.selectedIndexes()
        if len(indexes) < 1:
            QtGui.QMessageBox.critical(
                self, 'Error', 'No se selecciono ningun servicio',
                QtGui.QMessageBox.Ok)
            return
        row = indexes[0].row()
        index_type_service = self.table_model_result.index(row, 1)
        service_id = self.table_model_result.get_id_object_alchemy(row)
        service = session.query(Servicio).get(service_id)
        type_service = self.table_model_result.data(
            index_type_service, Qt.DisplayRole)
        label_service = QtGui.QLabel(str(type_service))
        widget_canceled = AdvCheckBox()
        widget_canceled.setChecked(service.cancelado)

        customs_widgets = [('Servicio:', label_service),
                           ('Cancelado', widget_canceled)]
        fields = ['precio_total']
        data_pay, result_pay = GenericFormDialog.get_data(
            Detalle, self, fields=fields, customs_widgets=customs_widgets)
        if result_pay:
            sale = SaleApi(float(data_pay['precio_total']), self.client_id)
            sale.generate_factura()
            sale.add_detail_service(id_service=service_id,
                                    canceled=data_pay['Cancelado'])
            sale.save_sale()
            QtGui.QMessageBox.information(self, 'Finalizado', 'Pago Guardado')
            sale.print_factura(self)
            QtGui.QMessageBox.information(self, 'Finalizado',
                                          'Ticket Imprimido')
            # very dangerous, we need use the same object session
            session.commit()
            self.update_last_query()
            self.tableview_results.model().refresh_data(self.array_data)
            self.tableview_results.resizeColumnsToContents()
            self.service_payment_realeased.emit(float(data_pay['precio_total']))

    def new_service_payment(self):
        if not self.exist_client:
            QtGui.QMessageBox.critical(
                self, 'Error', 'Primero Busque un Cliente',
                QtGui.QMessageBox.Ok)
            return
        data_type_service = ['%s %s' % (str(e.id), str(e.nombre))
                             for e in session.query(TipoServicio).all()]

        widget_type_service = AdvComboBox()
        widget_type_service.addItems(data_type_service)

        widget_canceled = AdvCheckBox()
        custom_widgets = [('TipoServicio', widget_type_service),
                          ('Cancelado', widget_canceled)]
        fields = ['precio_total']
        data_payment, result_payment = GenericFormDialog.get_data(
            Detalle, self, fields=fields, customs_widgets=custom_widgets)
        if result_payment:
            sale = SaleApi(float(data_payment['precio_total']), self.client_id)
            sale.generate_factura()
            sale.add_detail_service(type_service=data_payment['TipoServicio'],
                                    canceled=data_payment['Cancelado'])
            sale.save_sale()
            QtGui.QMessageBox.information(self, 'Finalizado', 'Pago Guardado')
            sale.print_factura(self)
            QtGui.QMessageBox.information(self, 'Finalizado',
                                          'Ticket Imprimido')

            # I need check why query it's this way
            # self.last_query_services = (
            #     session.query(Detalle.servicio).distinct().join(Factura).
            #     filter_by(cliente=self.client_id).all())
            #
            # self.array_data = [session.query(Servicio).get(service)
            #                    for service in self.last_query_services]
            self.update_last_query()
            self.tableview_results.model().refresh_data(self.array_data)
            self.tableview_results.resizeColumnsToContents()
            self.service_payment_realeased.emit(float(data_payment['precio_total']))
コード例 #14
0
class ClientDialog(QtGui.QDialog):
    def __init__(self, screen_size, parent=None):
        super(ClientDialog, self).__init__(parent)
        self.layout = QtGui.QFormLayout(self)
        self.label = QtGui.QLabel('Buscar Cliente')
        self.line_edit_search = QtGui.QLineEdit()
        header_names = ['ID', 'Nombre', 'Apellido', 'Direccion',
                        'Fecha Nacimiento', 'Telefono']
        self.tablemodel = MyTableModel(Cliente, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setModel(self.tablemodel)
        self.layout.addRow(self.label, self.line_edit_search)

        self.button_new_client = QtGui.QPushButton('Nuevo Cliente')
        self.button_new_client.setMaximumWidth(screen_size.height()/6)
        self.layout.addRow(self.button_new_client)
        self.layout.addRow(self.tableview)
        self.tableview.setMinimumSize(screen_size.width() / 2,
                                      screen_size.height() / 4)
        self.buttons = QtGui.QDialogButtonBox(
            QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel,
            QtCore.Qt.Horizontal, self)

        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)
        self.button_new_client.clicked.connect(self.new_client)
        self.line_edit_search.textChanged.connect(self.search_client)

        self.layout.addRow(self.buttons)
        self.setLayout(self.layout)
        self.setWindowTitle('Clientes Administrador')

    def search_client(self, text):
        self.tablemodel.setFilter('nombre', text)

    def new_client(self):
        data, result = GenericFormDialog.get_data(Cliente, self)
        if result:
            new_client = Cliente(
                data['nombre'],
                data['apellido'],
                data['direccion'],
                data['fecha_nacimiento'],
                data['telefono'],
            )
            session.add(new_client)
            session.commit()
            #QtCore.QAbstractTableModel.dataChanged()
            self.tableview.model().refresh_data()

    def get_id_selected_client(self):
        indexes = self.tableview.selectedIndexes()
        if len(indexes) < 1:
            client_id = None
        else:
            client_id = self.tablemodel.get_id_object_alchemy(indexes[0].row())
        return client_id

    @staticmethod
    def get_client(parent=None):
        dialog = ClientDialog(parent)
        result = dialog.exec_()
        id_client = dialog.get_id_selected_client()
        return (id_client, result == QtGui.QDialog.Accepted)
コード例 #15
0
    def initialize_search_group(self):
        self.layout_line_main = QtGui.QGridLayout()
        self.layout_line_radio = QtGui.QHBoxLayout()
        self.layout_line_search = QtGui.QHBoxLayout()
        self.layout_line_table = QtGui.QVBoxLayout()
        self.layout_line_gain = QtGui.QHBoxLayout()
        self.layout_line_expenses = QtGui.QHBoxLayout()

        self.search_bill_today = QRadioButton("Ver Facturas de Hoy")
        self.search_bill_name = QRadioButton("Buscar Factura por Nombre")
        self.search_bill_day = QRadioButton("Buscar Factura por Dia")
        self.edit_search = QtGui.QLineEdit(self)
        self.edit_date = QDateEdit(datetime.now())
        self.edit_date.setCalendarPopup(True)
        self.edit_date.setMaximumWidth(self.screenGeometry.width() / 8)
        self.edit_date.setDisplayFormat(('yyyy-MM-dd'))
        self.edit_search_name = QtGui.QLineEdit(self)
        self.edit_search_name.hide()
        self.edit_date.hide()

        self.search_bill_today.setChecked(True)

        self.search_bill_today.toggled.connect(self.add_searcher)
        self.search_bill_day.toggled.connect(self.add_date_searcher)
        self.search_bill_name.toggled.connect(self.add_searcher_name)

        self.day_gain = QtGui.QLabel("Ganancia del Dia ", self)
        self.day_expenses = QtGui.QLabel("Gastos del Dia ", self)
        self.edit_day_gain = QtGui.QLineEdit(self)
        self.edit_day_gain.setDisabled(True)
        self.edit_day_expenses = QtGui.QLineEdit(self)
        self.edit_day_expenses.setDisabled(True)
        
        self.button_add_table = QtGui.QPushButton('Ver Detalle de Factura')
        self.button_add_table.clicked.connect(self.view_detail_product)

        self.button_add_expense = QtGui.QPushButton("Agregar Gasto", self)
        self.button_add_expense.clicked.connect(self.add_expense)

        self.button_detail_expense = QtGui.QPushButton("Detalles de Gastos", self)
        self.button_detail_expense.clicked.connect(self.detail_expense)

        self.button_close_box = QtGui.QPushButton("Cerrar Caja de Hoy", self)
        self.button_close_box.clicked.connect(self.close_box)

        self.button_show_box = QtGui.QPushButton("Ver Caja del Dia", self)
        self.button_show_box.clicked.connect(self.show_box)
        self.button_show_box.hide()
        
        header_names = ['ID', 'Factura', 'Fecha']
        self.tablemodel = MyTableModel(Factura, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setAlternatingRowColors(True)
        self.tableview.setModel(self.tablemodel)
        self.tableview.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

        for row in xrange(self.tablemodel.rowCount()):
            self.tableview.openPersistentEditor(self.tablemodel.index(row, 3))

        self.layout_line_radio.addWidget(self.search_bill_today)
        self.layout_line_radio.addWidget(self.search_bill_day)
        self.layout_line_radio.addWidget(self.search_bill_name)
        self.layout_line_search.addWidget(self.edit_search)
        self.layout_line_search.addWidget(self.edit_date)
        self.layout_line_search.addWidget(self.edit_search_name)
        self.layout_line_gain.addWidget(self.day_gain)
        self.layout_line_gain.addWidget(self.edit_day_gain)
        self.layout_line_expenses.addWidget(self.day_expenses)
        self.layout_line_expenses.addWidget(self.edit_day_expenses)
        self.layout_line_expenses.addWidget(self.button_add_expense)
        self.layout_line_expenses.addWidget(self.button_detail_expense)
        self.layout_line_table.addWidget(self.tableview)
        self.layout_line_main.addLayout(self.layout_line_radio, 1, 1)
        self.layout_line_main.addLayout(self.layout_line_search, 2, 1)
        self.layout_line_main.addLayout(self.layout_line_table, 3, 1)
        self.layout_line_main.addWidget(self.button_add_table, 4, 1)
        self.layout_line_main.addLayout(self.layout_line_gain, 5, 1)
        self.layout_line_main.addLayout(self.layout_line_expenses, 6, 1)
        self.layout_line_main.addWidget(self.button_close_box, 7, 1)
        self.layout_line_main.addWidget(self.button_show_box, 7, 1)

        self.refresh_box_today()
        self.search_group.setLayout(self.layout_line_main)
        self.edit_search.textChanged.connect(self.on_search_table_edit_changed)
        self.edit_search_name.textChanged.connect(self.on_search_table_by_name_changed)
        self.edit_date.dateChanged.connect(self.on_search_table_by_date_changed)
コード例 #16
0
class Administrator_Tab(QtGui.QWidget):
    change_table = QtCore.pyqtSignal()

    def __init__(self):
        super(Administrator_Tab, self).__init__()

        self.screenGeometry = QtGui.QApplication.desktop().availableGeometry()
        self.last_query = (session.query(Producto).limit(12).all())
        self.central_layout = QtGui.QGridLayout()
        self.search_group = QtGui.QGroupBox(str("Busqueda"), self)
        self.control_singleton = False
        self.central_layout.addWidget(self.search_group, 0, 0)
        self.initialize_search_group()
        self.setLayout(self.central_layout)
        
    def initialize_search_group(self):
        self.layout_line_main = QtGui.QGridLayout()
        self.layout_line_radio = QtGui.QHBoxLayout()
        self.layout_line_search = QtGui.QHBoxLayout()
        self.layout_line_table = QtGui.QVBoxLayout()
        self.layout_line_gain = QtGui.QHBoxLayout()
        self.layout_line_expenses = QtGui.QHBoxLayout()

        self.search_bill_today = QRadioButton("Ver Facturas de Hoy")
        self.search_bill_name = QRadioButton("Buscar Factura por Nombre")
        self.search_bill_day = QRadioButton("Buscar Factura por Dia")
        self.edit_search = QtGui.QLineEdit(self)
        self.edit_date = QDateEdit(datetime.now())
        self.edit_date.setCalendarPopup(True)
        self.edit_date.setMaximumWidth(self.screenGeometry.width() / 8)
        self.edit_date.setDisplayFormat(('yyyy-MM-dd'))
        self.edit_search_name = QtGui.QLineEdit(self)
        self.edit_search_name.hide()
        self.edit_date.hide()

        self.search_bill_today.setChecked(True)

        self.search_bill_today.toggled.connect(self.add_searcher)
        self.search_bill_day.toggled.connect(self.add_date_searcher)
        self.search_bill_name.toggled.connect(self.add_searcher_name)

        self.day_gain = QtGui.QLabel("Ganancia del Dia ", self)
        self.day_expenses = QtGui.QLabel("Gastos del Dia ", self)
        self.edit_day_gain = QtGui.QLineEdit(self)
        self.edit_day_gain.setDisabled(True)
        self.edit_day_expenses = QtGui.QLineEdit(self)
        self.edit_day_expenses.setDisabled(True)
        
        self.button_add_table = QtGui.QPushButton('Ver Detalle de Factura')
        self.button_add_table.clicked.connect(self.view_detail_product)

        self.button_add_expense = QtGui.QPushButton("Agregar Gasto", self)
        self.button_add_expense.clicked.connect(self.add_expense)

        self.button_detail_expense = QtGui.QPushButton("Detalles de Gastos", self)
        self.button_detail_expense.clicked.connect(self.detail_expense)

        self.button_close_box = QtGui.QPushButton("Cerrar Caja de Hoy", self)
        self.button_close_box.clicked.connect(self.close_box)

        self.button_show_box = QtGui.QPushButton("Ver Caja del Dia", self)
        self.button_show_box.clicked.connect(self.show_box)
        self.button_show_box.hide()
        
        header_names = ['ID', 'Factura', 'Fecha']
        self.tablemodel = MyTableModel(Factura, header_names, self)
        self.tableview = QtGui.QTableView()
        self.tableview.setAlternatingRowColors(True)
        self.tableview.setModel(self.tablemodel)
        self.tableview.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

        for row in xrange(self.tablemodel.rowCount()):
            self.tableview.openPersistentEditor(self.tablemodel.index(row, 3))

        self.layout_line_radio.addWidget(self.search_bill_today)
        self.layout_line_radio.addWidget(self.search_bill_day)
        self.layout_line_radio.addWidget(self.search_bill_name)
        self.layout_line_search.addWidget(self.edit_search)
        self.layout_line_search.addWidget(self.edit_date)
        self.layout_line_search.addWidget(self.edit_search_name)
        self.layout_line_gain.addWidget(self.day_gain)
        self.layout_line_gain.addWidget(self.edit_day_gain)
        self.layout_line_expenses.addWidget(self.day_expenses)
        self.layout_line_expenses.addWidget(self.edit_day_expenses)
        self.layout_line_expenses.addWidget(self.button_add_expense)
        self.layout_line_expenses.addWidget(self.button_detail_expense)
        self.layout_line_table.addWidget(self.tableview)
        self.layout_line_main.addLayout(self.layout_line_radio, 1, 1)
        self.layout_line_main.addLayout(self.layout_line_search, 2, 1)
        self.layout_line_main.addLayout(self.layout_line_table, 3, 1)
        self.layout_line_main.addWidget(self.button_add_table, 4, 1)
        self.layout_line_main.addLayout(self.layout_line_gain, 5, 1)
        self.layout_line_main.addLayout(self.layout_line_expenses, 6, 1)
        self.layout_line_main.addWidget(self.button_close_box, 7, 1)
        self.layout_line_main.addWidget(self.button_show_box, 7, 1)

        self.refresh_box_today()
        self.search_group.setLayout(self.layout_line_main)
        self.edit_search.textChanged.connect(self.on_search_table_edit_changed)
        self.edit_search_name.textChanged.connect(self.on_search_table_by_name_changed)
        self.edit_date.dateChanged.connect(self.on_search_table_by_date_changed)

    def refresh_box_today(self):
        self.day = '%' + str(date.today()) + '%'

        self.query_expenses = (session.query(func.sum(Gasto.monto))
                                .filter(Gasto.fecha.like(self.day)).scalar())

        self.query_gain = (session.query(Detalle, func.sum(Detalle.precio_total))
                            .join(Factura).\
                            filter(Factura.fecha.like(self.day)).first())

        if(self.query_expenses is None):
            self.edit_day_expenses.setText("0.00")
        else:
            self.edit_day_expenses.setText(str(self.query_expenses))

        if(self.query_gain[1] is None):
            self.edit_day_gain.setText('0.00')
        else:
            self.edit_day_gain.setText(str(self.query_gain[1]))
        

    def refresh_box_day(self):
        string = self.edit_date.date()
        self.day = '%'+unicode(string.toString("yyyy-MM-dd").toUtf8(), encoding="UTF-8")+'%'

        #SELECT sum(Detalle.precio_total) FROM Detalle INNER JOIN Factura On Factura.id=Detalle.factura where Factura.fecha LIKE '%2016-08-12%'

        self.query_gain = (session.query(Detalle, func.sum(Detalle.precio_total))
                            .join(Factura).\
                            filter(Factura.fecha.like(self.day)).first())
        self.query_expenses = (session.query(func.sum(Gasto.monto))
                                .filter(Gasto.fecha.like(self.day)).scalar())

        if(self.query_expenses is None):
            self.edit_day_expenses.setText("0.00")
        else:
            self.edit_day_expenses.setText(str(self.query_expenses))

        if(self.query_gain[1] is None):
            self.edit_day_gain.setText('0.00')
        else:
            self.edit_day_gain.setText(str(self.query_gain[1]))
        

    def on_search_table_edit_changed(self, string):
        if self.search_bill_today.isChecked():
            self.tablemodel.searchBillToday(string)

    def on_search_table_by_name_changed(self, string):
        if self.search_bill_name.isChecked():
            self.tablemodel.setFilter('id', string)

    def on_search_table_by_date_changed(self, string):
        if self.search_bill_day.isChecked():
            string = string.toString("yyyy-MM-dd")
            self.tablemodel.searchBillDay(string)
            self.refresh_box_day()
        
    def add_searcher(self):
        self.edit_date.hide()
        self.edit_search_name.hide()
        self.edit_search.show()
        self.button_close_box.show()
        self.button_show_box.hide()
        self.button_add_expense.show()
        self.button_detail_expense.show()
        self.edit_day_gain.show()
        self.edit_day_expenses.show()
        self.day_expenses.show()
        self.day_gain.show()
        self.refresh_box_today()

    def add_date_searcher(self):
        self.edit_search.hide()
        self.edit_search_name.hide()
        self.edit_date.show()
        self.button_close_box.hide()
        self.button_show_box.show()
        self.button_add_expense.hide()
        self.button_detail_expense.show()
        self.edit_day_gain.show()
        self.edit_day_expenses.show()
        self.day_expenses.show()
        self.day_gain.show()

    def add_searcher_name(self):
        self.edit_date.hide()
        self.edit_search_name.show()
        self.edit_search.hide()
        self.button_close_box.hide()
        self.button_show_box.hide()
        self.button_add_expense.hide()
        self.button_detail_expense.hide()
        self.edit_day_gain.hide()
        self.edit_day_expenses.hide()
        self.day_expenses.hide()
        self.day_gain.hide()

    def add_expense(self):
        window, data = GenericFormDialog.get_data(Gasto, self)
        
    def detail_expense(self):
        if self.search_bill_today.isChecked():
            today = str(date.today())
            Detail_Expense(False,today).exec_()
        if self.search_bill_day.isChecked():
            string = self.edit_date.date()
            Detail_Expense(True,string).exec_()

    def view_detail_product(self):
        try:
            indexes = self.tableview.selectedIndexes()
            for index in indexes:
                product_id = self.tablemodel.get_id_object_alchemy(index.row())
            Detail_Bill(product_id, self).exec_()
        except:
            msgBox = QtGui.QMessageBox()
            msgBox.setText('Por favor seleccione una fila')
            msgBox.addButton(QtGui.QPushButton('Aceptar'), QtGui.QMessageBox.YesRole)
            msgBox.setWindowTitle("No Selecciono una fila")
            msgBox.exec_()

    def close_box(self):
        ok = QtGui.QMessageBox.question(self, u'Cerrar Caja',
                                            "Solo podra cerrar Caja una sola vez, desea cerrar la Caja de hoy?",
                                            QtGui.QMessageBox.Yes,
                                            QtGui.QMessageBox.No)
        if ok == QtGui.QMessageBox.Yes:
            self.refresh_box_today()
            self.last_query = (session.query(Caja)
                                .order_by(desc(Caja.id)).all())
            previous_balance = self.last_query[0].saldo_actual
            gains = self.edit_day_gain.text()
            expenses = self.edit_day_expenses.text()
            current_balance = float(previous_balance) + float(gains) - float(expenses)
            today = date.today()
            session.add(Caja(previous_balance,gains,expenses,current_balance,today))
            session.commit()
        else:
            return

    def show_box(self):
        string = self.edit_date.date()
        Show_Box(string ,self).exec_()