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)
Exemple #2
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()
Exemple #3
0
class DialogAjoutProduit(wx.Dialog):
    def __init__(self, inventaire):
        wx.Dialog.__init__(self, None, -1, title=u"Ajouter un produit", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE)

        self.inventaire = inventaire

        self.search_nom = wx.SearchCtrl(self, -1, "")
        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", fixedWidth=90),
            ColumnDefn("Nom", "left", -1, "nom"),
            ColumnDefn("Fournisseur", "left", -1, "fournisseur.nom", minimumWidth=100)
        ])

        self.search_nom.Bind(wx.EVT_TEXT, self.OnFilter)
        self.liste_produits.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnClickProduit)

        self.__set_properties()
        self.__remplissage_liste()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        self.SetMinSize((400,300))
        self.search_nom.SetDescriptiveText("Recherche sur le nom")
    
    def __remplissage_liste(self):
        try:
            requete = Produit.select().where(~(Produit.pk << self.inventaire.produits))
            self.liste_produits.SetObjects([p for p in requete])
            
            #On dimentionne le dialog selon la largeur des colonnes
            largeur = 0
            for num_colonne in range(3) :
                largeur += self.liste_produits.GetColumnWidth(num_colonne)
             
            self.liste_produits.SetMinSize((largeur+20,300))
            
        except BaseException as ex:
            print ex

    def __do_layout(self):
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.search_nom, 0, wx.LEFT|wx.RIGHT|wx.TOP|wx.EXPAND, 10)
        sizer.Add(self.liste_produits, 1, wx.ALL|wx.EXPAND, 10)
        self.SetSizer(sizer)
        sizer.Fit(self)
        self.Layout()

    def GetProduit(self):
        return self.liste_produits.GetSelectedObject()

    def OnClickProduit(self, event):
        self.EndModal(wx.ID_OK)
        
    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()
        event.Skip()
Exemple #4
0
class FicheInventaire(wx.Panel):
    def __init__(self, parent, inventaire=None):
        wx.Panel.__init__(self, parent, style=wx.TAB_TRAVERSAL)
        
        if inventaire:
            self.inventaire = inventaire
        else:
            inventaire = Inventaire.create()
            inventaire.initialisation()
            
        self.inventaire = inventaire

        self.sizer_inventaire_staticbox = wx.StaticBox(self, -1, "Liste des produits")
        self.label_titre_inventaire = wx.StaticText(self, -1, "Inventaire du ")
        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.search_nom = wx.SearchCtrl(self, -1, "")
        self.label_commentaire = wx.StaticText(self, -1, "Commentaires :")
        self.text_commentaire = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
        #self.bouton_ajout_produit = buttons.GenBitmapTextButton(self, -1, wx.Bitmap("../icons/16x16/ajouter.ico"), u" Ajouter un produit non listé", style=wx.BORDER_NONE)
        self.bouton_ajout_produit = wx.Button(self, -1, u"Ajouter un produit non listé")
        self.liste_lignes_inventaire = ObjectListView(self, -1,
                                                      style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_SINGLE_SEL)

        def update_stock_reel(li, valeur):
            if valeur<0:
                valeur = 0

            if li.produit.vrac:
                li.stock_reel = valeur *  1000
            else:
                li.stock_reel = valeur
                
            li.save()

            if self.inventaire.pret_a_valider():
                self.bouton_valider.Enable()
            
                
        def editor_stock_reel(olv, rowIndex, subItemIndex):
            if olv.GetObjectAt(rowIndex).produit.vrac:
                return StockFloatEditor(olv, subItemIndex, validator=CellEditor.NumericValidator("0123456789.,"))
            else:
                return StockIntEditor(olv, subItemIndex, validator=CellEditor.NumericValidator("0123456789"))
            
        
        self.liste_lignes_inventaire.SetColumns([
            ColumnDefn("Ref GASE", "left", -1, "produit.ref_GASE", fixedWidth=90),
            ColumnDefn("Nom", "left", -1, "produit.nom",  minimumWidth=100),
            ColumnDefn("Fournisseur", "left", -1, "produit.fournisseur.nom", minimumWidth=100),
            ColumnDefn(u"Stock théorique", "left", -1,
                       "stock_theorique_format",
                       stringConverter="%s", minimumWidth=80),
            ColumnDefn(u"Stock réel", "left", -1,
                       "stock_reel_format", isEditable=True,
                       cellEditorCreator = editor_stock_reel,
                       valueSetter=update_stock_reel, minimumWidth=80),
            ColumnDefn(u"Différence", "u_", -1,
                       "stock_difference", minimumWidth=80)
        ])

        def RFLignesInventaire(listItem, ligne_inventaire):
            if ligne_inventaire.stock_reel:
                listItem.SetBackgroundColour("#E3FFCB")
            else:
                listItem.SetBackgroundColour("#FFD3D3")
                
        #self.liste_lignes_inventaire.rowFormatter = RFLignesInventaire

        self.bouton_enregistrer = wx.Button(self, wx.ID_SAVE, "Enregistrer")
        self.bouton_valider = wx.Button(self, wx.ID_OK, u"Valider l'inventaire")

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

        self.combo_box_fournisseur.Bind(wx.EVT_COMBOBOX, self.OnFilter)
        self.search_nom.Bind(wx.EVT_TEXT, self.OnFilter)
        self.bouton_ajout_produit.Bind(wx.EVT_BUTTON, self.OnAjoutProduit)
        self.liste_lignes_inventaire.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnModifStock)
        self.bouton_enregistrer.Bind(wx.EVT_BUTTON, self.OnEnregistrer)
        self.bouton_valider.Bind(wx.EVT_BUTTON, self.OnValider)

        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)

    def __set_properties(self):
        self.label_titre_inventaire.SetFont(wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.text_commentaire.SetMinSize((-1, 200))
        self.combo_box_fournisseur.SetMinSize((200, -1))
        self.search_nom.SetMinSize((200, -1))
        self.search_nom.SetDescriptiveText("Recherche sur le nom")
        self.sizer_inventaire_staticbox.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        
        if self.inventaire.is_valide:
            self.text_commentaire.Disable()
            self.bouton_ajout_produit.Hide()
            self.bouton_enregistrer.Hide()
            self.bouton_valider.Hide()

    def __set_valeurs(self):
        self.label_titre_inventaire.SetLabel("Inventaire du %s" % self.inventaire.date.strftime("%d/%m/%y"))
        self.text_commentaire.SetValue(self.inventaire.commentaire)
        if not self.inventaire.pret_a_valider():
            self.bouton_valider.Disable()
        
    def __remplissage_liste(self):
        try:
            self.liste_lignes_inventaire.SetObjects([li for li in self.inventaire.lignes_inventaire])
            
            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 __do_layout(self):
        sizer_recherche = wx.BoxSizer(wx.HORIZONTAL)
        sizer_recherche.Add(self.search_nom, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_recherche.Add(self.label_fournisseur, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 10)
        sizer_recherche.Add(self.combo_box_fournisseur, 0, wx.ALIGN_CENTER_VERTICAL, 0)

        sizer_inventaire = wx.StaticBoxSizer(self.sizer_inventaire_staticbox, wx.VERTICAL)
        sizer_inventaire.Add(self.liste_lignes_inventaire, 1, wx.ALL|wx.EXPAND, 0)
        sizer_inventaire.Add(self.bouton_ajout_produit, 0, wx.TOP, 10)

        sizer_bouton = wx.BoxSizer(wx.HORIZONTAL)
        sizer_bouton.Add((20, 20), 1, 0, 0)
        sizer_bouton.Add(self.bouton_enregistrer, 0, 0, 0)
        sizer_bouton.Add((20, 20), 1, 0, 0)
        sizer_bouton.Add(self.bouton_valider, 0, 0, 0)
        sizer_bouton.Add((20, 20), 1, 0, 0)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.label_titre_inventaire, 0, wx.ALL|wx.EXPAND, 10)
        sizer.Add(self.label_commentaire, 0, wx.ALL|wx.EXPAND, 10)
        sizer.Add(self.text_commentaire, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10)
        sizer.Add(sizer_recherche, 0, wx.LEFT|wx.RIGHT|wx.TOP|wx.EXPAND, 10)
        sizer.Add(sizer_inventaire, 1, wx.ALL|wx.EXPAND, 10)
        sizer.Add(sizer_bouton, 0, wx.TOP|wx.BOTTOM|wx.EXPAND, 10)

        self.SetSizer(sizer)
        sizer.Fit(self)
        self.Layout()   

    def OnAjoutProduit(self, event):
        dlg = DialogAjoutProduit(self.inventaire)

        id_resultat = dlg.ShowModal()

        if id_resultat == wx.ID_OK:
            ligne_inventaire = LigneInventaire.create(inventaire=self.inventaire, produit=dlg.GetProduit())
            self.liste_lignes_inventaire.AddObject(ligne_inventaire)
            self.liste_lignes_inventaire.SelectObject(ligne_inventaire, ensureVisible=True)

        dlg.Destroy()

    def OnModifStock(self, event):
        if not self.inventaire.is_valide:
            self.liste_lignes_inventaire.StartCellEdit(self.liste_lignes_inventaire.GetFocusedRow(), 4)

    def OnEnregistrer(self, event):
        if self.Validate():
            msgbox = wx.MessageBox(u"Sauvegarder l'inventaire ?", u"Confirmation", wx.YES_NO | wx.ICON_QUESTION)

            if msgbox == wx.YES:
                self.inventaire.date = date.today()
                self.inventaire.commentaire = self.text_commentaire.GetValue()

                with DATABASE.transaction():
                    self.inventaire.save()

                event.Skip()
                
    def OnValider(self, event):
        if self.Validate() and self.inventaire.pret_a_valider():
            msgbox = wx.MessageBox(u"Valider l'inventaire ? Il ne sera plus modifiable.", u"Confirmation", wx.YES_NO | wx.ICON_QUESTION)

            if msgbox == wx.YES:
                self.inventaire.is_valide = True
                self.inventaire.date = date.today()

                with DATABASE.transaction():
                    self.inventaire.validation()
                    self.inventaire.save()

                self.__set_properties()

                event.Skip()

    def OnDestroy(self, event):
        if not self.inventaire.is_valide:
            dlg = wx.MessageDialog(parent=None, message=u"Voulez vous sauvegarder l'inventaire ?",
                                   caption=u"Sauvegarde de l'inventaire", style=wx.YES_NO|wx.ICON_QUESTION)
    
            if dlg.ShowModal() == wx.ID_YES:
                self.inventaire.date = date.today()
                self.inventaire.save()
                DATABASE.commit()
            else:
                DATABASE.rollback()
    
            dlg.Destroy()

        event.Skip()
        
    def OnFilter(self, event):
        filtre_texte = Filter.TextSearch(self.liste_lignes_inventaire, text=self.search_nom.GetValue())

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

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

        self.liste_lignes_inventaire.RepopulateList()
        event.Skip()
Exemple #5
0
class GestionAdherents(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, style=wx.TAB_TRAVERSAL)

        self.sizer_communication_staticbox = wx.StaticBox(self, -1, "Communication")
        self.sizer_autre_staticbox = wx.StaticBox(self, -1, "Autre")
        self.sizer_critere_utilisateur_staticbox = wx.StaticBox(self, -1, "Utilisateurs")
        self.checkbox_gase = wx.CheckBox(self, -1, "GASE")
        self.checkbox_paniers = wx.CheckBox(self, -1, "Paniers")
        self.radio_box_etat_adhesion = wx.RadioBox(self, -1, u"Etat de l'adhésion", choices=["Tous", u"Adhésion à jour", u"Adhésion à renouveler"], majorDimension=1, style=wx.RA_SPECIFY_COLS)
        self.checkbox_sans_email = wx.CheckBox(self, -1, "Sans email")
        self.checkbox_sans_telephone = wx.CheckBox(self, -1, u"Sans téléphone")
        self.checkbox_ancien_adherents = wx.CheckBox(self, -1, u"Anciens adhérents")
        self.bouton_ajout_adhesion = wx.BitmapButton(self, -1, wx.Bitmap("../icons/32x32/nouvelle_adhesion.ico", wx.BITMAP_TYPE_ANY))
        self.bouton_ajout_credit = wx.BitmapButton(self, -1, wx.Bitmap("../icons/32x32/ajout_credit.png", wx.BITMAP_TYPE_ANY))
        self.static_line_1 = wx.StaticLine(self, -1, style=wx.LI_VERTICAL)
        self.label_recherche = wx.StaticText(self, -1, "Recherche sur le nom")
        self.text_ctrl_recherche = wx.TextCtrl(self, -1, "")
        self.static_line_2 = wx.StaticLine(self, -1, style=wx.LI_VERTICAL)
        self.bouton_ajout_adherent = wx.BitmapButton(self, -1, wx.Bitmap("../icons/32x32/nouvel_adherent.ico", wx.BITMAP_TYPE_ANY))
        self.liste_adherents = ObjectListView(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_SINGLE_SEL)

        def AJour(value):
            if value:
                return "A jour"
            else:
                return u"Pas à jour"

        self.liste_adherents.SetColumns([
            ColumnDefn("Nom", "left", -1, "nom",  minimumWidth=100, useInitialLetterForGroupKey=True),
            ColumnDefn(u"Prénom", "left", -1, "prenom", minimumWidth=100),
            ColumnDefn("Ville", "left", -1, "ville", minimumWidth=100),
            ColumnDefn(u"Téléphone", "left", -1, "telephone", minimumWidth=100),
            ColumnDefn(u"Cotisation", "left", -1, "cotisation_type.nom", minimumWidth=100),
            ColumnDefn(u"Adhésion", "left", 100, "is_adhesion_a_jour", stringConverter=AJour, isSpaceFilling=True, minimumWidth=100)
        ])

        def RFListeAdherents(listItem, adherent):
            if adherent.is_adhesion_a_jour:
                listItem.SetBackgroundColour("#E3FFCB")
            else:
                listItem.SetBackgroundColour("#FFD3D3")

        self.liste_adherents.rowFormatter = RFListeAdherents

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

        self.filtres = {}

        self.Bind(wx.EVT_BUTTON, self.OnAjoutAdhesion, self.bouton_ajout_adhesion)
        self.Bind(wx.EVT_BUTTON, self.OnAjoutCredit, self.bouton_ajout_credit)
        self.Bind(wx.EVT_BUTTON, self.OnAjoutAdherent, self.bouton_ajout_adherent)
        self.Bind(wx.EVT_RADIOBOX, self.OnFilterAdhesion, self.radio_box_etat_adhesion)
        self.Bind(wx.EVT_CHECKBOX, self.OnFilterSansEmail, self.checkbox_sans_email)
        self.Bind(wx.EVT_CHECKBOX, self.OnFilterSansTelephone, self.checkbox_sans_telephone)
        self.Bind(wx.EVT_CHECKBOX, self.OnFilterUtilisateursPaniers, self.checkbox_paniers)
        self.Bind(wx.EVT_CHECKBOX, self.OnFilterAnciensAdherents, self.checkbox_ancien_adherents)
        self.Bind(wx.EVT_TEXT, self.OnFilterNom, self.text_ctrl_recherche)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnEditionAdherent, self.liste_adherents)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectionAdherent, self.liste_adherents)
        self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnDeselectionAdherent, self.liste_adherents)
        self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnClickDroitListe, self.liste_adherents)
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: GestionAdherents.__set_properties
        self.checkbox_gase.SetToolTipString("Afficher les utilisateurs du GASE")
        self.checkbox_paniers.SetToolTipString("Afficher les utilisateurs des paniers")
        self.radio_box_etat_adhesion.SetSelection(0)
        self.checkbox_sans_email.SetToolTipString(u"Afficher les adhérents n'ayant pas d'email")
        self.checkbox_sans_telephone.SetToolTipString(u"Afficher les adhérents n'ayant pas de téléphone")
        self.checkbox_ancien_adherents.SetToolTipString(u"Afficher les anciens adhérents")
        self.bouton_ajout_adhesion.SetToolTipString(u"Ajouter un adhésion")
        self.bouton_ajout_adhesion.Enable(False)
        self.bouton_ajout_adhesion.SetSize(self.bouton_ajout_adhesion.GetBestSize())
        self.bouton_ajout_credit.SetToolTipString(u"Ajouter un crédit")
        self.bouton_ajout_credit.Enable(False)
        self.bouton_ajout_credit.SetSize(self.bouton_ajout_credit.GetBestSize())
        self.text_ctrl_recherche.SetMinSize((200, -1))
        self.bouton_ajout_adherent.SetToolTipString(u"Ajouter un nouvel adhérent")
        self.bouton_ajout_adherent.SetSize(self.bouton_ajout_adherent.GetBestSize())
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: GestionAdherents.__do_layout
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer_toolbar = wx.BoxSizer(wx.HORIZONTAL)
        sizer_criteres = wx.BoxSizer(wx.HORIZONTAL)
        sizer_autre = wx.StaticBoxSizer(self.sizer_autre_staticbox, wx.VERTICAL)
        sizer_communication = wx.StaticBoxSizer(self.sizer_communication_staticbox, wx.VERTICAL)

        sizer_critere_utilisateur = wx.StaticBoxSizer(self.sizer_critere_utilisateur_staticbox, wx.VERTICAL)
        sizer_critere_utilisateur.Add(self.checkbox_gase, 0, 0, 0)
        sizer_critere_utilisateur.Add(self.checkbox_paniers, 0, 0, 0)
        sizer_criteres.Add(sizer_critere_utilisateur, 1, wx.EXPAND, 0)

        sizer_criteres.Add(self.radio_box_etat_adhesion, 1, 0, 20)

        sizer_communication.Add(self.checkbox_sans_email, 0, 0, 0)
        sizer_communication.Add(self.checkbox_sans_telephone, 0, 0, 0)
        sizer_criteres.Add(sizer_communication, 1, wx.EXPAND, 0)

        sizer_autre.Add(self.checkbox_ancien_adherents, 0, 0, 0)
        sizer_criteres.Add(sizer_autre, 1, wx.EXPAND, 0)

        sizer.Add(sizer_criteres, 0, wx.EXPAND, 0)

        sizer_toolbar.Add(self.bouton_ajout_adhesion, 0, wx.RIGHT, 5)
        sizer_toolbar.Add(self.bouton_ajout_credit, 0, 0, 0)
        sizer_toolbar.Add(self.static_line_1, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 5)
        sizer_toolbar.Add(self.label_recherche, 0, wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 10)
        sizer_toolbar.Add(self.text_ctrl_recherche, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_toolbar.Add(self.static_line_2, 0, wx.LEFT|wx.RIGHT|wx.EXPAND, 10)
        sizer_toolbar.Add(self.bouton_ajout_adherent, 0, 0, 0)
        sizer.Add(sizer_toolbar, 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 20)

        sizer.Add(self.liste_adherents, 1, wx.EXPAND, 0)
        self.SetSizer(sizer)
        sizer.Fit(self)
        # end wxGlade

    def __remplissage_liste(self):
        try:
            self.liste_adherents.SetObjects([a for a in Adherent.select()])
            self.liste_adherents.AutoSizeColumns()
        except BaseException as ex:
            print ex

    def OnAjoutAdhesion(self, event):
        dialog_adhesion = wx.Dialog(self, title=u"Nouvelle adhésion")
        FicheAdhesion(dialog_adhesion, adherent=self.liste_adherents.GetSelectedObject())
        dialog_adhesion.Fit()
        dialog_adhesion.ShowModal()
        dialog_adhesion.Destroy()

        if dialog_adhesion.GetReturnCode() == wx.ID_OK:
            self.liste_adherents.RefreshObject(self.liste_adherents.GetSelectedObject())
            self.liste_adherents.AutoSizeColumns()

    def OnAjoutCredit(self, event):
        print "Event handler `OnAjoutCredit' not implemented"
        event.Skip()

    def OnAjoutAdherent(self, event):
        try:
            CotisationType.select().get()

            dialog_adherent = wx.Dialog(self, title=u"Nouvel adhérent")
            fiche_adherent = FicheAdherent(dialog_adherent)
            dialog_adherent.Fit()
            dialog_adherent.ShowModal()
            dialog_adherent.Destroy()
            
            if dialog_adherent.GetReturnCode() == wx.ID_OK:
                adherent = fiche_adherent.GetAdherent()

                dialog_adhesion = wx.Dialog(self, title=u"Nouvelle adhésion")
                FicheAdhesion(dialog_adhesion, adherent=adherent)
                dialog_adhesion.Fit()
                dialog_adhesion.ShowModal()
                dialog_adhesion.Destroy()

                self.liste_adherents.AddObject(adherent)
                self.liste_adherents.AutoSizeColumns()

        except DoesNotExist:
            wx.MessageBox(u"Vous devez d'abord créer des cotisations", "Notification")

    def OnEditionAdherent(self, event):
        adherent = self.liste_adherents.GetSelectedObject()

        dialog_adherent = wx.Dialog(self, title=adherent.nom_prenom)
        FicheAdherent(dialog_adherent, adherent)
        dialog_adherent.Fit()
        dialog_adherent.ShowModal()
        dialog_adherent.Destroy()

        self.liste_adherents.RefreshObject(self.liste_adherents.GetSelectedObject())
        self.liste_adherents.AutoSizeColumns()

    def OnSelectionAdherent(self, event):
        self.bouton_ajout_adhesion.Enable()
        self.bouton_ajout_credit.Enable()

    def OnDeselectionAdherent(self, event):
        self.bouton_ajout_adhesion.Disable()
        self.bouton_ajout_credit.Disable()

    def OnClickDroitListe(self, event):
        menu = wx.Menu()

        menu.Append(1, u"Ajouter une adhésion")
        wx.EVT_MENU(menu, 1, self.OnAjoutAdhesion)

        menu.Append(2, u"Ajouter un crédit")
        wx.EVT_MENU(menu, 2, self.OnAjoutCredit)

        self.liste_adherents.PopupMenu(menu, event.GetPoint())
        menu.Destroy()

    #filtres de recherche

    def OnFilter(self, event):
        self.liste_adherents.SetFilter(Filter.Chain(*self.filtres.values()))
        self.liste_adherents.RepopulateList()
        event.Skip()

    def OnFilterNom(self, event):
        self.filtres["nom"] = Filter.TextSearch(self.liste_adherents,
                                            [self.liste_adherents.columns[0], self.liste_adherents.columns[1]],
                                            text=self.text_ctrl_recherche.GetValue())
        self.OnFilter(event)
        event.Skip()

    def OnFilterAdhesion(self, event):
        if self.radio_box_etat_adhesion.GetSelection() == 1:
            self.filtres["adhesion"] = Filter.Predicate(lambda x: x.is_adhesion_a_jour)
        elif self.radio_box_etat_adhesion.GetSelection() == 2:
            self.filtres["adhesion"] = Filter.Predicate(lambda x: not x.is_adhesion_a_jour)
        else:
            self.filtres.pop("adhesion")

        self.OnFilter(event)
        event.Skip()

    def OnFilterSansEmail(self, event):
        if self.checkbox_sans_email.IsChecked():
            self.filtres["sans_email"] = Filter.Predicate(lambda x: x.email=="")
        else:
            self.filtres.pop("sans_email")

        self.OnFilter(event)
        event.Skip()

    def OnFilterSansTelephone(self, event):
        if self.checkbox_sans_telephone.IsChecked():
            self.filtres["sans_telephone"] = Filter.Predicate(lambda x: x.telephone=="")
        else:
            self.filtres.pop("sans_telephone")

        self.OnFilter(event)
        event.Skip()

    def OnFilterUtilisateursPaniers(self, event):
        if self.checkbox_paniers.IsChecked():
            self.filtres["utilisateurs_paniers"] = Filter.Predicate(lambda x: x.utilisateur_paniers)
        else:
            self.filtres.pop("utilisateurs_paniers")

        self.OnFilter(event)
        event.Skip()

    def OnFilterAnciensAdherents(self, event):
        if self.checkbox_ancien_adherents.IsChecked():
            self.filtres["anciens_adherents"] = Filter.Predicate(lambda x: x.ancien_adherent)
        else:
            self.filtres.pop("anciens_adherents")

        self.OnFilter(event)
        event.Skip()
Exemple #6
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()