Esempio n. 1
0
class ContractEditor(QtGui.QWidget, QtCore.QObject):

    s_usine_selected = QtCore.Signal()
    enter_key_pressed = QtCore.Signal()
    s_contract_edited = QtCore.Signal()
    s_contract_validated = QtCore.Signal()
    s_close_widget = QtCore.Signal()
        
    def __init__(self, parent=None):
        super(ContractEditor, self).__init__(parent)
        self.ui = Ui_ContractEditor()
        self.ui.setupUi(self)
        self.setCreatorMode() # precis if we modify an existant contract or not
        
        self.cDB = ContractsDatabase()
        self.oil_market = Market()
#        self.comm = self.cDB.communicator
#        self.comm.s_cDB_updated.connect(self.updateCtrList)
#        self.new_contract = Contract()
        self.new_contract = None
        
        self.w_dlv = QtGui.QWidget()
        layout = QtGui.QVBoxLayout()
        label_detail = QtGui.QLabel("Détails :")
        self.t_dlv = QtGui.QTextEdit()
        self.w_dlv_date = CalendarDeliveries()
        layout.addWidget(self.w_dlv_date)
        layout.addWidget(label_detail)
        layout.addWidget(self.t_dlv)
        self.w_dlv.setLayout(layout)
        scrollArea = QtGui.QScrollArea()
        scrollArea.setWidgetResizable(True)
        scrollArea.setWidget(self.w_dlv)
        scrollArea.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)

        self.ui.formLayout.setWidget(11, QtGui.QFormLayout.FieldRole, scrollArea)

#        layout = QtGui.QVBoxLayout()
#        layout.addWidget(self.w_dlv_date)
#        self.ui.date_livraison.setLayout(layout)
#        
#        self.ui.date_livraison.updateGeometry()
#        self.ui.date_livraison.resize(self.w_dlv_date.minimumSize())
#        self.ui.date_livraison.adjustSize()
#        self.w_dlv_date.updateGeometry()
#        self.w_dlv_date.adjustSize()
#        self.ui.date_livraison.adjustSize()
        
        self.ui.n_contrat.setEnabled(True)
        self.ui.cb_adr_depart.view().setAlternatingRowColors(True)
        self.ui.cb_adr_livraison.view().setAlternatingRowColors(True)
        self.ui.cb_logement.view().setAlternatingRowColors(True)
        self.ui.cb_marchandise.view().setAlternatingRowColors(True)
        self.ui.cb_nom_acheteur.view().setAlternatingRowColors(True)
        self.ui.cb_nom_vendeur.view().setAlternatingRowColors(True)
        self.ui.cb_usine.view().setAlternatingRowColors(True)
#        self.ui.cb_usine.setMinimumHeight(100)
        
        self.ui.qte_total.setValidator(QtGui.QDoubleValidator(0.0, 999999.0, 10, self))
        self.ui.prix.setValidator(QtGui.QDoubleValidator(0.0, 999999.0, 10, self))
        self.initMonnaie()
        self.initMarchandiseList()
        self.initPaiementList()
        self.initLogementList()
        self.connectionsManager()
        self.repaint()
        
        
    def setCreatorMode(self, b = True):
        self.creator_mode = b
    
    
    def connectionsManager(self):
        self.ui.cb_marchandise.currentIndexChanged[int].connect(self.currentMarchandiseChanged)
#        self.ui.cb_nom_acheteur.editTextChanged[str].connect(self.updateClientList)
#        self.ui.cb_nom_vendeur.editTextChanged[str].connect(self.updateClientList)
        #lorsque un nom de client est selectionné dans la liste
        self.ui.cb_nom_acheteur.currentIndexChanged[int].connect(self.updateAdressList)
        self.ui.cb_nom_vendeur.currentIndexChanged[int].connect(self.updateAdressList)
        
        self.ui.cb_nom_acheteur.currentIndexChanged[int].connect(self.updateUsine)
        self.ui.cb_nom_vendeur.currentIndexChanged[int].connect(self.updateUsine)
        
        self.ui.cb_franco.toggled.connect(self.updateUsine)
        
#        self.ui.quantite.textEdited[str].connect(self.updateUnite)
        
        self.ui.b_valid.clicked.connect(self.validateContract)
        self.ui.b_cancel.clicked.connect(self.close)
        
        self.ui.b_fiche_acheteur.clicked.connect(self.openClientFile)
        self.ui.b_fiche_vendeur.clicked.connect(self.openFournissFile)
        
        
        
    def initEditor(self, ctr = None):
        print "initEditor"
        if ctr is None: 
            self.new_contract = self.cDB.newContract()
        else:
            self.new_contract = ctr
        
        
        self.ui.n_contrat.setText(self.new_contract.n_contrat)
        
        self.initClientList()
        
        if self.new_contract.marchandise is not None:
            if not isinstance(self.new_contract.marchandise, int):
                tmp_marchandise = self.oil_market.getMarchandiseFullName(self.new_contract.marchandise)
                self.ui.cb_marchandise.setCurrentIndex(self.ui.cb_marchandise.findText(tmp_marchandise))
            else:
                self.ui.cb_marchandise.setCurrentIndex(self.new_contract.marchandise)
            
        # INITIALIZATION OF FOURNISSEUR NAME AND FOUNISSEUR ADR IF EXIST
        if self.new_contract.usine_vendeur is not None: #usine vendeur
            index = 0
            while self.new_contract.usine_vendeur.proprietaire.nom not in self.ui.cb_nom_vendeur.itemText(index).encode('utf-8'):
                index += 1
                if index > self.ui.cb_nom_vendeur.count():
                    index = -1
                    break
            self.ui.cb_nom_vendeur.setCurrentIndex(index)
            self.updateAdressList(emitter=self.ui.cb_nom_vendeur)
            
            index = 0
            while self.new_contract.getAdr_uFourniss() != self.ui.cb_adr_depart.itemText(index).encode('utf-8'):
                index += 1
                if index > self.ui.cb_adr_depart.count():
                    index = -1
                    break
            self.ui.cb_adr_depart.setCurrentIndex(index)
            
            
        # INITIALIZATION OF CLIENT NAME AND CLIENT ADR IF EXIST
        if self.new_contract.usine_acheteur is not None:
            index = 0
            while self.new_contract.usine_acheteur.proprietaire.nom not in self.ui.cb_nom_acheteur.itemText(index).encode('utf-8'):
                index += 1
                if index > self.ui.cb_nom_acheteur.count():
                    index = -1
                    break
            self.ui.cb_nom_acheteur.setCurrentIndex(index)
            self.updateAdressList(emitter=self.ui.cb_nom_acheteur)
            
            index = 0
            while self.new_contract.getAdr_uClient() != self.ui.cb_adr_livraison.itemText(index).encode('utf-8'):
                index += 1
                if index > self.ui.cb_adr_livraison.count():
                    index = -1
                    break
            self.ui.cb_adr_livraison.setCurrentIndex(index)
            
        
        # INITIALIZATION OF CONTRACT DATE IF EXIST
        if self.new_contract.date_contrat is not None:
            self.ui.date_ctr.setDate(QtCore.QDate.fromString(self.new_contract.date_contrat, "dd/MM/yyyy"))
        else:
            self.ui.date_ctr.setDate(QtCore.QDate.currentDate())
            
        # INITIALIZATION OF CTR MONNEY
        if self.new_contract.monnaie is not None:
            for i in range(0, self.ui.cb_monnaie.count()):
                if self.ui.cb_monnaie.itemData(i) == self.new_contract.monnaie:
                    self.ui.cb_monnaie.setCurrentIndex(i)
                    break
                
        # INITIALIZATION OF CTR UNIT
        if self.new_contract.unite is not None:
            for i in range(0, self.ui.cb_unite.count()):
                if self.ui.cb_unite.itemData(i) == self.new_contract.unite:
                    self.ui.cb_unite.setCurrentIndex(i)
                    break
                
        if self.new_contract.descr_livraison is not None:
            self.t_dlv.setPlainText(self.new_contract.descr_livraison)
        if self.new_contract.prix is not None:
            self.ui.prix.setText(self.new_contract.prix)
        if self.new_contract.courtage is not None:
            self.ui.courtage.setText(self.new_contract.courtage)
        if self.new_contract.is_franco is True:
            self.ui.cb_franco.setChecked(True)
        if self.new_contract.usine_cible is not None:
            index = self.ui.cb_usine.findText(self.new_contract.getAdrCible())
            self.ui.cb_usine.setCurrentIndex(index)
        if self.new_contract.logement is not None:
            self.ui.cb_logement.setCurrentIndex(self.ui.cb_logement.findText(self.new_contract.logement))
        if self.new_contract.periode_livraison is not None:
            self.w_dlv_date.loadCalendar(self.new_contract.periode_livraison)
        if self.new_contract.quantite is not None:
            self.ui.quantite.setText(self.new_contract.quantite)
        if self.new_contract.qte_total is not None:
            self.ui.qte_total.setText(str(self.new_contract.qte_total))
        if self.new_contract.paiement is not None:
            self.ui.cb_paiement.setCurrentIndex(self.ui.cb_paiement.findText(self.new_contract.paiement))
        self.ui.t_notes.setText(self.new_contract.notes)
        
    def initMonnaie(self):
        print "initMonnaie"
        monnaies = getFromConfig('monnaie', 'monnaies')
        sorted_monnaies = sorted(monnaies, key = lambda m: m['code'])
        for m in sorted_monnaies:
            self.ui.cb_monnaie.addItem(m['sym'].encode('utf8'), userData=m['code'])
        self.ui.cb_monnaie.setCurrentIndex(0)
        
        unites = getFromConfig('unite', 'unites')
        for u in unites:
            self.ui.cb_unite.addItem(u['nom'].encode('utf8').title(), userData=u['sym'].lower())
        self.ui.cb_unite.setCurrentIndex(0)
        
    def initMarchandiseList(self):
        print "initMarchandiseList"
        marchandise_list = self.oil_market.marchandises_list['fr']
        ordered_marchandise_list = sorted(marchandise_list)
        self.updateComboBox(self.ui.cb_marchandise, ordered_marchandise_list)
        completer = QtGui.QCompleter(marchandise_list)
        completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
        self.ui.cb_marchandise.setCompleter(completer)
        
#    def updateMarchandiseList(self, current_list = None):
#        print "updateMarchandiseList"
#        if current_list is None:
#            marchandise_list = self.oil_market.marchandises_list['fr']
#        else:
#            marchandise_list = current_list
#        marchandise_list = sorted(marchandise_list)
#        if self.ui.cb_adr_depart.currentIndex() >= 0 or self.ui.cb_adr_livraison.currentIndex() >= 0:
#            if self.ui.cb_adr_livraison.currentIndex() >= 0:
#                from Classes import Usine
#                usine = self.ui.cb_adr_depart.itemData(i)
#                for marchandise in usine.produits:
#                    if 
    
    def initPaiementList(self):
        print "initPaiementList"
        paiement_list = self.oil_market.paiements['fr']
        ordered_paiement_list = sorted(paiement_list)
        self.updateComboBox(self.ui.cb_paiement, ordered_paiement_list)
        
        
    def initLogementList(self):
        print "initMarchandiseList"
        logement_list = self.oil_market.logements['fr']
        ordered_logement_list = sorted(logement_list)
        self.updateComboBox(self.ui.cb_logement, ordered_logement_list)
        
    @QtCore.Slot(str)
    def initClientList(self, marchandise_name = ""):
        # called when marchandise is edited
        print "initClientList"
        if len(marchandise_name) > 0:
            usine_acheteur_possibles = self.oil_market.get_clients_from_marchandise(marchandise_name, is_fournisseur=False)
            client_list = list(set([ u.proprietaire.nom for u in usine_acheteur_possibles ]))
        else:
            client_list = list(set([ c.nom for c in self.oil_market.get_client(is_fournisseur=False) ]))
#        print "acheteur_list \n ", client_list
        client_list = sorted(client_list)
        self.updateComboBox(self.ui.cb_nom_acheteur, client_list)
        completer = QtGui.QCompleter(client_list)
        completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        completer.setCompletionMode(QtGui.QCompleter.InlineCompletion)
        self.ui.cb_nom_acheteur.setCompleter(completer)
        
        if len(marchandise_name)>0:
            usine_vendeur_possibles = self.oil_market.get_clients_from_marchandise(marchandise_name, is_fournisseur=True)
            client_list = list(set([ u.proprietaire.nom for u in usine_vendeur_possibles ]))
        else:
            client_list = list(set([ c.nom for c in self.oil_market.get_client(is_fournisseur=True) ]))
#        print "vendeur_list \n ", client_list
        client_list = sorted(client_list)
        self.updateComboBox(self.ui.cb_nom_vendeur, client_list)
        completer = QtGui.QCompleter(client_list)
        completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        completer.setCompletionMode(QtGui.QCompleter.InlineCompletion)
        self.ui.cb_nom_vendeur.setCompleter(completer)


    def updateComboBox(self, cb, items = None, blockSignals = True, text = ""):
        print "updateComboBox ", cb.objectName()
        cb.blockSignals(blockSignals)
        cb.clear()
        if items is not None:
            cb.addItems(items)
        cb.setCurrentIndex(-1)
        cb.setEditText(text)
        cb.blockSignals(False)
            
    @QtCore.Slot(str)
    def updateTotalQte(self, text):
        matches = findall(r"[-+]?\d*\.*\d+", text)
        if len(matches) > 0:
            qte = matches[-1]
#            print qte
            self.ui.qte_total.setText(qte)
    
    @QtCore.Slot(str)    
    def updateUnite(self, text):
        if 'kilo' in text or 'kg' in text:
            self.ui.cb_unite.setCurrentIndex(self.ui.cb_unite.findData('kg'))
        else:
            self.ui.cb_unite.setCurrentIndex(self.ui.cb_unite.findData('t'))
            
            
#    @QtCore.Slot(str)    
#    def updateMarchandise(self, text):
#        # recupere l'emetteur et nettoie le combobox en question
#        sender = self.sender()
#        print self.ui.cb_marchandise.currentIndex()
#        print "updateMarchandise; signal from ", sender.objectName()
#        text = _format(text, True, True)
#        potentials = self.oil_market.getNearestMarchandise(text)
#        ordered_marchandise_list = sorted(potentials)
#        self.updateComboBox(sender, ordered_marchandise_list, text=text)     
            
    @QtCore.Slot(int)
    def currentMarchandiseChanged(self, index):
        sender = self.sender()
        print "currentMarchandiseChanged ", index, sender.itemText(index)
        
#        print "Marchandise : ", self.oil_market.get_code_from_name(sender.itemText(index)), self.oil_market.marchandiseExist(sender.itemText(index))
        self.new_contract.marchandise = self.oil_market.get_code_from_name(sender.itemText(index))

    @QtCore.Slot(str)
    def updateClientList(self, text, cb_widget = None):
        # recupere l'emetteur et nettoie le combobox en question
        # puis met a jour la liste des noms similaires
        cb_client = cb_widget or self.sender()
        print "updateClientList; signal from ", cb_client.objectName()
        
        clients = []
        if cb_client.objectName() == "cb_nom_vendeur" or cb_client.objectName() == "cb_nom_acheteur" :
            clients = self.oil_market.getNearestClient(text.encode('utf8'), 'vendeur' in cb_client.objectName())
        elif len(self.ui.cb_marchandise.currentText()) > 0:
            clients = [ u.proprietaire.nom for u in self.oil_market.get_clients_from_marchandise(self.ui.cb_marchandise.currentText(), 'vendeur' in cb_client.objectName())]
        else:
            clients = [ u.proprietaire.nom for u in self.oil_market.get_client(is_fournisseur = 'vendeur' in cb_client.objectName())]
        
        ordered_clients_list = sorted(clients)
        if len(ordered_clients_list) == 0:
            print("Probable error when updateClientList")
            
        self.updateComboBox(cb_client, ordered_clients_list, text=text)
        
        
    @QtCore.Slot(int)
    def updateAdressList(self, client_index = None, emitter = None):
        #recupere l'emetteur et la destination
        if emitter is None:
            cb_client = self.sender()
        else:
            cb_client = emitter
        print "updateAdressList; signal from ", cb_client.objectName(), client_index
        
        if 'vendeur' in cb_client.objectName():
            cb_adr = self.ui.cb_adr_depart
        else:
            cb_adr = self.ui.cb_adr_livraison
            
        cb_adr.blockSignals(True)
        # et met a jour la liste des adresses disponibles
        cb_adr.clear()
            
    
        # si la marchandise est bien renseignée, on ne met que les usines correspondantes. Sinon on les met toutes.
#        if len(self.ui.cb_marchandise.text()) > 0:
#            for usine in self.oil_market.get_clients_from_marchandise(self.ui.cb_marchandise.text(), 'vendeur' in cb_client.objectName()):
#                if usine.proprietaire.nom == cb_client.currentText().encode('utf-8'):
#                    cb_adr.addItem(getInlineArray(usine.adresse), userData = usine)
##                    cb_adr.setCurrentIndex(0)
#        else:
        client = self.oil_market.get_client(cb_client.currentText(), 'vendeur' in cb_client.objectName())
        if client is not None:
#            if len(client.siege) > 1: # is not None and client.siege.getAdr() is not None and len(client.siege.getAdr()) > 0:
#                cb_adr.addItem(client.siege, userData = client.usines[0])
#            for usine in client.usines:
#                adr = usine.getAdr()
#                print adr
#                cb_adr.addItem(adr, userData = usine)
            fact_adr = client.getFactAdr()
            for adr, v, u in fact_adr:
                cb_adr.addItem(adr, userData = [[adr, v], u])
            
        
#        cb_adr.setCurrentIndex(0)
        cb_adr.blockSignals(False)
        cb_adr.setCurrentIndex(-1)
        
        
    @QtCore.Slot(int)
    def updateAdrCtr(self, index):
        sender = self.sender()
        print "updateAdrCtr; signal from ", sender.objectName(), index
#        
#        if "depart" in sender.objectName():
#            self.new_contract.usine_vendeur = self.ui.cb_adr_depart.itemData(index)
#        elif "livraison" in sender.objectName():
#            self.new_contract.usine_acheteur = self.ui.cb_adr_livraison.itemData(index)

        
    @QtCore.Slot()
    def updateUsine(self):
        sender = self.sender()
        print "updateUsine sended from ", sender.objectName() 
        self.ui.cb_usine.clear()
        if self.ui.cb_franco.isChecked() and self.ui.cb_nom_acheteur.currentIndex() >= 0:
            acheteur = self.oil_market.get_client(self.ui.cb_nom_acheteur.currentText(), is_fournisseur=False)
            if acheteur is not None:
                usines = acheteur.getUsineAdr()
                for adr, v, u in usines:
                    self.ui.cb_usine.addItem(adr, userData = [[adr,v], u])
        elif self.ui.cb_franco.isChecked() is False and self.ui.cb_nom_vendeur.currentIndex() >= 0:
            vendeur = self.oil_market.get_client(self.ui.cb_nom_vendeur.currentText(), is_fournisseur=True)
            if vendeur is not None:
                usines = vendeur.getUsineAdr()
                for adr, v, u in usines:
                    self.ui.cb_usine.addItem(adr, userData = [[adr, v], u])
                    
                    
    @QtCore.Slot()
    def validateContract(self):
        
        if self.checkFormular() is False:
            return
        
        self.new_contract.n_contrat = self.ui.n_contrat.text()
        
        data = self.ui.cb_adr_depart.itemData( self.ui.cb_adr_depart.currentIndex() )
        self.new_contract.usine_vendeur = data[1]
        self.new_contract.adr_uFourniss = data[0]
        
        data = self.ui.cb_adr_livraison.itemData( self.ui.cb_adr_livraison.currentIndex() )
        self.new_contract.usine_acheteur = data[1]
        self.new_contract.adr_uClient = data[0]
            
        self.new_contract.date_contrat = str(self.ui.date_ctr.date().toString("dd/MM/yyyy"))
        self.new_contract.is_franco = self.ui.cb_franco.isChecked()
        data = self.ui.cb_usine.itemData( self.ui.cb_usine.currentIndex() )
        self.new_contract.usine_cible = data[1]
        self.new_contract.adr_uCible = data[0]
        
        tmp = findall(r"[-+]?\d*\.*\d+", self.ui.qte_total.text().replace(',','.'))
        if len(tmp) > 0:
            self.new_contract.qte_total = float(tmp[0])
        else:
            self.new_contract.qte_total = 0.0
            
        self.new_contract.periode_livraison = self.w_dlv_date.getSelection()[1]
        self.new_contract.descr_livraison = self.t_dlv.toPlainText()
        
        self.new_contract.prix = self.ui.prix.text().encode('utf8')
        self.new_contract.courtage = self.ui.courtage.text().encode('utf8')
        self.new_contract.paiement = self.ui.cb_paiement.currentText()
        self.new_contract.logement = self.ui.cb_logement.currentText()
        self.new_contract.quantite = self.ui.quantite.text()
        
        self.new_contract.monnaie = self.ui.cb_monnaie.itemData(self.ui.cb_monnaie.currentIndex())
        self.new_contract.unite = self.ui.cb_unite.itemData(self.ui.cb_unite.currentIndex())
        
        self.new_contract.notes = self.ui.t_notes.toPlainText()
#        self.new_contract.marchandise = self.ui.cb_marchandise.findText(self.ui.cb_marchandise.currentText())
        
        if self.cDB.confirmContract(self.new_contract) < 0:
            return 
        
        self.new_contract  = None
        self.close()
            
    def checkFormular(self):
        
        to_complete = 0
#        
        if self.ui.cb_nom_acheteur.currentIndex() < 0:
            to_complete += 1
            self.ui.cb_nom_acheteur.setStyleSheet("#cb_nom_acheteur { border: 3px solid red; }")
        else:
            self.ui.cb_nom_acheteur.setStyleSheet("")
            
        if self.ui.cb_nom_vendeur.currentIndex() < 0:
            to_complete += 1
            self.ui.cb_nom_vendeur.setStyleSheet("#cb_nom_vendeur { border: 3px solid red; }")
        else:
            self.ui.cb_nom_vendeur.setStyleSheet("")
            
        if self.ui.cb_usine.currentIndex() < 0:
            to_complete += 1
            self.ui.cb_usine.setStyleSheet("#cb_usine { border: 3px solid red; }")
        else:
            self.ui.cb_usine.setStyleSheet("")
        
        if self.ui.cb_adr_depart.currentIndex() < 0:
            to_complete += 1
            self.ui.cb_adr_depart.setStyleSheet("#cb_adr_depart { border: 3px solid red; }")
        else:
            self.ui.cb_adr_depart.setStyleSheet("")
            
        if self.ui.cb_adr_livraison.currentIndex() < 0:
            to_complete += 1
            self.ui.cb_adr_livraison.setStyleSheet("#cb_adr_livraison { border: 3px solid red; }")
        else:
            self.ui.cb_adr_livraison.setStyleSheet("")
        
        if self.new_contract.marchandise is None or len(self.new_contract.marchandise) < 0 or self.oil_market.marchandiseExist(self.new_contract.marchandise) is False:
            to_complete += 1
            self.ui.cb_marchandise.setStyleSheet("#cb_marchandise { border: 3px solid red; }")
        else:
            self.ui.cb_marchandise.setStyleSheet("")
        
        if len(self.ui.qte_total.text()) <= 0:
            to_complete += 1
            self.ui.qte_total.setStyleSheet("#qte_total { border: 3px solid red; }")
        else: 
            self.ui.qte_total.setStyleSheet("")
#            total = self.w_dlv_date.getSelection()[0]
#            if total == 0.0:
#                to_complete += 1
#                self.ui.date_livraison.setStyleSheet("#date_livraison { border: 3px solid red; }")
#            elif total > self.new_contract.qte_total:
#                to_complete += 1
#                self.ui.date_livraison.setStyleSheet("#date_livraison { border: 3px solid red; }")
#            else: 
#                self.ui.date_livraison.setStyleSheet("")
                
        if to_complete > 0:
            return False
        return True
    
        
        
            
            
            
    @QtCore.Slot(str)
    def saveLink(self, ctr_link):
        pass
#        self.new_contract.pdf_link = ctr_link
#        if self.creator_mode is True:
#            self.cDB.updateContract(self.new_contract)
##            self.resetPage()
#        else:
#            self.cDB.updateContract(self.new_contract)
#            self.parent().close()
#            self.s_contract_edited.emit()


    @QtCore.Slot()
    def resetPage(self):
        print "resetPage"
        self.blockSignals(True)
            
        items = (self.ui.formLayout.itemAt(i, QtGui.QFormLayout.FieldRole) for i in range(self.ui.formLayout.rowCount()) if self.ui.formLayout.itemAt(i, QtGui.QFormLayout.FieldRole) is not None) 
        for child in items:
            child = child.widget()
            if isinstance(child, QtGui.QLineEdit) or isinstance(child, QtGui.QPlainTextEdit) or isinstance(child, QtGui.QTextEdit):
                child.clear()
            elif isinstance(child, QtGui.QComboBox):
                self.updateComboBox(child)
        self.blockSignals(False)        


    @QtCore.Slot()
    def cancelContract(self):
        if self.creator_mode == True:
            message = "Êtes-vous sûr de vouloir annuler le contrat en cours ?"
            reply = QtGui.QMessageBox.question(self, 'Attention', message, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            
            if reply == QtGui.QMessageBox.Yes:
                self.cDB.cancelContract(self.new_contract)
                self.new_contract = None
                self.parent().parent().setCurrentIndex(0)
        else:
            message = "Annuler les modifications ?"
            reply = QtGui.QMessageBox.question(self, 'Attention', message, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            if reply == QtGui.QMessageBox.Yes:
                self.hide()
                self.closeWindow()
    
    
    def popupReinitialisation(self):
        msgBox = QtGui.QMessageBox()
        msgBox.setText("Avant de continuer : ")
        msgBox.setInformativeText("Souhaitez-vous initier un nouveau contrat ? ou modifier le courant ?")
        b_nouveau_ctr = msgBox.addButton(self.tr("Nouveau"), QtGui.QMessageBox.ActionRole)
        abortButton = msgBox.addButton(QtGui.QMessageBox.Abort)
        b_reinit_ctr = msgBox.addButton(self.tr("Réinitialiser"), QtGui.QMessageBox.ActionRole)
        
        msgBox.setDefaultButton(b_nouveau_ctr)
        
        msgBox.exec_()
        if msgBox.clickedButton() == abortButton:
            return 0
        elif msgBox.clickedButton() == b_reinit_ctr:
            return 1
        elif msgBox.clickedButton() == b_nouveau_ctr:
            return 2
    
    @QtCore.Slot()
    def openClientFile(self):
        client = self.oil_market.get_client(self.ui.cb_nom_acheteur.currentText(), is_fournisseur=False)

        if client is None:
            return
        
        client_file = client.sheet_path
        try:
            self.openWorkSheet(client_file[0], client_file[1])
        except:
            self.popupMessage("Fiche client introuvable...")
            
    
        
    @QtCore.Slot()
    def openFournissFile(self):
        fourniss = self.oil_market.get_client(self.ui.cb_nom_vendeur.currentText(), is_fournisseur=True)

        if fourniss is None:
            return
        
        fourniss_file = fourniss.sheet_path
        try:
            self.openWorkSheet(fourniss_file[0], fourniss_file[1])
        except:
            self.popupMessage("Fiche fournisseur introuvable...")
            
    
    def openWorkSheet(self, workbook_path, worksheet_name):
        if os.path.exists(workbook_path):
            xl = wc.Dispatch("Excel.Application")
            xl.Workbooks.Open(Filename=workbook_path, ReadOnly=1)
            xl.Worksheets(worksheet_name).Activate()
            xl.Visible = True
            del xl
        else:
            self.popupMessage("Worksheet introuvable...")
            
            
    def closeWindow(self):
        parent = self.parent()
        parent.close()
        
        
    def closeEvent(self, event):
        if self.creator_mode is False and self.new_contract is not None:
            message = "Annuler les modifications ?"
            reply = QtGui.QMessageBox.question(self, 'Attention', message, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            if reply == QtGui.QMessageBox.Yes:
                self.new_contract = None
                self.s_close_widget.emit()
                event.ignore()
            else:
                event.ignore()
        else:
            if self.parent().isVisible():
                self.s_close_widget.emit()
            event.accept()
                

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_Return or e.key() == QtCore.Qt.Key_Enter:
            self.validateContract()
    
    def popupMessage(self, message, is_question = False):
        msgBox = QtGui.QMessageBox()
        msgBox.setText(message)
        msgBox.setWindowTitle('Problème')
        if is_question:
            msgBox.setWindowTitle('Question')
            msgBox.setStandardButtons(QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)       
            msgBox.button(QtGui.QDialogButtonBox.Ok).setText("Valider")
            msgBox.button(QtGui.QDialogButtonBox.Cancel).setText("Annuler")
            msgBox.setDefaultButton(QtGui.QMessageBox.Ok)
        return msgBox.exec_()
        
    def main(self):
        self.show()
Esempio n. 2
0
class ContractIniter(QtGui.QMainWindow, QtCore.QObject):

    s_go_accueil = QtCore.Signal()
    enter_key_pressed = QtCore.Signal()

    def __init__(self, parent=None):
        super(ContractIniter, self).__init__(parent)
        self.ui = Ui_ContractIniter()
        self.ui.setupUi(self)

        scrollArea = QtGui.QScrollArea()
        scrollArea.setWidgetResizable(True)
        self.contractEditor = ContractEditor(scrollArea)
        self.contractEditor.initEditor()

        self.ui.tab_main.addTab(self.contractEditor, "Nouveau contrat")
        self.ui.tab_main.widget(1).setSizePolicy(
            QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Preferred)
        self.setWindowTitle("Créateur de contrat")

        self.oil_market = Market()
        self.cDB = ContractsDatabase()

        self.usine_selected = None
        self.m_completer = QtGui.QCompleter(
            self.oil_market.marchandises_list['fr'])
        self.m_completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.m_completer.setCompletionMode(
            QtGui.QCompleter.UnfilteredPopupCompletion)
        self.ui.produit.setCompleter(self.m_completer)

        self.ui.tab_main.setCurrentIndex(0)

        self.contractEditor.s_contract_validated.connect(self.close)
        self.contractEditor.s_close_widget.connect(self.close)
        self.connectionsManager(disconnect=False)

        self.ui.rb_fournisseur.setChecked(True)
#        self.resetPage()

    def connectionsManager(self, disconnect=False):
        if disconnect == False:
            connector = QtCore.QObject.connect
        else:
            connector = QtCore.QObject.disconnect

        connector(self.ui.rb_acheteur, QtCore.SIGNAL('toggled(bool)'),
                  self.resetResult)
        self.ui.produit.textEdited.connect(self.productNameEdited)
        #        connector(self.ui.produit, QtCore.SIGNAL ('textEdited(QString)'), self.productNameEdited)
        connector(self.ui.cb_classifier,
                  QtCore.SIGNAL('currentIndexChanged(int)'),
                  self.resultClassifier)
        connector(self.ui.b_rechercher, QtCore.SIGNAL('clicked()'),
                  self.launchSimulation)
        connector(self.ui.b_next, QtCore.SIGNAL('clicked()'),
                  self.validateSimulation)
        connector(self.ui.b_reset_simul, QtCore.SIGNAL('clicked()'),
                  self.resetPage)

    @QtCore.Slot(str)
    def productNameEdited(self, text):
        print "productNameEdited"
        self.resetResult()

    @QtCore.Slot()
    def launchSimulation(self):
        condition = 2
        if not (self.ui.rb_acheteur.isChecked()
                or self.ui.rb_fournisseur.isChecked()):
            self.ui.gb_type.setStyleSheet(
                "#gb_type { border: 3px solid red; }")
            condition = condition - 1
        else:
            self.ui.gb_type.setStyleSheet("")

        if len(self.ui.produit.text()) < 1:
            self.ui.produit.setStyleSheet(
                "#produit { border: 3px solid red; }")
            condition = condition - 1
        else:
            self.ui.produit.setStyleSheet("")

        if condition < 2:
            return

        self.freeLayout(self.ui.result_layout)
        clients = self.oil_market.get_clients_from_marchandise(
            self.ui.produit.text(),
            is_fournisseur=self.ui.rb_fournisseur.isChecked(),
            enlarge=self.ui.cb_enlarge.isChecked())
        #        print clients
        clients = self.ordonnateResult(clients)

        if len(clients) > 0:
            for c in clients:
                u = UsineLabel(self.ui.result_layout, c)
                self.ui.result_layout.addWidget(u)
                QtCore.QObject.connect(u, QtCore.SIGNAL('s_usine_selected()'),
                                       self.simulResultSelected)
        else:
            self.ui.result_layout.addWidget(
                QtGui.QLineEdit(
                    "Aucun client trouve.\n Verifiez la marchandise demandee et/ou la base de donnees."
                ))

    @QtCore.Slot(str)
    @QtCore.Slot(bool)
    def resetResult(self, text=None):
        self.freeLayout(self.ui.result_layout)
        self.repaint()

    @QtCore.Slot(int)
    def resultClassifier(self, index):
        sender = self.sender()
        if str(sender.currentText()).lower() == "conteneur":
            print(str(sender.currentText()))

    @QtCore.Slot()
    def simulResultSelected(self):
        print "simulResultSelected"

        #catch sender
        sender = self.sender()
        self.usine_selected = (sender.usine, self.ui.rb_acheteur.isChecked())
        # update visually labels
        clients_label_list = self.ui.gb_result.findChildren(UsineLabel)
        for child in clients_label_list:
            if child is not sender:
                child.unselected()
            else:
                child.selected()
        self.ui.b_next.setEnabled(True)

    @QtCore.Slot()
    def validateSimulation(self):
        if self.usine_selected is None:
            self.ui.gb_result.setStyleSheet(
                "#gb_result { border: 3px solid red; }")
            return
        else:
            self.ui.gb_result.setStyleSheet("")

        if self.contractEditor.new_contract is not None:
            if self.cDB.isCtrLocked(self.contractEditor.new_contract) is False:
                res = self.popupValidation()
                if res == 0:
                    return
                elif res == 1:
                    new_contract = self.contractEditor.new_contract
                elif res == 2:
                    new_contract = self.cDB.newContract()
            else:
                new_contract = self.contractEditor.new_contract
        else:
            new_contract = self.cDB.newContract()

        if self.usine_selected[1] == 0:  #usine vendeur
            new_contract.usine_vendeur = self.usine_selected[0]
        else:
            new_contract.usine_acheteur = self.usine_selected[0]
        new_contract.marchandise = self.ui.produit.text()

        self.contractEditor.initEditor(new_contract)
        self.ui.tab_main.setCurrentIndex(1)

    @QtCore.Slot()
    def resetPage(self):
        self.connectionsManager(disconnect=True)
        self.ui.b_next.setEnabled(False)
        self.ui.produit.clear()
        self.freeLayout(self.ui.result_layout)
        self.usine_selected = None
        #        self.initSimulation()
        self.connectionsManager(disconnect=False)

    @QtCore.Slot()
    def goBack(self):
        self.s_go_accueil.emit()

    def popupValidation(self):
        msgBox = QtGui.QMessageBox()
        msgBox.setText("Avant de continuer : ")
        msgBox.setInformativeText(
            "Souhaitez-vous initier un nouveau contrat ? ou modifier le courant ?"
        )
        b_nouveau_ctr = msgBox.addButton(self.tr("Nouveau"),
                                         QtGui.QMessageBox.ActionRole)
        b_cancel = msgBox.addButton(self.tr("Annuler"),
                                    QtGui.QMessageBox.ActionRole)
        b_maj_ctr = msgBox.addButton(self.tr("Modifier"),
                                     QtGui.QMessageBox.ActionRole)

        msgBox.setDefaultButton(b_nouveau_ctr)

        msgBox.exec_()
        if msgBox.clickedButton() == b_cancel:
            return 0
        elif msgBox.clickedButton() == b_maj_ctr:
            return 1
        elif msgBox.clickedButton() == b_nouveau_ctr:
            return 2

    def ordonnateResult(self, client_list):
        if str(self.ui.cb_classifier.currentText()).lower() == "pays":
            return sorted(client_list, key=lambda p: p.country_code)
        elif str(self.ui.cb_classifier.currentText()).lower() == "conteneur":
            pass
        return client_list

    def freeLayout(self, layout):
        for i in reversed(range(layout.count())):
            widgetToRemove = layout.itemAt(i).widget()
            layout.removeWidget(widgetToRemove)
            widgetToRemove.setParent(None)

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_Return or e.key() == QtCore.Qt.Key_Enter:
            self.launchSimulation()

    def closeEvent(self, event):

        #        self.contractEditor.blockSignals(True)
        current_contract = self.contractEditor.new_contract

        #        print "initer asked to close... ctr is ", current_contract
        #        if current_contract is not None:
        #            ctr = self.cDB.getContractsByNum(current_contract.n_contrat, True)
        #            if ctr is None:
        #                self.cDB.cancelContract(current_contract)

        if current_contract is not None:  # and self.cDB.isCtrLocked(current_contract):
            message = "Êtes-vous sûr de vouloir annuler le contrat en cours d'édition ?"

            reply = QtGui.QMessageBox.question(self, 'Attention', message,
                                               QtGui.QMessageBox.Yes,
                                               QtGui.QMessageBox.No)
            if reply == QtGui.QMessageBox.Yes:
                self.cDB.cancelContract(current_contract)
                #                self.s_close_widget.emit()
                event.accept()  # let the window close
            else:
                event.ignore()
#        else:
#            self.s_close_widget.emit()
#        self.contractEditor.blockSignals(False)

        print "tout doit se fermer"
#        self.contractEditor.close()

#    def showEvent(self):
#        print self.size()

    def closeWindow(self):
        #        self.contractEditor.close()
        self.close()

    def main(self):
        self.setWindowIcon(QtGui.QIcon('icone.png'))
        self.setWindowTitle('Gestionnaire de clients')
        self.show()