示例#1
0
class FicheAchat(wx.Dialog):
    """Permet d'éditer un achat. Dialog modal"""
    def __init__(self, parent, achat=None, adherent=None):
        wx.Dialog.__init__(self, parent, style=wx.DEFAULT_DIALOG_STYLE)

        if achat == None:
            if adherent == None:
                #TODO : à modifier quand le système d'identification sera en place
                adherent = Adherent.select().where(Adherent.id == 1).get()

            achat = Achat.create(adherent=adherent)

        self.achat = achat

        self.sizer_infos_staticbox = wx.StaticBox(self, -1, "Informations")

        self.label_credit_restant = wx.StaticText(self, -1, u"Crédit restant")
        self.label_cotisation = wx.StaticText(self, -1, u"Cotisation du mois")
        self.label_cotisation_payee = wx.StaticText(self, -1,
                                                    u"- Payée le xx-xx-xx")
        self.label_total_achats = wx.StaticText(self, -1, "Total des achats")
        self.label_solde = wx.StaticText(self, -1, u"Solde après achat")
        self.label_credit_restant_valeur = wx.StaticText(self, -1, u"0.00 ¤")
        self.label_cotisation_valeur = wx.StaticText(self, -1, u"0.00 ¤")
        self.label_total_achats_valeur = wx.StaticText(self,
                                                       -1,
                                                       u"0.00 ¤",
                                                       style=wx.ALIGN_RIGHT)
        self.label_cout_supplementaire = wx.StaticText(
            self, -1, u"Coût supplémentaire")
        self.text_cout_supplementaire = wx.TextCtrl(
            self,
            -1,
            validator=GenericTextValidator(VALIDATE_FLOAT, obligatoire=False))
        self.text_cout_supplementaire_commentaire = TextCtrlDescriptive(
            self, -1, style=wx.TE_MULTILINE)
        self.label_solde_valeur = wx.StaticText(self, -1, u"0.00 ¤")

        self.sizer_liste_produits_staticbox = wx.StaticBox(
            self, -1, "Liste des produits")
        self.label_titre_achat = wx.StaticText(self, -1, "Achat pour ")
        self.search_nom = wx.SearchCtrl(self, -1, "")
        self.liste_produits = ObjectListView(self,
                                             -1,
                                             style=wx.LC_REPORT
                                             | wx.SUNKEN_BORDER)

        self.liste_produits.SetColumns([
            ColumnDefn("Ref GASE", "left", -1, "ref_GASE", minimumWidth=70),
            ColumnDefn("Nom", "left", -1, "nom", minimumWidth=100),
            ColumnDefn("Prix",
                       "right",
                       -1,
                       "prix_vente_format",
                       minimumWidth=100,
                       isSpaceFilling=True)
        ])
        self.liste_produits.SetEmptyListMsg("Aucun produits")
        self.liste_produits.AutoSizeColumns()

        self.sizer_achat_staticbox = wx.StaticBox(self, -1, "Achat")
        self.liste_lignes_achat = ObjectListView(self,
                                                 -1,
                                                 style=wx.LC_REPORT
                                                 | wx.SUNKEN_BORDER)

        self.liste_lignes_achat.SetColumns([
            ColumnDefn("Ref GASE",
                       "left",
                       -1,
                       "produit.ref_GASE",
                       minimumWidth=70),
            ColumnDefn("Nom", "left", -1, "produit.nom", minimumWidth=100),
            ColumnDefn("Prix",
                       "left",
                       -1,
                       "produit.prix_vente_format",
                       minimumWidth=100),
            ColumnDefn(u"Quantité",
                       "left",
                       -1,
                       "quantite_format",
                       minimumWidth=70),
            ColumnDefn("Total TTC",
                       "right",
                       -1,
                       "prix_total",
                       stringConverter=u"%.2f ¤",
                       minimumWidth=70,
                       isSpaceFilling=True)
        ])
        self.liste_lignes_achat.AutoSizeColumns()

        self.liste_lignes_achat.SetEmptyListMsg(u"Produits achetés")

        self.bouton_sauvegarder = wx.Button(self, wx.ID_SAVE)
        self.bouton_annuler = wx.Button(self, wx.ID_CANCEL)

        self.__set_properties()
        self.__set_tooltips()
        self.__set_values()
        self.__do_layout()

        self.bouton_sauvegarder.Bind(wx.EVT_BUTTON, self.OnSauvegarder)
        self.bouton_annuler.Bind(wx.EVT_BUTTON, self.OnClose)
        self.text_cout_supplementaire.Bind(wx.EVT_TEXT, self.OnChangeCoutSupp)
        self.search_nom.Bind(wx.EVT_TEXT, self.OnFilter)
        self.liste_produits.Bind(wx.EVT_LIST_ITEM_ACTIVATED,
                                 self.OnAjoutProduit)
        self.liste_lignes_achat.Bind(wx.EVT_LIST_ITEM_ACTIVATED,
                                     self.OnModifProduit)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

    def __set_properties(self):
        self.label_titre_achat.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.sizer_infos_staticbox.SetFont(
            wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.sizer_liste_produits_staticbox.SetFont(
            wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.sizer_achat_staticbox.SetFont(
            wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))

        font_italic = self.label_cotisation.GetFont()
        font_italic.SetStyle(wx.ITALIC)

        self.label_cotisation_payee.SetFont(font_italic)
        """self.label_credit_restant.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_cotisation.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_total_achats.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_solde.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_credit_restant_valeur.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_cotisation_valeur.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_total_achats_valeur.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_solde_valeur.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))"""

        self.text_cout_supplementaire.SetMinSize((60, -1))
        self.text_cout_supplementaire_commentaire.SetMinSize((-1, 50))
        self.label_credit_restant.SetMinSize((130, -1))
        self.search_nom.SetMinSize((200, -1))
        self.search_nom.SetDescriptiveText("Recherche sur le nom")

    def __set_tooltips(self):
        self.text_cout_supplementaire_commentaire.SetToolTip(
            wx.ToolTip(u"Description des coûts supplémentaires"))

    def __set_values(self):
        try:
            produits = Produit.select().where((Produit.retrait == False) | (
                Produit.retrait == True and Produit.stock > 0))
            self.liste_produits.SetObjects([p for p in produits])
            self.liste_produits.AutoSizeColumns()

            self.liste_lignes_achat.SetObjects(
                [la for la in self.achat.lignes_achat])

            credit_restant = self.achat.adherent.solde - self.achat.total

            self.label_credit_restant_valeur.SetLabel(u"%.2f ¤" %
                                                      credit_restant)

            if credit_restant >= 0:
                self.label_credit_restant_valeur.SetForegroundColour("#00AA00")
            else:
                self.label_credit_restant_valeur.SetForegroundColour("#DD0000")

            cotisation_du_mois = self.achat.adherent.cotisation_du_mois

            if cotisation_du_mois:
                self.label_cotisation_valeur.SetLabel("\\")
                self.label_cotisation_payee.SetLabel(
                    u"- %.2f ¤, payée le %s" %
                    (cotisation_du_mois.montant,
                     cotisation_du_mois.date.strftime("%d-%m-%Y")))
            else:
                self.label_cotisation_valeur.SetLabel(
                    u"%.2f ¤" % self.achat.adherent.cotisation_type.prix)
                self.label_cotisation_payee.Hide()

            print self.achat.cout_supplementaire
            self.text_cout_supplementaire.SetValue(
                "%.2f" % float(self.achat.cout_supplementaire))
            self.text_cout_supplementaire_commentaire.SetValue(
                self.achat.cout_supplementaire_commentaire)

            self.__update_total()

        except BaseException as ex:
            print ex

    def __do_layout(self):
        grid_sizer_infos = rcs.RowColSizer()

        grid_sizer_infos.Add(self.label_credit_restant, row=0, col=0)
        grid_sizer_infos.Add(self.label_credit_restant_valeur,
                             flag=wx.ALIGN_RIGHT,
                             row=0,
                             col=1)
        grid_sizer_infos.Add(self.label_cotisation, row=1, col=0)
        grid_sizer_infos.Add(self.label_cotisation_valeur,
                             flag=wx.ALIGN_RIGHT,
                             row=1,
                             col=1)
        grid_sizer_infos.Add(self.label_cotisation_payee,
                             row=2,
                             col=0,
                             colspan=2)
        grid_sizer_infos.Add(self.label_total_achats, row=3, col=0)
        grid_sizer_infos.Add(self.label_total_achats_valeur,
                             flag=wx.ALIGN_RIGHT,
                             row=3,
                             col=1)
        grid_sizer_infos.Add(self.label_cout_supplementaire,
                             flag=wx.ALIGN_CENTER_VERTICAL,
                             row=4,
                             col=0)
        grid_sizer_infos.Add(self.text_cout_supplementaire,
                             flag=wx.ALIGN_RIGHT,
                             row=4,
                             col=1)
        grid_sizer_infos.Add(self.text_cout_supplementaire_commentaire,
                             flag=wx.EXPAND,
                             row=5,
                             col=0,
                             colspan=2)
        grid_sizer_infos.Add(wx.StaticLine(self, style=wx.LI_HORIZONTAL),
                             flag=wx.EXPAND,
                             row=6,
                             col=0,
                             colspan=2)
        grid_sizer_infos.Add(self.label_solde, row=7, col=0)
        grid_sizer_infos.Add(self.label_solde_valeur,
                             flag=wx.ALIGN_RIGHT,
                             row=7,
                             col=1)

        sizer_infos = wx.StaticBoxSizer(self.sizer_infos_staticbox,
                                        wx.VERTICAL)
        sizer_infos.Add(grid_sizer_infos, 1, wx.ALL | wx.EXPAND, 5)

        sizer_liste_produits = wx.StaticBoxSizer(
            self.sizer_liste_produits_staticbox, wx.VERTICAL)
        sizer_liste_produits.Add(self.search_nom, 0, wx.BOTTOM, 6)
        sizer_liste_produits.Add(self.liste_produits, 1, wx.EXPAND, 0)

        sizer_infos_produits = wx.BoxSizer(wx.HORIZONTAL)
        sizer_infos_produits.Add(sizer_infos, 0, wx.EXPAND | wx.RIGHT, 5)
        sizer_infos_produits.Add(sizer_liste_produits, 1, wx.EXPAND, 0)

        sizer_achat = wx.StaticBoxSizer(self.sizer_achat_staticbox,
                                        wx.VERTICAL)
        sizer_achat.Add(self.liste_lignes_achat, 1, wx.EXPAND, 0)

        sizer_boutons = wx.BoxSizer(wx.HORIZONTAL)
        sizer_boutons.Add(self.bouton_sauvegarder, 1)
        sizer_boutons.Add((10, 10), 1, wx.EXPAND)
        sizer_boutons.Add(self.bouton_annuler, 1)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.label_titre_achat, 0, wx.BOTTOM | wx.EXPAND, 10)
        sizer.Add(sizer_infos_produits, 1, wx.TOP | wx.BOTTOM | wx.EXPAND, 5)
        sizer.Add(sizer_achat, 1, wx.EXPAND, 0)
        sizer.Add(sizer_boutons, 0, wx.TOP | wx.ALIGN_CENTER_HORIZONTAL, 6)

        sizer_dialog = wx.BoxSizer(wx.VERTICAL)
        sizer_dialog.Add(sizer, 1, wx.ALL | wx.EXPAND, 10)

        self.SetSizer(sizer_dialog)
        sizer_dialog.Fit(self)

    def __update_total(self):
        solde = self.achat.adherent.solde

        self.label_total_achats_valeur.SetLabel(u"%.2f ¤" % self.achat.total)
        self.label_solde_valeur.SetLabel(u"%.2f ¤" % solde)

        if solde >= 0:
            self.label_solde_valeur.SetForegroundColour("#00AA00")
        else:
            self.label_solde_valeur.SetForegroundColour("#DD0000")

        self.Layout()

    def GetAchat(self):
        return self.achat

    def OnChangeCoutSupp(self, event):
        try:
            #PAS FINI !!
            if self.text_cout_supplementaire.GetValue() != "":
                self.achat.cout_supplementaire = float(
                    self.text_cout_supplementaire.GetValue())
                self.text_cout_supplementaire.SetBackgroundColour(
                    wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
                self.__update_total()
        except ValueError:
            self.text_cout_supplementaire.SetBackgroundColour('#ffcccc')

    def OnFilter(self, event):
        filtre_texte = Filter.TextSearch(self.liste_produits,
                                         text=self.search_nom.GetValue())
        self.liste_produits.SetFilter(filtre_texte)
        self.liste_produits.RepopulateList()

    def OnAjoutProduit(self, event):
        deja_ajoute = False
        produit_selectionne = self.liste_produits.GetSelectedObject()

        for la_liste in self.liste_lignes_achat.GetObjects():
            if la_liste.produit.get_id() == produit_selectionne.get_id():
                deja_ajoute = True
                break

        if deja_ajoute == False:
            la = LigneAchat(achat=self.achat, produit=produit_selectionne)

            dlg = DialogChoixQuantite(la)

            if dlg.ShowModal() == wx.ID_OK:
                if dlg.GetQuantite() != 0:
                    la.quantite = dlg.GetQuantite()
                    la.save()
                    self.liste_lignes_achat.AddObject(la)
                    self.liste_lignes_achat.AutoSizeColumns()

                    #Mise à jour du total de l'achat
                    self.__update_total()

            dlg.Destroy()

    def OnModifProduit(self, event):
        la_selectionnee = self.liste_lignes_achat.GetSelectedObject()

        dlg = DialogChoixQuantite(la_selectionnee)

        id_resultat = dlg.ShowModal()

        if id_resultat == wx.ID_OK and dlg.GetQuantite() != 0:
            la_selectionnee.quantite = dlg.GetQuantite()
            la_selectionnee.save()
            self.liste_lignes_achat.RefreshObject(la_selectionnee)
            self.liste_lignes_achat.AutoSizeColumns()
        elif id_resultat == wx.ID_DELETE or dlg.GetQuantite() == 0:
            self.liste_lignes_achat.RemoveObject(la_selectionnee)
            self.liste_lignes_achat.RefreshObject(la_selectionnee)
            la_selectionnee.delete_instance()
            self.liste_lignes_achat.AutoSizeColumns()

        #Mise à jour du total de la achat
        self.__update_total()

        dlg.Destroy()

    def OnSauvegarder(self, event):
        if self.Validate():
            cotisation = self.achat.adherent.paye_cotisation_du_mois()
            cotisation.save()

            self.achat.date = datetime.today()
            if self.text_cout_supplementaire.GetValue():
                self.achat.cout_supplementaire = float(
                    self.text_cout_supplementaire.GetValue())
            else:
                self.achat.cout_supplementaire = 0
            self.achat.cout_supplementaire_commentaire = self.text_cout_supplementaire_commentaire.GetValue(
            )
            self.achat.save()
            DATABASE.commit()
            wx.MessageBox(u"L'achat a été enregistré", "Notification")
            self.EndModal(wx.ID_SAVE)

    def OnClose(self, event):
        dlg = wx.MessageDialog(parent=None,
                               message=u"Voulez vous sauvegarder cet achat ?",
                               caption=u"Sauvegarde de l'achat",
                               style=wx.YES_NO | wx.ICON_QUESTION)

        if dlg.ShowModal() == wx.ID_YES:
            self.OnSauvegarder(event)
        else:
            DATABASE.rollback()
            self.EndModal(wx.ID_CANCEL)
class GestionCommandes(wx.Panel):
    def __init__(self, *args, **kwds):
        # begin wxGlade: SuiviCommandes.__init__
        kwds["style"] = wx.TAB_TRAVERSAL
        wx.Panel.__init__(self, *args, **kwds)

        #self.sizer_navigation_staticbox = wx.StaticBox(self, -1, u"Suivi des commandes")

        self.commande = None

        self.sizer_navigation_staticbox = wx.StaticBox(self, -1, "Gestion des commandes")
        #self.sizer_liste_commandes_staticbox = wx.StaticBox(self, -1, "Liste des commandes")
        self.sizer_commande_staticbox = wx.StaticBox(self, -1, u"Détails de la Commande")
        self.button_Modifier = wx.Button(self, -1, "Modifier")
        self.button_nouvelle_commande = wx.Button(self, -1, "Faire une nouvelle commande")
        self.button_Supprimer = wx.Button(self, -1, "Supprimer")
        self.button_Imprimer = wx.Button(self, -1, "Imprimer le bon de commande")
        self.button_PDF = wx.Button(self, -1, u"Générer le bon de commande")
        self.button_Email = wx.Button(self, -1, u"Envoyer le bon de commande")
        self.button_Commandee = wx.Button(self, -1, u"Commandée")
        self.button_Livree = wx.Button(self, -1, u"Livrée")
        self.button_Verifiee = wx.Button(self, -1, u"Vérifiée")
        self.label_nom_fournisseur = wx.StaticText(self, -1, "Fournisseur :")
        self.label_montant_commande = wx.StaticText(self, -1, "Montant :")
        self.label_nom_fournisseur_valeur = wx.StaticText(self, -1, "")
        self.label_montant_commande_valeur = wx.StaticText(self, -1, "")
        self.label_date_commande = wx.StaticText(self, -1, "Date de commande :")
        self.label_date_livraison = wx.StaticText(self, -1, u"Date de réception :")
        self.label_date_commande_valeur = wx.StaticText(self, -1, "")
        self.label_date_livraison_valeur = wx.StaticText(self, -1, "")

        #self.label_suivi_commandes = wx.StaticText(self, -1, u"Suivi des commandes")

        #self.label_suivi_commandes_description = wx.StaticText(self, -1, u"C'est là qu'on gère les commandes")

        self.liste_commandes = ObjectListView(self, -1, style=wx.LC_REPORT|
                                              wx.SUNKEN_BORDER|wx.LC_SINGLE_SEL)

        self.liste_commandes.SetColumns([
            ColumnDefn("Fournisseur", "left", -1, "fournisseur.nom", minimumWidth=100),
            ColumnDefn("Date commande", "left", -1, "date_commande", stringConverter=u"%d/%m/%y", minimumWidth=130),
            ColumnDefn("Total TTC", "left", -1, "total_TTC", stringConverter=u"%.2f ¤", minimumWidth=100),
            ColumnDefn("statut", "left", -1, "statut_nom", isSpaceFilling=True, minimumWidth=100)
        ])

        def rowFormatterLC(listItem, commande):
            if commande.statut == 0:
                #C5CBFF
                listItem.SetBackgroundColour("#D8DDFF")
            elif commande.statut == 1:
                #FFA3A2
                listItem.SetBackgroundColour("#FFD3D3")
            elif commande.statut == 2:
                #E8E9A0
                listItem.SetBackgroundColour("#FBFCC8")
            elif commande.statut == 3:
                #B7D69E
                listItem.SetBackgroundColour("#E3FFCB")

        self.liste_commandes.rowFormatter = rowFormatterLC
        self.liste_commandes.AutoSizeColumns()
        self.liste_commandes.SortBy(1, False)

        self.liste_commandes.SetEmptyListMsg("Il n'y a aucune commande")

        self.liste_lignes_commande = ObjectListView(self, -1,
                                                    style=wx.LC_REPORT|wx.SUNKEN_BORDER|
                                                    wx.LC_SINGLE_SEL)

        self.__set_lignes_commandes_colonnes()

        self.liste_lignes_commande.SetEmptyListMsg("La commande ne contient aucun produit")

        self.__set_properties()
        self.__do_layout()
        self.__remplissage_liste()
        self.__affichage_boutons(-1, 0)

        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectionCommande, self.liste_commandes)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnVerifLigne, self.liste_lignes_commande)
        self.Bind(wx.EVT_BUTTON, self.OnNouvelleCommande, self.button_nouvelle_commande)
        self.Bind(wx.EVT_BUTTON, self.OnModifier, self.button_Modifier)
        self.Bind(wx.EVT_BUTTON, self.OnSupprimer, self.button_Supprimer)
        self.Bind(wx.EVT_BUTTON, self.OnImprimer, self.button_Imprimer)
        self.Bind(wx.EVT_BUTTON, self.OnPDF, self.button_PDF)
        self.Bind(wx.EVT_BUTTON, self.OnEmail, self.button_Email)
        self.Bind(wx.EVT_BUTTON, self.OnCommandee, self.button_Commandee)
        self.Bind(wx.EVT_BUTTON, self.OnLivree, self.button_Livree)
        self.Bind(wx.EVT_BUTTON, self.OnVerifiee, self.button_Verifiee)
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: SuiviCommandes.__set_properties
        self.sizer_navigation_staticbox.SetFont(wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_nom_fournisseur.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        #self.label_suivi_commandes.SetFont(wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_montant_commande.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_date_commande.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_date_livraison.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_nom_fournisseur_valeur.SetMinSize((200, -1))
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: SuiviCommandes.__do_layout
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer_titre = wx.StaticBoxSizer(self.sizer_navigation_staticbox, wx.VERTICAL)

        sizer_haut = wx.BoxSizer(wx.HORIZONTAL)
        sizer_boutons = wx.BoxSizer(wx.VERTICAL)
        #wx.StaticBoxSizer(self.sizer_liste_commandes_staticbox,wx.VERTICAL)

        sizer_bas = wx.StaticBoxSizer(self.sizer_commande_staticbox, wx.VERTICAL)

        sizer_infos_commande = wx.BoxSizer(wx.HORIZONTAL)

        sizer_col4 = wx.BoxSizer(wx.VERTICAL)
        sizer_col3 = wx.BoxSizer(wx.VERTICAL)
        sizer_col2 = wx.BoxSizer(wx.VERTICAL)
        sizer_col1 = wx.BoxSizer(wx.VERTICAL)

        #sizer.Add(self.label_suivi_commandes, 0, wx.EXPAND, 0)
        #sizer_titre.Add(self.label_suivi_commandes_description, 1, wx.TOP|wx.BOTTOM|wx.EXPAND, 5)
        sizer_titre.Add(self.button_nouvelle_commande, 0, wx.TOP|wx.BOTTOM, 5)
        sizer.Add(sizer_titre, 0, wx.EXPAND, 0)

        #sizer haut
        sizer_boutons.Add(self.button_Modifier, 0, wx.BOTTOM|wx.EXPAND, 5)
        sizer_boutons.Add(self.button_Supprimer, 0, wx.BOTTOM|wx.EXPAND, 5)
        sizer_boutons.Add(self.button_Imprimer, 0, wx.BOTTOM|wx.EXPAND, 5)
        sizer_boutons.Add(self.button_PDF, 0, wx.BOTTOM|wx.EXPAND, 5)
        sizer_boutons.Add(self.button_Email, 0, wx.BOTTOM|wx.EXPAND, 5)
        sizer_boutons.Add(self.button_Commandee, 0, wx.BOTTOM|wx.EXPAND, 5)
        sizer_boutons.Add(self.button_Livree, 0, wx.BOTTOM|wx.EXPAND, 5)
        sizer_boutons.Add(self.button_Verifiee, 0, wx.EXPAND, 0)
        sizer_boutons.Add(sizer_boutons.GetMinSize(), 0, wx.EXPAND, 0)

        sizer_haut.Add(sizer_boutons, 0, wx.RIGHT|wx.EXPAND, 10)

        sizer_haut.Add(self.liste_commandes, 1, wx.TOP|wx.EXPAND, 0)

        sizer.Add(sizer_haut, 1, wx.TOP|wx.EXPAND, 5)

        #sizer infos
        sizer_col1.Add(self.label_nom_fournisseur, 0, 0, 0)
        sizer_col1.Add((20, 10), 0, 0, 0)
        sizer_col1.Add(self.label_montant_commande, 0, 0, 0)
        sizer_infos_commande.Add(sizer_col1, 0, wx.RIGHT|wx.EXPAND, 10)
        sizer_col2.Add(self.label_nom_fournisseur_valeur, 0, 0, 0)
        sizer_col2.Add((20, 10), 0, 0, 0)
        sizer_col2.Add(self.label_montant_commande_valeur, 0, 0, 0)
        sizer_infos_commande.Add(sizer_col2, 0, wx.RIGHT|wx.EXPAND, 20)
        sizer_col3.Add(self.label_date_commande, 0, 0, 0)
        sizer_col3.Add((20, 10), 0, 0, 0)
        sizer_col3.Add(self.label_date_livraison, 0, 0, 0)
        sizer_infos_commande.Add(sizer_col3, 0, wx.RIGHT|wx.EXPAND, 10)
        sizer_col4.Add(self.label_date_commande_valeur, 0, 0, 0)
        sizer_col4.Add((20, 10), 0, 0, 0)
        sizer_col4.Add(self.label_date_livraison_valeur, 0, 0, 0)
        sizer_infos_commande.Add(sizer_col4, 0, wx.EXPAND, 0)

        sizer_bas.Add(sizer_infos_commande, 0, wx.TOP|wx.EXPAND, 5)

        sizer.Add(sizer_bas, 0, wx.TOP|wx.EXPAND, 5)

        sizer.Add(self.liste_lignes_commande, 1, wx.TOP|wx.EXPAND, 5)

        self.SetSizer(sizer)
        sizer.Fit(self)
        # end wxGlade

    def __remplissage_liste(self):
        try:
            commandes = Commande.select()

            self.liste_commandes.SetObjects([c for c in commandes])
            self.liste_commandes.AutoSizeColumns()

        except BaseException as ex:
            print ex

    def __affichage_boutons(self, statut, n_lignes):
        if statut == 0:
            self.button_Modifier.Enable()
            self.button_Supprimer.Enable()
            if n_lignes>0:
                self.button_Imprimer.Enable()
                self.button_PDF.Enable()
                self.button_Email.Enable()
                self.button_Commandee.Show()
            else:
                self.button_Imprimer.Disable()
                self.button_PDF.Disable()
                self.button_Email.Disable()
                self.button_Commandee.Hide()

            self.button_Livree.Hide()
            self.button_Verifiee.Hide()
        elif statut == 1:
            self.button_Modifier.Enable()
            self.button_Supprimer.Disable()
            self.button_Imprimer.Enable()
            self.button_PDF.Enable()
            self.button_Email.Enable()
            self.button_Commandee.Hide()
            self.button_Livree.Show()
            self.button_Verifiee.Hide()
        elif statut == 2:
            self.button_Modifier.Disable()
            self.button_Supprimer.Disable()
            self.button_Imprimer.Enable()
            self.button_PDF.Enable()
            self.button_Email.Disable()
            self.button_Commandee.Hide()
            self.button_Livree.Hide()
            self.button_Verifiee.Show()
        elif statut == 3:
            self.button_Modifier.Disable()
            self.button_Supprimer.Disable()
            self.button_Imprimer.Enable()
            self.button_PDF.Enable()
            self.button_Email.Disable()
            self.button_Commandee.Hide()
            self.button_Livree.Hide()
            self.button_Verifiee.Hide()
        else:
            self.button_Modifier.Disable()
            self.button_Supprimer.Disable()
            self.button_Imprimer.Disable()
            self.button_PDF.Disable()
            self.button_Email.Disable()
            self.button_Commandee.Hide()
            self.button_Livree.Hide()
            self.button_Verifiee.Hide()

        self.Layout()

    def __set_lignes_commandes_colonnes(self):
        if self.commande:
            if self.commande.statut >= 2:

                def rowFormatter(listItem, lc):
                    if lc.is_verifiee:
                        if lc.quantite_livree != lc.quantite_commandee:
                            listItem.SetBackgroundColour("#FFD3D3")
                        else:
                            listItem.SetBackgroundColour("#E3FFCB")

                self.liste_lignes_commande.rowFormatter = rowFormatter

                self.liste_lignes_commande.SetColumns([
                    ColumnDefn("Ref Fournisseur", "left", -1, "produit.ref_fournisseur", minimumWidth=120),
                    ColumnDefn("Nom", "left", -1, "produit.nom", minimumWidth=200),
                    ColumnDefn(u"Quantité commandée", "left", -1, "quantite_commandee_conditionnement", minimumWidth=200),
                    ColumnDefn(u"Quantité livrée", "left", -1, "quantite_livree_conditionnement", minimumWidth=200, isSpaceFilling=True),
                    ])
                self.liste_lignes_commande.AutoSizeColumns()
            else:
                self.liste_lignes_commande.SetColumns([
                    ColumnDefn("Ref Fournisseur", "left", -1, "produit.ref_fournisseur", minimumWidth=120),
                    ColumnDefn("Nom", "left", -1, "produit.nom", minimumWidth=200),
                    ColumnDefn(u"Quantité commandée", "left", -1, "quantite_commandee_conditionnement", minimumWidth=150),
                    ColumnDefn("Total TTC", "right", -1, "prix_total_commande_ttc", stringConverter=u"%s ¤", isSpaceFilling=True, minimumWidth=100)
                    ])
                self.liste_lignes_commande.AutoSizeColumns()

    def OnSelectionCommande(self, event):
        self.commande = self.liste_commandes.GetSelectedObject()

        if self.commande:
            self.liste_lignes_commande.SetObjects([lc for lc in self.commande.lignes_commande])
            self.__set_lignes_commandes_colonnes()
            self.label_nom_fournisseur_valeur.SetLabel(self.commande.fournisseur.nom)

            if self.commande.statut > 1:
                self.label_montant_commande_valeur.SetLabel(u"%.2f ¤" % self.commande.total_livraison_TTC())
            else:
                self.label_montant_commande_valeur.SetLabel(u"%.2f ¤" % self.commande.total_commande_TTC())

            self.label_date_commande_valeur.SetLabel(self.commande.date_commande_format())
            self.label_date_livraison_valeur.SetLabel(self.commande.date_livraison_format())
            self.__affichage_boutons(self.commande.statut, self.commande.lignes_commande.count())

            if self.commande.fournisseur.email == "":
                self.button_Email.Disable()

        else:
            self.liste_lignes_commande.SetObjects(None)
            self.label_nom_fournisseur_valeur.SetLabel("")
            self.label_montant_commande_valeur.SetLabel("")
            self.label_date_commande_valeur.SetLabel("")
            self.label_date_livraison_valeur.SetLabel("")
            self.__affichage_boutons(-1, 0)

    def OnVerifLigne(self, event):
        if self.commande.statut == 2:
            lc_selectionne = self.liste_lignes_commande.GetSelectedObject()

            if lc_selectionne.produit.vrac:
                label_u = lc_selectionne.produit.conditionnement_format(majuscule=False)
                quantite = lc_selectionne.quantite_livree / lc_selectionne.produit.poids_volume
            else:
                label_u = u"unité(s)"
                quantite = lc_selectionne.quantite_livree

            dlg = ChoixQuantite("", label_u, quantite=quantite, validator=GenericTextValidator(flag=VALIDATE_INT))

            id_resultat = dlg.ShowModal()

            if id_resultat == wx.ID_OK:
                lc_selectionne.is_verifiee = True
                lc_selectionne.quantite_livree = dlg.GetValue()
                self.liste_lignes_commande.RefreshObject(lc_selectionne)

            elif id_resultat == wx.ID_DELETE:
                lc_selectionne.is_verifiee = True
                lc_selectionne.quantite_livree = 0
                self.liste_lignes_commande.RefreshObject(lc_selectionne)

            dlg.Destroy()

    def OnNouvelleCommande(self, event):
        nouvelle_commande = NouvelleCommande(self.GetTopLevelParent())
        nouvelle_commande.ShowModal()

    def OnModifier(self, event):
        if self.commande:
            if self.commande.statut < 2:
                ecranprincipal = self.GetTopLevelParent()
                ecranprincipal.SetPanelPrincipal(FicheCommande, session_close=False, commande=self.commande)

    def OnSupprimer(self, event):
        if self.commande:
            if self.commande.statut == 0:
                dlg = wx.MessageDialog(parent=None, message=u"Voulez vous vraiment supprimer la commande ?",
                                       caption=u"Suppression de la commande", style=wx.OK|wx.CANCEL|wx.ICON_QUESTION)

                if dlg.ShowModal() == wx.ID_OK:
                    self.liste_commandes.RemoveObject(self.commande)
                    self.liste_lignes_commande.SetObjects(None)

                    self.commande.delete_instance(recursive=True)

                    self.commande = None

                    self.OnSelectionCommande(None)

                    DATABASE.commit()

    def OnPDF(self, event):
        if self.commande:

            if not self.commande.date_commande:
                nom_fichier = self.commande.fournisseur.nom + " - Bon de commande du " + datetime.today().strftime("%d-%m-%Y") + ".pdf"
            else:
                nom_fichier = self.commande.fournisseur.nom + " - Bon de commande du " + self.commande.date_commande_format() + ".pdf"

            dlg = wx.FileDialog(
                self, message="Sauvegarde du bon de commande ...",
                defaultDir="",
                defaultFile=nom_fichier, wildcard="PDF (*.pdf)|*.pdf", style=wx.SAVE
                )

            if dlg.ShowModal() == wx.ID_OK:
                chemin = dlg.GetPath()
                self.commande.genere_PDF(chemin)

            dlg.Destroy()

    def OnEmail(self, event):
        if self.commande:
            if self.commande.statut < 2:
                envoi_email = EnvoiEmailCommande(self, self.commande)
                envoi_email.ShowModal()
                envoi_email.Destroy()

                if envoi_email.ShowModal() == wx.ID_OK:
                    self.commande.statut(1)
                    self.commande.save()
                    self.liste_commandes.RefreshObject(self.commande)
                    self.OnSelectionCommande(None)

                    DATABASE.commit()

    def OnImprimer(self, event):
        if self.commande:
            self.commande.genere_PDF(os.getcwd() + "/dernier_bon_imprime.pdf")

            '''if sys.platform.startswith('linux'):
			    subprocess.call(["xdg-open", os.getcwd() + "/dernier_bon_imprime.pdf"])
            else:
                os.startfile(file)'''

            desktop.open(os.getcwd() + "/dernier_bon_imprime.pdf")

            '''preview_pdf = PreviewPDF(os.getcwd() + "/dernier_bon_imprime.pdf")
            preview_pdf.ShowModal()
            preview_pdf.Destroy()'''

    def OnCommandee(self, event):
        if self.commande:
            dlg = wx.MessageDialog(parent=None, message=u"La commande a bien été commandée ?",
                                   caption=u"Commande de la commande", style=wx.YES_NO|wx.ICON_QUESTION)

            if dlg.ShowModal() == wx.ID_YES:
                self.commande.statut = 1
                self.commande.save()
                self.liste_commandes.RefreshObject(self.commande)
                self.OnSelectionCommande(None)
                DATABASE.commit()

            dlg.Destroy()

    def OnLivree(self, event):
        #TODO : ajouter la possibilité de choisir la date de livraison
        #Ajouter également une vérification sur les prix
        if self.commande:
            dlg = wx.MessageDialog(parent=None, message=u"La commande a bien été livrée ?",
                                   caption=u"Livraison de la commande", style=wx.YES_NO|wx.ICON_QUESTION)

            if dlg.ShowModal() == wx.ID_YES:
                self.commande.statut = 2
                self.commande.save()
                self.liste_commandes.RefreshObject(self.commande)
                self.OnSelectionCommande(None)
                DATABASE.commit()

            dlg.Destroy()

    def OnVerifiee(self, event):
        if self.commande:
            commande_verifiee = True

            for lc in self.liste_lignes_commande.GetObjects():
                if not lc.is_verifiee:
                    commande_verifiee = False

            if commande_verifiee:
                dlg = wx.MessageDialog(parent=None, message=u"La livraison a bien été vérifiée ?",
                                      caption=u"Vérification de la livraison", style=wx.YES_NO|wx.ICON_QUESTION)

                if dlg.ShowModal() == wx.ID_YES:
                    for lc in self.liste_lignes_commande.GetObjects():
                        lc.save()
                        
                    self.commande.statut = 3
                    self.commande.save()

                    self.liste_commandes.RefreshObject(self.commande)
                    self.OnSelectionCommande(None)

                    with DATABASE.transaction():
                        DATABASE.commit()

                dlg.Destroy()
            else:
                wx.MessageBox(u"La livraison n'a pas encoré été entièrement vérifiée", "Erreur", style=wx.ICON_ERROR)
示例#3
0
class GestionProduits(wx.Panel):
    def __init__(self, *args, **kwds):
        # begin wxGlade: GestionProduits.__init__
        kwds["style"] = wx.TAB_TRAVERSAL
        wx.Panel.__init__(self, *args, **kwds)
        self.sizer_navigation_staticbox = wx.StaticBox(self, -1, "Gestion des produits")
        self.label_Fournisseur = wx.StaticText(self, -1, "Fournisseur :")
        self.combo_box_Fournisseur = wx.ComboBox(self, -1,
                                                 choices=[], style=wx.CB_DROPDOWN|wx.CB_READONLY)
        self.label_RechercheNom = wx.StaticText(self, -1, "Recherche sur le nom :")
        self.text_ctrl_RechercheNom = wx.TextCtrl(self, -1, "")
        self.button_AjoutProduit = wx.Button(self, -1, "Ajouter un nouveau produit")
        self.button_ImpressionEtiquettes = wx.Button(self, -1,
                                                     u"Imprimer les étiquettes des produits cochés")
        self.liste_produits = ObjectListView(self, -1,
                                             style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_SINGLE_SEL)



        self.liste_produits.SetColumns([
            ColumnDefn("Ref GASE", "left", -1, "ref_GASE",
                       checkStateGetter="a_etiquetter", fixedWidth=90),
            ColumnDefn("Nom", "left", -1, "nom"),
            ColumnDefn("Fournisseur", "left", -1, "fournisseur.nom", minimumWidth=100),
            ColumnDefn("Prix de vente", "left", -1, "prix_vente_format", minimumWidth=120),
            ColumnDefn("Stock", "left", 100,
                       "stock_format",
                       stringConverter="%s",
                       isSpaceFilling=True, minimumWidth=100)
        ])

        def RFListeProduits(listItem, produit):
            if produit.retrait:
                listItem.SetTextColour("#AAAAAA")
            else:
                listItem.SetTextColour("#000000")

        self.liste_produits.rowFormatter = RFListeProduits

        self.__set_properties()
        self.__do_layout()
        self.__remplissage_liste()
        self.liste_produits.SetSortColumn(0, True)

        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnEditionProduit, self.liste_produits)
        self.Bind(wx.EVT_COMBOBOX, self.OnFilter, self.combo_box_Fournisseur)
        self.Bind(wx.EVT_TEXT, self.OnFilter, self.text_ctrl_RechercheNom)
        self.Bind(wx.EVT_BUTTON, self.OnAjoutProduit, self.button_AjoutProduit)
        self.Bind(wx.EVT_BUTTON, self.OnImpressionEtiquettes, self.button_ImpressionEtiquettes)
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: GestionProduits.__set_properties
        self.sizer_navigation_staticbox.SetFont(wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_Fournisseur.SetMinSize((200, -1))
        self.label_Fournisseur.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, ""))
        self.combo_box_Fournisseur.SetMinSize((200, -1))
        self.label_RechercheNom.SetMinSize((200, -1))
        self.label_RechercheNom.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, ""))
        self.text_ctrl_RechercheNom.SetMinSize((200, -1))
        # end wxGlade

    def __do_layout(self):
        grid_sizer = wx.FlexGridSizer(2, 2, 4, 0)
        grid_sizer.Add(self.label_Fournisseur, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer.Add(self.combo_box_Fournisseur, 0, 0, 0)
        grid_sizer.Add(self.label_RechercheNom, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer.Add(self.text_ctrl_RechercheNom, 0, 0, 0)

        sizer_boutons = wx.BoxSizer(wx.VERTICAL)
        sizer_boutons.Add(self.button_AjoutProduit, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT|wx.EXPAND, 5)
        sizer_boutons.Add(self.button_ImpressionEtiquettes, 0, wx.TOP|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, 5)

        sizer_header = wx.StaticBoxSizer(self.sizer_navigation_staticbox, wx.HORIZONTAL)
        sizer_header.Add(grid_sizer, 0, wx.TOP, 5)
        sizer_header.Add((20, 20), 1, wx.TOP|wx.EXPAND, 5)
        sizer_header.Add(sizer_boutons, 0, wx.TOP|wx.ALIGN_CENTER_VERTICAL, 5)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(sizer_header, 0, wx.EXPAND, 0)
        sizer.Add(self.liste_produits, 1, wx.TOP|wx.EXPAND, 10)
        self.SetSizer(sizer)
        sizer.Fit(self)
        # end wxGlade

    def __remplissage_liste(self):
        try:
            self.liste_produits.SetObjects([p for p in Produit.select()])
            self.combo_box_Fournisseur.Append("Tous", 0)

            fournisseurs = [f for f in Fournisseur.select().order_by(Fournisseur.nom.asc())]

            for fournisseur in fournisseurs:
                self.combo_box_Fournisseur.Append(fournisseur.nom, fournisseur.get_id())

            self.combo_box_Fournisseur.Select(0)

        except BaseException as ex:
            print ex

    def OnAjoutProduit(self, event):
        dialog_produit = wx.Dialog(self, title=u"Nouveau produit")
        fiche_produit = FicheProduit(dialog_produit)
        dialog_produit.Fit()
        dialog_produit.ShowModal()
        dialog_produit.Destroy()

        if dialog_produit.GetReturnCode() == wx.ID_OK:
            self.liste_produits.AddObject(fiche_produit.produit)
            self.liste_produits.AutoSizeColumns()

    def OnEditionProduit(self, event):
        produit = self.liste_produits.GetSelectedObject()

        dialog_produit = wx.Dialog(self, title=u"Produit : " + produit.nom)
        FicheProduit(dialog_produit, produit)
        dialog_produit.Fit()
        dialog_produit.ShowModal()
        dialog_produit.Destroy()

        if dialog_produit.GetReturnCode() == wx.ID_OK:
            self.liste_produits.RefreshObject(self.liste_produits.GetSelectedObject())
            self.liste_produits.AutoSizeColumns()

    def OnImpressionEtiquettes(self, event):
        lst = []
        ligne_etiquettes = []
        tableau_etiquettes = []
        tableau_style = []
        hauteurs_lignes = []

        tableau_style.append(('VALIGN', (0, 0), (-1, -1), 'MIDDLE'))
        tableau_style.append(('TOPPADDING', (0, 0), (-1, -1), 0))
        tableau_style.append(('BOTTOMPADDING', (0, 0), (-1, -1), 0))
        tableau_style.append(('LEFTPADDING', (0, 0), (-1, -1), 2))
        tableau_style.append(('RIGHTPADDING', (0, 0), (-1, -1), 2))
        tableau_style.append(('BOX', (0, 0), (-1, -1), 2, colors.black))
        tableau_style.append(('INNERGRID', (0, 0), (-1, -1), 2, colors.black))

        n_produit = 0

        ref_style = ParagraphStyle('RefProduit', alignment=TA_CENTER, leading=16, fontName='Helvetica-Bold', fontSize=14)
        nom_style = ParagraphStyle('NomProduit', alignment=TA_CENTER, leading=16, fontName='Helvetica-Bold', fontSize=12)
        prix_style = ParagraphStyle('PrixProduit', alignment=TA_CENTER, leading=16, fontName='Helvetica-Bold', fontSize=14)

        liste_produits_etiquettes = []

        for produit in self.liste_produits.GetObjects():
            if produit.a_etiquetter:
                n_produit += 1

                if n_produit%2 == 0:
                    x = 3
                else:
                    x = 0

                y = (n_produit-1)/2

                ligne_etiquettes.append(Paragraph(produit.ref_GASE, ref_style))
                ligne_etiquettes.append(Paragraph(produit.nom, nom_style))

                ligne_etiquettes.append(Paragraph(produit.prix_vente_format, prix_style))

                tableau_style.append(('BACKGROUND',
                                      (x, y), (x+2, y),
                                      produit.fournisseur.couleur))

                if n_produit%2 == 0:
                    tableau_etiquettes.append(ligne_etiquettes)
                    hauteurs_lignes.append(2*cm)
                    ligne_etiquettes = []

                produit.a_etiquetter = False
                liste_produits_etiquettes.append(produit)

        #Si aucun produit n'est selectionnee on ne continue pas
        if n_produit > 0:
            if n_produit%2 != 0:
                ligne_etiquettes.append("")
                ligne_etiquettes.append("")
                ligne_etiquettes.append("")
                tableau_etiquettes.append(ligne_etiquettes)
                hauteurs_lignes.append(2*cm)

            table_etiquettes = Table(tableau_etiquettes,
                                     colWidths=[2*cm, 5.5*cm, 2*cm, 2*cm, 5.5*cm, 2*cm],
                                     rowHeights=hauteurs_lignes)
            table_etiquettes.setStyle(TableStyle(tableau_style))

            lst.append(table_etiquettes)

            #Création des répertoires si ils n'existent pas
            rep = os.path.dirname(os.getcwd() + "/Etiquettes/")

            if not os.path.exists(rep):
                os.makedirs(rep)

            date_jour = datetime.now()

            chemin_fichier = os.path.join(rep, "Etiquettes - " + date_jour.strftime("%d-%m-%Y %H-%M-%S") + ".pdf")

            doc = SimpleDocTemplate(chemin_fichier, title="Etiquettes - " + date_jour.strftime("%d-%m-%Y %H-%M-%S"), pagesize=A4, topMargin=2*cm, bottomMargin=2*cm, leftMargin=1.5*cm, rightMargin=1.5*cm)

            doc.build(lst)

            #session.commit()
            self.liste_produits.RefreshObjects(self.liste_produits.GetObjects())

            '''preview_pdf = PreviewPDF(chemin_fichier)
            preview_pdf.ShowModal()
            preview_pdf.Destroy()'''

            desktop.open(chemin_fichier)

            try:
                for p in liste_produits_etiquettes:
                    p.save()

                DATABASE.commit()
            except:
                DATABASE.rollback()

    def OnFilter(self, event):
        filtre_texte = Filter.TextSearch(self.liste_produits, text=self.text_ctrl_RechercheNom.GetValue())

        pk_fournisseur = self.combo_box_Fournisseur.GetClientData(self.combo_box_Fournisseur.GetSelection())

        if pk_fournisseur != 0:
            filtre_fournisseur = Filter.Predicate(lambda x: x.fournisseur.get_id() == pk_fournisseur)
            self.liste_produits.SetFilter(Filter.Chain(filtre_texte, filtre_fournisseur))
        else:
            self.liste_produits.SetFilter(filtre_texte)

        self.liste_produits.RepopulateList()
        event.Skip()
示例#4
0
class GestionFournisseurs(wx.Panel):
    def __init__(self, *args, **kwds):
        # begin wxGlade: GestionFournisseurs.__init__
        kwds["style"] = wx.TAB_TRAVERSAL
        wx.Panel.__init__(self, *args, **kwds)
        self.sizer_navigation_staticbox = wx.StaticBox(
            self, -1, "Gestion des fournisseurs")
        self.button_ajout_fournisseur = wx.Button(
            self, -1, "Ajouter un nouveau fournisseur")
        self.button_tableau_fournisseur = wx.Button(
            self, -1, u"Générer la liste des fournisseurs")
        self.liste_fournisseurs = ObjectListView(
            self, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_SINGLE_SEL)

        self.liste_fournisseurs.SetColumns([
            ColumnDefn("Nom",
                       "left",
                       -1,
                       "nom",
                       imageGetter=self.IconeCouleurDef),
            ColumnDefn("Code postal",
                       "center",
                       -1,
                       "code_postal",
                       fixedWidth=90),
            ColumnDefn("Ville", "left", -1, "ville"),
            ColumnDefn(u"Tel fixe",
                       "left",
                       -1,
                       "telephone_fixe",
                       minimumWidth=100),
            ColumnDefn(u"Tel portable",
                       "left",
                       -1,
                       "telephone_portable",
                       minimumWidth=100),
            ColumnDefn(u"Nb référents",
                       "right",
                       100,
                       "referents.count",
                       isSpaceFilling=True,
                       minimumWidth=100)
        ])

        self.__set_properties()
        self.__do_layout()
        self.__remplissage_liste()

        self.Bind(wx.EVT_BUTTON, self.OnAjoutFournisseur,
                  self.button_ajout_fournisseur)
        self.Bind(wx.EVT_BUTTON, self.OnGenereTableauFournisseur,
                  self.button_tableau_fournisseur)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnModifFournisseur,
                  self.liste_fournisseurs)
        # end wxGlade

    def __set_properties(self):
        self.sizer_navigation_staticbox.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))

    def __do_layout(self):
        sizer_entete = wx.StaticBoxSizer(self.sizer_navigation_staticbox,
                                         wx.HORIZONTAL)
        sizer_entete.Add(self.button_tableau_fournisseur, 0,
                         wx.BOTTOM | wx.TOP | wx.ALIGN_LEFT, 5)
        sizer_entete.Add((1, 1), 1)
        sizer_entete.Add(self.button_ajout_fournisseur, 0,
                         wx.BOTTOM | wx.TOP | wx.ALIGN_RIGHT, 5)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(sizer_entete, 0, wx.BOTTOM | wx.EXPAND, 10)
        sizer.Add(self.liste_fournisseurs, 1, wx.EXPAND, 0)
        self.SetSizer(sizer)
        sizer.Fit(self)

    def __remplissage_liste(self):
        try:
            self.liste_fournisseurs.SetObjects(
                [f for f in Fournisseur.select()])
        except BaseException as ex:
            print ex

    def IconeCouleurDef(self, fournisseur):
        return self.liste_fournisseurs.AddImages(
            self.IconeCouleur16(fournisseur.couleur),
            self.IconeCouleur32(fournisseur.couleur))

    def IconeCouleur16(self, couleurHex):
        couleur_data = wx.Colour()
        couleur_data.SetFromString(couleurHex)
        return wx.EmptyBitmapRGBA(16, 16, couleur_data.Red(),
                                  couleur_data.Green(), couleur_data.Blue(),
                                  couleur_data.Alpha())

    def IconeCouleur32(self, couleurHex):
        couleur_data = wx.Colour()
        couleur_data.SetFromString(couleurHex)
        return wx.EmptyBitmapRGBA(32, 32, couleur_data.Red(),
                                  couleur_data.Green(), couleur_data.Blue(),
                                  couleur_data.Alpha())

    def OnAjoutFournisseur(self, event):
        dialog_fournisseur = wx.Dialog(self, title=u"Nouveau fournisseur")
        fiche_fournisseur = FicheFournisseur(dialog_fournisseur)
        dialog_fournisseur.Fit()
        dialog_fournisseur.ShowModal()
        dialog_fournisseur.Destroy()

        if dialog_fournisseur.GetReturnCode() == wx.ID_OK:
            self.liste_fournisseurs.AddObject(fiche_fournisseur.fournisseur)
            self.liste_fournisseurs.AutoSizeColumns()

    def OnModifFournisseur(self, event):
        fournisseur = self.liste_fournisseurs.GetSelectedObject()

        dialog_fournisseur = wx.Dialog(self,
                                       title=u"Fournisseur : " +
                                       fournisseur.nom)
        FicheFournisseur(dialog_fournisseur, fournisseur)
        dialog_fournisseur.Fit()
        dialog_fournisseur.ShowModal()
        dialog_fournisseur.Destroy()

        if dialog_fournisseur.GetReturnCode() == wx.ID_OK:
            self.liste_fournisseurs.RefreshObject(
                self.liste_fournisseurs.GetSelectedObject())
            self.liste_fournisseurs.AutoSizeColumns()

    def OnGenereTableauFournisseur(self, event):
        lst = []
        tableau = []
        tableau_style = []
        hauteurs_lignes = []

        tableau_style.append(('FONTSIZE', (0, 0), (-1, -1), 16))
        tableau_style.append(('FONTNAME', (0, 0), (-1, -1), 'Helvetica-Bold'))
        tableau_style.append(('VALIGN', (0, 0), (-1, -1), 'MIDDLE'))
        tableau_style.append(('TOPPADDING', (0, 0), (-1, -1), 0))
        tableau_style.append(('BOTTOMPADDING', (0, 0), (-1, -1), 0))
        tableau_style.append(('LEADING', (0, 0), (-1, -1), 20))

        for fournisseur in self.liste_fournisseurs.GetObjects():
            tableau.append([fournisseur.nom])
            i = len(tableau) - 1
            tableau_style.append(
                ('BACKGROUND', (0, i), (1, i), fournisseur.couleur))
            tableau_style.append(('BOX', (0, i), (1, i), 1, colors.black))
            tableau_style.append(
                ('INNERGRID', (0, i), (1, i), 1, colors.black))
            hauteurs_lignes.append(1 * cm)

            #Ajout du blanc
            tableau.append([""])
            i = len(tableau) - 1
            tableau_style.append(('BACKGROUND', (0, i), (1, i), colors.white))
            hauteurs_lignes.append(0.5 * cm)

        tableau_fournisseurs = Table(tableau, rowHeights=hauteurs_lignes)
        tableau_fournisseurs.setStyle(TableStyle(tableau_style))

        titre_style = ParagraphStyle('Titre',
                                     alignment=TA_CENTER,
                                     leading=40,
                                     fontName='Helvetica-Bold',
                                     fontSize=20)

        lst.append(Paragraph(u"Liste des fournisseurs", titre_style))
        lst.append(tableau_fournisseurs)

        rep = os.path.dirname(os.getcwd() + "/Fournisseurs/")

        if not os.path.exists(rep):
            os.makedirs(rep)

        chemin_fichier = os.path.join(rep, "Liste des fournisseurs.pdf")

        doc = SimpleDocTemplate(chemin_fichier,
                                title="Liste des fournisseurs",
                                pagesize=A4,
                                topMargin=2 * cm,
                                bottomMargin=2 * cm,
                                leftMargin=1.5 * cm,
                                rightMargin=1.5 * cm)

        doc.build(lst)
        '''pdfviewer = PreviewPDF(os.path.join(dir, "Liste des fournisseurs.pdf"))
        pdfviewer.ShowModal()
        pdfviewer.Destroy()   '''

        desktop.open(chemin_fichier)
示例#5
0
class FicheCommande(wx.Panel):
    def __init__(self, parent, commande=None):
        wx.Panel.__init__(self, parent, style=wx.TAB_TRAVERSAL)

        if commande == None:
            commande = Commande.create()

        self.commande = commande

        self.sizer_commande_staticbox = wx.StaticBox(self, -1, "Commande")
        self.sizer_fournisseur_produits_staticbox = wx.StaticBox(
            self, -1, "Liste des produits")
        self.label_titre_commande = wx.StaticText(self, -1, "Commande pour ")
        self.bouton_infos_fournisseur = wx.Button(
            self, -1, "Afficher les infos du fournisseur")
        self.label_date_commande = wx.StaticText(self, -1,
                                                 "Date de la commande :")
        self.datepicker_date_commande = wx.DatePickerCtrl(self, -1)
        self.label_FiltreRecherche = wx.StaticText(self, -1,
                                                   "Recherche sur le nom :")
        self.text_ctrl_FiltreRecherche = wx.TextCtrl(self, -1, "")
        self.liste_produits = ObjectListView(self,
                                             -1,
                                             style=wx.LC_REPORT
                                             | wx.SUNKEN_BORDER)
        self.label_total = wx.StaticText(self, -1, "Total de la commande :")
        self.label_total_valeur = wx.StaticText(self,
                                                -1,
                                                u"0.00 ¤",
                                                style=wx.ALIGN_RIGHT)
        self.liste_lignes_commande = ObjectListView(self,
                                                    -1,
                                                    style=wx.LC_REPORT
                                                    | wx.SUNKEN_BORDER)
        self.bouton_Sauvegarder = wx.Button(self, -1,
                                            "Enregistrer la commande")

        self.liste_produits.SetColumns([
            ColumnDefn("Ref GASE", "left", -1, "ref_GASE", minimumWidth=100),
            ColumnDefn("Nom", "left", -1, "nom", minimumWidth=100),
            ColumnDefn("Prix TTC",
                       "right",
                       -1,
                       "prix_achat_TTC",
                       stringConverter=u"%.2f ¤",
                       minimumWidth=100),
            ColumnDefn("Conditionnement",
                       "left",
                       -1,
                       "conditionnement_format",
                       isSpaceFilling=True,
                       minimumWidth=200)
        ])
        self.liste_produits.SetEmptyListMsg("Ce fournisseur n'a aucun produit")
        self.liste_produits.AutoSizeColumns()

        self.liste_lignes_commande.SetColumns([
            ColumnDefn("Ref Fournisseur",
                       "left",
                       -1,
                       "produit.ref_fournisseur",
                       minimumWidth=120),
            ColumnDefn("Nom", "left", -1, "produit.nom", minimumWidth=100),
            ColumnDefn(u"Quantité",
                       "left",
                       -1,
                       "quantite_commandee_conditionnement",
                       minimumWidth=150),
            ColumnDefn("Total TTC",
                       "right",
                       -1,
                       "prix_total_commande_ttc",
                       stringConverter=u"%s ¤",
                       isSpaceFilling=True,
                       minimumWidth=100)
        ])
        self.liste_lignes_commande.AutoSizeColumns()

        self.liste_lignes_commande.SetEmptyListMsg(
            "La commande ne contient aucun produit")

        self.__set_properties()
        self.__set_values()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.OnInfosFournisseur,
                  self.bouton_infos_fournisseur)
        self.Bind(wx.EVT_BUTTON, self.OnSauvegarder, self.bouton_Sauvegarder)
        self.Bind(wx.EVT_TEXT, self.OnFilter, self.text_ctrl_FiltreRecherche)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnAjoutProduit,
                  self.liste_produits)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnModifProduit,
                  self.liste_lignes_commande)
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: NouvelleCommande.__set_properties
        self.label_titre_commande.SetFont(
            wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.sizer_fournisseur_produits_staticbox.SetFont(
            wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.label_total.SetFont(
            wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.sizer_commande_staticbox.SetFont(
            wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.text_ctrl_FiltreRecherche.SetMinSize((200, -1))
        # end wxGlade

    def __set_values(self):
        if self.commande.fournisseur:
            self.SetFournisseur(self.commande.fournisseur)

            date = wx.DateTime()
            date.Set(self.commande.date_commande.day,
                     self.commande.date_commande.month - 1,
                     self.commande.date_commande.year)
            self.datepicker_date_commande.SetValue(date)

            self.liste_lignes_commande.SetObjects(
                [lc for lc in self.commande.lignes_commande])
            self.label_total_valeur.SetLabel(
                u"%.2f ¤" % self.commande.total_commande_TTC())

    def __do_layout(self):
        # begin wxGlade: NouvelleCommande.__do_layout
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer_boutons = wx.BoxSizer(wx.HORIZONTAL)
        sizer_entete = wx.BoxSizer(wx.HORIZONTAL)
        sizer_date_commande = wx.BoxSizer(wx.HORIZONTAL)
        sizer_commande = wx.StaticBoxSizer(self.sizer_commande_staticbox,
                                           wx.VERTICAL)
        sizer_fournisseur_produits = wx.StaticBoxSizer(
            self.sizer_fournisseur_produits_staticbox, wx.HORIZONTAL)
        sizer_ligne_total = wx.BoxSizer(wx.HORIZONTAL)
        sizer_liste_produits = wx.BoxSizer(wx.VERTICAL)
        sizer_fitre_recherche = wx.BoxSizer(wx.HORIZONTAL)

        sizer_entete.Add(self.label_titre_commande, 1, wx.EXPAND, 0)
        sizer_entete.Add(self.bouton_infos_fournisseur, 0, wx.EXPAND, 0)
        sizer.Add(sizer_entete, 0, wx.TOP | wx.BOTTOM | wx.EXPAND, 10)

        sizer_date_commande.Add(self.label_date_commande, 0,
                                wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 6)
        sizer_date_commande.Add(self.datepicker_date_commande, 0, 0, 0)
        sizer.Add(sizer_date_commande, 0, wx.EXPAND, 0)

        sizer_fitre_recherche.Add(self.label_FiltreRecherche, 0,
                                  wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 6)
        sizer_fitre_recherche.Add(self.text_ctrl_FiltreRecherche, 0, 0, 0)
        sizer_liste_produits.Add(sizer_fitre_recherche, 0,
                                 wx.BOTTOM | wx.EXPAND, 6)
        sizer_liste_produits.Add(self.liste_produits, 1, wx.EXPAND, 0)
        sizer_fournisseur_produits.Add(sizer_liste_produits, 1, wx.EXPAND, 0)
        sizer.Add(sizer_fournisseur_produits, 1, wx.TOP | wx.EXPAND, 10)

        sizer_ligne_total.Add(self.label_total, 0, wx.EXPAND | wx.RIGHT, 20)
        sizer_ligne_total.Add(self.label_total_valeur, 0, wx.ALIGN_RIGHT, 0)

        sizer_commande.Add(sizer_ligne_total, 0, wx.ALIGN_RIGHT | wx.BOTTOM, 6)
        sizer_commande.Add(self.liste_lignes_commande, 1, wx.EXPAND, 0)
        sizer.Add(sizer_commande, 1, wx.EXPAND, 0)

        sizer_boutons.Add(self.bouton_Sauvegarder, 0, 0, 0)
        sizer.Add(sizer_boutons, 0, wx.TOP | wx.ALIGN_CENTER_HORIZONTAL, 6)
        self.SetSizer(sizer)
        sizer.Fit(self)
        # end wxGlade

    def __update_total(self):
        self.label_total_valeur.SetLabel(u"%.2f ¤" %
                                         self.commande.total_commande_TTC())
        self.Layout()

    def SetFournisseur(self, fournisseur):
        self.commande.fournisseur = fournisseur

        self.label_titre_commande.SetLabel("Commande pour " +
                                           self.commande.fournisseur.nom)

        try:
            produits = Produit.select().where(
                (Produit.fournisseur == fournisseur)
                & (Produit.retrait == False))
            self.liste_produits.SetObjects([p for p in produits])
            self.liste_produits.AutoSizeColumns()

        except BaseException as ex:
            print ex

        self.Layout()

    def OnFilter(self, event):
        filtre_texte = Filter.TextSearch(
            self.liste_produits,
            text=self.text_ctrl_FiltreRecherche.GetValue())
        self.liste_produits.SetFilter(filtre_texte)
        self.liste_produits.RepopulateList()

    def OnInfosFournisseur(self,
                           event):  # wxGlade: NouvelleCommande.<event_handler>
        message = ""
        message += self.commande.fournisseur.nom + "\n\n"
        message += self.commande.fournisseur.adresse + "\n"
        message += self.commande.fournisseur.code_postal + " " + \
                   self.commande.fournisseur.ville + "\n\n"
        message += u"Tel fixe : " + self.commande.fournisseur.telephone_fixe + "\n"
        message += u"Tel portable : " + self.commande.fournisseur.telephone_portable + "\n"
        message += u"Email : " + self.commande.fournisseur.email + "\n\n"
        message += u"Nom du contact : " + self.commande.fournisseur.nom_contact + "\n\n"
        message += "Remarques : \n\n"

        message += fill(self.commande.fournisseur.remarques, 50)

        dlg = GMD.GenericMessageDialog(self, message,
                                       self.commande.fournisseur.nom,
                                       wx.OK | wx.ICON_INFORMATION)

        dlg.Fit()
        dlg.ShowModal()
        dlg.Destroy()

    def OnAjoutProduit(self, event):
        deja_ajoute = False
        produit_selectionne = self.liste_produits.GetSelectedObject()

        for lc_liste in self.liste_lignes_commande.GetObjects():
            if lc_liste.produit.get_id() == produit_selectionne.get_id():
                deja_ajoute = True
                break

        if deja_ajoute == False:
            lc = LigneCommande(commande=self.commande,
                               produit=produit_selectionne)

            dlg = DialogChoixQuantite(lc)

            if dlg.ShowModal() == wx.ID_OK:
                if dlg.GetQuantite() != 0:
                    lc.quantite_commandee = dlg.GetQuantite()
                    lc.save()
                    self.liste_lignes_commande.AddObject(lc)
                    self.liste_lignes_commande.AutoSizeColumns()

                    #Mise à jour du total de la commande
                    self.__update_total()

            dlg.Destroy()

    def OnModifProduit(self, event):
        lc_selectionnee = self.liste_lignes_commande.GetSelectedObject()

        dlg = DialogChoixQuantite(lc_selectionnee)

        id_resultat = dlg.ShowModal()

        if id_resultat == wx.ID_OK and dlg.GetQuantite() != 0:
            lc_selectionnee.quantite_commandee = dlg.GetQuantite()
            lc_selectionnee.save()
            self.liste_lignes_commande.RefreshObject(lc_selectionnee)
            self.liste_lignes_commande.AutoSizeColumns()
        elif id_resultat == wx.ID_DELETE or dlg.GetQuantite() == 0:
            self.liste_lignes_commande.RemoveObject(lc_selectionnee)
            self.liste_lignes_commande.RefreshObject(lc_selectionnee)
            lc_selectionnee.delete_instance()
            self.liste_lignes_commande.AutoSizeColumns()

        #Mise à jour du total de la commande
        self.__update_total()

        dlg.Destroy()

    def OnSauvegarder(self, event):
        try:
            date_commande = self.datepicker_date_commande.GetValue()
            print datetime(date_commande.GetYear(),
                           date_commande.GetMonth() + 1,
                           date_commande.GetDay())

            self.commande.date_commande = datetime(
                date_commande.GetYear(),
                date_commande.GetMonth() + 1, date_commande.GetDay())

            self.commande.save()
            DATABASE.commit()
            wx.MessageBox(u"La commande a été enregistrée", "Notification")
        except BaseException as ex:
            wx.MessageBox(u"Problème lors de l'enregistrement : %s" % ex,
                          "Erreur")

    def OnDestroy(self, event):
        if self.commande.fournisseur != None:
            dlg = wx.MessageDialog(
                parent=None,
                message=u"Voulez vous sauvegarder la commande ?",
                caption=u"Sauvegarde de la commande",
                style=wx.YES_NO | wx.ICON_QUESTION)

            if dlg.ShowModal() == wx.ID_YES:
                self.OnSauvegarder(None)
            else:
                DATABASE.rollback()

            dlg.Destroy()

        event.Skip()