Ejemplo n.º 1
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()
Ejemplo n.º 2
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()
Ejemplo n.º 3
0
class ContractsManager(QtGui.QMainWindow, QtCore.QObject):

    s_addDelivery = QtCore.Signal(object)

    def __init__(self, parent=None):
        super(ContractsManager, self).__init__(parent)
        self.ui = Ui_ContractsManager()
        self.ui.setupUi(self)

        #        self.widget = QtUiTools.QUiLoader().load("../interface_GC/accueil.ui")
        #        self.ui = self.widget()

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

        self.ui.t_ctr_list.deleteLater()
        self.t_ctr_list = MyTreeWidget(self)
        self.t_ctr_list.setObjectName("t_ctr_list")
        self.ui.horizontalLayout.addWidget(self.t_ctr_list)
        self.t_ctr_list.itemSelectionChanged.connect(self.itemSelected)
        self.t_ctr_list.customContextMenuRequested.connect(
            self.customContextMenu)
        self.t_ctr_list.s_dropped_delivery.connect(
            self.loadContractFromDeliveries)
        self.ui.t_ctr_total.setIndentation(0)
        self.initOrdererMarchandise()

        self.ui.cb_marchandise.view().setAlternatingRowColors(True)
        self.ui.cb_sort_client_2.view().setAlternatingRowColors(True)
        self.ui.cb_sort_fourniss.view().setAlternatingRowColors(True)

        self.printer = PDFCreator(self)
        self.printer.setAttribute(QtCore.Qt.WA_StyledBackground)

        self.popMenu = QtGui.QMenu(self)
        self.actionPDF = QtGui.QAction("Voir le contrat PDF", self)
        self.actionPDF.triggered.connect(self.openPdfContract)
        self.actionAddNumberC = QtGui.QAction("Ajouter numero client", self)
        self.actionAddNumberC.triggered.connect(self.setClientNumber)
        self.actionAddNumberF = QtGui.QAction("Ajouter numero fournisseur",
                                              self)
        self.actionAddNumberF.triggered.connect(self.setFournissNumber)
        self.actionAddDelivery = QtGui.QAction("Nouvelle livraison", self)
        self.actionAddDelivery.triggered.connect(self.addDelivery)
        self.actionRemoveCtr = QtGui.QAction("Supprimer le contrat", self)
        self.actionRemoveCtr.triggered.connect(self.removeContract)
        self.actionModifyCtr = QtGui.QAction("Voir/modifier le contrat", self)
        self.actionModifyCtr.triggered.connect(self.modifyContract)
        self.actionAccessToClient = QtGui.QAction("Fiche client", self)
        self.actionAccessToClient.triggered.connect(self.openClientFile)
        self.actionAccessToFournis = QtGui.QAction("Fiche fournisseur", self)
        self.actionAccessToFournis.triggered.connect(self.openFournisFile)
        self.actionPrint = QtGui.QAction("Créer le contrat PDF", self)
        self.actionPrint.triggered.connect(self.printContract)
        self.actionNotes = QtGui.QAction("Notes du contrat", self)
        self.actionNotes.triggered.connect(self.showCtrNotes)

        self.popMenu.addAction(self.actionAddDelivery)
        self.popMenu.addSeparator()
        self.popMenu.addAction(self.actionPDF)
        self.popMenu.addAction(self.actionPrint)
        self.popMenu.addAction(self.actionModifyCtr)
        self.popMenu.addAction(self.actionNotes)
        self.popMenu.addSeparator()
        self.popMenu.addAction(self.actionAccessToClient)
        self.popMenu.addAction(self.actionAccessToFournis)
        self.popMenu.addSeparator()
        self.popMenu.addAction(self.actionAddNumberC)
        self.popMenu.addAction(self.actionAddNumberF)
        self.popMenu.addSeparator()
        self.popMenu.addAction(self.actionRemoveCtr)

        self.initCtrList()
        self.initOrdererClient()
        self.initOrdererFourniss()
        self.updateOrdererYear()

        self.ui.cb_marchandise.currentIndexChanged.connect(self.updateCtrList)
        self.ui.cb_sort_year.currentIndexChanged.connect(self.updateCtrList)
        self.ui.cb_sort_client_2.currentIndexChanged.connect(
            self.updateCtrList)
        self.ui.cb_sort_fourniss.currentIndexChanged.connect(
            self.updateCtrList)

        #        self.comm.s_cDB_updated.connect(self.updateCtrList)
        self.comm.s_cDB_updated.connect(self.updateOrdererYear)
        self.ui.b_reinit_list.clicked.connect(self.reinitSorters)

        self.ui.l_n_client.installEventFilter(self)
        self.ui.l_n_ctr.installEventFilter(self)
        self.ui.l_n_fourniss.installEventFilter(self)
        self.ui.l_n_ctr.returnPressed.connect(self.researchContract)
        self.ui.l_n_client.returnPressed.connect(self.researchContract)
        self.ui.l_n_fourniss.returnPressed.connect(self.researchContract)

        self.ui.b_rechercher.clicked.connect(self.researchContract)
        self.ui.b_rechercher.setEnabled(False)

        self.ui.b_new_contract.clicked.connect(self.newContract)

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

    def customContextMenu(self, pos):
        if self.getSelectedContract() is not None:
            self.popMenu.exec_(self.t_ctr_list.mapToGlobal(pos))

    def reinitSorters(self):
        print "reinitSorters"
        self.ui.cb_sort_client_2.blockSignals(True)
        self.ui.cb_sort_fourniss.blockSignals(True)
        self.ui.cb_marchandise.blockSignals(True)
        self.ui.cb_sort_year.blockSignals(True)
        self.ui.cb_sort_client_2.setCurrentIndex(0)
        self.ui.cb_sort_fourniss.setCurrentIndex(0)
        self.ui.cb_marchandise.setCurrentIndex(0)
        self.ui.cb_sort_year.setCurrentIndex(0)
        self.ui.cb_sort_client_2.blockSignals(False)
        self.ui.cb_sort_fourniss.blockSignals(False)
        self.ui.cb_marchandise.blockSignals(False)
        self.ui.cb_sort_year.blockSignals(False)
        self.updateCtrList()

    def showCtrNotes(self):
        contract_selected = self.getSelectedContract()
        window = QtGui.QDialog()
        buttons = QtGui.QDialogButtonBox(
            QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok,
            QtCore.Qt.Horizontal, self)
        buttons.button(QtGui.QDialogButtonBox.Cancel).setText("Fermer")
        buttons.button(QtGui.QDialogButtonBox.Ok).setText("Enregistrer")
        mainLayout = QtGui.QVBoxLayout()
        w_notes = QtGui.QTextEdit()
        w_notes.setText(contract_selected.notes)
        mainLayout.addWidget(w_notes)
        mainLayout.addWidget(buttons)
        window.setLayout(mainLayout)

        buttons.rejected.connect(window.reject)
        buttons.accepted.connect(window.accept)

        result = window.exec_()
        if result == QtGui.QDialog.Accepted:
            contract_selected.notes = w_notes.toPlainText()
            self.cDB.updateContract(contract_selected)
        window.close()

    @QtCore.Slot()
    def openPdfContract(self):
        contract_selected = self.getSelectedContract()
        if contract_selected is not None:
            ctr_path = QtCore.QFileInfo(getFromConfig(
                "path", "words_contract")).absoluteFilePath()
            file_name = contract_selected.n_contrat + ".pdf"
            ctr_pdf = ""
            for f in listdir(ctr_path):
                if f.endswith(file_name):
                    ctr_pdf = join(ctr_path, file_name)
                    break
            if ctr_pdf == "":
                self.popupMessage("Contrat introuvable ou non édité...")
            else:
                startfile(ctr_pdf)
        else:
            self.popupMessage("Pb avec le contrat...")

    @QtCore.Slot()
    def openClientFile(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()

        contract_selected = self.getSelectedContract()
        if contract_selected is not None:
            client_file = contract_selected.getAcheteur().sheet_path

            progressDialog.setWindowTitle(u"Ouverture en cours...")
            text = u"\n\nOuverture du fichier \n" + client_file[0]
            progressDialog.setLabelText(text)
            progressDialog.show()
            QtGui.QApplication.processEvents()

            self.openWorkSheet(client_file[0], client_file[1])

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

        else:
            self.popupMessage("Fiche client inexistante...")

    @QtCore.Slot()
    def openFournisFile(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()

        contract_selected = self.getSelectedContract()
        if contract_selected is not None:
            client_file = contract_selected.getVendeur().sheet_path

            progressDialog.setWindowTitle(u"Ouverture en cours...")
            text = u"\n\nOuverture du fichier \n" + client_file[0]
            progressDialog.setLabelText(text)
            progressDialog.show()
            QtGui.QApplication.processEvents()

            self.openWorkSheet(client_file[0], client_file[1])

            progressDialog.close()
            QtGui.QApplication.processEvents()
        else:
            self.popupMessage("Fiche fournisseur introuvable...")

    def openWorkSheet(self, workbook_path, worksheet_name):

        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()

        if exists(workbook_path):

            progressDialog.setWindowTitle(u"Ouverture en cours...")
            text = u"\n\nOuverture du fichier \n" + workbook_path
            progressDialog.setLabelText(text)
            progressDialog.show()
            QtGui.QApplication.processEvents()

            xl = wc.Dispatch("Excel.Application")
            xl.Workbooks.Open(Filename=workbook_path, ReadOnly=1)
            xl.Worksheets(worksheet_name).Activate()
            xl.Visible = True
            del xl

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

        else:
            self.popupMessage("Worksheet introuvable...")

    def addDelivery(self):
        self.s_addDelivery.emit(self.getSelectedContract())

    def specifyResearch(self, sender):
        if "ctr" in sender.objectName():
            self.ui.rb_r_n_ctr.setChecked(True)
        elif "client" in sender.objectName():
            self.ui.rb_r_n_client.setChecked(True)
        elif "fourniss" in sender.objectName():
            self.ui.rb_r_n_fourniss.setChecked(True)
        self.ui.b_rechercher.setEnabled(True)

    def getSelectedContract(self):
        items_selected = self.t_ctr_list.selectedItems()
        if len(items_selected) < 1:
            #            self.setButtonEnabled(False)
            return None
        return items_selected[0].ctr

    @QtCore.Slot()
    def setClientNumber(self):
        print "setClientNumber"
        contract_selected = self.getSelectedContract()
        if contract_selected is None:
            return

        contract_selected.n_client = Question.askNumber(
            whatIsIt="Numéro de contract client : ")
        self.cDB.updateContract(contract_selected)

    def setFournissNumber(self):
        print "setClientNumber"
        contract_selected = self.getSelectedContract()
        if contract_selected is None:
            return

        contract_selected.n_fourniss = Question.askNumber(
            whatIsIt="Numéro de contract fournisseur : ")
        self.cDB.updateContract(contract_selected)

    @QtCore.Slot()
    def newContract(self):
        contract_maker = ContractIniter(self)
        #        contract_maker.resize(contract_maker.minimumSize())

        contract_maker.setAttribute(QtCore.Qt.WA_StyledBackground)
        contract_maker.show()

    @QtCore.Slot()
    def modifyContract(self):
        ctr = self.getSelectedContract()
        if ctr is None:
            return

        editor = QtGui.QMainWindow(self)
        editor.setWindowTitle('Éditeur de contrat')
        contract_editor = ContractEditor()
        contract_editor.setCreatorMode(False)
        contract_editor.ui.label_13.hide()
        contract_editor.initEditor(ctr)
        editor.setCentralWidget(contract_editor)

        editor.resize(980, 970)
        #        QtCore.QObject.connect(contract_editor, QtCore.SIGNAL('s_close_widget'), editor.close)
        contract_editor.s_close_widget.connect(editor.close)

        editor.show()

    def closeEditor(self):
        print "received"

    @QtCore.Slot()
    def printContract(self):
        try:
            self.printer.launch(self.getSelectedContract())
        except Exception as e:
            print e
            msgBox = QtGui.QMessageBox()
            msgBox.setText(
                "Une erreur est arrivée lors de l'édition du contrat !")
            msgBox.setStandardButtons(QtGui.QMessageBox.Ok)
            return msgBox.exec_()

    @QtCore.Slot()
    def removeContract(self):
        ctr = self.getSelectedContract()
        if ctr is not None:
            message = "Êtes-vous sûr de vouloir supprimer définitivement le contrat n°" + str(
                ctr.n_contrat) + " ?"
            reply = QtGui.QMessageBox.question(self, 'Attention', message,
                                               QtGui.QMessageBox.Yes,
                                               QtGui.QMessageBox.No)
            if reply == QtGui.QMessageBox.Yes:
                #                threading.Thread(target=self.cDB.removeContract, args=(ctr,None,)).start()
                self.cDB.removeContract(ctr)
        else:
            #            threading.Thread(target=self.cDB.removeContract, args=(ctr,None,)).start()
            self.cDB.clearBDD()

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

    def updateOrdererYear(self):
        self.ui.cb_sort_year.blockSignals(True)
        y_min, y_max = maxint, 0
        for ctr in self.cDB.getEveryContracts():
            if ctr is None:
                continue
            date = ctr.date_contrat
            year = int(date.split('/')[2])
            if year > y_max:
                y_max = year
            if year < y_min:
                y_min = year

        self.ui.cb_sort_year.clear()
        self.ui.cb_sort_year.addItem("Année", userData=None)
        for y in range(y_min, y_max + 1, 1):
            self.ui.cb_sort_year.addItem(str(y), userData=y)

        index = self.ui.cb_sort_year.findText(str(
            datetime.datetime.now().year))
        if index < 0: index = 0
        self.ui.cb_sort_year.setCurrentIndex(index)
        self.ui.cb_sort_year.blockSignals(False)
        self.ui.cb_sort_year.currentIndexChanged.emit(index)

    def initOrdererFourniss(self):
        self.ui.cb_sort_fourniss.blockSignals(True)
        self.ui.cb_sort_fourniss.clear()
        self.ui.cb_sort_fourniss.addItem("- Tous -", userData=None)

        client_list = self.oil_market.get_client(is_fournisseur=True)
        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_fourniss.addItem(n, c)

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

    def initOrdererClient(self):
        self.ui.cb_sort_client_2.blockSignals(True)
        self.ui.cb_sort_client_2.clear()
        self.ui.cb_sort_client_2.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_2.addItem(n, c)

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

    def initOrdererMarchandise(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 initCtrList(self):
        font = self.t_ctr_list.header().font()
        font.setPointSize(10)

        col1 = "Date".decode('utf-8').strip()
        col2 = "N°contrat".decode('utf-8').strip()
        col3 = "N°fournisseur".decode('utf-8').strip()
        col4 = "Client".decode('utf-8').strip()
        col5 = "Fournisseur".decode('utf-8').strip()
        col6 = "Modalité".decode('utf-8').strip()
        col7 = "Marchandise".decode('utf-8').strip()
        col8 = "Prix".decode('utf-8').strip()
        col9 = "Qte (T)".decode('utf-8').strip()
        col10 = "Échéancier".decode('utf-8').strip()
        col11 = "À livrer (T)".decode('utf-8').strip()
        col12 = "N°client".decode('utf-8').strip()
        col13 = "Courtage".decode('utf-8').strip()
        col14 = "À payer".decode('utf-8').strip()
        headers = [
            col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11,
            col12, col13, col14
        ]

        self.t_ctr_list.setHeaderLabels(headers)
        self.t_ctr_list.setSortingEnabled(True)
        self.t_ctr_list.header().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)
        self.t_ctr_list.header().setResizeMode(QtGui.QHeaderView.Interactive)
        self.t_ctr_list.header().setFont(font)
        for i in range(0, len(headers), 1):
            self.t_ctr_list.headerItem().setTextAlignment(
                i, QtCore.Qt.AlignCenter)

        col1 = "Qte totale (T)".decode('utf-8').strip()
        col2 = "Total à livrer (T)".decode('utf-8').strip()
        col3 = "Total à payer (€)".decode('utf-8').strip()
        headers = [col1, col2, col3]

        self.ui.t_ctr_total.setHeaderLabels(headers)
        self.ui.t_ctr_total.header().setFont(font)
        width = self.ui.t_ctr_total.parent().sizeHint().width()
        for i in range(0, len(headers), 1):
            self.ui.t_ctr_total.headerItem().setTextAlignment(
                i, QtCore.Qt.AlignCenter)
            self.ui.t_ctr_total.header().resizeSection(i, width / 3)
        self.ui.t_ctr_total.header().setStretchLastSection(True)

        self.updateCtrList()
        self.ui.t_ctr_total.header().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)
        self.ui.t_ctr_total.header().setResizeMode(
            QtGui.QHeaderView.Interactive)

    def sortContractList(self, index=None):

        year = self.ui.cb_sort_year.itemData(
            self.ui.cb_sort_year.currentIndex())
        client = self.ui.cb_sort_client_2.itemData(
            self.ui.cb_sort_client_2.currentIndex())
        fourniss = self.ui.cb_sort_fourniss.itemData(
            self.ui.cb_sort_fourniss.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)

        sorted_ctr_list = self.cDB.getContracts(by_year=year,
                                                by_client=client,
                                                by_fourniss=fourniss,
                                                by_marchandise=marchandise)

        return sorted_ctr_list

    def updateCtrList(self, ctr_list=None):
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 2)
        print "updateCtrList called by ", calframe[1][3]

        self.t_ctr_list.clear()
        if ctr_list is None or isinstance(ctr_list, list) == False:
            ctr_list = self.sortContractList()

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

                if not hasattr(ctr, "descr_livraison"):
                    setattr(ctr, "descr_livraison", "")
                    self.cDB.updateContract(ctr)

                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
                monnaie = ' ' + getFromConfig(
                    'monnaie', 'monnaies')[ctr.monnaie]['sym'].encode('utf8')

                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>"

                if ctr.is_franco:
                    modalite = "Franco <br/>"
                else:
                    modalite = "Départ <br/>"
                modalite += ctr.getVilleCible()

                itemlist = []
                itemlist.append(ctr.date_contrat)
                itemlist.append(ctr.n_contrat)
                itemlist.append(ctr.n_fourniss)
                itemlist.append(nom_client)
                itemlist.append(nom_fourniss)
                itemlist.append(modalite)
                itemlist.append(full_marchandise)
                itemlist.append(format_num(ctr.prix) + monnaie)
                itemlist.append(format_num(ctr.qte_total))
                itemlist.append("")
                itemlist.append(format_num(ctr.reste_livraison))
                itemlist.append(ctr.n_client)
                if '%' in ctr.courtage:
                    itemlist.append(format_num(ctr.courtage) + ' %')
                else:
                    itemlist.append(format_num(ctr.courtage) + ' €')
                itemlist.append(format_num(ctr.reste_paiement) + monnaie)

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

            newLine = TreeWidgetContract(self.t_ctr_list, ctr, blankItemlist)
            for i in range(0, len(itemlist)):
                item = itemlist[i]
                self.t_ctr_list.setItemWidget(newLine, i,
                                              TreeWidgetItemLabel(self, item))

            self.t_ctr_list.setItemWidget(newLine, 9,
                                          DeliveriesViewer(self, ctr))
#
        self.t_ctr_list.header().setResizeMode(
            QtGui.QHeaderView.ResizeToContents)
        self.t_ctr_list.header().setResizeMode(QtGui.QHeaderView.Interactive)
        for i in range(0, len(itemlist), 1):
            self.t_ctr_list.resizeColumnToContents(i)
        self.t_ctr_list.header().setResizeMode(
            self.t_ctr_list.columnCount() - 3, QtGui.QHeaderView.Stretch)
        #        self.repaint()
        self.updateTotal(ctr_list)

    def updateTotal(self, ctr_list):
        qte_totale = 0.0
        tot_a_livrer = 0.0
        tot_a_payer = 0.0
        self.ui.t_ctr_total.clear()

        for ctr in ctr_list:
            qte_totale += float(format_num(ctr.qte_total))
            tot_a_livrer += float(format_num(ctr.reste_livraison))
            tot_a_payer += float(format_num(ctr.reste_paiement))

        newLine = QtGui.QTreeWidgetItem(self.ui.t_ctr_total, [""] * 3)
        self.ui.t_ctr_total.setItemWidget(
            newLine, 0, TreeWidgetItemLabel(self, str(qte_totale)))
        self.ui.t_ctr_total.setItemWidget(
            newLine, 1, TreeWidgetItemLabel(self, str(tot_a_livrer)))
        self.ui.t_ctr_total.setItemWidget(
            newLine, 2, TreeWidgetItemLabel(self, str(tot_a_payer)))

        height = self.ui.t_ctr_total.visualItemRect(newLine).height()
        width = self.ui.t_ctr_total.parent().sizeHint().width()
        self.ui.t_ctr_total.setFixedHeight(height * 2 + 1)

        self.ui.t_ctr_total.header().resizeSection(0, width / 3)
        self.ui.t_ctr_total.header().resizeSection(1, width / 3)
        self.ui.t_ctr_total.header().resizeSection(2, width / 3)

    def setButtonEnabled(self, state):
        for i in range(self.ui.l_buttons.count()):
            b = self.ui.l_buttons.itemAt(i).widget()
            if isinstance(b, QtGui.QPushButton):
                b.setEnabled(state)

    @QtCore.Slot()
    def researchContract(self):
        if self.ui.rb_r_n_ctr.isChecked():
            num = str(self.ui.l_n_ctr.text())
            type_num = NUM_CTR
        elif self.ui.rb_r_n_client.isChecked():
            num = str(self.ui.l_n_client.text())
            type_num = NUM_CTR_C
        elif self.ui.rb_r_n_fourniss.isChecked():
            num = str(self.ui.l_n_fourniss.text())
            type_num = NUM_CTR_F
        if len(num) > 0:
            ctr_found = self.cDB.getContractsByNum(num.rstrip(), type_num)
            self.updateCtrList(ctr_found)
        else:
            self.updateCtrList()

    @QtCore.Slot(str)
    def loadContractFromDeliveries(self, n_deliv):
        n_deliv = n_deliv.split('-')
        n_ctr = n_deliv[0] + '-' + n_deliv[1]
        ctr = self.cDB.getContractsByNum(n_ctr, NUM_CTR)[0]
        self.updateCtrList([ctr])

    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_()

    @QtCore.Slot()
    def showEvent(self, event):
        #        self.updateCtrList()
        pass

    def FIAUpdated(self):
        for ctr in self.cDB.getEveryContracts():
            acheteur = ctr.getAcheteur()
            m_acheteur = self.oil_market.get_client(acheteur.nom,
                                                    acheteur.type_client)
            if m_acheteur is not None:
                for k, v in m_acheteur.__dict__.items():
                    if not hasattr(acheteur, k):
                        setattr(acheteur, k, v)
                        self.cDB.updateContract(ctr)


#    def paintEvent(self, event):
#        opt = QtGui.QStyleOption()
#        opt.initFrom(self)
#        p = QtGui.QPainter(self)
#        self.style().drawPrimitive(QtGui.QStyle.PE_Widget, opt, p, self)
#

    def main(self):
        self.show()