Exemplo 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()
Exemplo n.º 2
0
class DeliveryManager(QtGui.QMainWindow, QtCore.QObject):
    def __init__(self, parent=None):
        super(DeliveryManager, self).__init__(parent)
        self.ui = Ui_delivery_manager()
        self.ui.setupUi(self)

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

        self.ui.t_deliver_list.deleteLater()
        self.t_deliver_list = MyTreeWidget(self)
        self.t_deliver_list.setAlternatingRowColors(True)
        #        self.ui.t_ctr_list.header().setDefaultAlignment(QtCore.Qt.AlignCenter)
        self.t_deliver_list.setIndentation(0)
        self.t_deliver_list.s_dropped_contract.connect(
            self.loadDeliveriesFromContract)
        self.t_deliver_list.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.t_deliver_list.customContextMenuRequested.connect(
            self.customContextMenu)
        self.t_deliver_list.header().setStretchLastSection(True)
        #        self.t_deliver_list.header().setResizeMode(QtGui.QHeaderView.Interactive)
        self.t_deliver_list.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
        self.ui.horizontalLayout.addWidget(self.t_deliver_list)
        self.ui.t_deliv_tot.setIndentation(0)

        self.ui.l_ref_client.installEventFilter(self)
        self.ui.l_ref_fourniss.installEventFilter(self)
        self.ui.l_ref_charg.installEventFilter(self)
        self.ui.l_ref_client.returnPressed.connect(self.researchDelivery)
        self.ui.l_ref_fourniss.returnPressed.connect(self.researchDelivery)
        self.ui.l_ref_charg.returnPressed.connect(self.researchDelivery)
        self.ui.b_rechercher.clicked.connect(self.researchDelivery)
        self.ui.b_rechercher.setEnabled(False)

        self.popMenu = QtGui.QMenu(self)
        self.actionSetConfirm_dlv = QtGui.QAction(
            "Confirmer/infirmer la livraison", self)
        self.actionSetConfirm_dlv.triggered.connect(
            self.setConfirmationLivraison)
        self.actionSetPaied = QtGui.QAction("Confirmer/infirmer le paiement",
                                            self)
        self.actionSetPaied.triggered.connect(self.setPaiment)
        self.actionModifyDeliv = QtGui.QAction("Modifier la livraison", self)
        self.actionModifyDeliv.triggered.connect(self.modifyDelivery)
        self.actionRemove = QtGui.QAction("Supprimer la livraison", self)
        self.actionRemove.triggered.connect(self.removeDelivery)
        self.actionImport = QtGui.QAction(
            "Importer des livraisons depuis Execution.xlsx", self)
        self.actionImport.triggered.connect(self.importDeliveries)

        self.popMenu.addAction(self.actionSetConfirm_dlv)
        self.popMenu.addAction(self.actionSetPaied)
        self.popMenu.addSeparator()
        self.popMenu.addAction(self.actionModifyDeliv)
        self.popMenu.addSeparator()
        self.popMenu.addAction(self.actionRemove)
        self.popMenu.addSeparator()
        self.popMenu.addAction(self.actionImport)

        self.popMenu2 = QtGui.QMenu(self)
        self.actionImport2 = QtGui.QAction("Importer depuis Execution.xlsx",
                                           self)
        self.actionImport2.triggered.connect(self.importDeliveries)
        self.popMenu2.addAction(self.actionImport)

        self.ui.cb_marchandise.view().setAlternatingRowColors(True)
        self.ui.cb_sort_client.view().setAlternatingRowColors(True)
        self.ui.cb_sort_fourniss_2.view().setAlternatingRowColors(True)

        self.ui.rb_date_appel.setChecked(True)
        self.initMarchandiseList()
        self.initOrdererClient()
        self.initOrdererFourniss()
        self.initOrdererDate()
        self.initDelivList()

        self.t_deliver_list.itemSelectionChanged.connect(self.itemSelected)
        self.ui.cb_year.currentIndexChanged.connect(self.updateDelivList)
        self.ui.rb_date_appel.toggled.connect(self.updateDelivList)

        self.ui.cb_month.currentIndexChanged.connect(self.updateDelivList)
        self.ui.cb_sort_client.currentIndexChanged.connect(
            self.updateDelivList)
        self.ui.cb_sort_fourniss_2.currentIndexChanged.connect(
            self.updateDelivList)
        self.ui.cb_marchandise.currentIndexChanged.connect(
            self.updateDelivList)
        self.ui.b_reinit_list.clicked.connect(self.reinitSorters)
        self.comm.s_cDB_updated.connect(self.updateSorters)

    def eventFilter(self, obj, event):
        try:
            if event.type() == QtCore.QEvent.MouseButtonRelease:
                if obj == self.ui.l_ref_charg or obj == self.ui.l_ref_client or obj == self.ui.l_ref_fourniss:
                    self.specifyResearch(obj)
                    return True
        except:
            pass
        return False

    @QtCore.Slot()
    def itemSelected(self):
        #        modifiers = QtGui.QApplication.keyboardModifiers()
        #        if modifiers == QtCore.Qt.ControlModifier:
        #            self.t_deliver_list.setSelectionMode( QtGui.QAbstractItemView.MultiSelection )
        #        else:
        #            self.t_deliver_list.setSelectionMode( QtGui.QAbstractItemView.SingleSelection )
        pass

    def customContextMenu(self, pos):
        if self.getSelectedDelivery() is None:
            self.popMenu2.exec_(self.t_deliver_list.mapToGlobal(pos))
        else:
            self.popMenu.exec_(self.t_deliver_list.mapToGlobal(pos))

    def initMarchandiseList(self):
        self.ui.cb_marchandise.blockSignals(True)
        marchandise_list = self.oil_market.marchandises_list['fr']
        ordered_marchandise_list = sorted(marchandise_list)
        zipped = list(enumerate(ordered_marchandise_list))

        self.ui.cb_marchandise.clear()
        self.ui.cb_marchandise.addItem("- Toutes -", userData=None)

        for index, m in zipped:
            self.ui.cb_marchandise.addItem(m, index)

        self.ui.cb_marchandise.setCurrentIndex(0)
        self.ui.cb_marchandise.blockSignals(False)

    def initDelivList(self):
        font = self.t_deliver_list.header().font()
        font.setPointSize(10)

        col1 = "Date d'appel".decode('utf-8').strip()
        col2 = "Client".decode('utf-8').strip()
        col3 = "Fournisseur".decode('utf-8').strip()
        col4 = "Départ".decode('utf-8').strip()
        col5 = "Ville".decode('utf-8').strip()
        col6 = "Date de charg/livr".decode('utf-8').strip()
        col7 = "Heure".decode('utf-8').strip()
        col8 = "Quantité".decode('utf-8').strip()
        col9 = "Marchandise".decode('utf-8').strip()
        col10 = "Ctr Giraud".decode('utf-8').strip()
        col11 = "Ctr fournisseur".decode('utf-8').strip()
        col12 = "Réf. client".decode('utf-8').strip()
        col13 = "Réf. chargement".decode('utf-8').strip()
        col14 = "Statut".decode('utf-8').strip()
        headers = [
            col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11,
            col12, col13, col14
        ]
        self.t_deliver_list.setHeaderLabels(headers)
        self.t_deliver_list.setSortingEnabled(True)
        self.t_deliver_list.header().setFont(font)
        for i in range(0, len(headers), 1):
            self.t_deliver_list.headerItem().setTextAlignment(
                i, QtCore.Qt.AlignCenter)

        col1 = "Qte totale (T)".decode('utf-8').strip()
        col2 = "Qte à livrer (T)".decode('utf-8').strip()
        headers = [col1, col2]
        self.ui.t_deliv_tot.setHeaderLabels(headers)
        self.ui.t_deliv_tot.setSortingEnabled(True)
        self.ui.t_deliv_tot.header().setFont(font)
        width = self.ui.t_deliv_tot.parent().sizeHint().width()
        for i in range(0, len(headers), 1):
            self.ui.t_deliv_tot.headerItem().setTextAlignment(
                i, QtCore.Qt.AlignCenter)
            self.ui.t_deliv_tot.header().resizeSection(i, width / 3)
        self.ui.t_deliv_tot.header().setStretchLastSection(True)

        self.updateDelivList()
        self.t_deliver_list.header().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)
        self.t_deliver_list.header().setResizeMode(
            QtGui.QHeaderView.Interactive)

    def setConfirmationLivraison(self):
        livr_selected = self.getSelectedDelivery()
        if livr_selected is None:
            return
        error_occured = 0
        ctr = self.cDB.getContractByNum(livr_selected.n_ctr)
        res = Question.changeState(whatIsIt="À propos de la livraison :",
                                   button_1="Confimer",
                                   button_2="Déconfirmer")
        res = ctr.confirmDelivery(livr_selected, res)
        if res is None or res == 0:
            if self.cDB.updateContract(ctr) < 0:
                ctr.confirmDelivery(livr_selected, not res)
                error_occured += 1
        else:
            error_occured += 1

        if error_occured > 0:
            Question.warn(
                whatIsIt=
                "Erreur lors de l'édition de Execution \nVeuillez reessayer ultérieurement..."
            )

    def setPaiment(self):
        livr_selected = self.getSelectedDelivery()
        if livr_selected is None:
            return

        error_occured = 0
        ctr = self.cDB.getContractByNum(livr_selected.n_ctr)
        res = Question.confirmPaiment(whatIsIt="À propos du paiement :",
                                      button_1="Confimer",
                                      button_2="Déconfirmer")
        res = ctr.validatePaiment(livr_selected, res)
        if res is None or res == 0:
            if self.cDB.updateContract(ctr) < 0:
                ctr.validatePaiment(livr_selected, res)
                error_occured += 1
        else:
            error_occured += 1

        if error_occured > 0:
            Question.warn(
                whatIsIt=
                "Erreur lors de l'édition de Execution \nVeuillez reessayer ultérieurement..."
            )

    def addDelivery(self, ctr):
        if ctr is None:
            return
        error_occured = 0
        dic = deliveryEditor.commandDelivery(self, ctr)
        if dic is not None:
            res, newDeliv = ctr.newDelivery(dic)
            if res == 0:  # tout va bien
                if self.cDB.updateContract(ctr) < 0:
                    error_occured += 1
            else:
                error_occured += 1

        if error_occured > 0:
            Question.warn(
                whatIsIt=
                "Erreur lors de l'édition de Execution \nVeuillez reessayer ultérieurement..."
            )
            self.modifyDelivery(newDeliv)

    def modifyDelivery(self, dlv=None):
        checkDlvNumber = False
        if dlv is None:
            dlv = self.getSelectedDelivery()
        else:
            checkDlvNumber = True

        if dlv is None:
            return

        ctr = self.cDB.getContractByNum(dlv.n_ctr)
        if checkDlvNumber:
            dlv = ctr.checkKey(dlv)

        error_occured = 0
        dlv = deliveryEditor.updateDelivery(self, ctr, dlv)
        if dlv is not None:
            res = ctr.updateDelivery(dlv)
            if res is None:
                if self.cDB.updateContract(ctr, wait=True) < 0:
                    error_occured += 1
            else:
                error_occured += 1

        if error_occured > 0:
            Question.warn(
                whatIsIt=
                "Erreur lors de l'édition de Execution \nVeuillez reessayer ultérieurement..."
            )
            self.modifyDelivery(dlv)

    @QtCore.Slot()
    def removeDelivery(self):
        livr_selected = self.getSelectedDelivery()
        if livr_selected is None:
            return
        ctr = self.cDB.getContractsByNum(livr_selected.n_ctr, NUM_CTR)[0]
        message = "Êtes-vous sûr de vouloir supprimer définitivement cette livraison ?"
        reply = QtGui.QMessageBox.question(self, 'Attention', message,
                                           QtGui.QMessageBox.Yes,
                                           QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            res = ctr.removeDelivery(livr_selected)
            if res is None or res == 0:
                self.cDB.updateContract(ctr)
            else:
                Question.warn(
                    whatIsIt=
                    "Veuillez reessayer ultérieurement...\nErreur lors de l'édition de Execution.xlsx."
                )

#    from classes import Livraison

    @QtCore.Slot()
    def importDeliveries(self):
        progressDialog = QtGui.QProgressDialog()
        progressDialog.setAutoClose(False)
        progressDialog.setAutoReset(False)
        label = progressDialog.findChildren(QtGui.QLabel)[0]
        label.setFont(QtGui.QFont("Calibri", 12))
        button = progressDialog.findChildren(QtGui.QPushButton)[0]
        button.hide()
        progressBar = progressDialog.findChildren(QtGui.QProgressBar)[0]
        progressBar.hide()
        progressDialog.setWindowTitle(u"Travail en cours...")
        text = u"\n\nImport des livraisons à partir de Execution.xlsx"
        progressDialog.setLabelText(text)
        progressDialog.show()
        QtGui.QApplication.processEvents()

        if ReverseExecutionParser() < 0:
            Question.warn(
                whatIsIt=
                "Veuillez reessayer ultérieurement...\nErreur lors de l'édition de Execution.xlsx."
            )

        progressDialog.close()
        QtGui.QApplication.processEvents()

    def getSelectedDelivery(self):
        items_selected = self.t_deliver_list.selectedItems()
        if len(items_selected) < 1:
            #            self.setButtonEnabled(False)
            return None
        return items_selected[0].livr

    def updateSorters(self):
        self.initOrdererDate()
        self.updateDelivList()

    def reinitSorters(self):
        self.ui.cb_sort_client.blockSignals(True)
        self.ui.cb_sort_fourniss_2.blockSignals(True)
        self.ui.cb_marchandise.blockSignals(True)
        self.ui.cb_month.blockSignals(True)
        self.ui.cb_year.blockSignals(True)
        self.ui.cb_sort_client.setCurrentIndex(0)
        self.ui.cb_sort_fourniss_2.setCurrentIndex(0)
        self.ui.cb_marchandise.setCurrentIndex(0)
        self.ui.cb_month.setCurrentIndex(0)
        self.ui.cb_year.setCurrentIndex(0)
        self.ui.cb_sort_client.blockSignals(False)
        self.ui.cb_sort_fourniss_2.blockSignals(False)
        self.ui.cb_marchandise.blockSignals(False)
        self.ui.cb_month.blockSignals(False)
        self.ui.cb_year.blockSignals(False)
        self.updateDelivList()

    def initOrdererDate(self):
        try:
            sender = self.sender()
            print "initOrdererDate from " + sender.objectName()
        except:
            curframe = inspect.currentframe()
            calframe = inspect.getouterframes(curframe, 2)
            print "initOrdererDate called by ", calframe[1][3]

        self.ui.cb_month.blockSignals(True)
        self.ui.cb_year.blockSignals(True)
        month_names = [
            "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet",
            "Août", "Septembre", "Octobre", "Novembre", "Décembre"
        ]
        month_values = [
            "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "12"
        ]
        self.ui.cb_month.clear()
        self.ui.cb_month.addItem("Mois", userData=None)
        for n, v in zip(month_names, month_values):
            self.ui.cb_month.addItem(n, userData=v)
        self.ui.cb_month.setCurrentIndex(0)

        year_max = 0
        for ctr in self.cDB.getEveryContracts():
            if ctr is None: continue
            for livr in ctr.getDeliveries():
                d = livr.date_charg_livr
                if int(d.split('/')[-1]) > year_max:
                    year_max = int(d.split('/')[-1])
        year_now = datetime.datetime.now().year
        self.ui.cb_year.clear()
        self.ui.cb_year.addItem("Année", userData=None)
        for y in range(year_now, year_max + 1, 1):
            self.ui.cb_year.addItem(str(y), userData=str(y))

        index = self.ui.cb_year.findText(str(year_now))
        if index < 0: index = 0
        self.ui.cb_year.setCurrentIndex(index)

        self.ui.cb_month.blockSignals(False)
        self.ui.cb_year.blockSignals(False)
        print "end of initOrdererDate"

    def initOrdererClient(self):
        self.ui.cb_sort_client.blockSignals(True)
        self.ui.cb_sort_client.clear()
        self.ui.cb_sort_client.addItem("- Tous -", userData=None)
        client_list = self.oil_market.get_client(is_fournisseur=False)
        client_names = list(c.short_name.encode('utf-8') for c in client_list)

        zipped = zip(client_names, client_list)
        ordered_client_list = sorted(zipped, key=lambda client: client[0])
        for n, c in ordered_client_list:
            self.ui.cb_sort_client.addItem(n, c)

        self.ui.cb_sort_client.setCurrentIndex(0)
        self.ui.cb_sort_client.blockSignals(False)

    def initOrdererFourniss(self):
        self.ui.cb_sort_fourniss_2.blockSignals(True)
        self.ui.cb_sort_fourniss_2.clear()
        self.ui.cb_sort_fourniss_2.addItem("- Tous -", userData=None)
        fourniss_list = self.oil_market.get_client(is_fournisseur=True)
        fourniss_names = list(
            f.short_name.encode('utf-8') for f in fourniss_list)

        zipped = zip(fourniss_names, fourniss_list)
        ordered_fourniss_list = sorted(zipped,
                                       key=lambda fourniss: fourniss[0])
        for n, f in ordered_fourniss_list:
            self.ui.cb_sort_fourniss_2.addItem(n, f)

        self.ui.cb_sort_fourniss_2.setCurrentIndex(0)
        self.ui.cb_sort_fourniss_2.blockSignals(False)

    def specifyResearch(self, sender):
        if "client" in sender.objectName():
            self.ui.rb_ref_client.setChecked(True)
        elif "fourniss" in sender.objectName():
            self.ui.rb_ref_fourniss.setChecked(True)
        elif "charg" in sender.objectName():
            self.ui.rb_ref_charg.setChecked(True)
        elif "march" in sender.objectName():
            self.ui.rb_marchandise.setChecked(True)
        self.ui.b_rechercher.setEnabled(True)

    @QtCore.Slot()
    def researchDelivery(self):
        type_num = None
        if self.ui.rb_ref_client.isChecked():
            num = str(self.ui.l_ref_client.text())
            type_num = NUM_DLV_C
        elif self.ui.rb_ref_fourniss.isChecked():
            num = str(self.ui.l_ref_fourniss.text())
            type_num = NUM_DLV_F
        elif self.ui.rb_ref_charg.isChecked():
            num = str(self.ui.l_ref_charg.text())
            type_num = NUM_DLV_CH

        if type_num is not None and len(num) > 0:
            deliv_list = self.cDB.getDeliveryByNum(num.rstrip(), type_num)
            self.updateDelivList(deliv_list)
        else:
            self.updateDelivList()

    def sortDeliveryList(self, index=None):
        print "sortDeliveryList"

        year = self.ui.cb_year.itemData(self.ui.cb_year.currentIndex())
        month = self.ui.cb_month.itemData(self.ui.cb_month.currentIndex())
        client = self.ui.cb_sort_client.itemData(
            self.ui.cb_sort_client.currentIndex())
        fourniss = self.ui.cb_sort_fourniss_2.itemData(
            self.ui.cb_sort_fourniss_2.currentIndex())
        if self.ui.cb_marchandise.currentIndex() <= 0:
            marchandise = None
        else:
            marchandise = self.ui.cb_marchandise.itemText(
                self.ui.cb_marchandise.currentIndex())
            marchandise = self.oil_market.get_code_from_name(marchandise)

        deliv_list = self.cDB.getDeliveries(
            by_month=month,
            by_year=year,
            is_appel_date=self.ui.rb_date_appel.isChecked(),
            by_client=client,
            by_fourniss=fourniss,
            by_marchandise=marchandise)
        return deliv_list

    def updateDelivList(self, deliv_list=None):

        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 1)
        print "updateDelivList called by ", calframe[1][3]

        self.t_deliver_list.clear()
        if deliv_list is None or isinstance(deliv_list, list) == False:
            deliv_list = self.sortDeliveryList()

        if deliv_list is None:
            return

        font = ImageFont.truetype('times.ttf', 12)
        itemlist = []
        for deliv in deliv_list:
            if deliv is None:
                itemlist = [
                    ' - ', ' - ', ' - ', ' - ', ' - ', ' - ', ' - ', ' - ',
                    ' - ', ' - ', ' - ', ' - ', ' - '
                ]
            else:

                ctr = self.cDB.getContractByNum(deliv.n_ctr)
                if ctr.is_franco: depart = "Franco"
                else: depart = "Départ"
                state = "En attente"
                if deliv.is_confirmed: state = "Confirmé"
                if deliv.is_paid: state = "Payé"
                if self.oil_market.marchandiseExist(ctr.marchandise):
                    full_marchandise = self.oil_market.getMarchandiseFullName(
                        ctr.marchandise)
                    string = ""
                    current_size = 0
                    for word in full_marchandise.split(' '):
                        current_size += font.getsize(word)[0]
                        if current_size > 80:
                            string += "<br/>"
                            current_size = 0
                        string += word + ' '
                    full_marchandise = string
                else:
                    full_marchandise = ""

                nom_client = ctr.getClientName(shortest=True).upper(
                ) + "<br/>" + "<i>" + ctr.get_uVilleAcheteur() + "</i>"
                nom_fourniss = ctr.getFournissName(shortest=True).upper(
                ) + "<br/>" + "<i>" + ctr.get_uVilleVendeur() + "</i>"

                itemlist = [
                    deliv.date_appel, nom_client, nom_fourniss, depart,
                    deliv.ville, deliv.date_charg_livr,
                    deliv.horaire_charg_livr,
                    format_num(deliv.quantite), full_marchandise, deliv.n_ctr,
                    deliv.ref_fourniss, deliv.ref_client, deliv.ref_chargement,
                    state
                ]

            blankItemlist = list(
                re.sub(r"<[^>]*>", r'', s.replace("<br/>", '\n'))
                for s in itemlist)
            newline = TreeWidgetDelivery(self.t_deliver_list, deliv,
                                         blankItemlist)

            for i in range(0, len(itemlist)):
                item = itemlist[i]
                self.t_deliver_list.setItemWidget(
                    newline, i, TreeWidgetItemLabel(self, item))

        self.t_deliver_list.header().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)
        self.t_deliver_list.header().setResizeMode(
            QtGui.QHeaderView.Interactive)
        self.t_deliver_list.setAutoFillBackground(False)
        for i in range(0, len(itemlist), 1):
            self.t_deliver_list.resizeColumnToContents(i)


#        self.t_deliver_list.header().setResizeMode(self.t_deliver_list.columnCount()-3, QtGui.QHeaderView.Stretch)
        self.updateTotal(deliv_list)

    def updateTotal(self, deliv_list):
        qte_totale = 0.0

        self.ui.t_deliv_tot.clear()
        for deliv in deliv_list:
            qte_totale += float(format_num(deliv.quantite))

        qte_a_livrer = qte_totale
        for deliv in deliv_list:
            if deliv.is_confirmed:
                qte_a_livrer -= float(format_num(deliv.quantite))

        newLine = QtGui.QTreeWidgetItem(self.ui.t_deliv_tot, [""] * 2)
        self.ui.t_deliv_tot.setItemWidget(
            newLine, 0, TreeWidgetItemLabel(self, str(qte_totale)))
        self.ui.t_deliv_tot.setItemWidget(
            newLine, 1, TreeWidgetItemLabel(self, str(qte_a_livrer)))

        height = self.ui.t_deliv_tot.visualItemRect(newLine).height()
        width = self.ui.t_deliv_tot.parent().sizeHint().width()
        self.ui.t_deliv_tot.setFixedHeight(height * 2)
        self.ui.t_deliv_tot.header().resizeSection(0, width / 3)
        self.ui.t_deliv_tot.header().resizeSection(1, width / 3)

    @QtCore.Slot(str)
    def loadDeliveriesFromContract(self, ctr):
        ctr = self.cDB.getContractsByNum(ctr, NUM_CTR)[0]
        #        dlv = Contract.livraisons
        dlv_list = list(l for n, l in ctr.livraisons.items())
        self.updateDelivList(dlv_list)

    def main(self):
        self.show()