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

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

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

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

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

        self.ui.tab_main.setCurrentIndex(0)

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

        self.ui.rb_fournisseur.setChecked(True)
Beispiel #2
0
    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()
Beispiel #3
0
    def __init__(self, version=0.0, parent=None):
        super(Ui_manager, self).__init__(parent)
        self.ui = Ui_Accueil()
        self.ui.setupUi(self)
        self.setWindowIcon(QtGui.QIcon('icone.png'))
        self.setWindowTitle('Gestionnaire de clientèle')
        self.ui.splitter.setHandleWidth(15)
        self.version = version

        l_ctr = QtGui.QHBoxLayout()
        scroll_ctr = QtGui.QScrollArea()
        self.ctr_manager = ContractsManager(self)
        self.w_ctr = self.ctr_manager.ui.ctr_centralwidget
        self.w_ctr.setAttribute(QtCore.Qt.WA_StyledBackground)
        self.w_ctr.setObjectName("w_ctr")
        #        self.w_ctr.adjustSize()
        scroll_ctr.setWidgetResizable(True)
        scroll_ctr.setWidget(self.w_ctr)
        #        scroll_ctr.adjustSize()
        l_ctr.addWidget(scroll_ctr)
        self.ui.f_contracts.setLayout(l_ctr)
        self.ui.f_contracts.setFrameShape(QtGui.QFrame.NoFrame)

        l_deliv = QtGui.QHBoxLayout()
        scroll_deliv = QtGui.QScrollArea()
        self.dlv_manager = DeliveryManager(self)
        self.w_dlv = self.dlv_manager.ui.dlv_centralwidget
        self.w_dlv.setAttribute(QtCore.Qt.WA_StyledBackground)
        self.w_dlv.setObjectName("w_dlv")
        scroll_deliv.setWidget(self.w_dlv)
        scroll_deliv.setWidgetResizable(True)
        l_deliv.addWidget(scroll_deliv)
        self.ui.f_deliveries.setLayout(l_deliv)
        self.updateStyle()

        self.ctr_manager.s_addDelivery.connect(self.dlv_manager.addDelivery)

        self.oil_market = Market()
        #        self.ctr_manager.FIAUpdated()
        #        self.ctr_manager.FIFUpdated()
        self.ui.actionConfig.triggered.connect(
            self.oil_market.updateConfigLanguages)
        self.ui.actionFIA.triggered.connect(self.updateFIA)
        self.ui.actionFIF.triggered.connect(self.oil_market.updateFIF)
        self.ui.menuA_propos.aboutToShow.connect(self.a_propos)

        self.showMaximized()
Beispiel #4
0
def main():

    #    print isfile(getFromConfig("path", "stylesheet_file"))
    #    app.translate()

    ##########################################
    try:
        logging.basicConfig(level=logging.DEBUG)  #,
        #        format='%(asctime)-15s %(levelname)-8s %(message)s',
        #        datefmt='%Y-%m-%d %H:%M:%S',
        #        filename="Log.log",
        #        filemode='w')

        stdout_logger = logging.getLogger()
        stderr_logger = logging.getLogger()

        fh_debug = logging.FileHandler('Log.log')
        fh_debug.setLevel(logging.DEBUG)
        fh_debug.setFormatter(
            logging.Formatter('%(asctime)-15s %(levelname)-8s %(message)s'))
        stdout_logger.addHandler(fh_debug)

    #    sh = logging.StreamHandler(sys.stdout)
    #    sh.setLevel(logging.DEBUG)
    #    sh.setFormatter(logging.Formatter('%(asctime)-15s %(levelname)-8s %(message)s'))
    #    stdout_logger.addHandler(sh)


#        sys.stdout = StreamToLogger(stdout_logger, logging.DEBUG)
#        sys.stderr = StreamToLogger(stderr_logger, logging.ERROR)
    except:
        try:
            for handler in stdout_logger.handlers:
                handler.close()
                stdout_logger.removeFilter(handler)

            for handler in stderr_logger.handlers:
                handler.close()
                stderr_logger.removeFilter(handler)
        except:
            pass
    #########################################

    # INITIALIZATION ##
    Market()

    # EXECUTE
    setup = Ui_manager(version)
    setup.show()
    splash.finish(setup)

    sys.exit(app.exec_())
Beispiel #5
0
    def __init__(self, parent=None):
        super(PDFCreator, self).__init__(parent)
        self.ui = Ui_printer()
        self.ui.setupUi(self)
        self.setWindowTitle('Édition du document')
        self.oil_market = Market()

        self.lang_list = getFromConfig("langages", 'lang_list')
        for lang in self.lang_list:
            rb = langueRB(parent=self.ui.layout_langues,
                          text=lang['nom'],
                          data=lang)
            self.ui.layout_langues.addWidget(rb)

        for i in range(0, self.ui.layout_langues.count(), 1):
            w = self.ui.layout_langues.itemAt(i)
            if w is not None:
                w.widget().setChecked(True)
                break

        self.setAttribute(QtCore.Qt.WA_StyledBackground)
        self.ui.b_print.clicked.connect(self.createPDF)
        self.ui.b_close.clicked.connect(self.close)
        self.hide()
Beispiel #6
0
    def __init__(self, parent=None, ctr=None, delivery=None):
        super(deliveryEditor, self).__init__(parent)
        self.setWindowIcon(QtGui.QIcon('icone.png'))
        self.setWindowTitle('Éditeur de livraison')
        self.oil_market = Market()

        if ctr is None: return
        self.ctr = ctr
        self.mainWidget = ui_new_delivery(self)
        self.buttons = QtGui.QDialogButtonBox(
            QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok,
            QtCore.Qt.Horizontal, self)
        self.buttons.button(QtGui.QDialogButtonBox.Ok).setText("Valider")
        self.buttons.button(QtGui.QDialogButtonBox.Cancel).setText("Annuler")
        self.doNotClose = False

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.mainWidget)
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addLayout(layout)
        mainLayout.addWidget(self.buttons)
        self.setLayout(mainLayout)

        self.mainWidget.ui.l_qte.setValidator(
            QtGui.QDoubleValidator(0.0, 999999.0, 10, self))
        self.buttons.accepted.connect(self.checkDelivery)
        self.buttons.rejected.connect(self.reject)
        self.mainWidget.ui.cb_ville.setEditable(True)
        self.mainWidget.ui.cb_date.currentIndexChanged.connect(
            self.dateSelected)
        self.mainWidget.ui.rb_franco.toggled.connect(self.delivTypeChanged)
        self.mainWidget.ui.rb_depart.toggled.connect(self.delivTypeChanged)

        self.initWidget()
        if delivery is not None:
            self.updateWidget(delivery)
Beispiel #7
0
import numpy as np
import matplotlib.pyplot as plt
from classes import Market, deadw

baseline_params = 15, 0.5, -2, 0.5, 3
m = Market(*baseline_params)

q_max = m.quantity() * 2
q_grid = np.linspace(0.0, q_max, 100)
pd = m.inverse_demand(q_grid)
ps = m.inverse_supply(q_grid)
psno = m.inverse_supply_no_tax(q_grid)

fig, ax = plt.subplots()
ax.plot(q_grid, pd, lw=2, alpha=0.6, label='demanda')
ax.plot(q_grid, ps, lw=2, alpha=0.6, label='oferta')
ax.plot(q_grid, psno, '--k', lw=2, alpha=0.6, label='Oferta sin impuestos')
ax.set_xlabel('Cantidad', fontsize=14)
ax.set_xlim(0, q_max)
ax.set_ylabel('Precio', fontsize=14)
ax.legend(loc='lower right', frameon=False, fontsize=14)
plt.show()

baseline_params = 15, 0.5, -2, 0.5, 3
m = Market(*baseline_params)
peso = deadw(m)
print(peso)
Beispiel #8
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()
Beispiel #9
0
class PDFCreator(QtGui.QMainWindow, QtCore.QObject):
    s_printed = QtCore.Signal(str)

    def __init__(self, parent=None):
        super(PDFCreator, self).__init__(parent)
        self.ui = Ui_printer()
        self.ui.setupUi(self)
        self.setWindowTitle('Édition du document')
        self.oil_market = Market()

        self.lang_list = getFromConfig("langages", 'lang_list')
        for lang in self.lang_list:
            rb = langueRB(parent=self.ui.layout_langues,
                          text=lang['nom'],
                          data=lang)
            self.ui.layout_langues.addWidget(rb)

        for i in range(0, self.ui.layout_langues.count(), 1):
            w = self.ui.layout_langues.itemAt(i)
            if w is not None:
                w.widget().setChecked(True)
                break

        self.setAttribute(QtCore.Qt.WA_StyledBackground)
        self.ui.b_print.clicked.connect(self.createPDF)
        self.ui.b_close.clicked.connect(self.close)
        self.hide()

    def launch(self, ctr):
        self.ctr = ctr
        self.show()

    @QtCore.Slot()
    def createPDF(self, is_fourniss=False, filedir=None, tpl_path=None):

        self.hide()

        base_tpl_path = getFromConfig('path', 'templates_contract')
        words_path = getFromConfig('path', 'words_contract')

        for i in range(0, self.ui.layout_langues.count()):
            widget = self.ui.layout_langues.itemAt(i).widget()
            if widget != 0 and isinstance(widget, langueRB):
                if widget.isChecked():
                    langue_data = widget.data

        if tpl_path is None:
            filters = "MS Word Documents (*" + langue_data["code"] + ".docx)"
            #            selected_filter = "MS Word Documents (*"+langue_data["code"]+".docx)"
            options = QtGui.QFileDialog.DontResolveSymlinks
            fileDialog = QtGui.QFileDialog(
                self, "Selectionnez un modèle de contrat")
            fileDialog.setFilter(filters)
            fileDialog.setOptions(options)
            fileDialog.setDirectory(base_tpl_path)
            tpl_path = fileDialog.getOpenFileName()[0]
            #            tpl_path = QtGui.QFileDialog.getOpenFileName(self, "Selectionnez un template", base_tpl_path, filters, selected_filter, options)[0]
            #            tpl_path = fileDialog.getOpenFileName(self, "Selectionnez un template", dir=base_tpl_path, filter = filters, selected_filter, options)[0]
            if tpl_path is None or tpl_path == "":
                return

        filename = self.ctr.n_contrat

        #################################################
        ##             NUMERO de CONTRAT             ##
        #################################################
        n_ctr = self.ctr.n_contrat

        #################################################
        ##               DATE CONTRAT                  ##
        #################################################
        date_ctr = self.ctr.date_contrat

        #################################################
        ##             VILLE DE LVR/CHARG              ##
        #################################################

        ville = self.ctr.getVilleCible()
        if len(ville) < 1:
            ville = "<VILLE>"

        #################################################
        ##             ADRESSE  FACTURATION            ##
        #################################################
        if is_fourniss is True:
            adr_fact = self.ctr.getFactFourniss()
        else:
            adr_fact = self.ctr.getFactClient()

        if isinstance(adr_fact, list):
            adr_fact = adr_fact[FacturationSelection.getFacturationAdress(
                self, adr_fact)]
        tab_adr_fact = '\t\t\t\t\t\t\t\t'
        adr_fact = adr_fact.replace('\n', '\n' + tab_adr_fact)

        #################################################
        ##             ADRESSE  CLIENT                 ##
        #################################################
        adr_client = self.ctr.getAdr_uClient()
        if langue_data['code'] != 'fr' and len(
                re.findall("\\n\w+$", adr_client)) > 0:
            print "ETRANGER, ", adr_client
            pays = re.findall("\\n\w+$", adr_client)[0]
            print "PAYS, ", pays
            adr_client = adr_client.replace(pays, pays.replace("\n", "\t\t\t"))
            print "NEW adr, ", adr_client
        tab_adr_client = '\t\t\t'
        adr_client = adr_client.replace('\n', '\n' + tab_adr_client)

        #################################################
        ##                 TVA  CLIENT                 ##
        #################################################
        tva_client = self.ctr.getTVA_uClient()

        #################################################
        ##             ADRESSE  FOURNISSEUR            ##
        #################################################
        adr_fourniss = self.ctr.getAdr_uFourniss()
        if langue_data['code'] != 'fr' and len(
                re.findall("\\n\w+$", adr_fourniss)) > 0:
            pays = re.findall("\\n\w+$", adr_fourniss)[0]
            adr_fourniss = adr_fourniss.replace(pays,
                                                pays.replace("\n", "\t\t\t"))
        tab_adr_fourniss = '\t\t\t'
        adr_fourniss = adr_fourniss.replace('\n', '\n' + tab_adr_fourniss)

        #################################################
        ##                 TVA  FOURNISSEUR            ##
        #################################################
        tva_fourniss = self.ctr.getTVA_U_Fourniss()

        #################################################
        ##                MARCHANDISE                  ##
        #################################################
        #        m_nom = self.ctr.marchandise.decode('utf-8')
        m_nom = self.oil_market.getMarchandiseFullName(self.ctr.marchandise,
                                                       langue_data['code'])
        #        marchandise_list = self.oil_market.marchandises_list[langue_data['code']]
        #        m_nom = marchandise_list[self.ctr.marchandise]#.decode('utf-8')
        m_quantite = self.ctr.quantite

        if self.ctr.unite == 'kg':
            if langue_data['code'] == 'fr':
                m_unite = 'le '
            elif langue_data['code'] == 'en':
                m_unite = 'per '
            elif langue_data['code'] == 'es':
                m_unite = 'el '
            m_unite += langue_data['kg_unite']
        elif self.ctr.unite == 't':
            if langue_data['code'] == 'fr':
                m_unite = 'la '
            elif langue_data['code'] == 'en':
                m_unite = 'per '
            elif langue_data['code'] == 'es':
                m_unite = 'la '
            m_unite += langue_data['t_unite']

        #################################################
        ##                  PAIEMENT                   ##
        #################################################

        str_prix = self.ctr.prix
        matches = re.findall(r"[-+]?\d*\.*\d+", str_prix.replace(',', '.'))
        if len(matches) > 0:
            prix_num = matches[0]
            prix_words = num2words(float(prix_num), lang=langue_data['code'])
        else:
            prix_num = str_prix
            prix_words = ""

        if self.ctr.monnaie == 0:
            monnaie = u'\u20ac'.encode('utf8')
            prix_words += ' euros'
        elif self.ctr.monnaie == 1:
            monnaie = u'\u00a3'.encode('utf8')
            prix_words += ' dollars'
        elif self.ctr.monnaie == 2:
            monnaie = u'\u0024'.encode('utf8')
            prix_words += ' livres'
        else:
            monnaie = ""

        if len(self.ctr.paiement) > 0:
            index = self.oil_market.paiements["fr"].index(self.ctr.paiement)
            paiement = self.oil_market.paiements[langue_data['code']][index]
            courtage = self.ctr.courtage
        else:
            paiement = ""
            courtage = ""

        #################################################
        ##                 LIVRAISON                   ##
        #################################################
#        dlv_dic = self.ctr.periode_livraison
        try:
            periode_livraison = self.ctr.descr_livraison
        except:
            periode_livraison = ""

#        month_names = langue_data['months']
#        ordered_years = sorted(dlv_dic.keys())
#        for i in range(0, len(ordered_years), 1):
#            if len(periode_livraison) > 0 :
#                periode_livraison += '\n'
#            y = ordered_years[i]
#            for j in range(0, 12):
#                m = month_names[j]
#                total = int(float(dlv_dic[y][str(j+1).zfill(2)]["total"]))
#                if total == 0: continue
#                if len(periode_livraison) > 0 :
#                    periode_livraison += ', '+m
#                else:
#                    periode_livraison += m
#            periode_livraison += ' - '+str(y)

        if len(self.ctr.logement) > 0:
            index = self.oil_market.logements["fr"].index(self.ctr.logement)
            format_livraison = self.oil_market.logements[
                langue_data['code']][index]
        else:
            format_livraison = ""

        if self.ctr.is_franco is True:
            if langue_data['code'] == "fr":
                ville = "usine acheteur à ".decode('utf8') + ville.decode(
                    'utf8')
            if langue_data['type_deliv'][1] == "":
                type_deliv = langue_data['type_deliv'][0].lower()
            else:
                type_deliv = langue_data['type_deliv'][1].lower()
        else:
            if langue_data['code'] == "fr":
                ville = "usine vendeur à ".decode('utf8') + ville.decode(
                    'utf8')

            if langue_data['type_deliv'][3] == "":
                type_deliv = langue_data['type_deliv'][2].lower()
            else:
                type_deliv = langue_data['type_deliv'][3].lower()

        has_tva_client = False
        if len(tva_client) > 0:
            tva_client += '\n'
            has_tva_client = True

        has_tva_fourniss = False
        if len(tva_fourniss) > 0:
            tva_fourniss += '\n'
            has_tva_fourniss = True

        context = {
            'is_fourniss': is_fourniss,
            'date_ctr': R(date_ctr, size=24),
            'n_ctr': R(n_ctr, size=24),
            'adr_fact': R(adr_fact, size=24),
            'adr_fourniss': R(adr_fourniss, size=24),
            'tva_fourniss': R(tva_fourniss, size=24),
            'has_tva_fourniss': has_tva_fourniss,
            'adr_client': R(adr_client, size=24),
            'tva_client': R(tva_client, size=24),
            'has_tva_client': has_tva_client,
            'm_nom': R(m_nom, size=24),
            'm_quantite': R(m_quantite, size=24),
            'm_unite': R(m_unite, size=24),
            'format_livraison': R(format_livraison, size=24),
            'date_livraison': R(periode_livraison, size=24),
            'type_delivery': R(type_deliv, size=24),
            'ville': R(ville, size=24),
            'monnaie': R(monnaie, size=24),
            'prix_num': R(prix_num, size=24),
            'prix_words': R(prix_words, size=24),
            'paiement': R(paiement, size=24),
            'courtage': R(courtage, size=24)
        }

        if filedir is None:
            #            filedir = QtCore.QDir.absoluteFilePath(words_path)
            filedir = QtCore.QFileInfo(words_path).absoluteFilePath()


#            selected_filter = "MS Word Documents (*"+langue_data["code"]+".docx)"
#            fileDialog2 = QtGui.QFileDialog(self, "Où enregistrer ?")
#            options2 = QtGui.QFileDialog.DontResolveSymlinks
#            fileDialog2.setOptions(options2)
#            fileDialog2.setDirectory(words_path)
#            filedir = fileDialog2.getExistingDirectory()

#            filedir = QtGui.QFileDialog.getExistingDirectory(self, "Où enregistrer ?", words_path, QtGui.QFileDialog.ShowDirsOnly)# | QtGui.QFileDialog.DontResolveSymlinks)

        if filedir is None:
            return

        if not filedir.endswith('/'):
            filedir += '/'

        ctr = DocxTemplate(tpl_path)
        ctr.render(context)
        if is_fourniss is False:
            ctr_doc = filedir + filename + "_client.docx"
            ctr.save(ctr_doc)
        else:
            ctr_doc = filedir + filename + ".docx"
            ctr.save(ctr_doc)

        startfile(ctr_doc)

        if is_fourniss is False:
            return self.createPDF(is_fourniss=True,
                                  filedir=filedir,
                                  tpl_path=tpl_path)
Beispiel #10
0
    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)
Beispiel #11
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()
Beispiel #12
0
    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)
Beispiel #13
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()
Beispiel #14
0
from classes import Market

z = Market()
z.add_check('iPad')
z.add_check('iPhone')
z.add_check('apple')
z.my_cart()
z.delete_item('iPad')
z.my_cart()
Beispiel #15
0
class deliveryEditor(QtGui.QDialog, QtCore.QObject):
    def __init__(self, parent=None, ctr=None, delivery=None):
        super(deliveryEditor, self).__init__(parent)
        self.setWindowIcon(QtGui.QIcon('icone.png'))
        self.setWindowTitle('Éditeur de livraison')
        self.oil_market = Market()

        if ctr is None: return
        self.ctr = ctr
        self.mainWidget = ui_new_delivery(self)
        self.buttons = QtGui.QDialogButtonBox(
            QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok,
            QtCore.Qt.Horizontal, self)
        self.buttons.button(QtGui.QDialogButtonBox.Ok).setText("Valider")
        self.buttons.button(QtGui.QDialogButtonBox.Cancel).setText("Annuler")
        self.doNotClose = False

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.mainWidget)
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addLayout(layout)
        mainLayout.addWidget(self.buttons)
        self.setLayout(mainLayout)

        self.mainWidget.ui.l_qte.setValidator(
            QtGui.QDoubleValidator(0.0, 999999.0, 10, self))
        self.buttons.accepted.connect(self.checkDelivery)
        self.buttons.rejected.connect(self.reject)
        self.mainWidget.ui.cb_ville.setEditable(True)
        self.mainWidget.ui.cb_date.currentIndexChanged.connect(
            self.dateSelected)
        self.mainWidget.ui.rb_franco.toggled.connect(self.delivTypeChanged)
        self.mainWidget.ui.rb_depart.toggled.connect(self.delivTypeChanged)

        self.initWidget()
        if delivery is not None:
            self.updateWidget(delivery)

    def initWidget(self):
        self.mainWidget.ui.l_marchandise.setText(
            self.oil_market.getMarchandiseFullName(self.ctr.marchandise))
        if self.ctr.is_franco is True:
            self.mainWidget.ui.rb_franco.setChecked(True)
        else:
            self.mainWidget.ui.rb_depart.setChecked(True)

        dlv_dic = self.ctr.periode_livraison
        ordered_years = sorted(dlv_dic.keys())
        for i in range(0, len(ordered_years), 1):
            y = ordered_years[i]
            for j in range(0, 12):
                m = str(j + 1).zfill(2)
                total = format_num(dlv_dic[y][m]["total"])
                if float(total) == 0: continue
                date = m + '/' + str(y)
                self.mainWidget.ui.cb_date.addItem(date)

        if self.mainWidget.ui.cb_date.count() > 0:
            self.mainWidget.ui.cb_date.setCurrentIndex(0)

    def updateWidget(self, delivery):
        #        delivery = Livraison()
        if delivery.date_charg_livr is not None:
            date = delivery.date_charg_livr.split('/')
            if len(date) > 2:
                m = date[1]
                y = date[2]
            elif len(date) == 0:
                m = "00"
                y = "0000"
            else:
                m = date[0]
                y = date[1]
            date = m + "/" + y
            self.mainWidget.ui.cb_date.setCurrentIndex(
                self.mainWidget.ui.cb_date.findText(date))
#            self.mainWidget.ui.cb_jour.clear()
#            self.mainWidget.ui.cb_jour.addItems(list(str(j).zfill(2) for j in range(1, number_of_days(m,y)+1, 1)))

        if delivery.horaire_charg_livr is not None:
            self.mainWidget.ui.l_horaire.setText(delivery.horaire_charg_livr)
        if delivery.marchandise is not None:
            self.mainWidget.ui.l_marchandise.setText(delivery.marchandise)
        if delivery.quantite is not None:
            self.mainWidget.ui.l_qte.setText(delivery.quantite)
        if delivery.ref_client is not None:
            self.mainWidget.ui.l_ref_client.setText(delivery.ref_client)
        if delivery.ref_fourniss is not None:
            self.mainWidget.ui.l_ref_fourniss.setText(delivery.ref_fourniss)
        if delivery.ref_chargement is not None:
            self.mainWidget.ui.l_ref_charg.setText(delivery.ref_chargement)

    def dateSelected(self, index):
        sender = self.sender()
        if index < 0:
            return
        m, y = sender.itemText(index).split('/')[-2], sender.itemText(
            index).split('/')[-1]
        self.mainWidget.ui.d_date_reelle.setDate(
            QtCore.QDate.fromString('01/' + m + '/' + y, "dd/MM/yyyy"))
        total = format_num(self.ctr.periode_livraison[y][m]["total"])
        done = format_num(self.ctr.periode_livraison[y][m]["done"])
        maximum = format_num(float(total) - float(done))
        self.mainWidget.ui.l_qte.setPlaceholderText('max: ' + maximum)

    def delivTypeChanged(self):
        self.mainWidget.ui.cb_ville.clear()
        if self.mainWidget.ui.rb_franco.isChecked():
            adresses = self.ctr.getAcheteur().getUsineAdr()
            for adr, v, u in adresses:
                self.mainWidget.ui.cb_ville.addItem(adr, userData=v)
        else:
            adresses = self.ctr.getVendeur().getUsineAdr()
            for adr, v, u in adresses:
                self.mainWidget.ui.cb_ville.addItem(adr, userData=v)

    def checkDelivery(self):
        print "checkDelivery"
        to_complete = 0
        if self.mainWidget.ui.cb_date.currentIndex() < 0:
            to_complete += 1
            self.mainWidget.ui.cb_date.setStyleSheet(
                "#cb_date { border: 3px solid red; }")
        else:
            self.mainWidget.ui.cb_date.setStyleSheet("")

        if self.mainWidget.ui.cb_ville.currentIndex() < 0:
            to_complete += 1
            self.mainWidget.ui.cb_ville.setStyleSheet(
                "#cb_ville { border: 3px solid red; }")
        else:
            self.mainWidget.ui.cb_ville.setStyleSheet("")

        print self.mainWidget.ui.l_qte.text()
        if len(self.mainWidget.ui.l_qte.text()) < 1:
            to_complete += 1
            self.mainWidget.ui.l_qte.setStyleSheet(
                "#l_qte { border: 3px solid red; }")
        else:
            self.mainWidget.ui.l_qte.setStyleSheet("")

        if len(self.mainWidget.ui.l_marchandise.text()) < 1:
            to_complete += 1
            self.mainWidget.ui.l_marchandise.setStyleSheet(
                "#l_marchandise { border: 3px solid red; }")
        else:
            self.mainWidget.ui.l_marchandise.setStyleSheet("")

        if to_complete == 0:
            self.accept()

    @staticmethod
    def commandDelivery(parent, ctr, delivery=None):
        dialog = deliveryEditor(parent, ctr, delivery)
        result = dialog.exec_()
        if result == QtGui.QDialog.Accepted:
            dic = {}
            dic["date_appel"] = datetime.datetime.now().strftime("%d/%m/%Y")
            #            dic["date_charg_livr"] = dialog.mainWidget.ui.cb_jour.currentText() + '/' + dialog.mainWidget.ui.cb_date.currentText()
            dic["date_theorique"] = dialog.mainWidget.ui.cb_date.currentText()
            dic["date_charg_livr"] = dialog.mainWidget.ui.d_date_reelle.date(
            ).toString("dd/MM/yyyy")
            dic["horaire_charg_livr"] = dialog.mainWidget.ui.l_horaire.text()
            dic["quantite"] = dialog.mainWidget.ui.l_qte.text()
            dic["marchandise"] = dialog.mainWidget.ui.l_marchandise.text()
            dic["ville"] = dialog.mainWidget.ui.cb_ville.itemData(
                dialog.mainWidget.ui.cb_ville.currentIndex())
            dic["ref_client"] = dialog.mainWidget.ui.l_ref_client.text()
            dic["ref_fourniss"] = dialog.mainWidget.ui.l_ref_fourniss.text()
            dic["ref_chargement"] = dialog.mainWidget.ui.l_ref_charg.text()
            return dic
        else:
            return None

    @staticmethod
    def updateDelivery(parent, ctr, delivery):
        dialog = deliveryEditor(parent, ctr, delivery)
        result = dialog.exec_()
        if result == QtGui.QDialog.Accepted:
            #            delivery.date_charg_livr = dialog.mainWidget.ui.cb_jour.currentText()+"/"+dialog.mainWidget.ui.cb_date.currentText()
            #            from classes import Livraison
            delivery.date_theorique = dialog.mainWidget.ui.cb_date.currentText(
            )
            delivery.date_charg_livr = dialog.mainWidget.ui.d_date_reelle.date(
            ).toString("dd/MM/yyyy")
            delivery.horaire_charg_livr = dialog.mainWidget.ui.l_horaire.text()
            delivery.quantite = dialog.mainWidget.ui.l_qte.text()
            delivery.marchandise = dialog.mainWidget.ui.l_marchandise.text()
            delivery.ville = dialog.mainWidget.ui.cb_ville.itemData(
                dialog.mainWidget.ui.cb_ville.currentIndex())
            delivery.ref_client = dialog.mainWidget.ui.l_ref_client.text()
            delivery.ref_fourniss = dialog.mainWidget.ui.l_ref_fourniss.text()
            delivery.ref_chargement = dialog.mainWidget.ui.l_ref_charg.text()
            return delivery
        else:
            return None
Beispiel #16
0
class Ui_manager(QtGui.QMainWindow, QtCore.QObject):
    def __init__(self, version=0.0, parent=None):
        super(Ui_manager, self).__init__(parent)
        self.ui = Ui_Accueil()
        self.ui.setupUi(self)
        self.setWindowIcon(QtGui.QIcon('icone.png'))
        self.setWindowTitle('Gestionnaire de clientèle')
        self.ui.splitter.setHandleWidth(15)
        self.version = version

        l_ctr = QtGui.QHBoxLayout()
        scroll_ctr = QtGui.QScrollArea()
        self.ctr_manager = ContractsManager(self)
        self.w_ctr = self.ctr_manager.ui.ctr_centralwidget
        self.w_ctr.setAttribute(QtCore.Qt.WA_StyledBackground)
        self.w_ctr.setObjectName("w_ctr")
        #        self.w_ctr.adjustSize()
        scroll_ctr.setWidgetResizable(True)
        scroll_ctr.setWidget(self.w_ctr)
        #        scroll_ctr.adjustSize()
        l_ctr.addWidget(scroll_ctr)
        self.ui.f_contracts.setLayout(l_ctr)
        self.ui.f_contracts.setFrameShape(QtGui.QFrame.NoFrame)

        l_deliv = QtGui.QHBoxLayout()
        scroll_deliv = QtGui.QScrollArea()
        self.dlv_manager = DeliveryManager(self)
        self.w_dlv = self.dlv_manager.ui.dlv_centralwidget
        self.w_dlv.setAttribute(QtCore.Qt.WA_StyledBackground)
        self.w_dlv.setObjectName("w_dlv")
        scroll_deliv.setWidget(self.w_dlv)
        scroll_deliv.setWidgetResizable(True)
        l_deliv.addWidget(scroll_deliv)
        self.ui.f_deliveries.setLayout(l_deliv)
        self.updateStyle()

        self.ctr_manager.s_addDelivery.connect(self.dlv_manager.addDelivery)

        self.oil_market = Market()
        #        self.ctr_manager.FIAUpdated()
        #        self.ctr_manager.FIFUpdated()
        self.ui.actionConfig.triggered.connect(
            self.oil_market.updateConfigLanguages)
        self.ui.actionFIA.triggered.connect(self.updateFIA)
        self.ui.actionFIF.triggered.connect(self.oil_market.updateFIF)
        self.ui.menuA_propos.aboutToShow.connect(self.a_propos)

        self.showMaximized()

    def updateStyle(self):
        with open(getFromConfig("path", "stylesheet_file"), 'r') as f:
            style = f.read()
        self.setStyleSheet(style)

    def updateFIA(self):
        self.oil_market.updateFIA()
        self.ctr_manager.FIAUpdated()

    def updateFIF(self):
        self.oil_market.updateFIA()
        self.ctr_manager.FIFUpdated()

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_F5:
            self.updateStyle()
        elif event.key() == QtCore.Qt.Key_Escape:
            self.ctr_manager.t_ctr_list.clearSelection()
            self.dlv_manager.t_deliver_list.clearSelection()
        elif event.key() == QtCore.Qt.Key_Control:
            self.ctr_manager.t_ctr_list.setSelectionMode(
                QtGui.QAbstractItemView.MultiSelection)
            self.dlv_manager.t_deliver_list.setSelectionMode(
                QtGui.QAbstractItemView.MultiSelection)

    def keyReleaseEvent(self, event):
        if event.key() == QtCore.Qt.Key_Control:
            self.ctr_manager.t_ctr_list.setSelectionMode(
                QtGui.QAbstractItemView.SingleSelection)
            self.dlv_manager.t_deliver_list.setSelectionMode(
                QtGui.QAbstractItemView.SingleSelection)


#    def mouseReleaseEvent(self, event):
#        print "Ui_manager mouseReleaseEvent"

    def a_propos(self):
        #        message = "Logiciel développé par\nRaphaël Abelé\n pour\nC.Ciraud & Cie\n\nVersion: "+ str(self.version)
        about = QtGui.QMessageBox(None)
        about.setWindowFlags(QtCore.Qt.WindowSystemMenuHint
                             | QtCore.Qt.WindowTitleHint)
        about.setWindowTitle("A propos")
        about.setText(
            "<p align='center'>Logiciel développé par<br><b>Raphaël Abelé</b><br>pour<br><b>C.Giraud & Cie</b><br><br>Version : <b>"
            + str(self.version) + "</b>")
        about.exec_()

    def main(self):
        self.show()
Beispiel #17
0
class ContractIniter(QtGui.QMainWindow, QtCore.QObject):

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

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

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

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

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

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

        self.ui.tab_main.setCurrentIndex(0)

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

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

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

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

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

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

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

        if condition < 2:
            return

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

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

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

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

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

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

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

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

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

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

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

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

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

        msgBox.setDefaultButton(b_nouveau_ctr)

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

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

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

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

    def closeEvent(self, event):

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

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

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

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

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

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

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

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