Ejemplo n.º 1
0
 def getDateRangeWidget(self, minDate, maxDate):
     dateRange = QDateEdit()
     dateRange.setCalendarPopup(True)
     dateRange.setDisplayFormat('MMM d yy')
     dateRange.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
     dateRange.setMaximumDate(maxDate)
     dateRange.setMinimumDate(minDate)
     return dateRange
Ejemplo n.º 2
0
class AcquistoForm(QDialog):
    '''
    Widget per l'inserimento di un acquisto immediato.
    '''
    def __init__(self, conn):
        '''
        Parameters:
            conn : connection
                Connection to the database.
        '''
        super().__init__()
        self.setWindowTitle('Aggiungi Acquisto')
        self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint, False)

        self.conn = conn
        self.cursor = conn.cursor()

        self.books = dict()
        self.books_qt = dict()

        self.gen_layout = QVBoxLayout()

        self.form_layout = QFormLayout()
        self.form_layout.setRowWrapPolicy(QFormLayout.WrapLongRows)

        # Widgets
        self.client_field = QLineEdit()
        self.form_layout.addRow('Numero Cliente (facoltativo): ',
                                self.client_field)

        self.dip_field = QLineEdit()
        self.form_layout.addRow('Dipendente (CF): ', self.dip_field)

        self.date_picker = QDateEdit(QDate.currentDate())
        self.date_picker.setDisplayFormat("MM/dd/yyyy")
        self.date_picker.setCalendarPopup(True)
        self.form_layout.addRow('Data (mm/gg/aaaa): ', self.date_picker)

        self.importo_field = QDoubleSpinBox()
        self.importo_field.setMaximum(999999999.99)
        self.form_layout.addRow('Importo: ', self.importo_field)

        self.ins_layout = QHBoxLayout()
        self.libro_field = QLineEdit()
        self.quantita_field = QSpinBox()
        self.quantita_field.setMinimum(1)
        self.libro_button = QPushButton('Aggiungi')
        self.libro_button.clicked.connect(self.aggiungi_libro)
        self.ins_layout.addWidget(QLabel('Libro (ISBN): '))
        self.ins_layout.addWidget(self.libro_field)
        self.ins_layout.addWidget(QLabel('Quantità: '))
        self.ins_layout.addWidget(self.quantita_field)
        self.ins_layout.addWidget(self.libro_button)

        self.labels = ['ISBN', 'Quantità', '']
        self.table = QTableWidget(0, 3)
        self.table.setHorizontalHeaderLabels(self.labels)
        self.table.horizontalHeader().setSectionResizeMode(
            0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(
            1, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(
            2, QHeaderView.ResizeToContents)

        self.confirm_button = QPushButton('Conferma')
        self.confirm_button.clicked.connect(self.post_acquisto)

        self.gen_layout.addLayout(self.form_layout)
        self.gen_layout.addLayout(self.ins_layout)
        self.gen_layout.addWidget(self.table)
        self.gen_layout.addWidget(self.confirm_button)
        self.setLayout(self.gen_layout)

    def aggiungi_libro(self):
        self.books[self.libro_field.text()] = self.quantita_field.value()
        self.update_table()

    def remove_libro(self, book):
        self.books.pop(book, None)
        self.update_table()

    def update_table(self):
        self.table.clearContents()
        while self.table.rowCount() > 0:
            self.table.removeRow(0)
        for book in self.books.keys():
            row = self.table.rowCount()
            button = QPushButton('Rimuovi')
            button.clicked.connect(lambda: self.remove_libro(book))
            self.table.insertRow(row)
            self.table.setItem(row, 0, QTableWidgetItem(book))
            self.table.setItem(row, 1, QTableWidgetItem(str(self.books[book])))
            self.table.setCellWidget(row, 2, button)

    def verif_qty(self):
        '''
        Shows error messages based on the validity of inserted books, and
        returns False, or returns True if all the books are ok to sell right now.
        '''
        if len(self.books.items()) == 0:
            self._show_error('Non ci sono libri nell\'acquisto')
            return 1
        for book, qty in self.books.items():
            self.cursor.execute(FIND_QUANTITA, (book, ))
            result = self.cursor.fetchall()
            if not result:
                self._show_error('\'{}\' non è un libro valido.'.format(book))
                return 2
            stored = result[0][0]
            if stored < qty:
                return self.__show_are_you_sure(
                    'L\'acquisto richiede {} libri {}, ma ne sono presenti solo {}.\nNon sarà possibile sottrarre i libri acquistati.\nVuoi proseguire ugualmente?'
                    .format(qty, book, stored))
        return 0

    def verif_client_dip(self):
        '''
        Returns false and displays and error message if cliente and dipendente are
        not valid tuples in the database, returns true if they are ok
        '''
        cliente = self.client_field.text()
        if cliente:
            if not cliente.isdigit():
                self._show_error('Il codice del Cliente deve essere numerico.')
                return 1
            self.cursor.execute(FIND_CLIENTE, (cliente, ))
            result = self.cursor.fetchall()
            if not result or not result[0][0]:
                self._show_error('Cliente {} non esiste.'.format(cliente))
                return 2

        dipendente = self.dip_field.text()
        if not dipendente:
            self._show_error('Il Dipendente non può essere vuoto.')
            return 3
        self.cursor.execute(FIND_DIPENDENTE, (dipendente, ))
        result = self.cursor.fetchall()
        if not result or not result[0][0]:
            self._show_error('Dipendente {} non esiste.'.format(dipendente))
            return 4
        return 0

    def post_acquisto(self):
        if self.verif_client_dip():
            return
        should_show = self.verif_qty()
        if should_show > 0:
            return
        cliente = self.client_field.text().strip() if self.client_field.text(
        ).strip() else None
        importo = self.importo_field.value()
        self.cursor.execute(
            INSERT_ACQUISTO,
            (self.date_picker.date().toString('MM/dd/yyyy'),
             self.importo_field.value(), self.dip_field.text()))
        new_id = self.cursor.fetchall()[0][0]
        self.cursor.execute(INSERT_IMMEDIATO, (new_id, cliente))
        for book in self.books.keys():
            self.cursor.execute(INSERT_COMPRENDE,
                                (new_id, book, self.books[book]))
        self.conn.commit()
        if should_show == 0: self._show_confirm()
        self.accept()

    def __show_are_you_sure(self, msg=''):
        dialog = _AreYouSureDialog(msg)
        dialog.setWindowTitle('ATTENZIONE')
        result = dialog.exec_()
        return -1 if result == QDialog.Accepted else 3

    def _show_confirm(self):
        dialog = _ScalaAcquistiDialog(self.books, self.conn)
        dialog.setWindowTitle('Rimozione libri')
        dialog.exec_()

    def _show_error(self, msg=''):
        dialog = QMessageBox()
        dialog.setWindowTitle('ERRORE')
        dialog.setText(msg)
        dialog.exec_()
Ejemplo n.º 3
0
class ExchangeSpiderUI(QWidget):
    """ 数据抓取主页面 """
    def __init__(self, *args, **kwargs):
        super(ExchangeSpiderUI, self).__init__(*args, **kwargs)
        layout = QVBoxLayout()
        layout.setContentsMargins(QMargins(2, 0, 2, 1))
        main_splitter = QSplitter(self)
        main_splitter.setHandleWidth(1)
        self.tree_widget = ExchangeLibTree(self)
        main_splitter.addWidget(self.tree_widget)

        action_splitter = QSplitter(Qt.Vertical, self)
        action_splitter.setHandleWidth(1)

        spider_widget = QWidget(self)
        spider_widget.setAutoFillBackground(True)
        palette = QPalette()
        pix = QPixmap("images/spider_bg.png")
        pix = pix.scaled(QSize(700, 700), Qt.KeepAspectRatio)
        palette.setBrush(QPalette.Background, QBrush(pix))
        spider_widget.setPalette(palette)

        spider_layout = QVBoxLayout()

        tips_layout = QHBoxLayout()
        tips_layout.setSpacing(1)
        tips_layout.addWidget(QLabel("当前交易所:", self))
        self.spider_exchange_button = QPushButton("未选择", self)
        tips_layout.addWidget(self.spider_exchange_button)

        tips_layout.addWidget(QLabel(self))
        tips_layout.addWidget(QLabel("当前操作:", self))
        self.spider_action_button = QPushButton("未选择", self)
        tips_layout.addWidget(self.spider_action_button)

        tips_layout.addWidget(QLabel(self))
        tips_layout.addWidget(QLabel("选择日期:", self))
        self.spider_date_edit = QDateEdit(QDate.currentDate(), self)
        self.spider_date_edit.setCalendarPopup(True)
        self.spider_date_edit.setDisplayFormat("yyyy-MM-dd")
        tips_layout.addWidget(self.spider_date_edit)

        tips_layout.addWidget(QLabel(self))
        self.spider_start_button = QPushButton("开始", self)
        tips_layout.addWidget(self.spider_start_button)
        tips_layout.addStretch()

        spider_layout.addLayout(tips_layout)

        self.spider_status = QLabel("等待开始抓取", self)
        self.spider_status.setWordWrap(True)
        self.spider_status.setAlignment(Qt.AlignCenter)

        spider_layout.addWidget(self.spider_status)

        spider_widget.setLayout(spider_layout)

        action_splitter.addWidget(spider_widget)

        # 解析部分
        parser_widget = QWidget(self)
        parser_widget.setAutoFillBackground(True)
        palette = QPalette()
        pix = QPixmap("images/parser_bg.png")
        pix = pix.scaled(QSize(700, 700), Qt.KeepAspectRatio)
        palette.setBrush(QPalette.Background, QBrush(pix))
        parser_widget.setPalette(palette)

        parser_layout = QVBoxLayout()

        tips_layout = QHBoxLayout()
        tips_layout.setSpacing(1)
        tips_layout.addWidget(QLabel("当前交易所:", self))
        self.parser_exchange_button = QPushButton("未选择", self)
        tips_layout.addWidget(self.parser_exchange_button)

        tips_layout.addWidget(QLabel(self))
        tips_layout.addWidget(QLabel("当前操作:", self))
        self.parser_action_button = QPushButton("未选择", self)
        tips_layout.addWidget(self.parser_action_button)

        tips_layout.addWidget(QLabel(self))
        tips_layout.addWidget(QLabel("选择日期:", self))
        self.parser_date_edit = QDateEdit(QDate.currentDate(), self)
        self.parser_date_edit.setCalendarPopup(True)
        self.parser_date_edit.setDisplayFormat("yyyy-MM-dd")
        tips_layout.addWidget(self.parser_date_edit)

        tips_layout.addWidget(QLabel(self))
        self.parser_start_button = QPushButton("开始", self)
        tips_layout.addWidget(self.parser_start_button)
        tips_layout.addStretch()

        parser_layout.addLayout(tips_layout)

        self.parser_status = QLabel("等待开始解析", self)
        self.parser_status.setAlignment(Qt.AlignCenter)
        parser_layout.addWidget(self.parser_status)

        parser_widget.setLayout(parser_layout)

        action_splitter.addWidget(parser_widget)

        main_splitter.addWidget(action_splitter)

        main_splitter.setStretchFactor(0, 4)
        main_splitter.setStretchFactor(1, 6)

        layout.addWidget(main_splitter)
        self.setLayout(layout)

        main_splitter.setObjectName("mainSplitter")
        action_splitter.setObjectName("actionSplitter")

        self.spider_exchange_button.setObjectName("tipButton")
        self.spider_action_button.setObjectName("tipButton")
        self.spider_status.setObjectName("spiderStatus")

        self.parser_exchange_button.setObjectName("tipButton")
        self.parser_action_button.setObjectName("tipButton")
        self.parser_status.setObjectName("parserStatus")

        self.setStyleSheet(
            "#mainSplitter::handle{background-color:rgba(50,50,50,100)}"
            "#actionSplitter::handle{background-color:rgba(50,50,50,100)}"
            "#tipButton{border:none;color:rgb(220,100,100)}"
            "#spiderStatus,#parserStatus{font-size:16px;font-weight:bold;color:rgb(230,50,50)}"
        )
Ejemplo n.º 4
0
class VentanaAdministradorDePersonas(QFrame):
    def __init__(self, parent=None):
        super(VentanaAdministradorDePersonas, self).__init__(parent)
        raiz.setWindowTitle("Administracion de personas")
        self.operacionesConPersonas = OperacionesConPersonas()
        self.instanciarVentana()

    def instanciarVentana(self):
        #Contenedor De todas las cosas de arriba a abajo
        layoutGeneral = QVBoxLayout()

        #Cosas de Derecha
        layoutDerecha = QVBoxLayout()  #Ordena cosas de arriba a abajo
        layoutDerecha.setMargin(20)

        self.btnAgregarPersona = QPushButton("Agregar persona")
        self.btnAgregarPersona.setToolTip("Toma los datos ")
        self.btnAgregarPersona.clicked.connect(self.agregarPersona)
        layoutDerecha.addWidget(self.btnAgregarPersona)

        self.btnBuscarPersona = QPushButton("Buscar persona")
        self.btnBuscarPersona.setToolTip("Busca por cedula a una persona")
        self.btnBuscarPersona.clicked.connect(self.buscarPersona)
        layoutDerecha.addWidget(self.btnBuscarPersona)

        self.btnEliminarPersona = QPushButton("Eliminar persona")
        self.btnEliminarPersona.setToolTip(
            "Elimina a la persona que esta en busqueda")
        self.btnEliminarPersona.clicked.connect(self.eliminarPersona)
        layoutDerecha.addWidget(self.btnEliminarPersona)

        self.btnActualizarPersona = QPushButton("Actualizar persona")
        self.btnActualizarPersona.setToolTip(
            "Cambia los datos de la persona seleccionada")
        self.btnActualizarPersona.clicked.connect(self.actualizarPersona)
        layoutDerecha.addWidget(self.btnActualizarPersona)

        self.btnLimpiarTexto = QPushButton("Limpiar")
        self.btnLimpiarTexto.setToolTip(
            "Limpia los campos de texto para ingresar datos")
        self.btnLimpiarTexto.clicked.connect(self.limpiarCampos)
        layoutDerecha.addWidget(self.btnLimpiarTexto)

        self.btnVolverAlMenu = QPushButton("Volver")
        self.btnVolverAlMenu.setToolTip("Vuelve al menu principal")
        self.btnVolverAlMenu.clicked.connect(self.volverAlMenu)
        layoutDerecha.addWidget(self.btnVolverAlMenu)

        #Cosas de Izquierda
        layoutIzquierda = QVBoxLayout()  #ordena cosas de arriba a abajo

        self.lblDNI = QLabel("DNI: ")
        layoutIzquierda.addWidget(self.lblDNI)
        self.DNI = QLineEdit()
        layoutIzquierda.addWidget(self.DNI)

        self.lblPrimerNombre = QLabel("Primer nombre: ")
        layoutIzquierda.addWidget(self.lblPrimerNombre)
        self.PrimerNombre = QLineEdit()
        layoutIzquierda.addWidget(self.PrimerNombre)

        self.lblSegundoNombre = QLabel("Segundo nombre: ")
        layoutIzquierda.addWidget(self.lblSegundoNombre)
        self.SegundoNombre = QLineEdit()
        layoutIzquierda.addWidget(self.SegundoNombre)

        self.lblPrimerApellido = QLabel("Primer apellido: ")
        layoutIzquierda.addWidget(self.lblPrimerApellido)
        self.PrimerApellido = QLineEdit()
        layoutIzquierda.addWidget(self.PrimerApellido)

        self.lblSegundoApellido = QLabel("Segundo apellido: ")
        layoutIzquierda.addWidget(self.lblSegundoApellido)
        self.SegundoApellido = QLineEdit()
        layoutIzquierda.addWidget(self.SegundoApellido)

        self.lblFechaDeNacimiento = QLabel("Fecha de nacimiento")
        layoutIzquierda.addWidget(self.lblFechaDeNacimiento)
        self.fechaDeNacimiento = QDateEdit()
        self.fechaDeNacimiento.setDisplayFormat("yyyy-MM-dd")
        self.fechaDeNacimiento.setCalendarPopup(True)
        self.fechaDeNacimiento.setDate(date.today())
        layoutIzquierda.addWidget(self.fechaDeNacimiento)

        #Cosas de layout de arriba
        layoutSuperior = QHBoxLayout()  #Ordena cosas de derecha a izquierda
        layoutSuperior.addLayout(layoutIzquierda)
        layoutSuperior.addLayout(layoutDerecha)

        #Cosas layout de abajo
        layoutInferior = QVBoxLayout()
        self.mostrarError = QPlainTextEdit(readOnly=True)
        layoutInferior.addWidget(self.mostrarError)

        #cosas del layout general
        layoutGeneral.addLayout(layoutSuperior)
        layoutGeneral.addLayout(layoutInferior)
        self.setLayout(layoutGeneral)

        #Redimensionar
        raiz.adjustSize()
        self.adjustSize()

    def agregarPersona(self):
        self.limpiarErrores()
        try:
            laPersona = self.llenarPersona()
            salida = self.operacionesConPersonas.insertarPersona(laPersona)
            self.mostrarError.insertPlainText(str(salida))
            self.limpiarCampos(
            )  #habilitamos la edicion y evitamos dejar datos basura
        except Exception as e:
            self.mostrarError.insertPlainText(''.join(e.args))
        pass

    def buscarPersona(self):
        self.limpiarErrores()
        try:
            laPersona = self.operacionesConPersonas.buscarPersonaPorDNI(
                int(''.join(self.DNI.text())))
            if type(laPersona) == type(""):
                self.mostrarError.insertPlainText(''.join(laPersona))
                return None
            self.llenarCampos(laPersona)
        except Exception as e:
            self.mostrarError.insertPlainText(''.join(e.args))

    def eliminarPersona(self):
        self.limpiarErrores()
        try:
            laPersona = self.llenarPersona()
            mensajeDeConfirmacion = "DNI: " + self.DNI.text()
            opcionElegida = QMessageBox.question(
                self, "Desea eliminar a la persona?", mensajeDeConfirmacion,
                QMessageBox.Yes, QMessageBox.No)
            if opcionElegida == QMessageBox.Yes:
                respuesta = self.operacionesConPersonas.eliminarPersona(
                    laPersona)
                if type(respuesta) == type(""):
                    self.mostrarError.insertPlainText(''.join(respuesta))
                    self.limpiarCampos()
                    return None
        except Exception as e:
            self.mostrarError.insertPlainText(''.join(e.args))

    def actualizarPersona(self):
        self.limpiarErrores()
        try:
            laPersona = self.llenarPersona()
            mensajeDeConfirmacion = "DNI: " + self.DNI.text()
            opcionElegida = QMessageBox.question(
                self, "Desea eliminar a la persona?", mensajeDeConfirmacion,
                QMessageBox.Yes, QMessageBox.No)
            if opcionElegida == QMessageBox.Yes:
                respuesta = self.operacionesConPersonas.actualizarPersona(
                    laPersona)
                if type(respuesta) == type(""):
                    self.mostrarError.insertPlainText(''.join(respuesta))
                    self.limpiarCampos()
                    return None
        except Exception as e:
            print(e.args)

    def llenarCampos(self, laPersona):
        self.limpiarCampos()
        self.DNI.setText(str(laPersona.getDNI()))
        self.DNI.setReadOnly(True)
        self.PrimerNombre.setText(laPersona.getPrimerNombre())
        self.SegundoNombre.setText(laPersona.getSegundoNombre())
        self.PrimerApellido.setText(laPersona.getPrimerApellido())
        self.SegundoApellido.setText(laPersona.getSegundoApellido())
        self.fechaDeNacimiento.setDate(laPersona.getFechaDeNacimiento())

    def llenarPersona(self):
        return Persona(int(''.join(self.DNI.text())),
                       ''.join(self.PrimerNombre.text()),
                       ''.join(self.SegundoNombre.text()),
                       ''.join(self.PrimerApellido.text()),
                       ''.join(self.SegundoApellido.text()),
                       ''.join(self.fechaDeNacimiento.text()))

    def limpiarCampos(self):
        self.DNI.clear()
        self.DNI.setReadOnly(False)
        self.PrimerNombre.clear()
        self.SegundoNombre.clear()
        self.PrimerApellido.clear()
        self.SegundoApellido.clear()
        self.fechaDeNacimiento.setDate(date.today())
        #limpiar campos de texto y permitir la edicion de todos ellos

    def limpiarErrores(self):
        self.mostrarError.clear()

    def volverAlMenu(self):
        raiz.setCentralWidget(None)
        raiz.setCentralWidget(VentanaPrincipal())
Ejemplo n.º 5
0
    def __init__(self, db_session, **kwargs):
        super(MainPage, self).__init__()
        self.db_session = db_session

        # Create central widget that will contain everything
        # (Bit odd design decision from QT, I would say, to separate widgets and
        # layouts. Now we need to have central _widget_ to contain layout to contain
        # widgets)
        central_widget = QWidget()
        central_widget.setStyleSheet("background: white;")

        # Add central widget to main window

        # Create main grid layout that will organize everything
        main_grid = qt.QGridLayout(central_widget)

        self.setLayout(main_grid)

        main_grid.setSpacing(0)
        main_grid.setMargin(0)

        # Yet again interesting design decision. On QT you cannot set style for layout.
        # Thus, we create widget that will contain layout and now we can set style for the widget.

        widget_that_would_not_be_needed_if_qt_would_not_be_so_stupid = QWidget(
        )

        widget_that_would_not_be_needed_if_qt_would_not_be_so_stupid.setStyleSheet(
            '''
            QObject { background: #FF005AA1; }
            QPushButton {
                background: #FF005AA1;
                color: white;
                text-align: center;
                border: none;
                font-weight: 500;
                font-size: 15px;
                height: 48px;
                width: 120px;
            }
            QPushButton:hover {
               background-color: #FF014a82;
            }
            QPushButton:checked {
            background: #FF01508c;
            }
            QPushButton:pressed {
                color: #FF005AA1;
                background: white;
            }
            QWidget{
                background: #FF005AA1;
            }
            ''')

        # On left side we will have some (or at least one) button
        left_side_buttons = QVBoxLayout(
            widget_that_would_not_be_needed_if_qt_would_not_be_so_stupid)

        left_side_buttons.setSpacing(0)
        left_side_buttons.setMargin(0)

        # And add it to main box the left most cell
        main_grid.addWidget(
            widget_that_would_not_be_needed_if_qt_would_not_be_so_stupid, 0, 0)

        main_grid.setRowStretch(0, 1)

        # Column 0 must not stretch
        main_grid.setColumnStretch(0, 0)

        # Column 1 must stretch
        main_grid.setColumnStretch(1, 1)

        # Separator line
        line = qt.QFrame()
        line.setFrameShape(qt.QFrame.HLine)
        line.setFrameShadow(qt.QFrame.Sunken)

        # Add scan button
        self.scan_button = qt.QPushButton("Luo laskut")
        self.scan_button.clicked.connect(self.luo_lasku_pressed_handler)

        # Add widgets to container
        left_side_buttons.addWidget(self.scan_button)

        # Add separator line
        line = qt.QFrame()
        line.setFrameShape(qt.QFrame.HLine)
        line.setFrameShadow(qt.QFrame.Sunken)

        left_side_buttons.addWidget(line)

        # Add stretch that will stretch to fill rest of the space
        left_side_buttons.addStretch()

        self.list_of_visits = qt.QTreeWidget()

        self.list_of_visits.setColumnCount(3)
        self.list_of_visits.setHeaderLabels(
            ["Käyntipäivä", "Nimi", "Terapian laji", "Lisätiedot"])
        self.list_of_visits.setSortingEnabled(True)

        # Allow multiselect
        self.list_of_visits.setSelectionMode(
            qt.QAbstractItemView.ExtendedSelection)

        third_stupid_widget = QWidget()

        right_side_layout = qt.QVBoxLayout(third_stupid_widget)

        main_grid.addWidget(third_stupid_widget, 0, 1)

        new_visit_date = QDateEdit(datetime.datetime.now())
        new_visit_date.setCalendarPopup(True)
        new_visit_date.setDisplayFormat('dd.MM.yyyy')
        self.new_visit_customers_combobox = QComboBox()
        new_visit_type = QLineEdit()
        new_visit_type.setText("Terapia")

        self.update_page()

        self.new_visit_button = qt.QPushButton("Lisää käynti")

        second_stupid_widget = QWidget()
        new_visit_layout = QHBoxLayout(second_stupid_widget)
        right_side_layout.addWidget(second_stupid_widget)
        new_visit_layout.addWidget(new_visit_date)
        new_visit_layout.addWidget(self.new_visit_customers_combobox)
        new_visit_layout.addWidget(new_visit_type)
        new_visit_layout.addWidget(self.new_visit_button)

        right_side_layout.addWidget(self.list_of_visits)

        # Add properties view
        # main_grid.addWidget(qt.QPlainTextEdit(), 0, 2)

        def new_visit_handler():
            for _customer in self.customers:
                if _customer.name == self.new_visit_customers_combobox.currentText(
                ):
                    _customer.new_visit(
                        cost=_customer.hour_price,
                        visit_length_min=45,
                        visit_date=new_visit_date.date().toPython(),
                        visit_type=new_visit_type.text(),
                    )
                    self.update_page()
                    db_session.commit()

        self.new_visit_button.clicked.connect(new_visit_handler)
        # create context menu
        self.popMenu = qt.QMenu(self)
        self.popMenu.addAction(
            qt.QAction('Poista käynti',
                       self.list_of_visits,
                       triggered=self._delete_visit))

        # set button context menu policy
        self.list_of_visits.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.list_of_visits.customContextMenuRequested.connect(
            self.on_context_menu)
Ejemplo n.º 6
0
class TradeWidget(AbstractOperationDetails):
    def __init__(self, parent=None):
        AbstractOperationDetails.__init__(self, parent)
        self.name = "Trade"

        self.date_label = QLabel(self)
        self.settlement_label = QLabel()
        self.number_label = QLabel(self)
        self.account_label = QLabel(self)
        self.symbol_label = QLabel(self)
        self.qty_label = QLabel(self)
        self.price_label = QLabel(self)
        self.fee_label = QLabel(self)
        self.comment_label = QLabel(self)

        self.main_label.setText(g_tr("TradeWidget", "Buy / Sell"))
        self.date_label.setText(g_tr("TradeWidget", "Date/Time"))
        self.settlement_label.setText(g_tr("TradeWidget", "Settlement"))
        self.number_label.setText(g_tr("TradeWidget", "#"))
        self.account_label.setText(g_tr("TradeWidget", "Account"))
        self.symbol_label.setText(g_tr("TradeWidget", "Asset"))
        self.qty_label.setText(g_tr("TradeWidget", "Qty"))
        self.price_label.setText(g_tr("TradeWidget", "Price"))
        self.fee_label.setText(g_tr("TradeWidget", "Fee"))
        self.comment_label.setText(g_tr("TradeWidget", "Note"))

        self.timestamp_editor = QDateTimeEdit(self)
        self.timestamp_editor.setCalendarPopup(True)
        self.timestamp_editor.setTimeSpec(Qt.UTC)
        self.timestamp_editor.setFixedWidth(self.timestamp_editor.fontMetrics().width("00/00/0000 00:00:00") * 1.25)
        self.timestamp_editor.setDisplayFormat("dd/MM/yyyy hh:mm:ss")
        self.settlement_editor = QDateEdit(self)
        self.settlement_editor.setCalendarPopup(True)
        self.settlement_editor.setTimeSpec(Qt.UTC)
        self.settlement_editor.setFixedWidth(self.settlement_editor.fontMetrics().width("00/00/0000") * 1.5)
        self.settlement_editor.setDisplayFormat("dd/MM/yyyy")
        self.account_widget = AccountSelector(self)
        self.asset_widget = AssetSelector(self)
        self.qty_edit = AmountEdit(self)
        self.qty_edit.setAlignment(Qt.AlignRight)
        self.price_edit = AmountEdit(self)
        self.price_edit.setAlignment(Qt.AlignRight)
        self.fee_edit = AmountEdit(self)
        self.fee_edit.setAlignment(Qt.AlignRight)
        self.number = QLineEdit(self)
        self.comment = QLineEdit(self)

        self.layout.addWidget(self.date_label, 1, 0, 1, 1, Qt.AlignLeft)
        self.layout.addWidget(self.account_label, 2, 0, 1, 1, Qt.AlignLeft)
        self.layout.addWidget(self.symbol_label, 3, 0, 1, 1, Qt.AlignLeft)
        self.layout.addWidget(self.comment_label, 4, 0, 1, 1, Qt.AlignLeft)

        self.layout.addWidget(self.timestamp_editor, 1, 1, 1, 1, Qt.AlignLeft)
        self.layout.addWidget(self.account_widget, 2, 1, 1, 4)
        self.layout.addWidget(self.asset_widget, 3, 1, 1, 4)
        self.layout.addWidget(self.comment, 4, 1, 1, 4)

        self.layout.addWidget(self.settlement_label, 1, 2, 1, 1, Qt.AlignRight)
        self.layout.addWidget(self.settlement_editor, 1, 3, 1, 1, Qt.AlignLeft)

        self.layout.addWidget(self.number_label, 1, 5, 1, 1, Qt.AlignRight)
        self.layout.addWidget(self.qty_label, 2, 5, 1, 1, Qt.AlignRight)
        self.layout.addWidget(self.price_label, 3, 5, 1, 1, Qt.AlignRight)
        self.layout.addWidget(self.fee_label, 4, 5, 1, 1, Qt.AlignRight)

        self.layout.addWidget(self.number, 1, 6, 1, 1)
        self.layout.addWidget(self.qty_edit, 2, 6, 1, 1)
        self.layout.addWidget(self.price_edit, 3, 6, 1, 1)
        self.layout.addWidget(self.fee_edit, 4, 6, 1, 1)

        self.layout.addWidget(self.commit_button, 0, 8, 1, 1)
        self.layout.addWidget(self.revert_button, 0, 9, 1, 1)

        self.layout.addItem(self.verticalSpacer, 6, 6, 1, 1)
        self.layout.addItem(self.horizontalSpacer, 1, 6, 1, 1)

        super()._init_db("trades")
        self.mapper.setItemDelegate(TradeWidgetDelegate(self.mapper))

        self.account_widget.changed.connect(self.mapper.submit)
        self.asset_widget.changed.connect(self.mapper.submit)

        self.mapper.addMapping(self.timestamp_editor, self.model.fieldIndex("timestamp"))
        self.mapper.addMapping(self.settlement_editor, self.model.fieldIndex("settlement"))
        self.mapper.addMapping(self.account_widget, self.model.fieldIndex("account_id"))
        self.mapper.addMapping(self.asset_widget, self.model.fieldIndex("asset_id"))
        self.mapper.addMapping(self.number, self.model.fieldIndex("number"))
        self.mapper.addMapping(self.qty_edit, self.model.fieldIndex("qty"))
        self.mapper.addMapping(self.price_edit, self.model.fieldIndex("price"))
        self.mapper.addMapping(self.fee_edit, self.model.fieldIndex("fee"))
        self.mapper.addMapping(self.comment, self.model.fieldIndex("note"))

        self.model.select()

    def prepareNew(self, account_id):
        new_record = self.model.record()
        new_record.setNull("id")
        new_record.setValue("timestamp", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp()))
        new_record.setValue("settlement", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp()))
        new_record.setValue("number", '')
        new_record.setValue("account_id", account_id)
        new_record.setValue("asset_id", 0)
        new_record.setValue("qty", 0)
        new_record.setValue("price", 0)
        new_record.setValue("fee", 0)
        new_record.setValue("note", None)
        return new_record

    def copyToNew(self, row):
        new_record = self.model.record(row)
        new_record.setNull("id")
        new_record.setValue("timestamp", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp()))
        new_record.setValue("settlement", int(datetime.now().replace(tzinfo=tz.tzutc()).timestamp()))
        new_record.setValue("number", '')
        return new_record
Ejemplo n.º 7
0
class PrenotazioneForm(QDialog):
    '''
    Widget per l'inserimento di un acquisto immediato.
    '''
    def __init__(self, conn):
        '''
        Parameters:
            conn : connection
                Connection to the database.
        '''
        super().__init__()
        self.setWindowTitle('Aggiungi Prenotazione')
        self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint, False)

        self.conn = conn
        self.cursor = conn.cursor()

        self.books = dict()
        self.books_qt = dict()

        self.gen_layout = QVBoxLayout()

        self.form_layout = QFormLayout()
        self.form_layout.setRowWrapPolicy(QFormLayout.WrapLongRows)

        # Widgets
        self.client_field = QLineEdit()
        self.form_layout.addRow('Numero Cliente: ', self.client_field)

        self.dip_field = QLineEdit()
        self.form_layout.addRow('Dipendente (CF): ', self.dip_field)

        self.date_picker = QDateEdit(QDate.currentDate())
        self.date_picker.setDisplayFormat("MM/dd/yyyy")
        self.date_picker.setCalendarPopup(True)
        self.form_layout.addRow('Data (mm/gg/aaaa): ', self.date_picker)

        self.importo_field = QDoubleSpinBox()
        self.importo_field.setMaximum(999999999.99)
        self.form_layout.addRow('Importo: ', self.importo_field)

        self.ins_layout = QHBoxLayout()
        self.libro_field = QLineEdit()
        self.quantita_field = QSpinBox()
        self.quantita_field.setMinimum(1)
        self.libro_button = QPushButton('Aggiungi')
        self.libro_button.clicked.connect(self.aggiungi_libro)
        self.ins_layout.addWidget(QLabel('Libro (ISBN): '))
        self.ins_layout.addWidget(self.libro_field)
        self.ins_layout.addWidget(QLabel('Quantità: '))
        self.ins_layout.addWidget(self.quantita_field)
        self.ins_layout.addWidget(self.libro_button)

        self.labels = ['ISBN', 'Quantità', '']
        self.table = QTableWidget(0, 3)
        self.table.setHorizontalHeaderLabels(self.labels)
        self.table.horizontalHeader().setSectionResizeMode(
            0, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(
            1, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(
            2, QHeaderView.ResizeToContents)

        self.info_label = QLabel(
            'Le prenotazioni non riducono i libri disponibili.')
        self.confirm_button = QPushButton('Conferma')
        self.confirm_button.clicked.connect(self.post_prenotazione)

        self.gen_layout.addLayout(self.form_layout)
        self.gen_layout.addLayout(self.ins_layout)
        self.gen_layout.addWidget(self.table)
        self.gen_layout.addWidget(self.info_label)
        self.gen_layout.addWidget(self.confirm_button)
        self.setLayout(self.gen_layout)

    def aggiungi_libro(self):
        self.books[self.libro_field.text()] = self.quantita_field.value()
        self.update_table()

    def remove_libro(self, book):
        self.books.pop(book, None)
        self.update_table()

    def update_table(self):
        self.table.clearContents()
        while self.table.rowCount() > 0:
            self.table.removeRow(0)
        for book in self.books.keys():
            row = self.table.rowCount()
            button = QPushButton('Rimuovi')
            button.clicked.connect(lambda: self.remove_libro(book))
            self.table.insertRow(row)
            self.table.setItem(row, 0, QTableWidgetItem(book))
            self.table.setItem(row, 1, QTableWidgetItem(str(self.books[book])))
            self.table.setCellWidget(row, 2, button)

    def verif_libri(self):
        '''
        Shows error messages based on the validity of inserted books, and
        returns False, or returns True if all the books are ok to sell right now.
        '''
        if len(self.books.items()) == 0:
            self._show_error('Non ci sono libri nell\'acquisto')
            return False
        for book in self.books.keys():
            self.cursor.execute('SELECT * FROM libro WHERE isbn = %s',
                                (book, ))
            result = self.cursor.fetchall()
            if not result:
                self._show_error('\'{}\' non è un libro valido.'.format(book))
                return False
        return True

    def verif_client_dip(self):
        '''
        Returns false and displays and error message if cliente and dipendente are
        not valid tuples in the database, returns true if they are ok
        '''
        cliente = self.client_field.text()
        if not cliente:
            self._show_error('Il Cliente è necessario per una Prenotazione.')
            return False
        if cliente:
            if not cliente.isdigit():
                self._show_error('Il codice del Cliente deve essere numerico.')
                return False
            self.cursor.execute(FIND_CLIENTE, (cliente, ))
            result = self.cursor.fetchall()
            if not result or not result[0][0]:
                self._show_error('Cliente {} non esiste.'.format(cliente))
                return False

        dipendente = self.dip_field.text()
        if not dipendente:
            self._show_error('Il Dipendente non può essere vuoto.')
            return False
        self.cursor.execute(FIND_DIPENDENTE, (dipendente, ))
        result = self.cursor.fetchall()
        if not result or not result[0][0]:
            self._show_error('Dipendente {} non esiste.'.format(dipendente))
            return False
        return True

    def post_prenotazione(self):
        if not self.verif_libri():
            return
        if not self.verif_client_dip():
            return
        cliente = self.client_field.text().strip() if self.client_field.text(
        ).strip() else None
        importo = self.importo_field.value()
        self.cursor.execute(
            INSERT_ACQUISTO,
            (self.date_picker.date().toString('MM/dd/yyyy'),
             self.importo_field.value(), self.dip_field.text()))
        new_id = self.cursor.fetchall()[0][0]
        self.cursor.execute(INSERT_PRENOTAZIONE, (new_id, cliente))
        for book in self.books.keys():
            self.cursor.execute(INSERT_COMPRENDE,
                                (new_id, book, self.books[book]))
        self.conn.commit()
        self._show_confirm()
        self.accept()

    def _show_confirm(self):
        dialog = QMessageBox()
        dialog.setWindowTitle('Conferma Prenotazione')
        msg = 'Registrato prenotazione per i seguenti libri:\n{}'
        dialog.setText(
            msg.format('\n'.join(
                ['{} x {}'.format(k, v) for k, v in self.books.items()])))
        dialog.exec_()

    def _show_error(self, msg=''):
        dialog = QMessageBox()
        dialog.setWindowTitle('ERRORE')
        dialog.setText(msg)
        dialog.exec_()
Ejemplo n.º 8
0
class SpotPriceUI(QTabWidget):
    def __init__(self, *args, **kwargs):
        super(SpotPriceUI, self).__init__(*args, **kwargs)
        self.extra_data_widget = QWidget(self)
        # 提取数据tab
        layout = QVBoxLayout()
        # 现货价格源数据
        source_layout = QHBoxLayout()
        self.current_date = QDateEdit(self)
        self.current_date.setDisplayFormat("yyyy-MM-dd")
        self.current_date.setDate(QDate.currentDate())
        self.current_date.setCalendarPopup(True)
        source_layout.addWidget(self.current_date)

        source_layout.addWidget(QLabel("源数据:", self))
        self.source_edit = QLineEdit(self)
        source_layout.addWidget(self.source_edit)
        layout.addLayout(source_layout)
        # 分析
        analysis_layout = QHBoxLayout()
        self.analysis_button = QPushButton("提取数据", self)
        analysis_layout.addWidget(self.analysis_button)

        self.tip_label = QLabel("输入源数据后,点击提取数据进行数据提取.", self)
        analysis_layout.addWidget(self.tip_label)
        analysis_layout.addStretch()
        layout.addLayout(analysis_layout)

        # 预览数据的表格
        self.preview_table = QTableWidget(self)
        self.preview_table.setColumnCount(5)
        self.preview_table.setHorizontalHeaderLabels(["日期", "品种", "交易代码", "现货价", "增减"])
        layout.addWidget(self.preview_table)

        # 提交按钮
        commit_layout = QHBoxLayout()
        commit_layout.addStretch()
        self.commit_button = QPushButton("确认提交", self)
        commit_layout.addWidget(self.commit_button)
        layout.addLayout(commit_layout)

        self.extra_data_widget.setLayout(layout)

        self.addTab(self.extra_data_widget, "数据提取")   # 提取数据tab

        # 修改数据的tab
        self.modify_data_widget = QWidget(self)
        modify_layout = QVBoxLayout()
        params_layout = QHBoxLayout()
        params_layout.addWidget(QLabel("选择日期:", self))
        self.modify_date_edit = QDateEdit(self)
        self.modify_date_edit.setDate(QDate.currentDate())
        self.modify_date_edit.setCalendarPopup(True)
        self.modify_date_edit.setDisplayFormat("yyyy-MM-dd")
        params_layout.addWidget(self.modify_date_edit)
        self.modify_query_button = QPushButton("查询", self)
        params_layout.addWidget(self.modify_query_button)
        self.modify_tip_label = QLabel("选择日期查询出数据,双击要修改的数据编辑正确的数据,点击行尾修改.", self)
        params_layout.addWidget(self.modify_tip_label)
        params_layout.addStretch()

        modify_layout.addLayout(params_layout)

        # 数据表格
        self.modify_table = QTableWidget(self)
        self.modify_table.setColumnCount(6)
        self.modify_table.setHorizontalHeaderLabels(["ID", "日期", "品种", "现货价", "增减", "修改"])
        modify_layout.addWidget(self.modify_table)

        self.modify_data_widget.setLayout(modify_layout)

        self.addTab(self.modify_data_widget, "修改数据")

        self.setStyleSheet(
            "#modifyButton{border:none;color:rgb(180,30,50)}#modifyButton:hover{color:rgb(20,50,160)}"
        )
Ejemplo n.º 9
0
    def createButtonView(self):
        buttons = []
        datePickers = []
        buttonPanel = QWidget()
        buttonPanel.setContentsMargins(0, 0, 0, 0)
        buttonCurrent = QPushButton('Current tasks')
        buttonCurrent.setCheckable(True)
        buttonFinished = QPushButton('Finished tasks')
        buttonFinished.setCheckable(True)
        buttonFilter = QPushButton("Filter by end date")
        buttonApply = QPushButton("Apply")
        buttonFilter.setCheckable(True)
        buttonCurrent.setMaximumWidth(100)
        buttonFinished.setMaximumWidth(100)
        buttonFilter.setMaximumWidth(100)
        buttonApply.setMaximumWidth(100)
        buttonCurrent.setMinimumWidth(100)
        buttonFinished.setMinimumWidth(100)
        buttonFilter.setMinimumWidth(100)
        buttonApply.setMinimumWidth(100)
        buttons.append(buttonFilter)

        #
        labelStart = QLabel("Date start")
        datePickers.append(labelStart)
        dateStart = QDateEdit()
        dateStart.setDisplayFormat('dd/MM/yyyy')
        dateStart.setCalendarPopup(True)
        dateStart.setDate(QDate.currentDate())

        datePickers.append(dateStart)
        labelEnd = QLabel("Date end")
        datePickers.append(labelEnd)
        dateEnd = QDateEdit()
        dateEnd.setDisplayFormat('dd/MM/yyyy')
        dateEnd.setCalendarPopup(True)
        dateEnd.setDate(QDate.currentDate())
        datePickers.append(dateEnd)
        datePickers.append(buttonApply)

        buttonCurrent.clicked.connect(
            self.switchCurrentTask(buttonFinished, buttonCurrent, buttons))
        buttonFinished.clicked.connect(
            self.switchFinishedTask(buttonCurrent, buttonFinished, buttons))
        buttonFilter.clicked.connect(
            self.openDatePickerFilter(datePickers, buttonFilter))
        buttonApply.clicked.connect(
            self.ApplyDateFilterArchive(dateStart, dateEnd))
        buttonCurrent.setChecked(True)

        vBox = QVBoxLayout()
        vBox.addWidget(buttonCurrent)
        vBox.addWidget(buttonFinished)
        vBox.addSpacing(30)
        for bnt in buttons:
            bnt.setVisible(False)
            vBox.addWidget(bnt)
        for datePicker in datePickers:
            datePicker.setVisible(False)
            vBox.addWidget(datePicker)

        vBox.addStretch(1)
        buttonPanel.setLayout(vBox)
        return buttonPanel
Ejemplo n.º 10
0
class ClienteForm(QDialog):
    '''
    Dialog per l'inserimento di un ordine.
    '''
    def __init__(self, conn):
        '''
        Parameters:
            conn : connection
                Connection to the database.
        '''
        super().__init__()
        self.setWindowTitle('Aggiungi Cliente')
        self.setWindowFlag(QtCore.Qt.WindowContextHelpButtonHint, False)

        self.conn = conn
        self.cursor = conn.cursor()

        self.gen_layout = QVBoxLayout()

        self.form_layout = QFormLayout()
        self.form_layout.setRowWrapPolicy(QFormLayout.WrapLongRows)

        # Widgets

        self.nome_field = QLineEdit()
        self.form_layout.addRow('Nome: ', self.nome_field)

        self.cognome_field = QLineEdit()
        self.form_layout.addRow('Cognome: ', self.cognome_field)

        self.date_field = QDateEdit(QDate.currentDate())
        self.date_field.setDisplayFormat("MM/dd/yyyy")
        self.date_field.setCalendarPopup(True)
        self.form_layout.addRow('Data di nascita (mm/gg/aaaa): ',
                                self.date_field)

        self.phone_field = QLineEdit()
        self.form_layout.addRow('Telefono (solo cifre): ', self.phone_field)

        self.email_field = QLineEdit()
        self.form_layout.addRow('E-Mail: ', self.email_field)

        self.confirm_button = QPushButton('Conferma')
        self.confirm_button.clicked.connect(self.post_cliente)

        self.gen_layout.addLayout(self.form_layout)
        self.gen_layout.addWidget(self.confirm_button)
        self.setLayout(self.gen_layout)

    def verif_data(self):
        if not self.nome_field.text().strip():
            self._show_error('Il nome non può essere vuoto.')
            return False
        if not self.cognome_field.text().strip():
            self._show_error('Il cognome non può essere vuoto.')
            return False
        phone = self.phone_field.text().strip()
        email = self.email_field.text().strip()
        if not phone and not email:
            self._show_error(
                'Almeno uno fra telefono ed e-mail deve essere non vuoto.')
            return False
        if phone and not re.match('[0-9]{3,15}', phone):
            self._show_error('Numero di telefono non valido.')
            return False
        if email and not re.match('[A-Za-z0-9\.]{1,}@[A-Za-z0-9\.]{1,}',
                                  email):
            self._show_error('E-Mail non valida.')
            return False
        return True

    def post_cliente(self):

        if not self.verif_data():
            return

        nome = self.nome_field.text().strip()
        cognome = self.cognome_field.text().strip()
        data = self.date_field.date().toString('MM/dd/yyyy')
        phone = self.phone_field.text().strip()
        if not phone: phone = None
        email = self.email_field.text().strip()
        if not email: email = None

        self.cursor.execute(INSERT_CLIENTE,
                            (nome, cognome, data, phone, email))

        self.conn.commit()
        self.accept()

    def _show_error(self, msg=''):
        dialog = QMessageBox()
        dialog.setWindowTitle('ERRORE')
        dialog.setText(msg)
        dialog.exec_()