Ejemplo n.º 1
0
class CatalogFilterDate(CatalogFilter):
    def __init__(self, id):
        super(CatalogFilterDate, self).__init__(id)
        self.label = QLabel(TEXT_LABEL_BETWEEN)

        self.datetime_begin_edit = QDateEdit(QDate.currentDate())
        self.datetime_end_edit = QDateEdit(QDate.currentDate())
        self.datetime_begin_edit.setCalendarPopup(True)
        self.datetime_end_edit.setCalendarPopup(True)
        self.expand_widget(self.datetime_begin_edit)
        self.expand_widget(self.datetime_end_edit)

        value_item = QGridLayout()
        value_item.addWidget(self.datetime_begin_edit, 0, 0)
        value_item.addWidget(QLabel(TEXT_LABEL_AND), 0, 1)
        value_item.addWidget(self.datetime_end_edit, 0, 2)
        self.value_item = value_item

    def get_query_filters(self):
        # date request filter values are returned by get_datetime_begin/end
        return []

    def validate(self, errors):
        datetime_begin = self.datetime_begin_edit.dateTime()
        datetime_end = self.datetime_end_edit.dateTime()
        if datetime_begin.daysTo(datetime_end) < 0:
            errors.append("First value must be less than or equal to second for %s filter." % self.column_name)

    def get_datetime_begin(self):
        return self.datetime_begin_edit.dateTime().toString(DATETIME_FORMAT)

    def get_datetime_end(self):
        return self.datetime_end_edit.dateTime().toString(DATETIME_FORMAT)
Ejemplo n.º 2
0
 def createEditor(self, parent, option, index):
     dateedit = QDateEdit(parent)
     dateedit.setDateRange(self.minimum, self.maximum)
     dateedit.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
     dateedit.setDisplayFormat(self.format)
     dateedit.setCalendarPopup(True)
     return dateedit
Ejemplo n.º 3
0
class NewTaskDialog(QDialog):

    def __init__(self, parent=None):
        super(NewTaskDialog, self).__init__(parent)
        # task name
        nameLabel = QLabel(self.tr("Name:"))
        self.name = QLineEdit()
        nameLabel.setBuddy(self.name)
        # priority
        priorityLabel = QLabel(self.tr("Priority:"))
        self.priority = QComboBox()
        priorityLabel.setBuddy(self.priority)

        dateLabel = QLabel(self.tr("Deadline:"))
        self.deadline = QDateEdit()
        dateLabel.setBuddy(self.deadline)

        self.deadline.setCalendarPopup(True)
        self.deadline.calendarWidget().setFirstDayOfWeek(Qt.Monday)
        self.deadline.setDate(QDate(date.today()))

        createButton = QPushButton(self.tr("Save"))
        cancelButton = QPushButton(self.tr("Cancel"))

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch()
        buttonLayout.addWidget(createButton)
        buttonLayout.addWidget(cancelButton)

        layout = QGridLayout()
        layout.addWidget(nameLabel, 0, 0)
        layout.addWidget(self.name, 0, 1)

        layout.addWidget(priorityLabel, 1, 0)
        layout.addWidget(self.priority, 1, 1)

        layout.addWidget(dateLabel, 2, 0)
        layout.addWidget(self.deadline, 2, 1)
        layout.addLayout(buttonLayout, 3, 0, 3, 2)
        self.setLayout(layout)

        self.connect(self.deadline, SIGNAL("dateChanged(const QDate&)"), self, SLOT("changed()"))
        self.connect(createButton, SIGNAL("clicked()"), self, SLOT("accept()"))
        self.connect(cancelButton, SIGNAL("clicked()"), self, SLOT("reject()"))
        self.setWindowTitle(self.tr("Task"))
        self.resize(350, 120)
        self.setMinimumSize(QSize(250, 120))
        self.setMaximumSize(QSize(450, 120))


    @pyqtSlot()
    def changed(self):
        print(self.deadline.text())
Ejemplo n.º 4
0
    def _create_widget(cls, c, parent):
        dt = QDateEdit(parent)
        dt.setObjectName(u'{0}_{1}'.format(cls._TYPE_PREFIX, c.name))
        dt.setCalendarPopup(True)

        #Set ranges
        if c.min_use_current_date:
            dt.setMinimumDate(date.today())
        else:
            dt.setMinimumDate(c.minimum)

        if c.max_use_current_date:
            dt.setMaximumDate(date.today())
        else:
            dt.setMaximumDate(c.maximum)

        #Set maximum date as current date
        dt.setDate(date.today())

        return dt
Ejemplo n.º 5
0
class DlgCredito( QDialog ):
    def __init__( self, parent = None ):
        super( DlgCredito, self ).__init__( parent )

        self.dtFechaTope = QDateEdit( QDate.currentDate().addDays( 1 ) )
        self.dtFechaTope.setMinimumDate( QDate.currentDate().addDays( 1 ) )
        """
        @ivar: Este widget tiene la fecha tope en la que puede 
            pagarse el credito
        @type: QDateEdit
        """
        self.sbTaxRate = QDoubleSpinBox()
        """
        @ivar: Este widget contiene la tasa de multa que se
            le aplicara a este credito
        @typ: QDoubleSpinBox
        """

        self.setupUi()

    def setupUi( self ):
        vertical_layout = QVBoxLayout( self )

        form_layout = QFormLayout()

        self.dtFechaTope.setCalendarPopup( True )
        self.sbTaxRate.setSuffix( '%' )

        form_layout.addRow( u"<b>Fecha Tope</b>", self.dtFechaTope )
        form_layout.addRow( u"<b>Tasa de multa</b>", self.sbTaxRate )

        buttonbox = QDialogButtonBox( QDialogButtonBox.Ok |
                                      QDialogButtonBox.Cancel )

        vertical_layout.addLayout( form_layout )
        vertical_layout.addWidget( buttonbox )

        buttonbox.accepted.connect( self.accept )
        buttonbox.rejected.connect( self.reject )
Ejemplo n.º 6
0
 def createEditor(self, parent, option, index):
     if index.column() == DATAINS:
         editor = QDateEdit(parent)
         editor.setCalendarPopup(True)
         editor.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
         return editor
     elif index.column() == QT:
         editor = QLineEdit(parent)
         validator = QIntValidator(self)
         editor.setValidator(validator)
         editor.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
         return editor
     elif index.column() == IMP:
         editor = QLineEdit(parent)
         validator = QDoubleValidator(self)
         validator.setDecimals(3)
         editor.setValidator(validator)
         editor.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
         return editor
     else:
         return QSqlRelationalDelegate.createEditor(self, parent, option,
                                                    index)
Ejemplo n.º 7
0
class AddForm(QDialog):
    def __init__(self, parent=None):
        super(AddForm, self).__init__(parent)

        self.l1 = QLabel("Name")
        self.le = QLineEdit()
        self.le.setObjectName("name")
        self.le.setText("")

        self.l2 = QLabel("Start Date")
        self.le2 = QDateEdit()
        self.le2.setObjectName("startdate")
        self.le2.setCalendarPopup(True)

        self.l3 = QLabel("End Date")
        self.le3 = QDateEdit()
        self.le3.setObjectName("enddate")
        self.le3.setCalendarPopup(True)

        self.pb = QPushButton()
        self.pb.setObjectName("Submit")
        self.pb.setText("Submit")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        layout = QFormLayout()
        layout.addRow(self.l1, self.le)
        layout.addRow(self.l2, self.le2)
        layout.addRow(self.l3, self.le3)
        layout.addRow(self.pb1, self.pb)

        groupBox = QGroupBox('Add Session')
        groupBox.setLayout(layout)

        grid = QGridLayout()
        grid.addWidget(groupBox, 0, 0)
        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"),
                     lambda: self.button_click(self))
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close(self))
        self.setWindowTitle("Session Manager")

    def button_click(self, a):
        # shost is a QString object
        a.close()
        s1 = self.le.text()
        s2 = self.le2.date().toPyDate()
        s3 = self.le3.date().toPyDate()
        g = Db()
        try:
            if (len(s1) > 0):
                y = {'name': s1, 'start_date': s2, 'end_date': s3, 'active': 0}
                z = g.insert('session', y)
                if z and z > 0:
                    g.createExpenses(z)
                    g.createStores(z)
                    g.createAwards(z)
                    g.createConducts(z)
                    g.createMails(z)
                    g.createMedicals(z)
            else:
                pass
        except:
            pass

        try:
            self.button_close()
        except:
            pass
        try:
            self.close()
        except:
            pass

    def lunchForm(self):
        self.form = SessionForm()
        self.form.show()

    def button_close(self, a):
        a.close()
Ejemplo n.º 8
0
class LDSControls(QFrame):
        
    STATIC_IMG = ('error_static.png','linz_static.png','busy_static.png','clean_static.png')
    ANIM_IMG   = ('error.gif','linz.gif','layer.gif','clean.gif')
    
    IMG_SPEED  = 100
    IMG_WIDTH  = 64
    IMG_HEIGHT = 64
    
    MAX_WD = 450
    
    GD_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../bin/gdal/gdal-data'))
    STATUS = LU.enum('ERROR','IDLE','BUSY','CLEAN')
    
    def __init__(self,parent):
        super(LDSControls, self).__init__()
        self.parent = parent
        self.initConf()
        self.initEPSG()
        self.initUI()
        
    def initConf(self):
        '''Read files in conf dir ending in conf'''
        self.cflist = ConfigInitialiser.getConfFiles()
        #self.imgset = self.STATIC_IMG if ConfigWrapper().readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        #self.imgset = self.STATIC_IMG if self.parent.confconn.tp.src.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        sep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.SRCNAME,self.parent.confconn.uconf)
        self.imgset = self.STATIC_IMG if sep.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.SRCNAME)
        
    def initEPSG(self):
        '''Read GDAL EPSG files, splitting by NZ(RSR) and RestOfTheWorld'''

        gcsf = gdal.FindFile('gdal','gcs.csv') 
        if not gcsf:
            gcsf = os.path.join(self.GD_PATH,'gcs.csv')
        pcsf = gdal.FindFile('gdal','pcs.csv') 
        if not pcsf: 
            pcsf = os.path.join(self.GD_PATH,'pcs.csv')
        gcs = ConfigInitialiser.readCSV(gcsf)
        pcs = ConfigInitialiser.readCSV(pcsf)

        self.nzlsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]]
        self.rowsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]]
                   
                   
    def initUI(self):
        
        # 0      1          2       3       4       5      6    7    8
        #'destname','lgselect','layer','uconf','group','epsg','fd','td','int'
        
        #self.rdest,rlgselect,self.rlayer,ruconf,self.rgroup,repsg,rfd,rtd,rint = readlist 
        
        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        destLabel = QLabel('Destination')
        lgLabel = QLabel('Group/Layer')
        epsgLabel = QLabel('EPSG')
        fromDateLabel = QLabel('From Date')
        toDateLabel = QLabel('To Date')
        confLabel = QLabel('User Config')
        
        self.view = QLabel() 
        self.view.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.view.setAlignment(Qt.AlignCenter)

        self.confcombo = QComboBox(self)
        self.confcombo.setToolTip('Enter your user config name (file) here')
        self.confcombo.addItems(self.cflist)
        self.confcombo.setEditable(False)
        #self.confcombo.currentIndexChanged.connect(self.doLGEditUpdate)
        
        #combos
        self.lgcombo = QComboBox(self)
        self.lgcombo.setMaximumWidth(self.MAX_WD)
        self.lgcombo.setDuplicatesEnabled(False)
        #self.lgcombo.setInsertPolicy(QComboBox.InsertAlphabetically)#?doesnt seem to work
        self.lgcombo.setToolTip('Select either Layer or Group entry')
        self.lgcombo.setEditable(False)
        self.sepindex = None
        #self.updateLGValues()
        
        self.epsgcombo = QComboBox(self)
        self.epsgcombo.setMaximumWidth(self.MAX_WD)
        self.epsgcombo.setToolTip('Setting an EPSG number here determines the output SR of the layer')  
        self.epsgcombo.addItems([i[1] for i in self.nzlsr])
        self.epsgcombo.insertSeparator(len(self.nzlsr))
        self.epsgcombo.addItems([i[1] for i in self.rowsr])
        self.epsgcombo.setEditable(True)
        self.epsgcombo.setEnabled(False)
        
        self.destlist = self.getConfiguredDestinations()
        self.destcombo = QComboBox(self)
        self.destcombo.setToolTip('Choose the desired output type')   
        self.destcombo.setEditable(False)
        self.destcombo.addItems(self.destlist)

        #date selection
        self.fromdateedit = QDateEdit()
        self.fromdateedit.setCalendarPopup(True)
        self.fromdateedit.setEnabled(False)
        
        self.todateedit = QDateEdit()
        self.todateedit.setCalendarPopup(True)
        self.todateedit.setEnabled(False)
        
        #check boxes
        self.epsgenable = QCheckBox()
        self.epsgenable.setCheckState(False)
        self.epsgenable.clicked.connect(self.doEPSGEnable)       
        
        self.fromdateenable = QCheckBox()
        self.fromdateenable.setCheckState(False)
        self.fromdateenable.clicked.connect(self.doFromDateEnable)
        
        self.todateenable = QCheckBox()
        self.todateenable.setCheckState(False) 
        self.todateenable.clicked.connect(self.doToDateEnable)
        
        self.progressbar = QProgressBar()
        self.progressbar.setRange(0,100)
        self.progressbar.setVisible(True)
        self.progressbar.setMinimumWidth(self.MAX_WD)
        
        
        #buttons        
        self.initbutton = QPushButton("waiting")
        self.initbutton.setToolTip('Initialise the Layer Configuration')
        self.initbutton.clicked.connect(self.doInitClickAction)
        
        self.cleanbutton = QPushButton("Clean")
        self.cleanbutton.setToolTip('Clean the selected layer/group from local storage')
        self.cleanbutton.clicked.connect(self.doCleanClickAction)
        
        self.replicatebutton = QPushButton("Replicate")
        self.replicatebutton.setToolTip('Execute selected replication')
        self.replicatebutton.clicked.connect(self.doReplicateClickAction)
        
        self.cancelbutton = QPushButton("Close")
        self.cancelbutton.setToolTip('Close the LDS Replicate application')       
        self.cancelbutton.clicked.connect(self.parent.close)


        #set dialog values using GPR
        self.updateGUIValues(self.parent.gvs)
        
        #set onchange here otherwise we get circular initialisation
        self.destcombo.currentIndexChanged.connect(self.doDestChanged)
        self.confcombo.currentIndexChanged.connect(self.doConfChanged)
        self.lgcombo.currentIndexChanged.connect(self.doLGComboChanged)

        self.setStatus(self.STATUS.IDLE)
        
        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        
        #placement section ------------------------------------
        #---------+---------+--------+---------+--------
        # dest LB |         | dest DD
        # grp LB  |         | grp DD
        # conf LB |         | conf DD
        # epsg L  | epsg CB | epsg DD
        # f dt L  | f dt CB | f dt DD
        # t td L  | t td CB | t td DD
        # icon    |       <- progress ->
        # layer B | <- . -> |repl B  | clean B | close B 
        #---------+---------+--------+---------+--------

        grid.addWidget(destLabel, 1, 0)
        grid.addWidget(self.destcombo, 1, 2)

        #grid.addWidget(layerLabel, 2, 0)
        grid.addWidget(lgLabel, 2, 0)
        grid.addWidget(self.lgcombo, 2, 2)
        
        grid.addWidget(confLabel, 3, 0)
        grid.addWidget(self.confcombo, 3, 2)
        
        #grid.addWidget(groupLabel, 4, 0)
        #grid.addWidget(self.groupEdit, 4, 2)
        
        grid.addWidget(epsgLabel, 5, 0)
        grid.addWidget(self.epsgenable, 5, 1)
        grid.addWidget(self.epsgcombo, 5, 2)

        grid.addWidget(fromDateLabel, 6, 0)
        grid.addWidget(self.fromdateenable, 6, 1)
        grid.addWidget(self.fromdateedit, 6, 2)
        
        grid.addWidget(toDateLabel, 7, 0)
        grid.addWidget(self.todateenable, 7, 1)
        grid.addWidget(self.todateedit, 7, 2)
        
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.view) 
        hbox3.addStretch(1)
        hbox3.addWidget(self.progressbar)

        #hbox3.addLayout(vbox2)
        #hbox3.addLayout(vbox3)
        
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.initbutton)
        hbox4.addStretch(1)
        hbox4.addWidget(self.replicatebutton)
        hbox4.addWidget(self.cleanbutton)
        hbox4.addWidget(self.cancelbutton)
        

        vbox = QVBoxLayout()
        #vbox.addStretch(1)
        vbox.addLayout(grid)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        
        self.setLayout(vbox)  
       
    #def setProgress(self,pct):
    #    self.progressbar.setValue(pct)
        
    def setStatus(self,status,message='',tooltip=None):
        '''Sets indicator icon and statusbar message'''
        self.parent.statusbar.showMessage(message)
        self.parent.statusbar.setToolTip(tooltip if tooltip else '')

        #progress
        loc = os.path.abspath(os.path.join(IMG_LOC,self.imgset[status]))
        #loc = os.path.abspath(os.path.join(os.path.dirname(__file__),self.parent.IMG_LOC,self.imgset[status]))
        self.progressbar.setVisible(status in (self.STATUS.BUSY, self.STATUS.CLEAN))
        
        #icon
        anim = QMovie(loc, QByteArray(), self)
        anim.setScaledSize(QSize(self.IMG_WIDTH,self.IMG_HEIGHT))
        anim.setCacheMode(QMovie.CacheAll)
        anim.setSpeed(self.IMG_SPEED)
        self.view.clear()
        self.view.setMovie(anim)
        anim.start()

        self.view.repaint()
        QApplication.processEvents(QEventLoop.AllEvents)

    def mainWindowEnable(self,enable=True):
        cons = (self.lgcombo, self.confcombo, self.destcombo, 
                self.initbutton, self.replicatebutton, self.cleanbutton, self.cancelbutton,
                self.epsgenable,self.fromdateenable,self.todateenable,
                self.parent.menubar)
        for c in cons:
            c.setEnabled(enable)
            
        if enable:
            self.epsgcombo.setEnabled(self.epsgenable.checkState())
            self.fromdateedit.setEnabled(self.fromdateenable.checkState())
            self.todateedit.setEnabled(self.todateenable.checkState())
        else:
            self.epsgcombo.setEnabled(False)
            self.fromdateedit.setEnabled(False)
            self.todateedit.setEnabled(False)
   
        QApplication.restoreOverrideCursor() if enable else QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) 

    def refreshLGCombo(self):
        '''Re index LG combobox since a refreshLG call (new dest?) will usually mean new groups'''
        self.lgcombo.clear()
        self.lgcombo.addItems([i[2] for i in self.parent.confconn.lglist])
        #NOTE the separator consumes an index, if not clearing the combobox selectively remove the old sepindex (assumes g preceeds l)
        #if self.sepindex:
        #    self.lgcombo.removeItem(self.sepindex)
        self.sepindex = [i[0] for i in self.parent.confconn.lglist].count(LORG.GROUP)
        self.lgcombo.insertSeparator(self.sepindex)
        
    def updateLGValues(self,uconf,lgval,dest):
        '''Sets the values displayed in the Layer/Group combo'''
        #because we cant seem to sort combobox entries and want groups at the top, clear and re-add
        #TRACE#        
        #pdb.set_trace()
        sf = None
        try:
            self.parent.confconn.initConnections(uconf,lgval,dest)
        except Exception as e:
            sf=1
            ldslog.error('Error Updating UC Values. '+str(e))
            
        if sf:
            self.setStatus(self.STATUS.ERROR,'Error Updating UC Values', str(e))
        else:
            self.setStatus(self.STATUS.IDLE)
            
        self.refreshLGCombo()
        
    def centre(self):
        
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
    
    def gprParameters(self,rdest):
        '''Zip default and GPR values'''
        return [x if LU.assessNone(x) else y for x,y in zip(self.parent.gpr.readsec(rdest),self.parent.DEF_RVALS[1:])]
    
    def getLCE(self,ln):
        '''Read layer parameters'''
        dep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        #sep = self.parent.confconn.reg.openEndPoint('WFS',self.parent.confconn.uconf)
        self.parent.confconn.reg.setupLayerConfig(self.parent.confconn.tp,None,dep,initlc=False)
        lce = dep.getLayerConf().readLayerParameters(ln)
        #self.parent.confconn.reg.closeEndPoint('WFS')
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        sep,dep = None,None
        return lce
    
    
    def doDestChanged(self):
        '''Read the destname parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rvals = self.gprParameters(rdest)
        self.updateGUIValues([rdest]+rvals)    
        
        
    def doConfChanged(self):
        '''Read the user conf parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rlg,_,rep,rfd,rtd = self.gprParameters(rdest)
        ruc = str(self.cflist[self.confcombo.currentIndex()])
        self.updateGUIValues((rdest,rlg,ruc,rep,rfd,rtd))
        
        
    def doLGComboChanged(self):
        '''Read the layer/group value and change epsg to layer or gpr match'''
        #get a matching LG entry and test whether its a layer or group
        #lgi = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgi = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #lgi can be none if we init a new group, in which case we use the GPR value
        if lgi:
            lge = self.parent.confconn.lglist[lgi]
            lce = self.getLCE(lge[1]) if lge[0]==LORG.LAYER else None
        else:
            lce = None
        
        #look for filled layer conf epsg OR use prefs stored in gpr
        if lce and LU.assessNone(lce.epsg):
            epsgval = lce.epsg
        else:
            rdest = str(self.destlist[self.destcombo.currentIndex()])
            _,_,epsgval,_,_ = self.gprParameters(rdest)
        epsgindex = [i[0] for i in self.nzlsr+[(0,0)]+self.rowsr].index(epsgval)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(int(epsgindex))

        
    def updateGUIValues(self,readlist):
        '''Fill dialog values from provided list'''
        #TODO. Remove circular references when setCurrentIndex() triggers do###Changed()
        #Read user input
        rdest,self.rlgval,ruconf,repsg,rfd,rtd = readlist
        
        #--------------------------------------------------------------------
        
        #Destination Menu
        selecteddest = LU.standardiseDriverNames(rdest)
        if selecteddest not in self.destlist:
            self.destlist = self.getConfiguredDestinations()
            self.destcombo.addItem(selecteddest)
        destindex = self.destlist.index(selecteddest) if selecteddest else 0
        
        if self.destcombo.currentIndex() != destindex:
            self.destcombo.setCurrentIndex(destindex)
        
        #InitButton
        self.initbutton.setText('Layer Select')
        
        #Config File
        confindex = 0
        if LU.assessNone(ruconf):
            ruconf = ruconf.split('.')[0]
            if ruconf not in self.cflist:
                self.cflist += [ruconf,]
                self.confcombo.addItem(ruconf)
            confindex = self.cflist.index(ruconf)
            
        if self.confcombo.currentIndex() != confindex:
            self.confcombo.setCurrentIndex(confindex)
        #self.confEdit.setText(ruconf if LU.assessNone(ruconf) else '')
        
        #Layer/Group Selection
        self.updateLGValues(ruconf,self.rlgval,rdest)
        lgindex = None
        if LU.assessNone(self.rlgval):
            #index of list value
            lgindex = self.parent.confconn.getLayerGroupIndex(self.rlgval,col=1)
            
        if LU.assessNone(lgindex):
            #advance by 1 for sep
            lgindex += 1 if lgindex>self.sepindex else 0 
        else:
            #using the separator index sets the combo to blank
            lgindex = self.sepindex
        if self.lgcombo.currentIndex() != lgindex:
            self.lgcombo.setCurrentIndex(lgindex)
        #self.doLGEditUpdate()
        
        #EPSG
        #                                user > layerconf
        #useepsg = LU.precedence(repsg, lce.epsg if lce else None, None)
        epsgindex = [i[0] for i in self.nzlsr+[(None,None)]+self.rowsr].index(repsg)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(epsgindex)
            
        #epsgedit = self.epsgcombo.lineEdit()
        #epsgedit.setText([e[1] for e in self.nzlsr+self.rowsr if e[0]==repsg][0])
        
        #epsgedit.setText([e for e in self.nzlsr+self.rowsr if re.match('^\s*(\d+).*',e).group(1)==repsg][0])
        
        #To/From Dates
        if LU.assessNone(rfd):
            self.fromdateedit.setDate(QDate(int(rfd[0:4]),int(rfd[5:7]),int(rfd[8:10])))
        else:
            early = DataStore.EARLIEST_INIT_DATE
            self.fromdateedit.setDate(QDate(int(early[0:4]),int(early[5:7]),int(early[8:10])))
            
        if LU.assessNone(rtd):
            self.todateedit.setDate(QDate(int(rtd[0:4]),int(rtd[5:7]),int(rtd[8:10]))) 
        else:
            today = DataStore.getCurrent()
            self.todateedit.setDate(QDate(int(today[0:4]),int(today[5:7]),int(today[8:10])))
            
        #Internal/External CheckBox
#        if LU.assessNone(rint):
#            self.internalTrigger.setChecked(rint.lower()==DataStore.CONF_INT)
#        else:
#            self.internalTrigger.setChecked(DataStore.DEFAULT_CONF==DataStore.CONF_INT)
        
        
    def getConfiguredDestinations(self):
        defml = ['',]+DataStore.DRIVER_NAMES.values()
        return [d for d in self.parent.gpr.getDestinations() if d in defml]
        
    def doEPSGEnable(self):
        self.epsgcombo.setEnabled(self.epsgenable.isChecked())
        
    def doFromDateEnable(self):
        self.fromdateedit.setEnabled(self.fromdateenable.isChecked())
          
    def doToDateEnable(self):
        self.todateedit.setEnabled(self.todateenable.isChecked())  
          
    def readParameters(self):
        '''Read values out of dialogs'''
        destination = LU.assessNone(str(self.destlist[self.destcombo.currentIndex()]))
        #lgindex = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgindex = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #NB need to test for None explicitly since zero is a valid index
        lgval = self.parent.confconn.lglist[lgindex][1] if LU.assessNone(lgindex) else None       
        #uconf = LU.standardiseUserConfigName(str(self.confcombo.lineEdit().text()))
        #uconf = str(self.confcombo.lineEdit().text())
        uconf = str(self.cflist[self.confcombo.currentIndex()])
        ee = self.epsgenable.isChecked()
        epsg = None if ee is False else re.match('^\s*(\d+).*',str(self.epsgcombo.lineEdit().text())).group(1)
        fe = self.fromdateenable.isChecked()
        te = self.todateenable.isChecked()
        fd = None if fe is False else str(self.fromdateedit.date().toString('yyyy-MM-dd'))
        td = None if te is False else str(self.todateedit.date().toString('yyyy-MM-dd'))
        
        return destination,lgval,uconf,epsg,fe,te,fd,td
    
    def doInitClickAction(self):
        '''Initialise the LC on LC-button-click, action'''
        try:
            try:
                self.setStatus(self.STATUS.BUSY,'Opening Layer-Config Editor')  
                self.progressbar.setValue(0)
                self.parent.runLayerConfigAction()
            finally:
                self.setStatus(self.STATUS.IDLE,'Ready')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Error in Layer-Config',str(sys.exc_info()))#e))
        
    def doCleanClickAction(self):
        '''Set clean anim and run clean'''
        #lgo = self.lgcombo.currentText().toUtf8().data()
        lgo = LQ.readWidgetText(self.lgcombo.currentText())
        
        try:
            self.setStatus(self.STATUS.CLEAN,'Running Clean '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(True)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Clean of '+lgo,str(sys.exc_info()))#e))
        
    def doReplicateClickAction(self):
        '''Set busy anim and run repl'''
        lgo = self.lgcombo.currentText()#.toUtf8().data()#only used for error messages
        try:
            self.setStatus(self.STATUS.BUSY,'Running Replicate '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(False)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Replication of '+lgo,str(sys.exc_info()))#e))

    def runReplicationScript(self,clean=False):
        '''Run the layer/group repliction script'''
        destination,lgval,uconf,epsg,fe,te,fd,td = self.readParameters()
        uconf_path = LU.standardiseUserConfigName(uconf)
        destination_path = LU.standardiseLayerConfigName(destination)
        destination_driver = LU.standardiseDriverNames(destination)

        if not os.path.exists(uconf_path):
            self.userConfMessage(uconf_path)
            return
        elif not MainFileReader(uconf_path).hasSection(destination_driver):
            self.userConfMessage(uconf_path,destination_driver)
            return
        #-----------------------------------------------------
        #'destname','layer','uconf','group','epsg','fd','td','int'
     
        self.parent.gpr.write((destination_driver,lgval,uconf,epsg,fd,td))        
        ldslog.info(u'dest={0}, lg={1}, conf={2}, epsg={3}'.format(destination_driver,lgval,uconf,epsg))
        ldslog.info('fd={0}, td={1}, fe={2}, te={3}'.format(fd,td,fe,te))
        lgindex = self.parent.confconn.getLayerGroupIndex(lgval,col=1)
        #lorg = self.parent.confconn.lglist[lgindex][0]
        #----------don't need lorg in TP anymore but it is useful for sorting/counting groups
        #self.parent.confconn.tp.setLayerOrGroup(lorg)
        self.parent.confconn.tp.setLayerGroupValue(lgval)
        if self.fromdateenable.isChecked(): self.parent.confconn.tp.setFromDate(fd)
        if self.todateenable.isChecked(): self.parent.confconn.tp.setToDate(td)
        self.parent.confconn.tp.setUserConf(uconf)
        if self.epsgenable: self.parent.confconn.tp.setEPSG(epsg)
        
        #because clean state persists in TP
        if clean:
            self.parent.confconn.tp.setCleanConfig()
        else:
            self.parent.confconn.tp.clearCleanConfig()
        #(re)initialise the data source since uconf may have changed
        #>>#self.parent.confconn.tp.src = self.parent.confconn.initSourceWrapper()
        #--------------------------
        ###ep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        
        ###self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        ###ep = None
        #Open ProcessRunner and run with TP(proc)/self(gui) instances
        #HACK temp add of dest_drv to PR call
        try:
            #TODO. Test for valid LC first
            self.tpr = ProcessRunner(self,destination_driver)
        except Exception as e:
            ldslog.error('Cannot create ProcessRunner {}. NB Possible missing Layer Config {}'.format(str(e),destination_path))
            self.layerConfMessage(destination_path)
            return
        #If PR has been successfully created we must vave a valid dst    
        self.tpr.start()
        
    def quitProcessRunner(self):
        self.tpr.join()
        self.tpr.quit()
        self.trp = None

        
    def userConfMessage(self,uconf,secname=None):
        ucans = QMessageBox.warning(self, 'User Config Missing/Incomplete', 
                                'Specified User-Config file, '+str(uconf)+' does not exist' if secname is None else 'User-Config file does not contain '+str(secname)+' section', 
                                'Back','Initialise User Config')
        if not ucans:
            #Retry
            ldslog.warn('Retry specifying UC')
            #self.confcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset User Config Wizard')
        self.parent.runWizardAction()


    def layerConfMessage(self,dest):
        lcans = QMessageBox.warning(self, 'Layer Config Missing', 
                                'Required Layer-Config file, '+str(dest)+' does not exist', 
                                'Back','Run Layer Select')
        if not lcans:
            #Retry
            ldslog.warn('Retry specifying LC')
            #self.destcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset Layer Config')
        self.doInitClickAction()
Ejemplo n.º 9
0
class QtDateSelector(QtBoundedDate, ProxyDateSelector):
    """ A Qt implementation of an Enaml ProxyDateSelector.

    """

    #: A reference to the widget created by the proxy.
    widget = Typed(QDateEdit)

    # --------------------------------------------------------------------------
    # Initialization API
    # --------------------------------------------------------------------------
    def create_widget(self):
        """ Create the QDateEdit widget.

        """
        self.widget = QDateEdit(self.parent_widget())

    def init_widget(self):
        """ Initialize the widget.

        """
        super(QtDateSelector, self).init_widget()
        d = self.declaration
        self.set_date_format(d.date_format)
        self.set_calendar_popup(d.calendar_popup)
        self.widget.dateChanged.connect(self.on_date_changed)

    # --------------------------------------------------------------------------
    # Abstract API Implementation
    # --------------------------------------------------------------------------
    def get_date(self):
        """ Return the current date in the control.

        Returns
        -------
        result : date
            The current control date as a date object.

        """
        return self.widget.date().toPyDate()

    def set_minimum(self, date):
        """ Set the widget's minimum date.

        Parameters
        ----------
        date : date
            The date object to use for setting the minimum date.

        """
        self.widget.setMinimumDate(date)

    def set_maximum(self, date):
        """ Set the widget's maximum date.

        Parameters
        ----------
        date : date
            The date object to use for setting the maximum date.

        """
        self.widget.setMaximumDate(date)

    def set_date(self, date):
        """ Set the widget's current date.

        Parameters
        ----------
        date : date
            The date object to use for setting the date.

        """
        self._guard |= CHANGED_GUARD
        try:
            self.widget.setDate(date)
        finally:
            self._guard &= ~CHANGED_GUARD

    def set_date_format(self, format):
        """ Set the widget's date format.

        Parameters
        ----------
        format : str
            A Python time formatting string.

        """
        # XXX make sure Python's and Qt's format strings are the
        # same, or convert between the two.
        self.widget.setDisplayFormat(format)

    def set_calendar_popup(self, popup):
        """ Set whether a calendar popup is available on the widget.

        Parameters
        ----------
        popup : bool
            Whether the calendar popup is enabled.

        """
        self.widget.setCalendarPopup(popup)
Ejemplo n.º 10
0
 def createEditor(self, parent, option, index):
     editor = QDateEdit(parent)
     editor.setCalendarPopup(True)
     return editor
Ejemplo n.º 11
0
class TalkDetailsWidget(QWidget):
    def __init__(self, parent=None):
        super(TalkDetailsWidget, self).__init__(parent)

        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.buttonLayout = QHBoxLayout()

        saveIcon = QIcon.fromTheme("document-save")
        self.saveButton = QPushButton('Save Talk')
        self.saveButton.setIcon(saveIcon)
        self.buttonLayout.addWidget(self.saveButton)

        self.layout.addLayout(self.buttonLayout, 0, 1, 1, 1)

        self.titleLabel = QLabel('Title')
        self.titleLineEdit = QLineEdit()
        self.presenterLabel = QLabel('Presenter')
        self.presenterLineEdit = QLineEdit()
        self.layout.addWidget(self.titleLabel, 1, 0, 1, 1)
        self.layout.addWidget(self.titleLineEdit, 1, 1, 1, 1)
        self.layout.addWidget(self.presenterLabel, 1, 2, 1, 1)
        self.layout.addWidget(self.presenterLineEdit, 1, 3, 1, 1)

        self.eventLabel = QLabel('Event')
        self.eventLineEdit = QLineEdit()
        self.categoryLabel = QLabel('Category')
        self.categoryLineEdit = QLineEdit()

        self.layout.addWidget(self.eventLabel, 2, 0, 1, 1)
        self.layout.addWidget(self.eventLineEdit, 2, 1, 1, 1)
        self.layout.addWidget(self.categoryLabel, 2, 2, 1, 1)
        self.layout.addWidget(self.categoryLineEdit, 2, 3, 1, 1)

        self.roomLabel = QLabel('Room')
        self.roomLineEdit = QLineEdit()
        self.dateLayout = QHBoxLayout()
        self.dateLabel = QLabel('Date')
        self.dateEdit = QDateEdit()
        currentDate = QDate()
        self.dateEdit.setDate(currentDate.currentDate())
        self.dateEdit.setCalendarPopup(True)

        self.layout.addWidget(self.roomLabel, 3, 0, 1, 1)
        self.layout.addWidget(self.roomLineEdit, 3, 1, 1, 1)
        self.dateLayout.addWidget(self.dateEdit)
        self.layout.addWidget(self.dateLabel, 3, 2, 1, 1)
        self.layout.addLayout(self.dateLayout, 3, 3, 1, 1)

        self.startTimeLayout = QHBoxLayout()
        self.startTimeLabel = QLabel('Start Time')
        self.startTimeEdit = QTimeEdit()
        self.startTimeLayout.addWidget(self.startTimeEdit)
        self.endTimeLayout = QHBoxLayout()
        self.endTimeLabel = QLabel('End Time')
        self.endTimeEdit = QTimeEdit()
        self.endTimeLayout.addWidget(self.endTimeEdit)

        self.layout.addWidget(self.startTimeLabel, 4, 0, 1, 1)
        self.layout.addLayout(self.startTimeLayout, 4, 1, 1, 1)
        self.layout.addWidget(self.endTimeLabel, 4, 2, 1, 1)
        self.layout.addLayout(self.endTimeLayout, 4, 3, 1, 1)

        self.descriptionLabel = QLabel('Description')
        self.descriptionLabel.setAlignment(Qt.AlignTop)
        self.descriptionTextEdit = QPlainTextEdit()
        self.layout.addWidget(self.descriptionLabel, 5, 0, 1, 1)
        self.layout.addWidget(self.descriptionTextEdit, 5, 1, 1, 3)

    def enable_input_fields(self):
        self.titleLineEdit.setPlaceholderText("Enter Talk Title")
        self.presenterLineEdit.setPlaceholderText("Enter Presenter Name")
        self.categoryLineEdit.setPlaceholderText("Enter Category Type")
        self.eventLineEdit.setPlaceholderText("Enter Event Name")
        self.roomLineEdit.setPlaceholderText("Enter Room Location")
        self.titleLineEdit.setEnabled(True)
        self.presenterLineEdit.setEnabled(True)
        self.categoryLineEdit.setEnabled(True)
        self.eventLineEdit.setEnabled(True)
        self.roomLineEdit.setEnabled(True)
        self.dateEdit.setEnabled(True)
        self.startTimeEdit.setEnabled(True)
        self.endTimeEdit.setEnabled(True)
        self.descriptionTextEdit.setEnabled(True)

    def disable_input_fields(self):
        self.titleLineEdit.setPlaceholderText("")
        self.presenterLineEdit.setPlaceholderText("")
        self.categoryLineEdit.setPlaceholderText("")
        self.eventLineEdit.setPlaceholderText("")
        self.roomLineEdit.setPlaceholderText("")
        self.titleLineEdit.setEnabled(False)
        self.presenterLineEdit.setEnabled(False)
        self.categoryLineEdit.setEnabled(False)
        self.eventLineEdit.setEnabled(False)
        self.roomLineEdit.setEnabled(False)
        self.dateEdit.setEnabled(False)
        self.startTimeEdit.setEnabled(False)
        self.endTimeEdit.setEnabled(False)
        self.descriptionTextEdit.setEnabled(False)
Ejemplo n.º 12
0
class UserDialog(QDialog):

    holdc = {}

    def __init__(self, parent=None):
        super(UserDialog, self).__init__(parent)
        self.pagetitle = self.sessionname
        self.tableFont = QFont('Century Gothic', 8)
        self.table = QTableWidget()
        self.cols = [
            'SN', 'ITEM', 'QUANTITY', 'UNIT AMOUNT', 'TOTAL AMOUNT', 'DATE'
        ]
        self.h1_pull_box = QVBoxLayout()

        #self.tableFont.setFamily('Century Gothic')
        self.tableHeaderStyle = "::section {" "background-color: teal; color:white}"
        #pull all CA
        self.editID = 0
        self.hold_unit = {}
        self.hold_store = {}
        self.hold_storeGroup = {}
        self.hold_borrowed = {}

        from_label = QLabel('From:')
        to_label = QLabel('To:')
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)
        menu = QMenu()
        menu.addAction('All', lambda: self.reloadTable(0))
        menu.addAction('In-Stock', lambda: self.reloadTable(1))
        menu.addAction('Out-Stock', lambda: self.reloadTable(2))
        menu.addAction('Damaged', lambda: self.reloadTable(3))
        menu.addAction('Borrowed', lambda: self.reloadTable(4))
        self.pull_btn = QPushButton()
        self.pull_btn.setText("Load")
        self.pull_btn.setMenu(menu)
        h_pull_box = QHBoxLayout()
        h_pull_box.addWidget(from_label)
        h_pull_box.addWidget(self.fromData)
        h_pull_box.addWidget(to_label)
        h_pull_box.addWidget(self.toData)
        h_pull_box.addWidget(self.pull_btn)

        storeGroup = self.pullGroupStore()
        unit = self.pullUnit()

        self.storeGroupText = QLabel('Category')
        self.storeGroupData = QComboBox()
        self.storeGroupData.currentIndexChanged.connect(self.reloadStore)
        self.storeText = QLabel('Items')
        self.storeData = QComboBox()

        self.amountText = QLabel('Total Cost')
        self.amountData = QLineEdit()
        self.amountData.setPlaceholderText('0000.00')
        self.tellerText = QLabel('Reciept No.')
        self.tellerData = QLineEdit()
        self.tellerData.setPlaceholderText('xxxxxxxxx')
        self.quantityText = QLabel('Quantity.')
        self.quantityData = QLineEdit()
        self.quantityData.setPlaceholderText('00.0')
        self.periodText = QLabel('Period (days)')
        self.periodData = QLineEdit()
        self.periodData.setPlaceholderText('00.0')
        self.personText = QLabel('Recieved By:')
        self.personData = QLineEdit()
        self.personData.setPlaceholderText('00.0')
        self.unitText = QLabel('Unit')
        self.unitData = QComboBox()
        self.borrowedText = QLabel('Borrowed')
        self.borrowedData = QComboBox()
        self.dateText = QLabel('Date')
        self.dateData = QDateEdit()
        self.dateData.setDate(currentDate.currentDate())
        self.dateData.setCalendarPopup(True)
        self.descriptionText = QLabel('Description')
        self.descriptionData = QPlainTextEdit()
        self.descriptionData.move(200, 100)
        self.borrowedText.hide()
        self.borrowedData.hide()

        mboz = QVBoxLayout()
        hboz = QHBoxLayout()
        self.state = QLabel('')
        self.r1 = QRadioButton('In-stock')
        self.r1.setChecked(True)
        self.r1.toggled.connect(lambda: self.changeStates())
        self.r2 = QRadioButton('Out-stock')
        self.r2.toggled.connect(lambda: self.changeStates())
        self.r3 = QRadioButton('Damaged')
        self.r3.toggled.connect(lambda: self.changeStates())
        self.r4 = QRadioButton('Borrowed')
        self.r4.toggled.connect(lambda: self.changeStates())
        self.r5 = QRadioButton('Returned')
        self.r5.toggled.connect(lambda: self.changeStates())
        hboz.addWidget(self.r1)
        hboz.addWidget(self.r2)
        hboz.addWidget(self.r3)
        hboz.addWidget(self.r4)
        hboz.addWidget(self.r5)

        i = 0
        for a in storeGroup:
            self.hold_storeGroup[i] = a['id']
            tex = str(a['name']).upper()
            self.storeGroupData.addItem(tex)
            i += 1

        i = 0
        str_key = self.hold_storeGroup[self.storeGroupData.currentIndex()]
        store = self.pullStore(str_key)
        for a in store:
            self.hold_store[i] = a['id']
            tex = str(a['name']).upper()
            self.storeData.addItem(tex)
            i += 1

        i = 0
        for a in unit:
            self.hold_unit[i] = a['id']
            tex = str(a['name']).upper()
            self.unitData.addItem(tex)
            i += 1

        self.reloadBorrowed()
        self.FormLayout = QFormLayout()
        self.FormLayout.addRow(self.storeGroupText, self.storeGroupData)
        self.FormLayout.addRow(self.storeText, self.storeData)
        self.FormLayout.addRow(self.tellerText, self.tellerData)
        self.FormLayout.addRow(self.quantityText, self.quantityData)
        self.FormLayout.addRow(self.amountText, self.amountData)
        self.FormLayout.addRow(self.dateText, self.dateData)
        self.FormLayout.addRow(self.periodText, self.periodData)
        self.FormLayout.addRow(self.borrowedText, self.borrowedData)
        self.FormLayout.addRow(self.personText, self.personData)
        self.FormLayout.addRow(self.descriptionText, self.descriptionData)
        self.periodText.hide()
        self.periodData.hide()

        mboz.addLayout(hboz)
        mboz.addLayout(self.FormLayout)
        mboz.addWidget(self.state)

        groupBox1 = QGroupBox('Add Store Item')
        groupBox1.setLayout(mboz)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Store Item")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Edit")
        self.pb1.setText("Edit Row")
        self.pb1.setEnabled(False)

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Close")
        self.pb2.setText("Close")

        self.pb3 = QPushButton()
        self.pb3.setObjectName("Delete")
        self.pb3.setText("Delete Row")
        self.pb3.setEnabled(False)

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Reset")
        self.pb4.setText("Reset")
        self.pb4.hide()

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Change")
        self.pb5.setText("Change Store")
        self.pb5.hide()

        self.pb6 = QPushButton()
        self.pb6.setObjectName("Clear")
        self.pb6.setText("Clear Selection")
        self.pb6.setEnabled(False)

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb)
        hbo.addWidget(self.pb5)
        hbo.addWidget(self.pb4)
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('Store Data')
        groupBox2.setLayout(hbo)

        al = self.pullStoreData(0)
        if al and len(al) > 0:
            al = al
        else:
            al = {}

        self.storeData.currentIndexChanged.connect(
            lambda: self.reloadBorrowed())

        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Store")
        self.table.setStyleSheet("color:white")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        #self.table.resizeColumnsToContents()
        self.table.setRowCount(len(al))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        i = 0
        for q in al:
            #row id
            if q['state'] == 1:
                color = QColor(100, 0, 0)
            elif q['state'] == 2:
                color = QColor(100, 100, 0)
            elif q['state'] == 3:
                color = QColor(100, 0, 100)
            elif q['state'] == 4:
                color = QColor(0, 100, 100)
            else:
                color = QColor(0, 50, 150)

            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.item(i, 0).setBackground(color)
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['itemname']).upper()))
            self.table.item(i, 1).setBackground(color)
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['quantity']).upper()))
            self.table.item(i, 2).setBackground(color)
            try:
                zamt = str("{:,}".format(float(q['amount'])))
            except:
                zamt = ''
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            self.table.item(i, 3).setBackground(color)
            try:
                if len(q['amount']) > 0 and float(q['amount']) > 0:
                    tot = float(q['amount']) * float(q['quantity'])
                else:
                    tot = 0
            except:
                tot = 0
            self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper()))
            self.table.item(i, 4).setBackground(color)
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 5, QTableWidgetItem(str(damt)))
            self.table.item(i, 5).setBackground(color)
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        v_pull_box = QVBoxLayout()

        self.h1_pull_box.addWidget(self.table)
        v_pull_box.addLayout(h_pull_box)
        v_pull_box.addLayout(self.h1_pull_box)
        h2_pull_box = QHBoxLayout()
        h2_pull_box.addWidget(self.pb1)
        h2_pull_box.addWidget(self.pb3)
        h2_pull_box.addWidget(self.pb6)
        v_pull_box.addLayout(h2_pull_box)

        groupBox3 = QGroupBox()
        groupBox3.setLayout(hbo)
        groupBox2.setLayout(v_pull_box)

        grid = QGridLayout()
        grid.addWidget(groupBox1, 0, 0)
        grid.addWidget(groupBox2, 0, 1, 2, 1)
        grid.addWidget(groupBox3, 1, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_editshow())
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_close(self))
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_reset())
        self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit())
        self.connect(self.pb6, SIGNAL("clicked()"),
                     lambda: self.button_clear())
        #self.connect(self.pull_btn, SIGNAL("clicked()"), lambda x =1: self.reloadTable(x))

        self.setWindowTitle(self.pagetitle)

    def stateReciept(self):
        self.amountText.show()
        self.amountData.show()
        self.tellerText.show()
        self.tellerData.show()
        self.tellerText.setText('Reciept No.')
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Recieved By:')
        self.personData.setPlaceholderText('Fullname or department')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(1)

    def stateIssue(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.show()
        self.tellerData.show()
        self.tellerText.setText('Issue No.')
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Issued to:')
        self.personData.setPlaceholderText('Fullname or department issued to')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(2)

    def stateDamage(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Reported By:')
        self.personData.setPlaceholderText('Fullname or department')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(3)

    def stateBorrowed(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.show()
        self.periodData.show()
        self.personText.setText('Given to:')
        self.personData.setPlaceholderText(
            'Fullname or department borrowed to')
        self.borrowedText.hide()
        self.borrowedData.hide()
        self.reloadTable(4)

    def stateReturned(self):
        self.amountText.hide()
        self.amountData.hide()
        self.tellerText.hide()
        self.tellerData.hide()
        self.periodText.hide()
        self.periodData.hide()
        self.personText.setText('Returned By:')
        self.personData.setPlaceholderText(
            'Fullname or department borrowed to')
        self.borrowedText.show()
        self.borrowedData.show()
        self.reloadBorrowed()
        self.reloadTable(5)

    def changeStates(self):
        self.getQuantity()
        if self.r1.isChecked():
            self.stateReciept()
        elif self.r2.isChecked():
            self.stateIssue()
        elif self.r3.isChecked():
            self.stateDamage()
        elif self.r4.isChecked():
            self.stateBorrowed()
        elif self.r5.isChecked():
            self.stateReturned()

    def handleHeaderMenu(self, pos):
        print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos))
        menu = QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QCursor.pos())

    def pullGroupStore(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 23, "active": 0})
        return arr

    def pullStore(self, a):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"subID": a})
        return arr

    def pullUnit(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0})
        return arr

    def pullStoreData(self, a=None):
        st_date = self.fromData.date().toPyDate()
        en_date = self.toData.date().toPyDate()
        st_date = time.mktime(st_date.timetuple())
        en_date = time.mktime(en_date.timetuple())

        db = 'school_stores' + str(self.session)
        cn = Db()
        arr = cn.selectStoreDate(db, st_date, en_date, a)
        return arr

    def mySelectTable(self):
        '''
        get the selected rpws in a table
        returns list or row ids
        '''
        sels = self.table.selectedIndexes()
        sels = self.table.selectionModel().selectedRows()

        park = []
        park1 = []
        for j in sels:
            park.append(j.row())

        for i in set(park):
            selected = self.table.item(i, 0).text()
            park1.append(selected)

        return park1

    def editRow(self, a):
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        data = g.selectn(db, '', 1, {'id': a})
        if len(data) > 0:
            try:
                amt = float(data['amount'])
                qty = float(data['quantity'])
                if amt > 0 and qty > 0:
                    cost = amt * qty
                else:
                    cost = 0
            except:
                cost = 0
                amt = 0
                qty = 0

            if data['state'] == 1:
                self.r1.setChecked(True)
            elif data['state'] == 2:
                self.r2.setChecked(True)
            elif data['state'] == 3:
                self.r3.setChecked(True)
            elif data['state'] == 4:
                self.r4.setChecked(True)
            elif data['state'] == 5:
                self.r5.setChecked(True)

            self.amountData.setText(str(cost))
            self.descriptionData.clear()
            self.descriptionData.insertPlainText(str(data['description']))
            self.tellerData.setText(str(data['teller']))
            self.periodData.setText(str(data['period']))
            self.personData.setText(str(data['person']))
            self.quantityData.setText(str(qty))
            stID = self.hold_store.keys()[self.hold_store.values().index(
                data['itemID'])]
            self.storeData.setCurrentIndex(stID)

    def reloadBorrowed(self):
        self.getQuantity()
        _store = self.hold_store[self.storeData.currentIndex()]
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        data = g.selectn(db, '', '', {'itemID': _store, 'state': 4})
        fig = 0
        self.borrowedData.clear()
        self.hold_borrowed = {}
        i = 0
        for a in data:
            ret = g.selectStoreReturned(db, a['id'])

            if ret:
                retu = ret['qty']
            else:
                retu = 0

            fig = float(a['quantity']) - float(retu)
            damz = float(a['datepaid'])
            if float(fig) > 0:
                self.hold_borrowed[i] = a['id']
                damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
                tex = str(damt) + " " + str(
                    a['person']).upper() + " (" + str(fig).upper() + ")"
                self.borrowedData.addItem(tex)
                i += 1

    def reloadStore(self):
        self.getQuantity()
        cat = self.hold_storeGroup[self.storeGroupData.currentIndex()]
        store = self.pullStore(cat)
        self.storeData.clear()
        self.hold_store = {}
        i = 0
        for a in store:
            self.hold_store[i] = a['id']
            tex = str(a['name']).upper()
            self.storeData.addItem(tex)
            i += 1

    def getQuantity(self):
        if self.storeData.currentIndex() > -1:
            s = self.hold_store[self.storeData.currentIndex()]
            _session = self.session
            g = Db()
            db = 'school_stores' + str(_session)
            fi = g.selectStoreQuantity(db, s)
            remain = 0
            arr = {}
            for a in fi:
                arr[a['state']] = a['qty']

            if 1 in arr:
                re = arr[1]
            else:
                re = 0

            if 2 in arr:
                isu = arr[2]
            else:
                isu = 0

            if 3 in arr:
                dam = arr[3]
            else:
                dam = 0

            if 4 in arr:
                bor = arr[4]
            else:
                bor = 0

            if 5 in arr:
                ret = arr[5]
            else:
                ret = 0

            borrowed = float(bor) - float(ret)
            issued = float(isu) + float(borrowed) + float(dam)
            remain = float(re) - float(issued)
            self.quantityText.setText('QTY: ' + str(remain))
            if remain == 0 and (self.r2.isChecked() or self.r3.isChecked()
                                or self.r4.isChecked()):
                self.quantityData.setEnabled(False)
            else:
                self.quantityData.setEnabled(True)
            return remain

    def reloadTable(self, a):
        self.getQuantity()
        if not a == 0:
            data = self.pullStoreData(a)
        else:
            data = self.pullStoreData()

        self.table.close()
        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Stores")
        self.table.setStyleSheet("color:white")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        self.table.resizeColumnsToContents()
        self.table.setRowCount(len(data))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        i = 0
        for q in data:
            #row id

            if q['state'] == 1:
                color = QColor(100, 0, 0)
            elif q['state'] == 2:
                color = QColor(100, 100, 0)
            elif q['state'] == 3:
                color = QColor(100, 0, 100)
            elif q['state'] == 4:
                color = QColor(0, 100, 100)
            else:
                color = QColor(0, 50, 150)

            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.item(i, 0).setBackground(color)
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['itemname']).upper()))
            self.table.item(i, 1).setBackground(color)
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['quantity']).upper()))
            self.table.item(i, 2).setBackground(color)
            try:
                zamt = str("{:,}".format(float(q['amount'])))
            except:
                zamt = ''
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            self.table.item(i, 3).setBackground(color)
            try:
                if len(q['amount']) > 0 and float(q['amount']) > 0:
                    tot = float(q['amount']) * float(q['quantity'])
                else:
                    tot = 0
            except:
                tot = 0
            self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper()))
            self.table.item(i, 4).setBackground(color)
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 5, QTableWidgetItem(str(damt)))
            self.table.item(i, 5).setBackground(color)
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        self.h1_pull_box.addWidget(self.table)
        self.table.show()

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def confirmSelection(self):
        item = self.mySelectTable()
        if len(item) == 1:
            self.pb1.setEnabled(True)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        elif len(item) > 1:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        else:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(False)
            self.pb6.setEnabled(False)

    def button_close(self, b):
        b.close()

    def button_editshow(self):
        item = self.mySelectTable()
        self.editRow(item[0])
        self.pb.hide()
        self.pb4.show()
        self.pb5.show()

    def button_delete(self):
        item = self.mySelectTable()
        _session = self.session
        g = Db()
        db = 'school_stores' + str(_session)
        for j in item:
            g.delete(db, {'id': j})
        self.reloadTable(1)

    def button_edit(self):
        _session = self.session
        _amounts = self.amountData.text()
        _teller = self.tellerData.text()
        _quantity = self.quantityData.text()
        _person = self.personData.text()
        _period = self.periodData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _store = self.hold_store[self.storeData.currentIndex()]
        _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]

        arr = {}
        #recieved
        if self.r1.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 1
        #issued
        elif self.r2.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 2
        #damaged
        elif self.r3.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 3

        elif self.r4.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['state'] = 4

        elif self.r5.isChecked() and int(_store) > 0 and int(_quantity) > 0:
            _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['active'] = _borrowed
            arr['state'] = 5

        ups = {}
        ups['id'] = self.editID
        if int(self.editID) > 0 and len(arr) > 0:
            db = 'school_stores' + str(_session)
            g = Db()
            g.update(db, arr, ups)
            if int(self.editID) > 0:
                self.button_reset()

    def button_reset(self):
        self.getQuantity()
        self.reloadTable(1)
        self.amountData.setText('')
        self.descriptionData.clear()
        self.tellerData.setText('')
        self.personData.setText('')
        self.periodData.setText('')
        self.quantityData.setText('')
        self.pb4.hide()
        self.pb5.hide()
        self.pb.show()
        self.editID = 0
        self.button_clear()
        self.confirmSelection()
        self.reloadBorrowed()

    def button_clear(self):
        self.table.selectionModel().clearSelection()

    def button_click(self):
        _session = self.session
        _amounts = self.amountData.text()
        _teller = self.tellerData.text()
        _quantity = self.quantityData.text()
        _person = self.personData.text()
        _period = self.periodData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _store = self.hold_store[self.storeData.currentIndex()]

        arr = {}
        #recieved
        if self.r1.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 1
        #issued
        elif self.r2.isChecked() and _amounts and not (
                _amounts == 0) and int(_store) > 0 and int(_quantity) > 0:
            _amount = float(_amounts) / float(_quantity)
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 2
        #damaged
        elif self.r3.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['teller'] = _teller
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['state'] = 3

        elif self.r4.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0:
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['state'] = 4

        elif self.r5.isChecked() and int(_store) > 0 and int(
                float(_quantity)) > 0 and self.borrowedData.currentIndex() > 0:
            _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()]
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['itemID'] = _store
            arr['quantity'] = _quantity
            arr['person'] = _person
            arr['period'] = _period
            arr['active'] = _borrowed
            arr['state'] = 5

        if len(arr) > 0:
            db = 'school_stores' + str(_session)
            g = Db()
            ins = g.insert(db, arr)
            if int(ins) > 0:
                self.button_reset()
Ejemplo n.º 13
0
class FormStudentMisconduct(QDialog):
    def __init__(self, student, term, edit=None, parent=None):
        super(FormStudentMisconduct, self).__init__(parent)
        self.student = student
        self.term = term

        self.db_class = 'student_class' + str(self.term)
        self.db_subject = 'student_subject' + str(self.term)

        student = self.pullData('students', 1, {'id': self.student})
        term = self.pullData('terms', 1, {'id': self.term})
        session = self.pullData('session', 1, {'id': term['sessionID']})

        self.session = str(
            str(session['name']) + " " + str(term['name'] + " Term")).title()
        self.fullname = str(
            str(student['surname']) + " " + str(student['firstname'])).title()
        self.sessionID = session['id']

        fullnameLbl = QLabel(self.fullname)
        fullnameLbl.setFont(QFont("Candara", 14, QFont.Bold))
        termLbl = QLabel(self.session)
        termLbl.setFont(QFont("Candara", 12, QFont.Bold))

        actionLbl = QLabel('Action')
        reactionLbl = QLabel('Corrective/Punitive Measure')
        issuerLbl = QLabel('Issuer')
        self.actionData = QPlainTextEdit()
        self.reactionData = QPlainTextEdit()
        self.staffData = QLineEdit()
        self.staffData.setPlaceholderText(
            'Staff Name or  Deparment or Organisation')

        self.pb = QPushButton()
        self.pb.setObjectName("close")
        self.pb.setText("Close")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Add")
        self.pb1.setText("Add")

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Edit")
        self.pb2.setText("Edit")

        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_click())
        self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_edit())
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_close())

        self.dateLbl = QLabel('Choose Date:')
        currentDate = QDate()
        self.dateData = QDateEdit()
        self.dateData.setDate(currentDate.currentDate())
        self.dateData.setCalendarPopup(True)

        h_box = QHBoxLayout()
        h_box.addWidget(self.dateLbl)
        h_box.addWidget(self.dateData)

        h_box2 = QHBoxLayout()
        h_box2.addWidget(issuerLbl)
        h_box2.addWidget(self.staffData)

        h_box1 = QHBoxLayout()
        h_box1.addWidget(self.pb)
        h_box1.addWidget(self.pb1)
        h_box1.addWidget(self.pb2)

        self.v_box = QVBoxLayout()
        self.v_box.addWidget(fullnameLbl)
        self.v_box.addWidget(termLbl)
        self.v_box.addLayout(h_box)
        self.v_box.addWidget(actionLbl)
        self.v_box.addWidget(self.actionData)
        self.v_box.addWidget(reactionLbl)
        self.v_box.addWidget(self.reactionData)
        self.v_box.addLayout(h_box2)
        self.v_box.addLayout(h_box1)

        if edit and len(edit) > 0:
            self.edit = edit
            self.editRow(edit)
            self.pb1.hide()
            self.pb2.show()
        else:
            self.edit = None
            self.pb1.show()
            self.pb2.hide()

        self.setLayout(self.v_box)
        self.setWindowTitle("Misconduct Report Form")

    def pullData(self, db, sid, arr):
        g = Db()
        data = g.selectn(db, '', sid, arr)
        return data

    def convert_arr(self, arr):
        ar = []
        for a in arr:
            ar.append(a['subjectID'])

        return ar

    def editrow(self, a):
        e = a.split('_')
        g = Db()
        self.mainrow = e[1]
        self.mainses = e[0]
        db = 'school_conducts' + str(self.mainses)
        data = g.selectn(db, '', 1, {'id': self.mainrow})
        if data and len(data) > 0:
            self.ailmentData.clear()
            self.ailmentData.insertPlainText(str(data['action']))
            self.staffData.setText(str(data['staffname']))
            self.treatmentData.clear()
            self.treatmentData.insertPlainText(str(data['reaction']))

    def button_close(self):
        self.reject()

    def button_click(self):
        action = self.actionData.toPlainText()
        reaction = self.reactionData.toPlainText()
        staff = self.staffData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())

        db = 'school_conducts' + str(self.sessionID)

        if len(action) > 0 and len(reaction) > 0:
            arr = {}
            arr['studentID'] = self.student
            arr['action'] = action
            arr['reaction'] = reaction
            arr['datepaid'] = _date
            arr['staffname'] = staff
            arr['state'] = 1
            g = Db()
            g.insert(db, arr)

        ## set subject
        self.getValue()

    def button_edit(self):
        action = self.actionData.toPlainText()
        reaction = self.reactionData.toPlainText()
        staff = self.staffData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())

        db = 'school_conducts' + str(self.sessionID)

        if len(action) > 0 and len(reaction) > 0:
            arr = {}
            arr['action'] = action
            arr['reaction'] = reaction
            arr['datepaid'] = _date
            arr['staffname'] = staff

            g = Db()
            g.update(db, arr, {'id': self.edit})

        ## set subject
        self.getValue()

    def getValue(self):
        self.accept()
Ejemplo n.º 14
0
class AddTalkWidget(QWidget):
    '''
    classdocs
    '''
    def __init__(self, parent=None):
        '''
        Constructor
        '''
        QWidget.__init__(self, parent)
        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        self.addTalkGroupBox = QGroupBox("Add Talk")
        self.mainLayout.addWidget(self.addTalkGroupBox)

        self.addTalkLayout = QFormLayout()
        self.addTalkGroupBox.setLayout(self.addTalkLayout)

        # Title
        self.titleLabel = QLabel("Title")
        self.titleLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.titleLineEdit.setPlaceholderText("Title of the presentation")
        self.titleLabel.setBuddy(self.titleLineEdit)
        self.addTalkLayout.addRow(self.titleLabel, self.titleLineEdit)

        # Presenter
        self.presenterLabel = QLabel("Presenter")
        self.presenterLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.presenterLineEdit.setPlaceholderText(
                "Name person or people presenting (comma separated)")
        self.presenterLabel.setBuddy(self.presenterLineEdit)
        self.addTalkLayout.addRow(self.presenterLabel, self.presenterLineEdit)

        # Event
        self.eventLabel = QLabel("Event")
        self.eventLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.eventLineEdit.setPlaceholderText(
                "The name of the Event this talk is being presented at")
        self.eventLabel.setBuddy(self.eventLineEdit)
        self.addTalkLayout.addRow(self.eventLabel, self.eventLineEdit)

        # Room
        self.roomLabel = QLabel("Room")
        self.roomLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.roomLineEdit.setPlaceholderText(
                "The Room in which the presentation is taking place")
        self.roomLabel.setBuddy(self.roomLineEdit)
        self.addTalkLayout.addRow(self.roomLabel, self.roomLineEdit)

        # Date
        current_date = QDate()
        self.dateLabel = QLabel("Date")
        self.dateEdit = QDateEdit()
        self.dateEdit.setDate(current_date.currentDate())
        self.dateLabel.setBuddy(self.dateEdit)
        self.addTalkLayout.addRow(self.dateLabel, self.dateEdit)

        self.dateEdit.setCalendarPopup(True)

        # Time
        current_time = QTime()
        self.timeLabel = QLabel("Time")
        self.timeEdit = QTimeEdit()
        self.timeEdit.setTime(current_time.currentTime())
        self.timeLabel.setBuddy(self.dateEdit)
        self.addTalkLayout.addRow(self.timeLabel, self.timeEdit)

        # Buttons
        addIcon = QIcon.fromTheme("list-add")
        cancelIcon = QIcon.fromTheme("edit-clear")

        self.buttonsWidget = QHBoxLayout()
        self.addButton = QPushButton("Add")
        self.addButton.setIcon(addIcon)
        self.cancelButton = QPushButton("Cancel")
        self.cancelButton.setIcon(cancelIcon)
        self.buttonsWidget.addWidget(self.addButton)
        self.buttonsWidget.addWidget(self.cancelButton)
        self.addTalkLayout.addRow(None, self.buttonsWidget)
Ejemplo n.º 15
0
class TermPayDialog(QDialog):

    holdc = {}

    def __init__(self, student, term, parent=None):
        super(TermPayDialog, self).__init__(parent)
        #term data
        self.term = term
        terms = self.pullOnes('terms', self.term)
        session = self.pullOnes('session', terms['sessionID'])
        self.termname = str(
            session['name']) + ' ' + terms['name'] + ' Term Report'
        self.pagetitle = self.termname

        #student data
        self.student = student
        st = self.pullStudent(self.student)
        fullname = str(st['surname'] + ' ' + st['firstname'] + ' ' +
                       st['othername']).title()
        schno = st['schno']
        db_class = 'student_class' + str(self.term)
        student_clasz = self.pullOne(db_class, {'studentID': self.student})

        clasz = self.pullOne('datas', {'id': student_clasz['classID']})
        self.clasz = clasz['subID']
        armz = self.pullOne('datas', {'id': clasz['subID']})
        classname = armz['abbrv'] + ' ' + clasz['abbrv']
        #pull all CA

        fullNameText = QLabel(fullname)
        schnoText = QLabel(schno)
        classText = QLabel(classname)

        topLay = QGridLayout()
        topLay.addWidget(fullNameText, 0, 0)
        topLay.addWidget(schnoText, 1, 0)
        topLay.addWidget(classText, 2, 0)

        groupBox = QGroupBox('Current Payment')
        groupBox.setLayout(topLay)

        payAmountText = QLabel('Amount')
        self.payBalanceText = QLabel('Balance')
        self.payBalanceAmount = QLabel('0.0')
        self.payAmount = QLineEdit()
        self.payAmount.setObjectName("pay")
        self.payAmount.setPlaceholderText("000.00")
        payText = QLabel('Select Account')
        self.payMethod = QComboBox()
        accounts = self.pullAccount()
        self.holdaccount = {}
        i = 0
        for h in accounts:
            tex = str(h['name']).upper()
            self.payMethod.addItem(tex)
            self.holdaccount[i] = h['id']

        payDateText = QLabel('Balance')
        self.payDate = QDateEdit()
        self.payDate.setDateTime(QDateTime.currentDateTime())
        self.payDate.setCalendarPopup(True)
        tellerText = QLabel('Teller/Receipt No.')
        self.teller = QLineEdit()
        self.teller.setObjectName("teller")
        self.teller.textChanged.connect(self.pullTeller)
        self.teller.setPlaceholderText("0000000")

        self.hw = QGridLayout()
        self.hw.addWidget(payAmountText, 0, 0)
        self.hw.addWidget(self.payAmount, 0, 1)
        self.hw.addWidget(tellerText, 0, 2)
        self.hw.addWidget(self.teller, 0, 3)
        self.hw.addWidget(payText, 1, 0)
        self.hw.addWidget(self.payMethod, 1, 1)
        self.hw.addWidget(payDateText, 1, 2)
        self.hw.addWidget(self.payDate, 1, 3)

        head_col1 = QLabel('ITEM')
        head_col2 = QLabel('AMOUNT')
        head_col3 = QLabel('FULL PAY')
        head_col4 = QLabel('PART PAY')
        head_col5 = QLabel('BALANCE')

        layout1 = QGridLayout()
        layout1.addWidget(head_col1, 0, 0)
        layout1.addWidget(head_col2, 0, 1)
        layout1.addWidget(head_col3, 0, 2)
        layout1.addWidget(head_col4, 0, 3)
        layout1.addWidget(head_col5, 0, 4)

        arr = self.pullFees()
        feex = arr[1]
        payx = arr[2]

        normal_pay = []
        full_pay = []
        part_pay = []
        bal_pay = []
        ko = 1

        self.holdval = []
        self.holdfee = {}
        self.holdtextfee = {}
        self.holdtextfeeperm = {}
        self.holdpaid = {}
        self.holdcpaid = {}
        self.holdtextpaid = {}
        self.holdpayments = {}
        self.holdtextbal = {}
        self.holdbal = {}

        for val in arr[0]:
            paid = False
            s_normal_pay = []
            s_full_pay = []
            s_part_pay = []
            self.holdval.append(val)
            mz = self.pullOne('datas', {'id': val})
            self.num = val
            self.d = QLabel('Text')
            self.d.setText(str(mz['name']).upper())
            self.d1 = QLabel()
            if val in feex:
                fk = feex[int(val)].values()
                normal_pay.append(float(fk[0]))
                s_normal_pay.append(float(fk[0]))
                self.d1.setText(str("{:,}".format(float(fk[0]))).upper())
            else:
                self.d1.setText(str('-.-').upper())

            nHbo1 = QVBoxLayout()
            if val in feex:
                fk = feex[int(val)].values()
                fky = feex[int(val)].keys()
                self.c = QCheckBox('cb' + str(val))
                self.c.setEnabled(False)
                self.c.setText(str("{:,}".format(float(fk[0]))).upper())
                self.c.setObjectName("chk" + str(val))
                self.holdfee[int(val)] = self.c
                self.holdtextfee[int(val)] = fk[0]
                self.holdtextfeeperm[int(val)] = fk[0]
                self.c.toggled.connect(lambda state, x=fky[0], fee=int(
                    val), money=fk[0]: self.chkFunc(x, fee, money, self.c))
                if (val in payx) and len(payx[int(val)]) == 1:
                    pk = payx[int(val)].values()
                    self.c.setChecked(True)
                    if float(pk[0]) == float(fk[0]):
                        full_pay.append(float(fk[0]))
                        s_full_pay.append(float(fk[0]))
                        paid = True
                else:
                    self.c.setChecked(False)
                nHbo1.addWidget(self.c)
            else:
                nHbo1.addWidget(QLabel('-.-'))
                #nHbo1.hide()

            nHbo2 = QHBoxLayout()
            fk = feex[int(val)].values()
            fky = feex[int(val)].keys()
            c2 = QCheckBox()
            c2.setEnabled(False)
            c2.setMaximumWidth(15)
            c2.setObjectName("chk2" + str(val))
            p = QLineEdit()
            p.setDisabled(True)
            p.setMaximumWidth(50)
            p.setFixedWidth(51)
            p.setObjectName("pay" + str(val))
            p.setPlaceholderText("00.0")
            self.holdpaid[int(val)] = p
            self.holdcpaid[int(val)] = c2
            self.holdtextpaid[int(val)] = list()
            c2.toggled.connect(
                lambda state, x=fky[0], fee=int(val): self.chkFunc1(x, fee, p))
            if paid == False:
                nHbo2.addWidget(c2)
                nHbo2.addWidget(p)
                if val in payx and len(payx[val]) > 0:
                    for j in payx[int(val)]:
                        self.c1 = QCheckBox('cb1' + str(j))
                        self.c1.setEnabled(False)
                        self.c1.setText(str(payx[int(val)][j]).upper())
                        self.c1.setObjectName("chk" + str(j))
                        self.c1.toggled.connect(
                            lambda state, x=j: self.chkFunc1(x))
                        self.c1.setChecked(True)
                        part_pay.append(float(fk[0]))
                        s_part_pay.append(float(fk[0]))
                        self.holdpayments[j] = self.c1
                        self.holdtextpaid[val].append(float(fk[0]))
                        nHbo2.addWidget(self.c1)
                else:
                    pass
            else:
                p.hide()
                c2.hide()
                nHbo2.addWidget(c2)
                nHbo2.addWidget(p)

            s_tot = sum(s_normal_pay) - (sum(s_full_pay) + sum(s_part_pay))
            bal_pay.append(float(s_tot))
            d2 = QLabel('')
            self.holdbal[int(val)] = d2
            d2.setText(str("{:,}".format(s_tot)).upper())
            self.holdtextbal[int(val)] = s_tot

            layout1.addWidget(self.d, ko, 0)
            layout1.addWidget(self.d1, ko, 1)
            layout1.addLayout(nHbo1, ko, 2)
            layout1.addLayout(nHbo2, ko, 3)
            layout1.addWidget(d2, ko, 4)
            ko += 1

        normal_payx = sum(normal_pay)
        full_payx = sum(full_pay)
        part_payx = sum(part_pay)
        bal_payx = sum(bal_pay)

        self.head_col1 = QLabel('ITEM')
        self.head_col2 = QLabel(str("{:,}".format(normal_payx)).upper())
        self.head_col3 = QLabel(str("{:,}".format(full_payx)).upper())
        self.head_col4 = QLabel(str("{:,}".format(part_payx)).upper())
        self.head_col5 = QLabel(str("{:,}".format(bal_payx)).upper())

        layout1.addWidget(self.head_col1, ko, 0)
        layout1.addWidget(self.head_col2, ko, 1)
        layout1.addWidget(self.head_col3, ko, 2)
        layout1.addWidget(self.head_col4, ko, 3)
        layout1.addWidget(self.head_col5, ko, 4)

        self.hw1 = QGridLayout()
        self.hw1.addWidget(self.payBalanceText, 0, 0)
        self.hw1.addWidget(self.payBalanceAmount, 1, 0)

        second1 = QGridLayout()
        second1.addLayout(self.hw, 0, 0)
        second1.addLayout(layout1, 1, 0)
        second1.addLayout(self.hw1, 2, 0)

        groupBox1 = QGroupBox('Current Payment')
        groupBox1.setLayout(second1)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Fees")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Add")
        self.pb2.setText("Print Receipts")

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb1)
        hbo.addStretch()
        hbo.addWidget(self.pb)
        hbo.addStretch()
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('')
        groupBox2.setLayout(hbo)

        grid = QGridLayout()
        grid.addWidget(groupBox, 0, 0)
        grid.addWidget(groupBox1, 1, 0)
        grid.addWidget(groupBox2, 2, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close(self))

        self.setWindowTitle(self.pagetitle)

    def reCalFull(self):
        fees_arr = self.holdfee
        fee_store = list()
        for a in fees_arr:
            if fees_arr[a].isChecked() == True:
                h = self.holdtextfee[a]
                fee_store.append(float(h))
            else:
                pass

        fee_sum = sum(fee_store)
        self.head_col3.setText('{:,}'.format(fee_sum))

    def reCalPart(self):
        fees_arr = self.holdtextpaid
        fee_store = list()
        for a in fees_arr:
            if self.holdtextpaid[a]:
                h = sum(self.holdtextpaid[a])
                fee_store.append(float(h))

        fee_sum = sum(fee_store)
        self.head_col4.setText('{:,}'.format(fee_sum))

    def reCalBal(self):
        bal_arr = self.holdbal
        bal_store = list()
        for a in bal_arr:
            h = self.holdtextbal[a]
            bal_store.append(float(h))

        bal_sum = sum(bal_store)
        self.head_col5.setText('{:,}'.format(bal_sum))

    def reCalSingleBal(self):
        bal_arr = self.holdval
        fees_arr = self.holdfee
        for a in bal_arr:
            if fees_arr[a].isChecked() == True:
                b = self.holdtextfee[a]
                self.holdbal[a].setText('{:,}'.format(0))
                self.holdtextbal[a] = 0
            elif fees_arr[a].isChecked() == False:
                b = self.holdtextfee[a]
                self.holdbal[a].setText('{:,}'.format(float(b)))
                self.holdtextbal[a] = float(b)

        self.reCalBal()

    def chkFunc(self, a, c, d, b):
        # checkbox select to make fuul payment
        self.a = a
        db_fee = 'student_fee' + str(self.term)
        db_pay = 'student_pay' + str(self.term)
        amount = self.payAmount.text()
        teller = self.teller.text()
        # get all paments made for that fee
        # get the check box
        g = Db()
        fee = g.selectn(db_fee, '', 1, {'id': a})
        loc = self.holdfee[int(fee['feeID'])]
        poc = self.holdpaid[int(fee['feeID'])]
        pocc = self.holdcpaid[int(fee['feeID'])]

        try:
            ## fee was checked full pay
            ## confirm if money posted and its greater than or equals
            # confimr if teller number was provided
            ## if those conditions are met payment of fees is possible

            if (float(amount) >= float(d)) and len(str(teller)) > 0:
                # confirm if the checkbox was checked
                if loc.isChecked() == True:

                    #if it was checked prepare to insert payment data
                    pay = {}
                    pay['studentID'] = self.student
                    pay['accountID'] = self.payAmount.text()
                    pay['amount'] = d
                    pay['teller'] = teller
                    pay['feeID'] = fee['feeID']
                    pay['datepaid'] = self.payDate.date().toPyDate()
                    # however confirm if full payment had bee made b4
                    dat = g.select(db_pay, '', '', {
                        'studentID': self.student,
                        'feeID': fee['feeID']
                    })
                    if dat and len(dat) > 0 and float(
                            dat[0]['amount']) > 0 and float(
                                dat[0]['amount']) == float(d):
                        # full payment made
                        # dont post
                        # keep part pay disabled
                        poc.hide()
                        pocc.hide()
                        # inform user
                        msg = QMessageBox()
                        msg.setIcon(QMessageBox.Information)
                        msg.setWindowTitle("Info")
                        msg.setText(
                            "This fee has already been paid for. You cannot repay for it"
                        )
                        msg.setStandardButtons(QMessageBox.Cancel)
                        msg.exec_()
                    else:
                        # post payment
                        h = g.insert(db_pay, pay)
                        if int(h) > 0:
                            # deduct from balance

                            # keep part pay disabled]
                            poc.hide()
                            pocc.hide()
                            # recalculate
                            self.reCalFull()
                            self.reCalSingleBal()
                        else:
                            poc.show()

                else:
                    # money was not posted
                    if len(str(self.teller.text())) > 0:
                        pay = {}
                        pay['studentID'] = self.student
                        pay['teller'] = self.teller.text()
                        pay['feeID'] = fee['feeID']
                        h = g.delete(db_pay, pay)
                        poc.show()
                        pocc.show()
                        self.reCalFull()
                        self.reCalSingleBal()

                    else:
                        msg = QMessageBox()
                        msg.setIcon(QMessageBox.Information)
                        msg.setWindowTitle("Info")
                        msg.setText(
                            "Please provide the teller/receipt details before removing amount."
                        )
                        msg.setStandardButtons(QMessageBox.Cancel)
                        msg.exec_()
                    #add to money
            ## if those conditions are not met
            # payment of fees is not possible
            # however user might want to revoke a payment
            # meaning checkbox was unchecked
            else:
                if loc.isChecked() == False:
                    # prepare to remove payment
                    pay = {}
                    pay['studentID'] = self.student
                    pay['teller'] = self.teller.text()
                    pay['feeID'] = fee['feeID']
                    # remove payment
                    h = g.delete(db_pay, pay)
                    # confirm if removal was succesful
                    if h == 1:
                        # if successful
                        poc.show()
                        pocc.show()
                        # refund balance

                        # recalculate
                        self.reCalFull()
                        self.reCalSingleBal()
                    else:
                        # not sussefull
                        # details not complete
                        #restore it to check
                        #loc.setChecked(True)
                        poc.hide()
                        pocc.hide()
                        # inform user
                        msg = QMessageBox()
                        msg.setIcon(QMessageBox.Information)
                        msg.setWindowTitle("Safety Measure:")
                        msg.setText(
                            "You will need to enter the correct teller/receipt details for this payment before removing it"
                        )
                        msg.setStandardButtons(QMessageBox.Cancel)
                        msg.exec_()

                # user trying to make payment with no funds
                else:
                    # uncheck user
                    loc.setChecked(False)
                    poc.show()
                    pocc.show()
                    #give info
                    msg = QMessageBox()
                    msg.setIcon(QMessageBox.Information)
                    msg.setWindowTitle(" Payment Error")
                    msg.setText(
                        "Please provide teller/receipt details or Insufficient funds to make full payments "
                    )
                    msg.setStandardButtons(QMessageBox.Cancel)
                    msg.exec_()
        except:
            if loc.isChecked() == False:
                # money was not posted
                if len(str(self.teller.text())) > 0:
                    pay = {}
                    pay['studentID'] = self.student
                    pay['teller'] = self.teller.text()
                    pay['feeID'] = fee['feeID']
                    h = g.delete(db_pay, pay)
                    poc.show()
                    pocc.show()
                    self.reCalFull()
                    self.reCalSingleBal()
                else:
                    pass

            else:
                loc.setChecked(False)
                poc.show()
                pocc.show()
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Information)
                msg.setWindowTitle(" Payment Error:")
                msg.setText("Please insert amount and Teller/Receipt details ")
                msg.setStandardButtons(QMessageBox.Cancel)
                msg.exec_()

    def chkFunc1(self, a, b, c):
        # checkbox select to make fuul payment
        self.a = a
        db_fee = 'student_fee' + str(self.term)
        db_pay = 'student_pay' + str(self.term)

        amount = self.payAmount.text()
        teller = self.teller.text()
        # get all paments made for that fee
        # get the check box
        g = Db()
        fee = g.selectn(db_fee, '', 1, {'id': a})
        loc = self.holdfee[b]
        payfull = self.holdtextfee[b]
        pocc = self.holdpaid[b]
        poc = self.holdcpaid[b]

        d = pocc.text()

        try:
            ## fee was checked full pay
            ## confirm if money posted and its greater than or equals
            # confimr if teller number was provided
            ## if those conditions are met payment of fees is possible
            if (float(amount) >= float(d)) and len(str(teller)) > 0:
                # confirm if the checkbox was checked
                if poc.isChecked() == True:
                    #if it was checked prepare to insert payment data
                    pay = {}
                    pay['studentID'] = self.student
                    pay['accountID'] = self.payAmount.text()
                    pay['teller'] = teller
                    pay['feeID'] = fee['feeID']
                    pay['datepaid'] = self.payDate.date().toPyDate()
                    # however confirm if full payment had bee made b4
                    dat = g.selectn(db_pay, '', '', {
                        'studentID': self.student,
                        'feeID': fee['feeID']
                    })

                    if dat and len(dat) > 0:
                        mon = list()
                        for dd in dat:
                            mon.append(float(dd['amount']))
                        # full payment made
                        # dont post
                        # keep part pay disabled
                        total_money_paid = sum(mon)
                        #no payments required
                        if float(total_money_paid) >= float(payfull):
                            pass
                        #payment required
                        elif float(total_money_paid) < float(payfull):
                            if float(amount) >= float(d):
                                pay['amount'] = d
                                #post
                                h = g.insert(db_pay, pay)
                                if int(h) > 0:
                                    # deduct from balance

                                    # keep part pay disabled]
                                    loc.hide()
                                    pocc.setDisabled(True)
                                    # recalculate
                                    self.reCalFull()
                                    self.reCalPart()
                                    self.reCalSingleBal()
                                else:
                                    poc.show()
                            else:
                                msg = QMessageBox()
                                msg.setIcon(QMessageBox.Information)
                                msg.setWindowTitle("Info")
                                msg.setText("Insufficient funds.")
                                msg.setStandardButtons(QMessageBox.Cancel)
                                msg.exec_()

                        loc.hide()
                        pocc.setDisabled(True)
                        # inform user

                    else:
                        # post payment
                        if float(amount) >= float(d):
                            pay['amount'] = d

                            #post
                            h = g.insert(db_pay, pay)

                            if int(h) > 0:
                                # deduct from balance

                                # keep part pay disabled]
                                loc.hide()
                                pocc.setDisabled(True)
                                # recalculate
                                self.reCalFull()
                                self.reCalSingleBal()
                            else:
                                poc.show()

                    # money was not posted
                    if len(str(self.teller.text())) > 0:
                        pay = {}
                        pay['studentID'] = self.student
                        pay['teller'] = self.teller.text()
                        pay['feeID'] = fee['feeID']
                        h = g.delete(db_pay, pay)
                        poc.show()
                        pocc.show()
                        self.reCalFull()
                        self.reCalSingleBal()

                    else:
                        msg = QMessageBox()
                        msg.setIcon(QMessageBox.Information)
                        msg.setWindowTitle("Info")
                        msg.setText(
                            "Please provide the teller/receipt details before removing amount."
                        )
                        msg.setStandardButtons(QMessageBox.Cancel)
                        msg.exec_()
                    #add to money
            ## if those conditions are not met
            # payment of fees is not possible
            # however user might want to revoke a payment
            # meaning checkbox was unchecked
            else:
                if loc.isChecked() == False:
                    # prepare to remove payment
                    pay = {}
                    pay['studentID'] = self.student
                    pay['teller'] = self.teller.text()
                    pay['feeID'] = fee['feeID']
                    # remove payment
                    h = g.delete(db_pay, pay)
                    # confirm if removal was succesful
                    if h == 1:
                        # if successful
                        poc.show()
                        pocc.show()
                        # refund balance

                        # recalculate
                        self.reCalFull()
                        self.reCalSingleBal()
                    else:
                        # not sussefull
                        # details not complete
                        #restore it to check
                        #loc.setChecked(True)
                        poc.hide()
                        pocc.hide()
                        # inform user
                        msg = QMessageBox()
                        msg.setIcon(QMessageBox.Information)
                        msg.setWindowTitle("Safety Measure:")
                        msg.setText(
                            "You will need to enter the correct teller/receipt details for this payment before removing it"
                        )
                        msg.setStandardButtons(QMessageBox.Cancel)
                        msg.exec_()

                # user trying to make payment with no funds
                else:
                    # uncheck user
                    loc.setChecked(False)
                    poc.show()
                    pocc.show()
                    #give info
                    msg = QMessageBox()
                    msg.setIcon(QMessageBox.Information)
                    msg.setWindowTitle(" Payment Error")
                    msg.setText(
                        "Please provide teller/receipt details or Insufficient funds to make full payments "
                    )
                    msg.setStandardButtons(QMessageBox.Cancel)
                    msg.exec_()
        except:

            if loc.isChecked() == False:
                # money was not posted
                if len(str(self.teller.text())) > 0:
                    pay = {}
                    pay['studentID'] = self.student
                    pay['teller'] = self.teller.text()
                    pay['feeID'] = fee['feeID']
                    h = g.delete(db_pay, pay)
                    poc.show()
                    pocc.show()
                    self.reCalFull()
                    self.reCalSingleBal()
                else:
                    pass

            else:
                loc.setChecked(False)
                poc.show()
                pocc.show()
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Information)
                msg.setWindowTitle(" Payment Error:")
                msg.setText("Please insert amount and Teller/Receipt details ")
                msg.setStandardButtons(QMessageBox.Cancel)
                msg.exec_()

    def getClass(self, x):
        # shost is a QString object
        class_arr = []
        for i in self.cla_arr:
            if self.cla_arr[i].checkState(0) == Qt.Checked:
                class_arr.append(i)

        c = self.getClassStudent(class_arr)
        self.feesPop.setText('Total: ' + str(c[0]))
        self.cla = class_arr
        self.students = c[1]

    def pullStudent(self, student):
        cn = Db()
        arr = cn.selectn('students', '', 1, {'id': student})
        return arr

    def pullTeller(self):
        cn = Con()
        teller = self.teller.text()
        if len(str(teller)) > 0:
            h1 = self.holdfee
            for x in h1:
                h1[x].setEnabled(True)

            h2 = self.holdpaid
            h3 = self.holdcpaid
            for x in h2:
                h2[x].setEnabled(True)
                h3[x].setEnabled(True)
        else:
            h1 = self.holdfee
            for x in h1:
                h1[x].setEnabled(False)

            h2 = self.holdpaid
            h3 = self.holdcpaid
            for x in h2:
                h2[x].setEnabled(False)
                h3[x].setEnabled(False)

        arr = cn.getTeller(self.term, self.student, teller)
        arr1 = cn.getNonTeller(self.term, self.student, teller)

        amount = self.payAmount.text()

        if amount and (float(amount) > 0):
            if arr1 and float(arr1['amount']) > 0:
                self.payBalanceAmount.setText('This teller :' + str(teller) +
                                              ' is already in use ')
            else:
                if arr and float(arr['amount']) > 0:
                    amt = arr['amount']
                    amt_a = "{:,}".format(float(amt))
                    bl = float(amount) - float(amt)
                    bl_a = "{:,}".format(float(bl))
                    self.payBalanceAmount.setText(
                        'The sum of' + str(amt_a) +
                        ' has been deducted from this teller')
                    self.payBalanceText.setText('Balance on ' + str(teller) +
                                                ' : ' + str(bl_a) + '')
                else:
                    bl = float(amount)
                    bl_a = "{:,}".format(float(bl))
                    self.payBalanceAmount.setText(
                        'No transaction on teller :' + str(teller))
                    self.payBalanceText.setText('Balance on ' + str(teller) +
                                                ' : ' + str(bl_a) + '')
        else:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Information)
            msg.setWindowTitle("Error")
            msg.setText("Error! Please enter an amount before you proceed...")
            msg.setStandardButtons(QMessageBox.Cancel)
            msg.exec_()

    def pullFees(self):
        term = self.term
        student = self.student
        fee_id_array = []
        cn = Db()
        db_fee = 'student_fee' + str(term)
        db_pay = 'student_pay' + str(term)

        fee = cn.selectn(db_fee, '', '', {'studentID': student})
        pay = cn.selectn(db_pay, '', '', {'studentID': student})
        #get all fees
        arr = {}
        arr1 = {}
        for r in fee:
            fee_id_array.append(int(r['feeID']))
            arr[int(r['feeID'])] = {}

        for r in pay:
            fee_id_array.append(int(r['feeID']))
            arr1[int(r['feeID'])] = {}

        for r in fee:
            get_mon = cn.selectn(
                'datas', '', 1, {
                    'pubID': 'fee',
                    'subID': self.term,
                    'name': self.clasz,
                    'abbrv': r['feeID']
                })
            if arr[int(r['feeID'])] and isinstance(arr[int(r['feeID'])], dict):
                arr[int(r['feeID'])][int(r['id'])] = get_mon['description']
            else:
                arr[int(r['feeID'])] = {}
                arr[int(r['feeID'])][int(r['id'])] = get_mon['description']

        for r in pay:
            if arr1[int(r['feeID'])] and isinstance(arr1[int(r['feeID'])],
                                                    dict):
                arr1[int(r['feeID'])][int(r['id'])] = r['amount']
            else:
                arr1[int(r['feeID'])] = {}
                arr1[int(r['feeID'])][int(r['id'])] = r['amount']

        fee_ids = list(set(fee_id_array))
        fin = [fee_ids, arr, arr1]
        return fin

    def pullOne(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, b)
        return arr

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def pullAccount(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0})
        return arr

    def pullRep(self):
        cn = Db()
        ca = "rep"
        arr = cn.selectn('datas', '', '', {"subID": self.sid, "pubID": ca})
        return arr

    def button_close(self, b):
        b.close()

    def button_click(self):
        tex = ' Please wait processing, do not cancel or close..'
        self.feesPop.setText(tex)
        _term = self.term
        _class = self.cla
        _students = self.students
        _amount = self.feesAmount.text()
        _fee = self.hol[self.feesCombo.currentIndex()]

        for j in _class:
            data = {}
            data['pubID'] = 'fee'
            data['subID'] = _term
            data['abbrv'] = _fee
            data['name'] = j

            cn = Db()
            feeStudent = self.feeStudents(_term, _students, _fee, _amount)
            check = cn.selectn('datas', '', 1, data)
            if (check and check['id'] == 0):
                pass
            else:
                data['description'] = _amount
                cn.insert('datas', data)

        ins = feeStudent
        tex = ' TOTAL of ' + str(ins) + ' inserted'
        self.feesPop.setText(tex)

    def feeStudents(self, session, students, fee, amount):
        db = 'student_fee' + str(session)
        cn = Db()
        fd = []
        ed = []

        for s in students:
            data = {}
            data['studentID'] = s[0]
            data['feeID'] = fee

            chk = cn.selectn(db, '', 1, data)
            if (chk and int(chk['id']) > 0):
                #confirm if money available
                pass
            else:
                #if money not set , set
                e = cn.insert(db, data)
                ed.append(e)

        return len(ed)

    def lunchEditForm(self, row):
        term = self.term
        self.close()
        self.post = EditReportDialog(term, row)
        self.post.show()

    def lunchDeleteForm(self, row):
        cn = Db()
        arr = cn.update('datas', {"active": 1})
        self.close()
        self.__init__(self.term, self.termname)
Ejemplo n.º 16
0
class SessionsManager(QDialog):
    def __init__(self, n, parent=None):
        super(SessionsManager, self).__init__(parent)
        self.par = n
        #main
        title = Settingz().positions(30)
        self.titleID = title['id']
        self.titlePage = title['page']
        self.titleName = title['name']
        self.titleSub = title['subID']
        self.titleIcon = title['icon']
        self.pagetitle = self.titlePage
        #stylesheet
        stylesheet = Valid().background() + Valid().font()
        treeStyleSheet = Valid().treez()

        self.groupBox1 = QGroupBox(self.titleName)
        self.groupBox2 = QGroupBox('Add')

        #items
        self.tree = QTreeWidget()
        self.tree.setHeaderLabel("Choose " + self.titleName)
        #tree.setItemDelegate(Delegate())
        self.tree.setItemDelegate(Delegates())
        self.tree.headerItem().setText(0, 'Name')
        self.tree.setStyleSheet(treeStyleSheet)
        self.makeTree()
        self.tree.setMinimumHeight(250)
        self.tree.clicked.connect(lambda: self.getSelection())
        self.tree.itemClicked.connect(lambda state: self.getChecked(state))
        #buttons
        #add
        nImg = Buttons().addButton()
        self.pb = QPushButton()
        self.pb.setFlat(True)
        self.pb.setIcon(QIcon(nImg))
        self.pb.setMaximumHeight(30)
        self.pb.setMaximumWidth(30)

        nImg1 = Buttons().closeButton()
        self.pb1 = QPushButton()
        self.pb1.setFlat(True)
        self.pb1.setIcon(QIcon(nImg1))
        self.pb1.setMaximumHeight(30)
        self.pb1.setMaximumWidth(30)

        nImg2 = Buttons().editButton()
        self.pb2 = QPushButton()
        self.pb2.setFlat(True)
        self.pb2.setIcon(QIcon(nImg2))
        self.pb2.setMaximumHeight(30)
        self.pb2.setMaximumWidth(30)

        nImg3 = Buttons().deleteButton()
        self.pb3 = QPushButton()
        self.pb3.setFlat(True)
        self.pb3.setIcon(QIcon(nImg3))
        self.pb3.setMaximumHeight(30)
        self.pb3.setMaximumWidth(30)

        nImg4 = Buttons().saveButton()
        self.pb4 = QPushButton()
        self.pb4.setFlat(True)
        self.pb4.setIcon(QIcon(nImg4))
        self.pb4.setMaximumHeight(30)
        self.pb4.setMaximumWidth(30)

        nImg5 = Buttons().resetButton()
        self.pb5 = QPushButton()
        self.pb5.setFlat(True)
        self.pb5.setIcon(QIcon(nImg5))
        self.pb5.setMaximumHeight(30)
        self.pb5.setMaximumWidth(30)

        nImg6 = Buttons().closeButton()
        self.pb6 = QPushButton()
        self.pb6.setFlat(True)
        self.pb6.setIcon(QIcon(nImg6))
        self.pb6.setMaximumHeight(30)
        self.pb6.setMaximumWidth(30)

        nImg7 = Buttons().addButton()
        self.pb7 = QPushButton()
        self.pb7.setFlat(True)
        self.pb7.setIcon(QIcon(nImg7))
        self.pb7.setMaximumHeight(30)
        self.pb7.setMaximumWidth(30)

        hbo = QHBoxLayout()
        hbo.addStretch()
        hbo.addWidget(self.pb1)
        hbo.addWidget(self.pb3)
        hbo.addWidget(self.pb2)
        hbo.addWidget(self.pb7)

        vbo = QVBoxLayout()
        vbo.addWidget(self.tree)
        vbo.addLayout(hbo)

        self.l1 = QLabel("Name")
        self.le1 = QLineEdit()
        self.le1.setObjectName("name")
        vals1 = Valid().fullNum()
        self.le1.setValidator(vals1)
        self.le1.setPlaceholderText("Lowercase max 25 letters")

        self.fromLbl = QLabel("Starts")
        self.toLbl = QLabel("Ends")
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)

        FormLayout = QFormLayout()
        FormLayout.addRow(self.l1, self.le1)
        FormLayout.addRow(self.fromLbl, self.fromData)
        FormLayout.addRow(self.toLbl, self.toData)

        Hlayout1 = QHBoxLayout()
        Hlayout1.addStretch()
        Hlayout1.addWidget(self.pb6)
        Hlayout1.addWidget(self.pb5)
        Hlayout1.addWidget(self.pb4)
        Hlayout1.addWidget(self.pb)

        Vlayout1 = QVBoxLayout()
        Vlayout1.addLayout(FormLayout)
        Vlayout1.addLayout(Hlayout1)

        self.groupBox1.setLayout(vbo)
        self.groupBox2.setLayout(Vlayout1)
        self.groupBox2.hide()

        self.connect(self.pb, SIGNAL("clicked()"),
                     lambda: self.button_add())  #add
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close())  #close
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_edit())  #edit
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())  #delete
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_save())  #save
        self.connect(self.pb5, SIGNAL("clicked()"),
                     lambda: self.button_reset())  #reset

        self.pb4.hide()
        self.pb7.hide()

        grid = QGridLayout()
        grid.addWidget(self.groupBox1, 0, 0)
        grid.addWidget(self.groupBox2, 1, 0)

        self.setLayout(grid)
        self.setStyleSheet(stylesheet)
        self.setWindowIcon(QIcon(self.titleIcon))
        self.setWindowTitle(self.pagetitle)

    def makeTree(self):
        self.tree.clear()
        arr = Db().selectn('session', '', 5)
        self.hold_data = {}
        self.hold_mdata = {}
        self.hold_data_add = {}
        self.hold_data_add_item = {}
        current = time.time()

        if self.titleSub and self.titleSub > 0:
            if arr and len(arr) > 0:
                for val in arr:
                    ch = Valid().pullData('terms', '',
                                          {'sessionID': val['id']})
                    child = QTreeWidgetItem(self.tree)
                    child.setIcon(0, QIcon('icons.cfolder.png'))
                    try:
                        ts = int(float(val['start_date']))
                    except:
                        ts = int(current)
                    ts = datetime.utcfromtimestamp(ts).strftime('%d-%m-%Y')

                    try:
                        ts1 = int(float(val['end_date']))
                    except:
                        ts1 = int(current)
                    ts1 = datetime.utcfromtimestamp(ts1).strftime('%d-%m-%Y')

                    child.setText(
                        0,
                        str(val['name']).upper() + " - " + ts + " " + ts1)
                    self.hold_mdata[val['id']] = child

                    for va in ch:
                        child1 = QTreeWidgetItem(child)
                        child1.setFlags(child1.flags()
                                        | Qt.ItemIsUserCheckable)

                        try:
                            ts2 = int(float(va['start_date']))
                        except:
                            ts2 = int(current)
                        ts2 = datetime.utcfromtimestamp(ts2).strftime(
                            '%d-%m-%Y')
                        try:
                            ts3 = int(float(va['end_date']))
                        except:
                            ts3 = int(current)
                        ts3 = datetime.utcfromtimestamp(ts3).strftime(
                            '%d-%m-%Y')

                        child1.setText(
                            0,
                            str(va['name']).upper() + " " + ts2 + " " + ts3)
                        self.hold_data[va['id']] = child1
                        if (va['active'] == 1):
                            child1.setCheckState(0, Qt.Checked)
                        else:
                            child1.setCheckState(0, Qt.Unchecked)

                    child1 = QTreeWidgetItem(child)
                    child1.setFlags(child1.flags() | Qt.ItemIsUserCheckable)
                    child1.setText(0, 'Add New Term')
                    self.hold_data_add_item[val['id']] = child1
        else:
            if arr and len(arr) > 0:
                for val in arr:
                    child = QTreeWidgetItem(self.tree)
                    child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
                    child.setText(0, str(val['name']).upper())
                    child.setText(1, str(val['abbrv']).upper())
                    self.hold_data[val['id']] = child
                    if (val['active'] == 0):
                        child.setCheckState(0, Qt.Checked)
                    else:
                        child.setCheckState(0, Qt.Unchecked)

        child = QTreeWidgetItem(self.tree)
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setText(0, 'Add New Session')
        self.hold_data_add['addnew'] = child

    def getChecked(self, a):
        arr_hold = []
        g = Db()
        for i in self.hold_data:
            if self.hold_data[i].checkState(0) == Qt.Checked:
                arr_hold.append(i)
                self.hold_data[i].setCheckState(0, Qt.Checked)
                g.update('terms', {'active': 0}, {'active': 1})
                g.update('terms', {'active': 1}, {'id': i})
                tt = g.selectn('terms', '', 1, {'id': i})
                g.update('session', {'active': 0}, {'active': 1})
                g.update('session', {'active': 1}, {'id': tt['sessionID']})
                g.selectn('session', '', 1, {'id': tt['sessionID']})
            else:
                self.hold_data[i].setCheckState(0, Qt.Unchecked)

        self.reloadTerm()

    def reloadTerm(self):
        session = self.par.activeTerm()
        activeTerm = str(session[1]) + ' SESSION ' + str(session[3]) + ' TERM'
        self.par.majorSession = session[2]
        self.par.lbl.setText(activeTerm)

    def getSelected(self):
        r = False
        self.sessionMain = False
        for i in self.hold_mdata:
            if self.hold_mdata[i].isSelected():
                r = i

        if r and r > 0:
            self.groupBox2.show()
            self.sessionMain = True
            return r
        else:
            for i in self.hold_data:
                if self.hold_data[i].isSelected():
                    r = i
            if r and r > 0:
                self.sessionMain = False
                self.groupBox2.show()
                return r
            else:
                self.groupBox2.hide()

    def getSession(self):
        self.sessionID = None
        for i in self.hold_data_session:
            if self.hold_data_session[i].isSelected():
                r = i
        if r and r > 0:
            self.sessionID = r

    def getSelection(self):
        self.le1.clear()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.toData.setDate(currentDate.currentDate())
        self.sessionMain = False

        if self.hold_data_add['addnew'].isSelected():
            self.groupBox2.setTitle('Add New')
            self.groupBox2.show()
            self.sessionMain = True
            self.sessionID = False
        else:
            self.sessionMain = False
            r = None
            for i in self.hold_data_add_item:
                if self.hold_data_add_item[i].isSelected():
                    r = i
            if r:
                g = Db()
                v = g.selectn('session', '', 1, {'id': r})
                vname = str(v['name']).upper() + ' Session'
                self.groupBox2.setTitle('ADD ' + str(vname) + ' Term')
                self.sessionID = r
                self.groupBox2.show()
            else:
                self.groupBox2.setTitle('Add')
                self.sessionID = False
                self.groupBox2.hide()

    def setActive(self):
        g = Db()
        for i in self.hold_data:
            if self.hold_data[i].checkState(0) == Qt.Checked:
                g.update('datas', {'active': 0}, {'id': i})
            else:
                g.update('datas', {'active': 1}, {'id': i})

    def button_add(self):
        s1 = self.le1.text()
        _datef = self.fromData.date().toPyDate()
        _datef = time.mktime(_datef.timetuple())
        _datee = self.toData.date().toPyDate()
        _datee = time.mktime(_datee.timetuple())
        g = Db()

        if self.sessionID and self.sessionID > 0:
            try:
                if (len(s1) > 0):
                    y = {
                        'name': s1.lower(),
                        'start_date': _datef,
                        'sessionID': self.sessionID,
                        'end_date': _datee,
                        'active': 0
                    }
                    z = g.insert('terms', y)
                    if z and z > 0:
                        g.createClass(z)
                        g.createSubject(z)
                        g.createFee(z)
                        g.createPay(z)
                        g.createResult(z)
                        g.createAffective(z)
                        g.createPsychomoto(z)
                    self.makeTree()
                    self.button_reset()
                    self.par.menuSession()
                    self.par.dropdownSession()
                else:
                    pass
            except:
                pass
        else:
            try:
                if (len(s1) > 0):
                    y = {
                        'name': s1.lower(),
                        'start_date': _datef,
                        'end_date': _datee,
                        'active': 0
                    }
                    z = g.insert('session', y)
                    if z and z > 0:
                        g.createExpenses(z)
                        g.createStores(z)
                        g.createAwards(z)
                        g.createConducts(z)
                        g.createMails(z)
                        g.createMedicals(z)
                    self.makeTree()
                    self.button_reset()
                    self.par.menuSession()
                    self.par.dropdownSession()
                else:
                    pass
            except:
                pass

    def button_save(self):
        row = self.editrow
        s1 = self.le1.text()
        _datef = self.fromData.date().toPyDate()
        _datef = time.mktime(_datef.timetuple())
        _datee = self.toData.date().toPyDate()
        _datee = time.mktime(_datee.timetuple())

        g = Db()

        if (len(s1) > 0) and row and row > 0:
            if self.sessionID and self.sessionID > 0:
                try:
                    if (len(s1) > 0):
                        y = {
                            'name': s1.lower(),
                            'start_date': _datef,
                            'sessionID': self.sessionID,
                            'end_date': _datee,
                            'active': 0
                        }
                        k = {'id': row}
                        g.update('terms', y, k)
                        z = row
                        if z and z > 0:
                            g.createClass(z)
                            g.createSubject(z)
                            g.createFee(z)
                            g.createPay(z)
                            g.createResult(z)
                            g.createAffective(z)
                            g.createPsychomoto(z)
                        self.makeTree()
                        self.button_reset()
                        self.par.menuSession()
                        self.par.dropdownSession()
                    else:
                        pass
                except:
                    pass
            else:
                try:
                    if (len(s1) > 0):
                        y = {
                            'name': s1.lower(),
                            'start_date': _datef,
                            'end_date': _datee,
                            'active': 0
                        }
                        k = {'id': row}
                        g.update('session', y, k)
                        z = row
                        if z and z > 0:
                            g.createExpenses(z)
                            g.createStores(z)
                            g.createAwards(z)
                            g.createConducts(z)
                            g.createMails(z)
                            g.createMedicals(z)
                        self.makeTree()
                        self.button_reset()
                        self.par.menuSession()
                        self.par.dropdownSession()
                    else:
                        pass
                except:
                    pass

    def button_delete(self):
        row = self.getSelected()
        g = Db()
        try:
            if row and row > 0:
                y = {'abbrv': '', 'active': 2}
                z = {'id': row}
                g.update('datas', y, z)
                self.makeTree()
            else:
                pass
        except:
            pass

    def button_reset(self):
        self.le1.clear()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.toData.setDate(currentDate.currentDate())
        self.groupBox2.setTitle('Add')
        self.groupBox2.hide()
        self.pb.show()
        self.pb4.hide()

    def button_edit(self):
        row = self.getSelected()
        currentDate = QDate()
        if row:
            self.editrow = row
            g = Db()
            if self.sessionMain:
                data = g.selectn('session', '', 1, {'id': row})
                data_name = str(data['name'])
                self.groupBox2.setTitle('Edit')
                self.sessionID = False
            else:
                data = g.selectn('terms', '', 1, {'id': row})
                data_sess = g.selectn('session', '', 1,
                                      {'id': data['sessionID']})
                data_name = str(data['name'])
                self.sessionID = data['sessionID']
                self.groupBox2.setTitle('Edit ' + str(data_sess['name']))
            try:
                self.le1.setText(data_name)
            except:
                self.le1.setText('')
            try:
                self.fromData.setDate(data['start_date'])
            except:
                self.fromData.setDate(currentDate.currentDate())
            try:
                self.toData.setDate(data['end_date'])
            except:
                self.toData.setDate(currentDate.currentDate())
            self.pb.hide()
            self.pb4.show()

    def button_close(self):
        self.close()
Ejemplo n.º 17
0
class TalkDetailsWidget(QWidget):

    def __init__(self, parent=None):
        super(TalkDetailsWidget, self).__init__(parent)

        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.buttonLayout = QHBoxLayout()

        saveIcon = QIcon.fromTheme("document-save")
        self.saveButton = QPushButton('Save Talk')
        self.saveButton.setIcon(saveIcon)
        self.buttonLayout.addWidget(self.saveButton)

        self.layout.addLayout(self.buttonLayout, 0, 1, 1, 1)

        self.titleLabel = QLabel('Title')
        self.titleLineEdit = QLineEdit()
        self.presenterLabel = QLabel('Presenter')
        self.presenterLineEdit = QLineEdit()
        self.layout.addWidget(self.titleLabel, 1, 0, 1, 1)
        self.layout.addWidget(self.titleLineEdit, 1, 1, 1, 1)
        self.layout.addWidget(self.presenterLabel, 1, 2, 1, 1)
        self.layout.addWidget(self.presenterLineEdit, 1, 3, 1, 1)

        self.eventLabel = QLabel('Event')
        self.eventLineEdit = QLineEdit()
        self.categoryLabel = QLabel('Category')
        self.categoryLineEdit = QLineEdit()

        self.layout.addWidget(self.eventLabel, 2, 0, 1, 1)
        self.layout.addWidget(self.eventLineEdit, 2, 1, 1, 1)
        self.layout.addWidget(self.categoryLabel, 2, 2, 1, 1)
        self.layout.addWidget(self.categoryLineEdit, 2, 3, 1, 1)

        self.roomLabel = QLabel('Room')
        self.roomLineEdit = QLineEdit()
        self.dateLayout = QHBoxLayout()
        self.dateLabel = QLabel('Date')
        self.dateEdit = QDateEdit()
        currentDate = QDate()
        self.dateEdit.setDate(currentDate.currentDate())
        self.dateEdit.setCalendarPopup(True)

        self.layout.addWidget(self.roomLabel, 3, 0, 1, 1)
        self.layout.addWidget(self.roomLineEdit, 3, 1, 1, 1)
        self.dateLayout.addWidget(self.dateEdit)
        self.layout.addWidget(self.dateLabel, 3, 2, 1, 1)
        self.layout.addLayout(self.dateLayout, 3, 3, 1, 1)

        self.startTimeLayout = QHBoxLayout()
        self.startTimeLabel = QLabel('Start Time')
        self.startTimeEdit = QTimeEdit()
        self.startTimeLayout.addWidget(self.startTimeEdit)
        self.endTimeLayout = QHBoxLayout()
        self.endTimeLabel = QLabel('End Time')
        self.endTimeEdit = QTimeEdit()
        self.endTimeLayout.addWidget(self.endTimeEdit)

        self.layout.addWidget(self.startTimeLabel, 4, 0, 1, 1)
        self.layout.addLayout(self.startTimeLayout, 4, 1, 1, 1)
        self.layout.addWidget(self.endTimeLabel, 4, 2, 1, 1)
        self.layout.addLayout(self.endTimeLayout, 4, 3, 1, 1)

        self.descriptionLabel = QLabel('Description')
        self.descriptionLabel.setAlignment(Qt.AlignTop)
        self.descriptionTextEdit = QPlainTextEdit()
        self.layout.addWidget(self.descriptionLabel, 5, 0, 1, 1)
        self.layout.addWidget(self.descriptionTextEdit, 5, 1, 1, 3)

    def enable_input_fields(self):
            self.titleLineEdit.setPlaceholderText("Enter Talk Title")
            self.presenterLineEdit.setPlaceholderText("Enter Presenter Name")
            self.categoryLineEdit.setPlaceholderText("Enter Category Type")
            self.eventLineEdit.setPlaceholderText("Enter Event Name")
            self.roomLineEdit.setPlaceholderText("Enter Room Location")
            self.titleLineEdit.setEnabled(True)
            self.presenterLineEdit.setEnabled(True)
            self.categoryLineEdit.setEnabled(True)
            self.eventLineEdit.setEnabled(True)
            self.roomLineEdit.setEnabled(True)
            self.dateEdit.setEnabled(True)
            self.startTimeEdit.setEnabled(True)
            self.endTimeEdit.setEnabled(True)
            self.descriptionTextEdit.setEnabled(True)

    def disable_input_fields(self):
            self.titleLineEdit.setPlaceholderText("")
            self.presenterLineEdit.setPlaceholderText("")
            self.categoryLineEdit.setPlaceholderText("")
            self.eventLineEdit.setPlaceholderText("")
            self.roomLineEdit.setPlaceholderText("")
            self.titleLineEdit.setEnabled(False)
            self.presenterLineEdit.setEnabled(False)
            self.categoryLineEdit.setEnabled(False)
            self.eventLineEdit.setEnabled(False)
            self.roomLineEdit.setEnabled(False)
            self.dateEdit.setEnabled(False)
            self.startTimeEdit.setEnabled(False)
            self.endTimeEdit.setEnabled(False)
            self.descriptionTextEdit.setEnabled(False)
Ejemplo n.º 18
0
class QtDateSelector(QtBoundedDate, ProxyDateSelector):
    """ A Qt implementation of an Enaml ProxyDateSelector.

    """
    #: A reference to the widget created by the proxy.
    widget = Typed(QDateEdit)

    #--------------------------------------------------------------------------
    # Initialization API
    #--------------------------------------------------------------------------
    def create_widget(self):
        """ Create the QDateEdit widget.

        """
        self.widget = QDateEdit(self.parent_widget())

    def init_widget(self):
        """ Initialize the widget.

        """
        super(QtDateSelector, self).init_widget()
        d = self.declaration
        self.set_date_format(d.date_format)
        self.set_calendar_popup(d.calendar_popup)
        self.widget.dateChanged.connect(self.on_date_changed)

    #--------------------------------------------------------------------------
    # Abstract API Implementation
    #--------------------------------------------------------------------------
    def get_date(self):
        """ Return the current date in the control.

        Returns
        -------
        result : date
            The current control date as a date object.

        """
        return self.widget.date().toPyDate()

    def set_minimum(self, date):
        """ Set the widget's minimum date.

        Parameters
        ----------
        date : date
            The date object to use for setting the minimum date.

        """
        self.widget.setMinimumDate(date)

    def set_maximum(self, date):
        """ Set the widget's maximum date.

        Parameters
        ----------
        date : date
            The date object to use for setting the maximum date.

        """
        self.widget.setMaximumDate(date)

    def set_date(self, date):
        """ Set the widget's current date.

        Parameters
        ----------
        date : date
            The date object to use for setting the date.

        """
        self._guard |= CHANGED_GUARD
        try:
            self.widget.setDate(date)
        finally:
            self._guard &= ~CHANGED_GUARD

    def set_date_format(self, format):
        """ Set the widget's date format.

        Parameters
        ----------
        format : str
            A Python time formatting string.

        """
        # XXX make sure Python's and Qt's format strings are the
        # same, or convert between the two.
        self.widget.setDisplayFormat(format)

    def set_calendar_popup(self, popup):
        """ Set whether a calendar popup is available on the widget.

        Parameters
        ----------
        popup : bool
            Whether the calendar popup is enabled.

        """
        self.widget.setCalendarPopup(popup)
Ejemplo n.º 19
0
class AddTalkWidget(QWidget):
    '''
    classdocs
    '''

    def __init__(self, parent=None):
        '''
        Constructor
        '''
        QWidget.__init__(self, parent)
        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        self.addTalkGroupBox = QGroupBox("Add Talk")
        self.mainLayout.addWidget(self.addTalkGroupBox)

        self.addTalkLayout = QFormLayout()
        self.addTalkGroupBox.setLayout(self.addTalkLayout)

        # Title
        self.titleLabel = QLabel("Title")
        self.titleLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.titleLineEdit.setPlaceholderText("Title of the presentation")
        self.titleLabel.setBuddy(self.titleLineEdit)
        self.addTalkLayout.addRow(self.titleLabel, self.titleLineEdit)

        # Presenter
        self.presenterLabel = QLabel("Presenter")
        self.presenterLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.presenterLineEdit.setPlaceholderText("Name person or people presenting (comma separated)")
        self.presenterLabel.setBuddy(self.presenterLineEdit)
        self.addTalkLayout.addRow(self.presenterLabel, self.presenterLineEdit)

        # Event
        self.eventLabel = QLabel("Event")
        self.eventLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.eventLineEdit.setPlaceholderText("The name of the Event this talk is being presented at")
        self.eventLabel.setBuddy(self.eventLineEdit)
        self.addTalkLayout.addRow(self.eventLabel, self.eventLineEdit)

        # Room
        self.roomLabel = QLabel("Room")
        self.roomLineEdit = QLineEdit()
        if hasattr(QLineEdit(), 'setPlaceholderText'):
            self.roomLineEdit.setPlaceholderText("The Room in which the presentation is taking place")
        self.roomLabel.setBuddy(self.roomLineEdit)
        self.addTalkLayout.addRow(self.roomLabel, self.roomLineEdit)

        # Date
        current_date = QDate()
        self.dateLabel = QLabel("Date")
        self.dateEdit = QDateEdit()
        self.dateEdit.setDate(current_date.currentDate())
        self.dateLabel.setBuddy(self.dateEdit)
        self.addTalkLayout.addRow(self.dateLabel, self.dateEdit)

        self.dateEdit.setCalendarPopup(True)

        # Time
        current_time = QTime()
        self.timeLabel = QLabel("Time")
        self.timeEdit = QTimeEdit()
        self.timeEdit.setTime(current_time.currentTime())
        self.timeLabel.setBuddy(self.dateEdit)
        self.addTalkLayout.addRow(self.timeLabel, self.timeEdit)

        # Buttons
        addIcon = QIcon.fromTheme("list-add")
        cancelIcon = QIcon.fromTheme("edit-clear")

        self.buttonsWidget = QHBoxLayout()
        self.addButton = QPushButton("Add")
        self.addButton.setIcon(addIcon)
        self.cancelButton = QPushButton("Cancel")
        self.cancelButton.setIcon(cancelIcon)
        self.buttonsWidget.addWidget(self.addButton)
        self.buttonsWidget.addWidget(self.cancelButton)
        self.addTalkLayout.addRow(None, self.buttonsWidget)
Ejemplo n.º 20
0
class ExpensesDialog(QDialog):

    holdc = {}

    def __init__(self, session, parent=None):
        super(ExpensesDialog, self).__init__(parent)
        self.session = session
        session = self.pullOnes('session', session)
        self.sessionname = str(session['name']) + ' Session'
        self.pagetitle = self.sessionname
        self.tableFont = QFont('Century Gothic', 8)
        #self.tableFont.setFamily('Century Gothic')
        self.tableHeaderStyle = "::section {" "background-color: teal; color:white}"
        #pull all CA
        self.editID = 0
        self.hold_account = {}
        self.hold_expenses = {}
        self.hold_expensesGroup = {}

        from_label = QLabel('From:')
        to_label = QLabel('To:')
        self.fromData = QDateEdit()
        self.toData = QDateEdit()
        currentDate = QDate()
        self.fromData.setDate(currentDate.currentDate())
        self.fromData.setCalendarPopup(True)
        self.toData.setDate(currentDate.currentDate())
        self.toData.setCalendarPopup(True)
        self.pull_btn = QPushButton()
        self.pull_btn.setText("Load")
        h_pull_box = QHBoxLayout()
        h_pull_box.addWidget(from_label)
        h_pull_box.addWidget(self.fromData)
        h_pull_box.addWidget(to_label)
        h_pull_box.addWidget(self.toData)
        h_pull_box.addWidget(self.pull_btn)

        expensesGroup = self.pullGroupExpenses()
        account = self.pullAccount()

        self.expenseGroupText = QLabel('Category')
        self.expenseGroupData = QComboBox()
        self.expenseGroupData.currentIndexChanged.connect(self.reloadExpenses)
        self.expenseText = QLabel('Expenses')
        self.expenseData = QComboBox()
        self.amountText = QLabel('Amount')
        self.amountData = QLineEdit()
        self.amountData.setPlaceholderText('0000.00')
        self.tellerText = QLabel('Teller/Reciept No.')
        self.tellerData = QLineEdit()
        self.tellerData.setPlaceholderText('xxxxxxxxx')
        self.accountText = QLabel('Account')
        self.accountData = QComboBox()
        self.dateText = QLabel('Date')
        self.dateData = QDateEdit()
        self.dateData.setDate(currentDate.currentDate())
        self.dateData.setCalendarPopup(True)
        self.descriptionText = QLabel('Brief Description')
        self.descriptionData = QPlainTextEdit()
        self.descriptionData.move(200, 100)
        hboz = QHBoxLayout()
        self.gender = QLabel('State')
        self.r1 = QRadioButton('Expenses')
        self.r1.setChecked(True)
        self.r2 = QRadioButton('Refund')
        hboz.addWidget(self.r1)
        hboz.addWidget(self.r2)

        i = 0
        for a in expensesGroup:
            self.hold_expensesGroup[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseGroupData.addItem(tex)
            i += 1

        i = 0
        exp_key = self.hold_expensesGroup[self.expenseGroupData.currentIndex()]
        expenses = self.pullExpenses(exp_key)
        for a in expenses:
            self.hold_expenses[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseData.addItem(tex)
            i += 1

        i = 0
        for a in account:
            self.hold_account[i] = a['id']
            tex = str(a['name']).upper()
            self.accountData.addItem(tex)
            i += 1

        self.FormLayout = QFormLayout()
        self.FormLayout.addRow(self.expenseGroupText, self.expenseGroupData)
        self.FormLayout.addRow(self.expenseText, self.expenseData)
        self.FormLayout.addRow(self.accountText, self.accountData)
        self.FormLayout.addRow(self.tellerText, self.tellerData)
        self.FormLayout.addRow(self.amountText, self.amountData)
        self.FormLayout.addRow(self.gender, hboz)
        self.FormLayout.addRow(self.dateText, self.dateData)
        self.FormLayout.addRow(self.descriptionText, self.descriptionData)

        groupBox1 = QGroupBox('Add Expenses')
        groupBox1.setLayout(self.FormLayout)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Expenses")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Edit")
        self.pb1.setText("Edit Row")
        self.pb1.setEnabled(False)

        self.pb2 = QPushButton()
        self.pb2.setObjectName("Close")
        self.pb2.setText("Close")

        self.pb3 = QPushButton()
        self.pb3.setObjectName("Delete")
        self.pb3.setText("Delete Row")
        self.pb3.setEnabled(False)

        self.pb4 = QPushButton()
        self.pb4.setObjectName("Reset")
        self.pb4.setText("Reset")
        self.pb4.hide()

        self.pb5 = QPushButton()
        self.pb5.setObjectName("Change")
        self.pb5.setText("Change Expenses")
        self.pb5.hide()

        self.pb6 = QPushButton()
        self.pb6.setObjectName("Clear")
        self.pb6.setText("Clear Selection")
        self.pb6.setEnabled(False)

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb)
        hbo.addWidget(self.pb5)
        hbo.addWidget(self.pb4)
        hbo.addWidget(self.pb2)
        groupBox2 = QGroupBox('Expenses Data')
        groupBox2.setLayout(hbo)

        self.cols = ['SN', 'EXPENSES', 'ACCOUNT', 'AMOUNT', 'DATE']
        al = self.pullExpensesData()
        if len(al) > 0:
            al = al
        else:
            al = {}

        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Expenses")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        #self.table.resizeColumnsToContents()
        self.table.setRowCount(len(al))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        i = 0
        for q in al:
            #row id
            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['expensename']).upper()))
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['accountname']).upper()))
            zamt = str("{:,}".format(float(q['amount'])))
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 4, QTableWidgetItem(str(damt)))
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        v_pull_box = QVBoxLayout()
        self.h1_pull_box = QVBoxLayout()
        self.h1_pull_box.addWidget(self.table)
        v_pull_box.addLayout(h_pull_box)
        v_pull_box.addLayout(self.h1_pull_box)
        h2_pull_box = QHBoxLayout()
        h2_pull_box.addWidget(self.pb1)
        h2_pull_box.addWidget(self.pb3)
        h2_pull_box.addWidget(self.pb6)
        v_pull_box.addLayout(h2_pull_box)

        groupBox3 = QGroupBox()
        groupBox3.setLayout(hbo)
        groupBox2.setLayout(v_pull_box)

        grid = QGridLayout()
        grid.addWidget(groupBox1, 0, 0)
        grid.addWidget(groupBox2, 0, 1, 2, 1)
        grid.addWidget(groupBox3, 1, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_editshow())
        self.connect(self.pb2, SIGNAL("clicked()"),
                     lambda: self.button_close(self))
        self.connect(self.pb3, SIGNAL("clicked()"),
                     lambda: self.button_delete())
        self.connect(self.pb4, SIGNAL("clicked()"),
                     lambda: self.button_reset())
        self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit())
        self.connect(self.pb6, SIGNAL("clicked()"),
                     lambda: self.button_clear())
        self.connect(self.pull_btn,
                     SIGNAL("clicked()"),
                     lambda x=1: self.reloadTable(x))

        self.setWindowTitle(self.pagetitle)

    def handleHeaderMenu(self, pos):
        print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos))
        menu = QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QCursor.pos())

    def pullGroupExpenses(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 15, "active": 0})
        return arr

    def pullExpenses(self, a):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"subID": a})
        return arr

    def pullAccount(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0})
        return arr

    def pullExpensesData(self):
        st_date = self.fromData.date().toPyDate()
        en_date = self.toData.date().toPyDate()
        st_date = time.mktime(st_date.timetuple())
        en_date = time.mktime(en_date.timetuple())

        db = 'school_expenses' + str(self.session)
        cn = Db()
        arr = cn.selectExpenseDate(db, st_date, en_date)
        return arr

    def mySelectTable(self):
        '''
        get the selected rpws in a table
        returns list or row ids
        '''
        sels = self.table.selectedIndexes()
        sels = self.table.selectionModel().selectedRows()

        park = []
        park1 = []
        for j in sels:
            park.append(j.row())

        for i in set(park):
            selected = self.table.item(i, 0).text()
            park1.append(selected)

        return park1

    def editRow(self, a):
        _session = self.session
        g = Db()
        db = 'school_expenses' + str(_session)
        data = g.selectn(db, '', 1, {'id': a})
        if len(data) > 0:
            self.editID = int(data['id'])
            if float(data['amount']) < 0:
                amt = float(data['amount']) * -1
                self.amountData.setText(str(amt))
                self.r1.setChecked(True)
            else:
                amt = float(data['amount'])
                self.amountData.setText(str(amt))
                self.r2.setChecked(True)

            self.descriptionData.clear()
            self.descriptionData.insertPlainText(str(data['description']))
            self.tellerData.setText(str(data['teller']))
            acID = self.hold_account.keys()[self.hold_account.values().index(
                data['accountID'])]
            self.accountData.setCurrentIndex(acID)
            exID = self.hold_expenses.keys()[self.hold_expenses.values().index(
                data['expenseID'])]
            self.expenseData.setCurrentIndex(exID)

    def reloadExpenses(self):
        cat = self.hold_expensesGroup[self.expenseGroupData.currentIndex()]
        expenses = self.pullExpenses(cat)
        self.expenseData.clear()
        self.hold_expenses = {}
        i = 0
        for a in expenses:
            self.hold_expenses[i] = a['id']
            tex = str(a['name']).upper()
            self.expenseData.addItem(tex)
            i += 1

    def reloadTable(self, a):
        data = self.pullExpensesData()
        self.table.close()
        self.table = QTableWidget()
        header = self.table.horizontalHeader()
        header.setResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)
        header.setStyleSheet(self.tableHeaderStyle)
        vheader = self.table.verticalHeader()
        vheader.setStyleSheet(self.tableHeaderStyle)
        # Body
        self.table.setWindowTitle("Expenses")
        self.table.resize(300, 250)
        self.table.setFont(self.tableFont)
        self.table.setSortingEnabled(2)
        self.table.resizeColumnsToContents()
        self.table.setRowCount(len(data))
        self.table.setColumnCount(len(self.cols))
        self.table.setHorizontalHeaderLabels(self.cols)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.handleHeaderMenu)
        self.table.hideColumn(0)
        self.table.setSelectionMode(QAbstractItemView.MultiSelection)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        i = 0
        for q in data:
            #row id
            self.table.setItem(i, 0, QTableWidgetItem(str(q['id'])))
            self.table.setItem(i, 1,
                               QTableWidgetItem(str(q['expensename']).upper()))
            self.table.setItem(i, 2,
                               QTableWidgetItem(str(q['accountname']).upper()))
            zamt = str("{:,}".format(float(q['amount'])))
            self.table.setItem(i, 3, QTableWidgetItem(zamt))
            damz = float(q['datepaid'])
            damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y')
            self.table.setItem(i, 4, QTableWidgetItem(str(damt)))
            i += 1
        self.table.itemSelectionChanged.connect(self.confirmSelection)
        self.table.resizeRowsToContents()
        self.h1_pull_box.addWidget(self.table)
        self.table.show()

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def confirmSelection(self):
        item = self.mySelectTable()
        if len(item) == 1:
            self.pb1.setEnabled(True)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        elif len(item) > 1:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(True)
            self.pb6.setEnabled(True)
        else:
            self.pb1.setEnabled(False)
            self.pb3.setEnabled(False)
            self.pb6.setEnabled(False)

    def button_close(self, b):
        b.close()

    def button_editshow(self):
        item = self.mySelectTable()
        self.editRow(item[0])
        self.pb.hide()
        self.pb4.show()
        self.pb5.show()

    def button_delete(self):
        item = self.mySelectTable()
        _session = self.session
        g = Db()
        db = 'school_expenses' + str(_session)
        for j in item:
            g.delete(db, {'id': j})

        self.reloadTable(1)

    def button_edit(self):
        _session = self.session
        _amount = self.amountData.text()
        _teller = self.tellerData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _account = self.hold_account[self.accountData.currentIndex()]
        _expense = self.hold_expenses[self.expenseData.currentIndex()]
        if self.r1.isChecked():
            _amount = float(_amount)
        else:
            _amount = float(_amount) * -1

        arr = {}
        if _amount and not (_amount
                            == 0) and int(_expense) > 0 and int(_account) > 0:
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['accountID'] = _account
            arr['expenseID'] = _expense
            arr['teller'] = _teller

            ups = {}
            ups['id'] = self.editID
            if int(self.editID) > 0:
                db = 'school_expenses' + str(_session)
                g = Db()
                g.update(db, arr, ups)
                if int(self.editID) > 0:
                    self.button_reset()

    def button_reset(self):
        self.reloadTable(1)
        self.amountData.setText('')
        self.descriptionData.clear()
        self.tellerData.setText('')
        self.pb4.hide()
        self.pb5.hide()
        self.pb.show()
        self.editID = 0
        self.button_clear()
        self.confirmSelection()

    def button_clear(self):
        self.table.selectionModel().clearSelection()

    def button_click(self):
        _session = self.session
        _amount = self.amountData.text()
        _teller = self.tellerData.text()
        _date = self.dateData.date().toPyDate()
        _date = time.mktime(_date.timetuple())
        _description = self.descriptionData.toPlainText()
        _account = self.hold_account[self.accountData.currentIndex()]
        _expense = self.hold_expenses[self.expenseData.currentIndex()]
        if self.r1.isChecked():
            _amount = float(_amount)
        else:
            _amount = float(_amount) * -1

        arr = {}
        if _amount and not (_amount
                            == 0) and int(_expense) > 0 and int(_account) > 0:
            arr['amount'] = _amount
            arr['datepaid'] = _date
            arr['description'] = _description
            arr['accountID'] = _account
            arr['expenseID'] = _expense
            arr['teller'] = _teller

            db = 'school_expenses' + str(_session)
            g = Db()
            ins = g.insert(db, arr)
            if int(ins) > 0:
                self.button_reset()
Ejemplo n.º 21
0
 def createEditor(self, parent, option, index):
     """Create the Date edit widget to set the payment date"""
     qde = QDateEdit(parent)
     qde.setDisplayFormat(self.format)
     qde.setCalendarPopup(True)
     return qde
Ejemplo n.º 22
0
class LDSControls(QFrame):
        
    STATIC_IMG = ('error_static.png','linz_static.png','busy_static.png','clean_static.png')
    ANIM_IMG   = ('error.gif','linz.gif','layer.gif','clean.gif')
    
    IMG_SPEED  = 100
    IMG_WIDTH  = 64
    IMG_HEIGHT = 64
    
    MAX_WD = 450
    
    GD_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../../bin/gdal/gdal-data'))
    STATUS = LU.enum('ERROR','IDLE','BUSY','CLEAN')
    
    def __init__(self,parent):
        super(LDSControls, self).__init__()
        self.parent = parent
        self.initConf()
        self.initEPSG()
        self.initUI()
        
    def initConf(self):
        '''Read files in conf dir ending in conf'''
        self.cflist = ConfigInitialiser.getConfFiles()
        #self.imgset = self.STATIC_IMG if ConfigWrapper().readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        #self.imgset = self.STATIC_IMG if self.parent.confconn.tp.src.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        sep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.SRCNAME,self.parent.confconn.uconf)
        self.imgset = self.STATIC_IMG if sep.confwrap.readDSProperty('Misc','indicator')=='static' else self.ANIM_IMG
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.SRCNAME)
        
    def initEPSG(self):
        '''Read GDAL EPSG files, splitting by NZ(RSR) and RestOfTheWorld'''

        gcsf = gdal.FindFile('gdal','gcs.csv') 
        if not gcsf:
            gcsf = os.path.join(self.GD_PATH,'gcs.csv')
        pcsf = gdal.FindFile('gdal','pcs.csv') 
        if not pcsf: 
            pcsf = os.path.join(self.GD_PATH,'pcs.csv')
        gcs = ConfigInitialiser.readCSV(gcsf)
        pcs = ConfigInitialiser.readCSV(pcsf)

        self.nzlsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD'     in e[1] or  'RSRGD'     in e[1]]
        self.rowsr = [(e[0],e[0]+' - '+e[3]) for e in gcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]] \
                   + [(e[0],e[0]+' - '+e[1]) for e in pcs if 'NZGD' not in e[1] and 'RSRGD' not in e[1]]
                   
                   
    def initUI(self):
        
        # 0      1          2       3       4       5      6    7    8
        #'destname','lgselect','layer','uconf','group','epsg','fd','td','int'
        
        #self.rdest,rlgselect,self.rlayer,ruconf,self.rgroup,repsg,rfd,rtd,rint = readlist 
        
        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        destLabel = QLabel('Destination')
        lgLabel = QLabel('Group/Layer')
        epsgLabel = QLabel('EPSG')
        fromDateLabel = QLabel('From Date')
        toDateLabel = QLabel('To Date')
        confLabel = QLabel('User Config')
        
        self.view = QLabel() 
        self.view.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.view.setAlignment(Qt.AlignCenter)

        self.confcombo = QComboBox(self)
        self.confcombo.setToolTip('Enter your user config name (file) here')
        self.confcombo.addItems(self.cflist)
        self.confcombo.setEditable(False)
        #self.confcombo.currentIndexChanged.connect(self.doLGEditUpdate)
        
        #combos
        self.lgcombo = QComboBox(self)
        self.lgcombo.setMaximumWidth(self.MAX_WD)
        self.lgcombo.setDuplicatesEnabled(False)
        #self.lgcombo.setInsertPolicy(QComboBox.InsertAlphabetically)#?doesnt seem to work
        self.lgcombo.setToolTip('Select either Layer or Group entry')
        self.lgcombo.setEditable(False)
        self.sepindex = None
        #self.updateLGValues()
        
        self.epsgcombo = QComboBox(self)
        self.epsgcombo.setMaximumWidth(self.MAX_WD)
        self.epsgcombo.setToolTip('Setting an EPSG number here determines the output SR of the layer')  
        self.epsgcombo.addItems([i[1] for i in self.nzlsr])
        self.epsgcombo.insertSeparator(len(self.nzlsr))
        self.epsgcombo.addItems([i[1] for i in self.rowsr])
        self.epsgcombo.setEditable(True)
        self.epsgcombo.setEnabled(False)
        
        self.destlist = self.getConfiguredDestinations()
        self.destcombo = QComboBox(self)
        self.destcombo.setToolTip('Choose the desired output type')   
        self.destcombo.setEditable(False)
        self.destcombo.addItems(self.destlist)

        #date selection
        self.fromdateedit = QDateEdit()
        self.fromdateedit.setCalendarPopup(True)
        self.fromdateedit.setEnabled(False)
        
        self.todateedit = QDateEdit()
        self.todateedit.setCalendarPopup(True)
        self.todateedit.setEnabled(False)
        
        #check boxes
        self.epsgenable = QCheckBox()
        self.epsgenable.setCheckState(False)
        self.epsgenable.clicked.connect(self.doEPSGEnable)       
        
        self.fromdateenable = QCheckBox()
        self.fromdateenable.setCheckState(False)
        self.fromdateenable.clicked.connect(self.doFromDateEnable)
        
        self.todateenable = QCheckBox()
        self.todateenable.setCheckState(False) 
        self.todateenable.clicked.connect(self.doToDateEnable)
        
        self.progressbar = QProgressBar()
        self.progressbar.setRange(0,100)
        self.progressbar.setVisible(True)
        self.progressbar.setMinimumWidth(self.MAX_WD)
        
        
        #buttons        
        self.initbutton = QPushButton("waiting")
        self.initbutton.setToolTip('Initialise the Layer Configuration')
        self.initbutton.clicked.connect(self.doInitClickAction)
        
        self.cleanbutton = QPushButton("Clean")
        self.cleanbutton.setToolTip('Clean the selected layer/group from local storage')
        self.cleanbutton.clicked.connect(self.doCleanClickAction)
        
        self.replicatebutton = QPushButton("Replicate")
        self.replicatebutton.setToolTip('Execute selected replication')
        self.replicatebutton.clicked.connect(self.doReplicateClickAction)
        
        self.cancelbutton = QPushButton("Close")
        self.cancelbutton.setToolTip('Close the LDS Replicate application')       
        self.cancelbutton.clicked.connect(self.parent.close)


        #set dialog values using GPR
        self.updateGUIValues(self.parent.gvs)
        
        #set onchange here otherwise we get circular initialisation
        self.destcombo.currentIndexChanged.connect(self.doDestChanged)
        self.confcombo.currentIndexChanged.connect(self.doConfChanged)
        self.lgcombo.currentIndexChanged.connect(self.doLGComboChanged)

        self.setStatus(self.STATUS.IDLE)
        
        #grid
        grid = QGridLayout()
        grid.setSpacing(10)
        
        
        #placement section ------------------------------------
        #---------+---------+--------+---------+--------
        # dest LB |         | dest DD
        # grp LB  |         | grp DD
        # conf LB |         | conf DD
        # epsg L  | epsg CB | epsg DD
        # f dt L  | f dt CB | f dt DD
        # t td L  | t td CB | t td DD
        # icon    |       <- progress ->
        # layer B | <- . -> |repl B  | clean B | close B 
        #---------+---------+--------+---------+--------

        grid.addWidget(destLabel, 1, 0)
        grid.addWidget(self.destcombo, 1, 2)

        #grid.addWidget(layerLabel, 2, 0)
        grid.addWidget(lgLabel, 2, 0)
        grid.addWidget(self.lgcombo, 2, 2)
        
        grid.addWidget(confLabel, 3, 0)
        grid.addWidget(self.confcombo, 3, 2)
        
        #grid.addWidget(groupLabel, 4, 0)
        #grid.addWidget(self.groupEdit, 4, 2)
        
        grid.addWidget(epsgLabel, 5, 0)
        grid.addWidget(self.epsgenable, 5, 1)
        grid.addWidget(self.epsgcombo, 5, 2)

        grid.addWidget(fromDateLabel, 6, 0)
        grid.addWidget(self.fromdateenable, 6, 1)
        grid.addWidget(self.fromdateedit, 6, 2)
        
        grid.addWidget(toDateLabel, 7, 0)
        grid.addWidget(self.todateenable, 7, 1)
        grid.addWidget(self.todateedit, 7, 2)
        
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.view) 
        hbox3.addStretch(1)
        hbox3.addWidget(self.progressbar)

        #hbox3.addLayout(vbox2)
        #hbox3.addLayout(vbox3)
        
        hbox4 = QHBoxLayout()
        hbox4.addWidget(self.initbutton)
        hbox4.addStretch(1)
        hbox4.addWidget(self.replicatebutton)
        hbox4.addWidget(self.cleanbutton)
        hbox4.addWidget(self.cancelbutton)
        

        vbox = QVBoxLayout()
        #vbox.addStretch(1)
        vbox.addLayout(grid)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        
        self.setLayout(vbox)  
       
    #def setProgress(self,pct):
    #    self.progressbar.setValue(pct)
        
    def setStatus(self,status,message='',tooltip=None):
        '''Sets indicator icon and statusbar message'''
        self.parent.statusbar.showMessage(message)
        self.parent.statusbar.setToolTip(tooltip if tooltip else '')

        #progress
        loc = os.path.abspath(os.path.join(IMG_LOC,self.imgset[status]))
        #loc = os.path.abspath(os.path.join(os.path.dirname(__file__),self.parent.IMG_LOC,self.imgset[status]))
        self.progressbar.setVisible(status in (self.STATUS.BUSY, self.STATUS.CLEAN))
        
        #icon
        anim = QMovie(loc, QByteArray(), self)
        anim.setScaledSize(QSize(self.IMG_WIDTH,self.IMG_HEIGHT))
        anim.setCacheMode(QMovie.CacheAll)
        anim.setSpeed(self.IMG_SPEED)
        self.view.clear()
        self.view.setMovie(anim)
        anim.start()

        self.view.repaint()
        QApplication.processEvents(QEventLoop.AllEvents)

    def mainWindowEnable(self,enable=True):
        cons = (self.lgcombo, self.confcombo, self.destcombo, 
                self.initbutton, self.replicatebutton, self.cleanbutton, self.cancelbutton,
                self.epsgenable,self.fromdateenable,self.todateenable,
                self.parent.menubar)
        for c in cons:
            c.setEnabled(enable)
            
        if enable:
            self.epsgcombo.setEnabled(self.epsgenable.checkState())
            self.fromdateedit.setEnabled(self.fromdateenable.checkState())
            self.todateedit.setEnabled(self.todateenable.checkState())
        else:
            self.epsgcombo.setEnabled(False)
            self.fromdateedit.setEnabled(False)
            self.todateedit.setEnabled(False)
   
        QApplication.restoreOverrideCursor() if enable else QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) 

    def refreshLGCombo(self):
        '''Re index LG combobox since a refreshLG call (new dest?) will usually mean new groups'''
        self.lgcombo.clear()
        self.lgcombo.addItems([i[2] for i in self.parent.confconn.lglist])
        #NOTE the separator consumes an index, if not clearing the combobox selectively remove the old sepindex (assumes g preceeds l)
        #if self.sepindex:
        #    self.lgcombo.removeItem(self.sepindex)
        self.sepindex = [i[0] for i in self.parent.confconn.lglist].count(LORG.GROUP)
        self.lgcombo.insertSeparator(self.sepindex)
        
    def updateLGValues(self,uconf,lgval,dest):
        '''Sets the values displayed in the Layer/Group combo'''
        #because we cant seem to sort combobox entries and want groups at the top, clear and re-add
        #TRACE#        
        #pdb.set_trace()
        sf = None
        try:
            self.parent.confconn.initConnections(uconf,lgval,dest)
        except Exception as e:
            sf=1
            ldslog.error('Error Updating UC Values. '+str(e))
            
        if sf:
            self.setStatus(self.STATUS.ERROR,'Error Updating UC Values', str(e))
        else:
            self.setStatus(self.STATUS.IDLE)
            
        self.refreshLGCombo()
        
    def centre(self):
        
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
    
    def gprParameters(self,rdest):
        '''Zip default and GPR values'''
        return [x if LU.assessNone(x) else y for x,y in zip(self.parent.gpr.readsec(rdest),self.parent.DEF_RVALS[1:])]
    
    def getLCE(self,ln):
        '''Read layer parameters'''
        dep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        #sep = self.parent.confconn.reg.openEndPoint('WFS',self.parent.confconn.uconf)
        self.parent.confconn.reg.setupLayerConfig(self.parent.confconn.tp,None,dep,initlc=False)
        lce = dep.getLayerConf().readLayerParameters(ln)
        #self.parent.confconn.reg.closeEndPoint('WFS')
        self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        sep,dep = None,None
        return lce
    
    
    def doDestChanged(self):
        '''Read the destname parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rvals = self.gprParameters(rdest)
        self.updateGUIValues([rdest]+rvals)    
        
        
    def doConfChanged(self):
        '''Read the user conf parameter and fill dialog with matching GPR values'''
        rdest = str(self.destlist[self.destcombo.currentIndex()])
        rlg,_,rep,rfd,rtd = self.gprParameters(rdest)
        ruc = str(self.cflist[self.confcombo.currentIndex()])
        self.updateGUIValues((rdest,rlg,ruc,rep,rfd,rtd))
        
        
    def doLGComboChanged(self):
        '''Read the layer/group value and change epsg to layer or gpr match'''
        #get a matching LG entry and test whether its a layer or group
        #lgi = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgi = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #lgi can be none if we init a new group, in which case we use the GPR value
        if lgi:
            lge = self.parent.confconn.lglist[lgi]
            lce = self.getLCE(lge[1]) if lge[0]==LORG.LAYER else None
        else:
            lce = None
        
        #look for filled layer conf epsg OR use prefs stored in gpr
        if lce and LU.assessNone(lce.epsg):
            epsgval = lce.epsg
        else:
            rdest = str(self.destlist[self.destcombo.currentIndex()])
            _,_,epsgval,_,_ = self.gprParameters(rdest)
        epsgindex = [i[0] for i in self.nzlsr+[(0,0)]+self.rowsr].index(epsgval)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(int(epsgindex))

        
    def updateGUIValues(self,readlist):
        '''Fill dialog values from provided list'''
        #TODO. Remove circular references when setCurrentIndex() triggers do###Changed()
        #Read user input
        rdest,self.rlgval,ruconf,repsg,rfd,rtd = readlist
        
        #--------------------------------------------------------------------
        
        #Destination Menu
        selecteddest = LU.standardiseDriverNames(rdest)
        if selecteddest not in self.destlist:
            self.destlist = self.getConfiguredDestinations()
            self.destcombo.addItem(selecteddest)
        destindex = self.destlist.index(selecteddest) if selecteddest else 0
        
        if self.destcombo.currentIndex() != destindex:
            self.destcombo.setCurrentIndex(destindex)
        
        #InitButton
        self.initbutton.setText('Layer Select')
        
        #Config File
        confindex = 0
        if LU.assessNone(ruconf):
            ruconf = ruconf.split('.')[0]
            if ruconf not in self.cflist:
                self.cflist += [ruconf,]
                self.confcombo.addItem(ruconf)
            confindex = self.cflist.index(ruconf)
            
        if self.confcombo.currentIndex() != confindex:
            self.confcombo.setCurrentIndex(confindex)
        #self.confEdit.setText(ruconf if LU.assessNone(ruconf) else '')
        
        #Layer/Group Selection
        self.updateLGValues(ruconf,self.rlgval,rdest)
        lgindex = None
        if LU.assessNone(self.rlgval):
            #index of list value
            lgindex = self.parent.confconn.getLayerGroupIndex(self.rlgval,col=1)
            
        if LU.assessNone(lgindex):
            #advance by 1 for sep
            lgindex += 1 if lgindex>self.sepindex else 0 
        else:
            #using the separator index sets the combo to blank
            lgindex = self.sepindex
        if self.lgcombo.currentIndex() != lgindex:
            self.lgcombo.setCurrentIndex(lgindex)
        #self.doLGEditUpdate()
        
        #EPSG
        #                                user > layerconf
        #useepsg = LU.precedence(repsg, lce.epsg if lce else None, None)
        epsgindex = [i[0] for i in self.nzlsr+[(None,None)]+self.rowsr].index(repsg)
        if self.epsgcombo.currentIndex() != epsgindex:
            self.epsgcombo.setCurrentIndex(epsgindex)
            
        #epsgedit = self.epsgcombo.lineEdit()
        #epsgedit.setText([e[1] for e in self.nzlsr+self.rowsr if e[0]==repsg][0])
        
        #epsgedit.setText([e for e in self.nzlsr+self.rowsr if re.match('^\s*(\d+).*',e).group(1)==repsg][0])
        
        #To/From Dates
        if LU.assessNone(rfd):
            self.fromdateedit.setDate(QDate(int(rfd[0:4]),int(rfd[5:7]),int(rfd[8:10])))
        else:
            early = DataStore.EARLIEST_INIT_DATE
            self.fromdateedit.setDate(QDate(int(early[0:4]),int(early[5:7]),int(early[8:10])))
            
        if LU.assessNone(rtd):
            self.todateedit.setDate(QDate(int(rtd[0:4]),int(rtd[5:7]),int(rtd[8:10]))) 
        else:
            today = DataStore.getCurrent()
            self.todateedit.setDate(QDate(int(today[0:4]),int(today[5:7]),int(today[8:10])))
            
        #Internal/External CheckBox
#        if LU.assessNone(rint):
#            self.internalTrigger.setChecked(rint.lower()==DataStore.CONF_INT)
#        else:
#            self.internalTrigger.setChecked(DataStore.DEFAULT_CONF==DataStore.CONF_INT)
        
        
    def getConfiguredDestinations(self):
        defml = ['',]+DataStore.DRIVER_NAMES.values()
        return [d for d in self.parent.gpr.getDestinations() if d in defml]
        
    def doEPSGEnable(self):
        self.epsgcombo.setEnabled(self.epsgenable.isChecked())
        
    def doFromDateEnable(self):
        self.fromdateedit.setEnabled(self.fromdateenable.isChecked())
          
    def doToDateEnable(self):
        self.todateedit.setEnabled(self.todateenable.isChecked())  
          
    def readParameters(self):
        '''Read values out of dialogs'''
        destination = LU.assessNone(str(self.destlist[self.destcombo.currentIndex()]))
        #lgindex = self.parent.confconn.getLayerGroupIndex(self.lgcombo.currentText().toUtf8().data())
        lgindex = self.parent.confconn.getLayerGroupIndex(LQ.readWidgetText(self.lgcombo.currentText()))
        #NB need to test for None explicitly since zero is a valid index
        lgval = self.parent.confconn.lglist[lgindex][1] if LU.assessNone(lgindex) else None       
        #uconf = LU.standardiseUserConfigName(str(self.confcombo.lineEdit().text()))
        #uconf = str(self.confcombo.lineEdit().text())
        uconf = str(self.cflist[self.confcombo.currentIndex()])
        ee = self.epsgenable.isChecked()
        epsg = None if ee is False else re.match('^\s*(\d+).*',str(self.epsgcombo.lineEdit().text())).group(1)
        fe = self.fromdateenable.isChecked()
        te = self.todateenable.isChecked()
        fd = None if fe is False else str(self.fromdateedit.date().toString('yyyy-MM-dd'))
        td = None if te is False else str(self.todateedit.date().toString('yyyy-MM-dd'))
        
        return destination,lgval,uconf,epsg,fe,te,fd,td
    
    def doInitClickAction(self):
        '''Initialise the LC on LC-button-click, action'''
        try:
            try:
                self.setStatus(self.STATUS.BUSY,'Opening Layer-Config Editor')  
                self.progressbar.setValue(0)
                self.parent.runLayerConfigAction()
            finally:
                self.setStatus(self.STATUS.IDLE,'Ready')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Error in Layer-Config',str(sys.exc_info()))#e))
        
    def doCleanClickAction(self):
        '''Set clean anim and run clean'''
        #lgo = self.lgcombo.currentText().toUtf8().data()
        lgo = LQ.readWidgetText(self.lgcombo.currentText())
        
        try:
            self.setStatus(self.STATUS.CLEAN,'Running Clean '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(True)
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Clean of '+lgo,str(sys.exc_info()))#e))
        
    def doReplicateClickAction(self):
        '''Set busy anim and run repl'''
        lgo = self.lgcombo.currentText()#.toUtf8().data()#only used for error messages
        try:
            self.setStatus(self.STATUS.BUSY,'Running Replicate '+lgo)
            self.progressbar.setValue(0)
            self.runReplicationScript(False)
            ldslog.debug('TRPfinish')
        except Exception as e:
            self.setStatus(self.STATUS.ERROR,'Failed Replication of '+lgo,str(sys.exc_info()))#e))

    def runReplicationScript(self,clean=False):
        '''Run the layer/group repliction script'''
        destination,lgval,uconf,epsg,fe,te,fd,td = self.readParameters()
        uconf_path = LU.standardiseUserConfigName(uconf)
        destination_path = LU.standardiseLayerConfigName(destination)
        destination_driver = LU.standardiseDriverNames(destination)

        if not os.path.exists(uconf_path):
            self.userConfMessage(uconf_path)
            return
        elif not MainFileReader(uconf_path).hasSection(destination_driver):
            self.userConfMessage(uconf_path,destination_driver)
            return
        #-----------------------------------------------------
        #'destname','layer','uconf','group','epsg','fd','td','int'
     
        self.parent.gpr.write((destination_driver,lgval,uconf,epsg,fd,td))        
        ldslog.info(u'dest={0}, lg={1}, conf={2}, epsg={3}'.format(destination_driver,lgval,uconf,epsg))
        ldslog.info('fd={0}, td={1}, fe={2}, te={3}'.format(fd,td,fe,te))
        lgindex = self.parent.confconn.getLayerGroupIndex(lgval,col=1)
        #lorg = self.parent.confconn.lglist[lgindex][0]
        #----------don't need lorg in TP anymore but it is useful for sorting/counting groups
        #self.parent.confconn.tp.setLayerOrGroup(lorg)
        self.parent.confconn.tp.setLayerGroupValue(lgval)
        if self.fromdateenable.isChecked(): self.parent.confconn.tp.setFromDate(fd)
        if self.todateenable.isChecked(): self.parent.confconn.tp.setToDate(td)
        self.parent.confconn.tp.setUserConf(uconf)
        if self.epsgenable: self.parent.confconn.tp.setEPSG(epsg)
        
        #because clean state persists in TP
        if clean:
            self.parent.confconn.tp.setCleanConfig()
        else:
            self.parent.confconn.tp.clearCleanConfig()
        #(re)initialise the data source since uconf may have changed
        #>>#self.parent.confconn.tp.src = self.parent.confconn.initSourceWrapper()
        #--------------------------
        ###ep = self.parent.confconn.reg.openEndPoint(self.parent.confconn.destname,self.parent.confconn.uconf)
        
        ###self.parent.confconn.reg.closeEndPoint(self.parent.confconn.destname)
        ###ep = None
        #Open ProcessRunner and run with TP(proc)/self(gui) instances
        #HACK temp add of dest_drv to PR call
        try:
            #TODO. Test for valid LC first
            self.tpr = ProcessRunner(self,destination_driver)
        except Exception as e:
            ldslog.error('Cannot create ProcessRunner {}. NB Possible missing Layer Config {}'.format(str(e),destination_path))
            self.layerConfMessage(destination_path)
            return
        #If PR has been successfully created we must vave a valid dst    
        ldslog.debug('TRPstart')
        self.tpr.start()
        
#     def quitProcessRunner(self):
#         self.tpr.join()
#         self.tpr.quit()
#         self.trp = None

        
    def userConfMessage(self,uconf,secname=None):
        ucans = QMessageBox.warning(self, 'User Config Missing/Incomplete', 
                                'Specified User-Config file, '+str(uconf)+' does not exist' if secname is None else 'User-Config file does not contain '+str(secname)+' section', 
                                'Back','Initialise User Config')
        if not ucans:
            #Retry
            ldslog.warn('Retry specifying UC')
            #self.confcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset User Config Wizard')
        self.parent.runWizardAction()


    def layerConfMessage(self,dest):
        lcans = QMessageBox.warning(self, 'Layer Config Missing', 
                                'Required Layer-Config file, '+str(dest)+' does not exist', 
                                'Back','Run Layer Select')
        if not lcans:
            #Retry
            ldslog.warn('Retry specifying LC')
            #self.destcombo.setCurrentIndex(0)
            return
        #Init
        ldslog.warn('Reset Layer Config')
        self.doInitClickAction()