Source

pacient db / main.py~

Full commit
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import QtSql
from auxiliar import Adresa, SGA
from analize import Analize
import sys 

class First(QtGui.QMainWindow):
    def __init__(self,parent=None):
        #tre sa fac o clasa care sa sa ocupe de tranzactiile sqlite: verificat daca exista entry
        #sa faca prepare and stuff
        self.pacientidb=QtSql.QSqlDatabase.addDatabase("QSQLITE") #TODO: overwrite closeEvent to close database connection
        self.pacientidb.setDatabaseName('data.db') #TODO with pacientidb.close(self?)
        if not self.pacientidb.open():#asta trebe aplicata la fiecare operatiune?
            QtGui.QMessageBox.warning(None, "Eroare tati", \
                        QString("Database Error: %1").arg(self.pacientidb.lastError().text()))
            sys.exit(1)
        self.query=QtSql.QSqlQuery()
        QtGui.QDialog.__init__(self,parent)
        self.setWindowTitle('principale')
        self.centralWidget=QtGui.QWidget(self)

        pacient=QtGui.QPushButton('Adauga pacient')
        evaluare=QtGui.QPushButton('Evaluare pacient')
        salvare=QtGui.QPushButton('salveaza online baza de date')
        salvare.setEnabled(False)
        layout=QtGui.QHBoxLayout()
        layout.addWidget(pacient)
        layout.addWidget(salvare)
        layout.addWidget(evaluare)
        self.centralWidget.setLayout(layout)
        self.setCentralWidget(self.centralWidget)
        self.connect(pacient, QtCore.SIGNAL('clicked()'),self.pacient)
        self.connect(evaluare, QtCore.SIGNAL('clicked()'), self.evaluare)
        
        self.show()
    def focusChanged(self):
        print str(QtGui.QApplication.focusWidget().objectName())
        print QtGui.QApplication.focusWidget().parentWidget().objectName()
    def evaluare(self):
        self.hide()
        self.evaluare_d=Evaluare(self.query,self)
        self.show()
    def pacient(self):
        self.hide()
        self.pacient_d=Pacient(self.query,self)
        self.show()
    def closeEvent(self,event):
        try:
            QtSql.QSqlDatabase.close(self.pacientidb) 
            QtSql.QSqlDatabase.removeDatabase('data.db')
            event.accept()
        except:
            print 'nu am inchis baza de date'
            print self.pacientidb.lastError().text()
            event.ignore()
class Evaluare(QtGui.QDialog):
    def __init__(self,query,parent=None):
        #qcompleter, fuzzy search
        #fuzzy://code.activestate.com/recipes/475148/
        self.query=query
        self.cnp=0
        QtGui.QDialog.__init__(self,parent)
        self.setObjectName('Evaluare')
        self.setWindowTitle('Evaluare')
        cauta=QtGui.QLabel('Cauta pacient')
        self.cautat=QtGui.QLineEdit()
        self.cauta=QtGui.QPushButton('Cauta')
        self.rezultat=QtGui.QListWidget()
        self.adaugaEvaluare_pre=QtGui.QPushButton('Pacient Predializa')
        self.adaugaEvaluare_sga=QtGui.QPushButton('Evaluare SGA')
        self.adaugaEvaluare_adresa=QtGui.QPushButton('Completare adresa Pacient') #TODO later
        layout=QtGui.QGridLayout()
        layout.addWidget(cauta)
        layout.addWidget(self.cautat)
        layout.addWidget(self.cauta)
        layout.addWidget(self.rezultat)
        layout.addWidget(self.adaugaEvaluare_pre)
        layout.addWidget(self.adaugaEvaluare_sga)
        layout.addWidget(self.adaugaEvaluare_adresa)
        self.setLayout(layout)
        self.connect(self.cauta, QtCore.SIGNAL('clicked()'), self.cauta_f)
        self.connect(self.cautat,QtCore.SIGNAL('textChanged(const QString &)'), self.textChangedHandler)
        self.connect(self.cautat,QtCore.SIGNAL('returnPressed()'),self.cauta,QtCore.SLOT('click()'))
        self.connect(self.adaugaEvaluare_pre, QtCore.SIGNAL('clicked()'),\
            lambda:self.adaugaEvaluare_f(self.cnp,"pre"))
        self.connect(self.adaugaEvaluare_adresa, QtCore.SIGNAL('clicked()'),\
            lambda:self.adaugaEvaluare_f(self.cnp,"adresa"))
        self.connect(self.adaugaEvaluare_sga, QtCore.SIGNAL('clicked()'),\
            lambda:self.adaugaEvaluare_f(self.cnp,"sga"))
        self.exec_()

        
    def veziEval(self):
        self.hide()
        eval=Evaluari(self.query,self.cnp,self)
        self.show()
    def textChangedHandler(self):
        print(self.cautat.text())
        print('hai salvarea')

    def textChangedHandler1(self):
        print('a scris ceva')
        a=self.cautat.text().toLower()
        self.query.prepare('select * from pacienti where lower(nume)=?*')
        self.query.exec_()
        while self.query.next():
            print(self.query.value(0).toString())
    def cauta_f(self):
        self.rezultat.clear()
        try:
            a=int(self.cautat.text())
            self.query.prepare('select * from pacienti where cnp=?')
            self.query.addBindValue(QtCore.QVariant(a))
            self.query.exec_()
            self.returnRezult()
        except ValueError:
            self.query.prepare('select * from pacienti where lower(nume)=?')
        for k in 'b':
            self.query.addBindValue(QtCore.QVariant(QtCore.QString(self.cautat.text().toLower())))
            self.query.exec_()
            nume,prenume, data_diabet,data_dializa,cnp =range(5)
            while self.query.next():#a,b,c,d is qstring
                a=self.query.value(nume).toString()
                b=self.query.value(prenume).toString()
                c=self.query.value(data_diabet).toDate()
                d=self.query.value(data_dializa).toDate()
                self.cnp=self.query.value(cnp).toString()#[0]
                final=a+' '+b+'\t'+self.cnp #ma rog....
                self.rezultat.addItem(final)
    def adaugaEvaluare_f(self,cnp,tip):
        if self.rezultat.selectedItems():
            continut=self.rezultat.selectedItems()
            nume=continut[0].text().split('\t')[0]
            cnp=continut[0].text().split('\t')[1]
        else:
            a=QtGui.QErrorMessage(self)
            a.showMessage(QtCore.QString('cauta si tu pa cineva'))
            a.exec_()

        if tip=="pre":
            self.hide()
            self.analize=Analize(self.query,nume,cnp,self) 
            self.show()
        if tip=="sga":
            self.hide()
            self.sga=SGA(self.query,nume,cnp,self)
            self.show()
        if tip=="adresa":
            self.hide()
            self.adresa=Adresa(self.query,cnp,self.rezultat.selectedItems(),self)
            self.show()


       
    

    
class Pacient(QtGui.QDialog):
    def __init__(self,query,parent=None):
        self.query=query
        self.query.exec_("create table  if not exists pacienti (nume varchar(15), prenume varchar(25), data_dializa date,data_diabet date, cnp integer primary key) ")
        #QtGui.QApplication.processEvents()
        QtGui.QDialog.__init__(self,parent)
        self.setWindowTitle('Pacient')
        self.setObjectName('Pacient')
        nume=QtGui.QLabel('Nume')
        self.nume=QtGui.QLineEdit()
        prenume=QtGui.QLabel('Prenume')
        self.prenume=QtGui.QLineEdit()
        cnp=QtGui.QLabel('CNP')
        self.cnp=QtGui.QLineEdit()
        v=QtGui.QRegExpValidator(QtCore.QRegExp("[0-9]{13}"),self.cnp)
        #prima cifra din cnp nu trebe sa fie 0!
        self.cnp.setValidator(v)
        data_diabet=QtGui.QLabel('Debutul Diabetului')
        self.data_diabet=QtGui.QDateEdit()
        self.data_diabet.setCalendarPopup(True)
        data_dializa=QtGui.QLabel('Debutul Dializei')
        self.data_dializa=QtGui.QDateEdit()
        self.data_dializa.setCalendarPopup(True)
        self.adresa=QtGui.QCheckBox("bag si adresa")
        self.adresa.setCheckState(QtCore.Qt.Checked)
        butoane=QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok|QtGui.QDialogButtonBox.Cancel)
        layout=QtGui.QGridLayout()
        layout.addWidget(nume)
        layout.addWidget(self.nume)
        layout.addWidget(prenume)
        layout.addWidget(self.prenume)
        layout.addWidget(cnp)
        layout.addWidget(self.cnp)
        layout.addWidget(data_diabet)
        layout.addWidget(self.data_diabet)
        layout.addWidget(data_dializa)
        layout.addWidget(self.data_dializa)
        layout.addWidget(self.adresa)
        layout.addWidget(butoane)
        self.setLayout(layout)
        #self.connect(butoane,QtCore.SIGNAL('accepted()'),QtCore.SLOT('accept()'))
        self.connect(butoane,QtCore.SIGNAL('rejected()'), QtCore.SLOT('reject()'))
        self.connect(butoane,QtCore.SIGNAL('accepted()'),self.verifica)
        self.connect(self,QtCore.SIGNAL('accepted()'),QtCore.SLOT('accept()'))
        cnpBun=(2,0)
        self.exec_()
    def verifica(self):
        #if self.exec_()==QtGui.QDialog.Accepted and \
        #    v.validate(self.cnp.text(),0)==cnpBun:
        #        self.adaugaPacient()
        #        #self.emit(accept())
        #        self.emit(QtCore.SIGNAL('accepted()'))
        if self.exec_()==QtGui.QDialog.Accepted and \
            v.validate(self.cnp.text(),0) !=cnpBun:
            a=QtGui.QErrorMessage(self)
            a.showMessage(QtCore.QString('cnpu nu e bun'))
            a.exec_()
        else:
            self.adaugaPacient()
            print(self.query.lastError())
            self.emit(QtCore.SIGNAL('accepted()'))


    def insert_pacient(self,nume,prenume,data_dializa,data_diabet,cnp):
        self.query.prepare("select * from pacienti where cnp=?")
        self.query.addBindValue(QtCore.QVariant(QtCore.QString(cnp)))
        self.query.exec_()
        nume_cautat=[]
        prenume_cautat=[]
        cnp_cautat=[]
        while self.query.next():
            nume_cautat.append(self.query.value(0))
            prenume_cautat.append(self.query.value(1))
            cnp_cautat.append(self.query.value(2))
        if nume and cnp_cautat:
            QtGui.QMessageBox.warning(self, "nu e bine", "CNPu cautat %(cnp)s e deja in baza de date pentru %(nume)s" %{'cnp':cnp,'nume':nume})
        else:
            self.query.prepare("insert into pacienti (nume, prenume, data_dializa, data_diabet, cnp) values (?,?,?,?,?)")
            self.query.addBindValue(QtCore.QVariant(QtCore.QString(nume)))
            self.query.addBindValue(QtCore.QVariant(QtCore.QString(prenume)))
            self.query.addBindValue(QtCore.QVariant(data_dializa))
            self.query.addBindValue(QtCore.QVariant(data_diabet))
            self.query.addBindValue(QtCore.QVariant(QtCore.QString(cnp)))
            self.query.exec_()
  
    def adaugaPacient(self):
        try:
            self.insert_pacient(self.nume.text().toLower(),self.prenume.text().toLower(), self.data_dializa.date(), \
                       self.data_diabet.date(),self.cnp.text())
        except ValueError,e: #am reparat CNPU nu stiu la ce value error sa mai astept
            a=QtGui.QErrorMessage(self)
            a.showMessage(QtCore.QString('una din valorile introduse nu e buna'))
            a.exec_()

        #QtGui.QApplication.processEvents()
        if self.adresa.isChecked():Adresa(self.query,self.cnp.text(),self.nume.text().toLower()) #urat..de refacut

class Main(object):
    def __init__(self,argv):
        self.argv=argv
        self.qapp=QtGui.QApplication([self.argv])
        self.first=First()
        QtCore.QObject.connect(self.qapp, QtCore.SIGNAL("focusChanged(\
        QWidget *, QWidget*)"), self.first.focusChanged)

        sys.exit(self.qapp.exec_())
a=Main(sys.argv)