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
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_()
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)
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
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_()