Пример #1
0
 def GetValue(self):
     "Get the value from the editor"
     dt = DatePickerCtrl.GetValue(self)
     if dt.IsOk():
         return datetime.date(dt.Year, dt.Month + 1, dt.Day)
     else:
         return None
Пример #2
0
class DataBaseManagement(scrolled.ScrolledPanel):
    def __init__(self, parent, statusbar):
        scrolled.ScrolledPanel.__init__(self, parent)
        self.statusbar = statusbar
        self.parent = parent

        if _platform == "linux" or _platform == "linux2":
            size_StaticBox = (950, 140)
            size_combobox = (130, -1)
            font = wx.Font(10, wx.DEFAULT, wx.ITALIC, wx.BOLD)
            font_combobox = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL,
                                    False, u'Arial')
            font_TextCtrl = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL,
                                    False, u'Arial')
            vStatictextsize = 16
            size_text = (85, 22)
        elif _platform == "win32":
            size_StaticBox = (960, 140)
            size_combobox = (130, -1)
            font = wx.Font(9, wx.DEFAULT, wx.ITALIC, wx.BOLD)
            font_combobox = wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False,
                                    u'Arial')
            font_TextCtrl = wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False,
                                    u'Arial')
            vStatictextsize = 16
            size_text = (85, 22)
        elif _platform == 'darwin':
            size_StaticBox = (980, 140)
            size_combobox = (130, -1)
            font = wx.Font(12, wx.DEFAULT, wx.ITALIC, wx.BOLD)
            font_combobox = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL,
                                    False, u'Arial')
            font_TextCtrl = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL,
                                    False, u'Arial')
            vStatictextsize = 18
            size_text = (85, 22)

        flagSizer = wx.ALL | wx.ALIGN_CENTER_VERTICAL
        """Action box"""
        action_box = wx.StaticBox(self,
                                  -1,
                                  " Select your action ",
                                  size=size_StaticBox)
        action_box.SetFont(font)
        action_box_sizer = wx.StaticBoxSizer(action_box, wx.VERTICAL)
        in_action_box_sizer = wx.GridBagSizer(hgap=2, vgap=0)

        label_1 = b"Show selected data"
        label_2 = b"Delete some data"

        self.rb1 = wx.RadioButton(self, label=label_1, style=wx.RB_GROUP)
        self.rb2 = wx.RadioButton(self, label=label_2)

        self.rb1.Bind(wx.EVT_RADIOBUTTON, self.on_set_val)
        self.rb2.Bind(wx.EVT_RADIOBUTTON, self.on_set_val)
        self.state = [True, False]
        self.rb1.SetValue(True)

        in_action_box_sizer.Add(self.rb1, pos=(0, 0), flag=flagSizer)
        in_action_box_sizer.Add(self.rb2, pos=(2, 0), flag=flagSizer)
        action_box_sizer.Add(in_action_box_sizer, 0, wx.ALL, 5)
        """ Id part """
        self.search_Id = wx.NewId()
        self.cb_name_Id = wx.NewId()
        self.name_Id = wx.NewId()
        self.cb_crystal_Id = wx.NewId()
        self.crystal_Id = wx.NewId()
        self.cb_geom_Id = wx.NewId()
        self.geom_Id = wx.NewId()
        self.cb_model_Id = wx.NewId()
        self.model_Id = wx.NewId()
        self.cb_date_Id = wx.NewId()
        self.date_Id = wx.NewId()

        self.Id_cb_list = [
            self.cb_name_Id, self.cb_crystal_Id, self.cb_geom_Id,
            self.cb_model_Id, self.cb_date_Id
        ]
        self.Id_combo_list = [
            self.name_Id, self.crystal_Id, self.geom_Id, self.model_Id
        ]

        cb_name = wx.CheckBox(self,
                              id=self.cb_name_Id,
                              label='Name',
                              pos=(20, 20))
        cb_name.SetValue(False)
        cb_name.Bind(wx.EVT_CHECKBOX, self.un_check_choice)
        name_choice = ["None"]
        self.name = wx.ComboBox(self,
                                id=self.name_Id,
                                pos=(50, 30),
                                choices=name_choice,
                                style=wx.CB_READONLY,
                                size=size_combobox)
        self.name.SetFont(font_combobox)
        self.Bind(wx.EVT_COMBOBOX, self.on_select_combobox, self.name)

        cb_crystal = wx.CheckBox(self,
                                 id=self.cb_crystal_Id,
                                 label='Crystal',
                                 pos=(20, 20))
        cb_crystal.SetValue(False)
        cb_crystal.Bind(wx.EVT_CHECKBOX, self.un_check_choice)
        crystal_choice = ["None"]
        self.crystal = wx.ComboBox(self,
                                   id=self.crystal_Id,
                                   pos=(50, 30),
                                   choices=crystal_choice,
                                   style=wx.CB_READONLY,
                                   size=size_combobox)
        self.crystal.SetFont(font_combobox)
        self.Bind(wx.EVT_COMBOBOX, self.on_select_combobox, self.crystal)

        cb_geom = wx.CheckBox(self,
                              id=self.cb_geom_Id,
                              label='Geometry',
                              pos=(20, 20))
        cb_geom.SetValue(False)
        cb_geom.Bind(wx.EVT_CHECKBOX, self.un_check_choice)
        geom_choice = ["None"]
        self.geom = wx.ComboBox(self,
                                id=self.geom_Id,
                                pos=(50, 30),
                                choices=geom_choice,
                                style=wx.CB_READONLY,
                                size=size_combobox)
        self.geom.SetFont(font_combobox)
        self.Bind(wx.EVT_COMBOBOX, self.on_select_combobox, self.geom)

        cb_model = wx.CheckBox(self,
                               id=self.cb_model_Id,
                               label='Model',
                               pos=(20, 20))
        cb_model.SetValue(False)
        cb_model.Bind(wx.EVT_CHECKBOX, self.un_check_choice)
        model_choice = ["None"]
        self.model = wx.ComboBox(self,
                                 id=self.model_Id,
                                 pos=(50, 30),
                                 choices=model_choice,
                                 style=wx.CB_READONLY,
                                 size=size_combobox)
        self.model.SetFont(font_combobox)
        self.Bind(wx.EVT_COMBOBOX, self.on_select_combobox, self.model)

        cb_date = wx.CheckBox(self,
                              id=self.cb_date_Id,
                              label='Date',
                              pos=(20, 20))
        cb_date.SetValue(False)
        cb_date.Bind(wx.EVT_CHECKBOX, self.un_check_choice)
        now = wx.DateTime().Today()
        self.dpc_1 = DatePickerCtrl(self,
                                    size=(120, -1),
                                    style=DP_DROPDOWN | DP_SHOWCENTURY
                                    | DP_ALLOWNONE)
        self.dpc_2 = DatePickerCtrl(self,
                                    size=(120, -1),
                                    style=DP_DROPDOWN | DP_SHOWCENTURY
                                    | DP_ALLOWNONE)
        self.Bind(EVT_DATE_CHANGED, self.on_select_combobox, self.dpc_1)
        self.Bind(EVT_DATE_CHANGED, self.on_select_combobox, self.dpc_2)
        self.dpc_1.SetValue(now)
        self.dpc_2.SetValue(now)

        date_choice = ["None"]
        self.date = wx.ComboBox(self,
                                id=self.date_Id,
                                pos=(50, 30),
                                choices=date_choice,
                                style=wx.CB_READONLY,
                                size=size_combobox)
        self.date.SetFont(font_combobox)
        self.Bind(wx.EVT_COMBOBOX, self.on_select_combobox, self.date)

        self.search_btn = wx.Button(self, id=self.search_Id, label=" Search")
        self.search_btn.Bind(wx.EVT_BUTTON, self.on_search_in_DB)

        txt_db = u'DataBase number of lines:'
        db_nb_lines_txt = wx.StaticText(self,
                                        -1,
                                        label=txt_db,
                                        size=(180, vStatictextsize))
        self.db_nb_lines = wx.TextCtrl(self,
                                       style=wx.TE_PROCESS_ENTER,
                                       size=size_text,
                                       validator=TextValidator(DIGIT_ONLY))
        self.db_nb_lines.SetFont(font_TextCtrl)
        self.db_nb_lines.SetValue(str(100))
        P4Rm.db_nb_line = 100

        bmp = _bp_btn2.GetBitmap()
        self.nb_lines_btn = wx.BitmapButton(self, -1, bmp)
        self.nb_lines_btn.SetToolTip("Update database list")
        # self.nb_lines_btn.SetToolTipString("Update database list")
        self.Bind(wx.EVT_BUTTON,
                  self.nb_lines_DB,
                  id=self.nb_lines_btn.GetId())
        self.Bind(wx.EVT_TEXT_ENTER, self.nb_lines_DB, self.db_nb_lines)

        self.cb_list = [cb_name, cb_crystal, cb_geom, cb_model, cb_date]

        self.combo_list = [
            self.name, self.crystal, self.geom, self.model, self.date
        ]
        for i in range(len(self.combo_list)):
            self.combo_list[i].Disable()

        mastersizer = wx.BoxSizer(wx.VERTICAL)
        DBLine = wx.BoxSizer(wx.HORIZONTAL)
        choice_sizer = wx.GridBagSizer(hgap=8, vgap=4)

        DBLine.Add(db_nb_lines_txt, 0, flag=flagSizer)
        DBLine.Add(self.db_nb_lines, 0, flag=flagSizer)
        DBLine.Add(self.nb_lines_btn, 0, wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 5)

        choice_sizer.Add(cb_name, pos=(0, 0), flag=flagSizer)
        choice_sizer.Add(self.name, pos=(0, 1), flag=flagSizer)

        choice_sizer.Add(cb_crystal, pos=(1, 0), flag=flagSizer)
        choice_sizer.Add(self.crystal, pos=(1, 1), flag=flagSizer)

        choice_sizer.Add(cb_geom, pos=(2, 0), flag=flagSizer)
        choice_sizer.Add(self.geom, pos=(2, 1), flag=flagSizer)

        choice_sizer.Add(cb_model, pos=(3, 0), flag=flagSizer)
        choice_sizer.Add(self.model, pos=(3, 1), flag=flagSizer)

        choice_sizer.Add(cb_date, pos=(4, 0), flag=flagSizer)
        choice_sizer.Add(self.date, pos=(4, 1), flag=flagSizer)
        choice_sizer.Add(self.dpc_1, pos=(4, 2), flag=flagSizer)
        choice_sizer.Add(self.dpc_2, pos=(4, 3), flag=flagSizer)

        choice_sizer.Add(self.search_btn, pos=(6, 0), flag=flagSizer)

        mastersizer.Add(action_box_sizer, 0, wx.ALL, 5)
        mastersizer.Add(DBLine, 0, wx.ALL, 10)
        mastersizer.Add(choice_sizer, 0, wx.ALL, 10)

        pub.subscribe(self.on_delete_data, pubsub_sup_data_DB)
        pub.subscribe(self.on_add_new_name_to_combobox,
                      pubsub_refill_list_name_DB)
        pub.subscribe(self.on_search_in_DB, pubsub_search_combobox_DB)

        self.SetSizer(mastersizer)
        self.Layout()
        self.SetAutoLayout(1)
        self.SetupScrolling()
        self.on_fill_combobox()

    def on_set_val(self, event):
        self.state = []
        state1 = self.rb1.GetValue()
        state2 = self.rb2.GetValue()
        self.state = [state1, state2]

    def on_fill_combobox(self):
        a = P4Rm()
        choice_list = []
        c = DataBaseUse()
        c.on_read_part_DB()

        if P4Rm.DBDict['name']:
            choice_list.append(a.DBDict['name'])
        else:
            choice_list.append(["List empty"])
        choice_list.append(a.crystal_list)
        choice_list.append(p4R.sample_geometry)
        choice_list.append(p4R.Strain_DW_choice)
        choice_list.append(["equal", "=<", ">=", "between"])

        for i in range(len(self.combo_list)):
            self.combo_list[i].SetItems(choice_list[i])
            self.combo_list[i].SetStringSelection(choice_list[i][0])

        self.dpc_1.Hide()
        self.dpc_2.Hide()

    def on_add_new_name_to_combobox(self):
        a = P4Rm()
        if not a.PathDict['project_name'] in a.DBDict['name']:
            c = DataBaseUse()
            c.on_read_part_DB()
            self.name.SetItems(a.DBDict['name'])
            self.name.SetStringSelection(a.DBDict['name'][0])
            self.Layout()
            self.SetAutoLayout(1)

    def un_check_choice(self, event):
        widget = event.GetId()
        isChecked = event.GetEventObject().GetValue()
        indexx = self.Id_cb_list.index(widget)
        if isChecked:
            self.combo_list[indexx].Enable()
        else:
            self.combo_list[indexx].Disable()
        if widget == self.cb_date_Id:
            if isChecked:
                self.dpc_1.Show()
                if self.date.GetStringSelection() == 'between':
                    self.dpc_2.Show()
            else:
                self.dpc_1.Hide()
                self.dpc_2.Hide()

    def on_select_combobox(self, event):
        widget = event.GetId()
        val = event.GetString()
        if widget == self.date_Id:
            if val == 'between':
                self.dpc_2.Show()
            else:
                self.dpc_2.Hide()

    def nb_lines_DB(self, event):
        obj = self.db_nb_lines.GetValue()
        P4Rm.db_nb_line = int(obj)
        pub.sendMessage(pubsub_update_db_nb_line)

    def on_search_in_DB(self, event=None):
        list_temp = []
        P4Rm.DBDict['choice_state'] = self.rb1.GetValue()
        for i in range(len(self.cb_list)):
            if self.cb_list[i].IsChecked():
                list_temp.append(self.combo_list[i].GetStringSelection())
            else:
                list_temp.append(None)
        P4Rm.DBDict['choice_combo'] = list_temp
        if self.cb_list[-1].IsChecked():
            P4Rm.DBDict['date_1'] = '{:%Y-%m-%d %H:%M:%S}'.format(
                wxdate2pydate(self.dpc_1.GetValue()))
            P4Rm.DBDict['date_2'] = '{:%Y-%m-%d %H:%M:%S}'.format(
                wxdate2pydate(self.dpc_2.GetValue()))
        c = DataBaseUse()
        c.on_search_in_DB()

    def on_delete_data(self):
        a = P4Rm()
        _msg = "Do you really want to delete these datas?"
        dlg = GMD.GenericMessageDialog(None,
                                       _msg,
                                       "Confirm Suppression",
                                       agwStyle=wx.OK | wx.CANCEL
                                       | wx.ICON_QUESTION)
        result = dlg.ShowModal()
        dlg.Destroy()
        if result == wx.ID_OK:
            c = DataBaseUse()
            c.on_delete_data()
            self.on_fill_combobox()
            state1 = self.rb1.SetValue(True)
            state2 = self.rb2.SetValue(False)
            self.state = [state1, state2]
            for i in range(len(self.cb_list)):
                self.cb_list[i].SetValue(False)
                self.combo_list[i].Disable()
            empty = a.DBDict['session'].query(RadMaxData).first()
            if empty is None:
                s = a.DBDict['session'].query(RadMaxData).order_by(
                    RadMaxData.id)
                c.on_read_database_and_fill_list(s)
            else:
                self.on_search_in_DB()
Пример #3
0
class Panel(wx.Panel):
    def __init__(self,
                 parent,
                 selectionLignes=[],
                 selectionPersonnes=[],
                 selectionDates=(None, None)):
        wx.Panel.__init__(self,
                          parent,
                          -1,
                          name="panel_applicModele",
                          style=wx.TAB_TRAVERSAL)
        self.parent = parent

        self.selectionLignes = selectionLignes
        self.selectionPersonnes = selectionPersonnes
        self.selectionDates = selectionDates

        self.panel_base_1 = wx.Panel(self, -1)
        self.panel_base_2 = wx.Panel(self.panel_base_1, -1)
        self.sizer_modeles_staticbox = wx.StaticBox(
            self.panel_base_2, -1, _(u"Sélection des modèles"))
        self.sizer_parametres_staticbox = wx.StaticBox(
            self.panel_base_2, -1,
            _(u"Sélection de la période et des personnes"))
        self.radio_btn_1 = wx.RadioButton(self.panel_base_2, -1, u"")
        self.radio_btn_2 = wx.RadioButton(
            self.panel_base_2, -1, _(u"Selon les paramètres suivants :"))
        self.label_periode = wx.StaticText(self.panel_base_2, -1,
                                           _(u"Période du :"))
        self.date_debut = DatePickerCtrl(self.panel_base_2,
                                         -1,
                                         style=DP_DROPDOWN)
        self.label_au = wx.StaticText(self.panel_base_2, -1, "au")
        self.date_fin = DatePickerCtrl(self.panel_base_2,
                                       -1,
                                       style=DP_DROPDOWN)
        self.label_personnes = wx.StaticText(self.panel_base_2, -1,
                                             "Personnes :")
        self.list_ctrl_personnes = listCtrl_Personnes(self.panel_base_2)
        self.list_ctrl_personnes.SetMinSize((20, 80))
        self.list_ctrl_modeles = listCtrl_Modeles(self.panel_base_2)
        self.list_ctrl_modeles.SetMinSize((20, 20))
        self.bouton_ajouter = wx.BitmapButton(
            self.panel_base_2, -1,
            wx.Bitmap(Chemins.GetStaticPath("Images/16x16/Ajouter.png"),
                      wx.BITMAP_TYPE_ANY))
        self.bouton_modifier = wx.BitmapButton(
            self.panel_base_2, -1,
            wx.Bitmap(Chemins.GetStaticPath("Images/16x16/Modifier.png"),
                      wx.BITMAP_TYPE_ANY))
        self.bouton_dupliquer = wx.BitmapButton(
            self.panel_base_2, -1,
            wx.Bitmap(Chemins.GetStaticPath("Images/16x16/Dupliquer.png"),
                      wx.BITMAP_TYPE_ANY))
        self.bouton_supprimer = wx.BitmapButton(
            self.panel_base_2, -1,
            wx.Bitmap(Chemins.GetStaticPath("Images/16x16/Supprimer.png"),
                      wx.BITMAP_TYPE_ANY))
        self.bouton_aide = wx.BitmapButton(
            self.panel_base_2, -1,
            wx.Bitmap(
                Chemins.GetStaticPath("Images/BoutonsImages/Aide_L72.png"),
                wx.BITMAP_TYPE_ANY))
        self.bouton_ok = wx.BitmapButton(
            self.panel_base_2, -1,
            wx.Bitmap(Chemins.GetStaticPath("Images/BoutonsImages/Ok_L72.png"),
                      wx.BITMAP_TYPE_ANY))
        self.bouton_annuler = wx.BitmapButton(
            self.panel_base_2, -1,
            wx.Bitmap(
                Chemins.GetStaticPath("Images/BoutonsImages/Annuler_L72.png"),
                wx.BITMAP_TYPE_ANY))

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_RADIOBUTTON, self.OnRadio1, self.radio_btn_1)
        self.Bind(wx.EVT_RADIOBUTTON, self.OnRadio2, self.radio_btn_2)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonAide, self.bouton_aide)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonOk, self.bouton_ok)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonAnnuler, self.bouton_annuler)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonAjouter, self.bouton_ajouter)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonModifier, self.bouton_modifier)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonSupprimer, self.bouton_supprimer)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonDupliquer, self.bouton_dupliquer)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.boutonsEnabled(True, False, False)
        self.SetLabelRadio1()

        # Définit les dates des datePickers
        if self.selectionDates[0] != None:
            jour = self.selectionDates[0].day
            mois = self.selectionDates[0].month - 1
            annee = self.selectionDates[0].year
            date = wx.DateTime()
            date.Set(jour, mois, annee)
            self.date_debut.SetValue(date)

        if self.selectionDates[1] != None:
            jour = self.selectionDates[1].day
            mois = self.selectionDates[1].month - 1
            annee = self.selectionDates[1].year
            date = wx.DateTime()
            date.Set(jour, mois, annee)
            self.date_fin.SetValue(date)

    def __set_properties(self):
        self.bouton_ajouter.SetToolTip(
            wx.ToolTip(_(u"Cliquez ici pour créer un modèle")))
        self.bouton_modifier.SetToolTip(
            wx.ToolTip(
                _(u"Cliquez ici pour modifier le modèle sélectionné dans la liste"
                  )))
        self.bouton_supprimer.SetToolTip(
            wx.ToolTip(
                _(u"Cliquez ici pour supprimer le modèle sélectionné dans la liste"
                  )))
        self.bouton_dupliquer.SetToolTip(
            wx.ToolTip(
                _(u"Cliquez ici pour dupliquer le modèle sélectionné dans la liste"
                  )))

    def __do_layout(self):
        sizer_base_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_base_2 = wx.BoxSizer(wx.VERTICAL)
        grid_sizer_base = wx.FlexGridSizer(rows=3, cols=1, vgap=10, hgap=10)
        grid_sizer_boutons = wx.FlexGridSizer(rows=1, cols=5, vgap=10, hgap=10)
        sizer_modeles = wx.StaticBoxSizer(self.sizer_modeles_staticbox,
                                          wx.VERTICAL)
        grid_sizer_modeles = wx.FlexGridSizer(rows=1, cols=2, vgap=5, hgap=5)
        grid_sizer_boutons_modeles = wx.FlexGridSizer(rows=4,
                                                      cols=1,
                                                      vgap=5,
                                                      hgap=5)
        sizer_parametres = wx.StaticBoxSizer(self.sizer_parametres_staticbox,
                                             wx.VERTICAL)
        grid_sizer_parametres = wx.FlexGridSizer(rows=3,
                                                 cols=1,
                                                 vgap=10,
                                                 hgap=10)
        grid_sizer_manuel = wx.FlexGridSizer(rows=2, cols=2, vgap=10, hgap=10)
        grid_sizer_dates = wx.FlexGridSizer(rows=1, cols=3, vgap=10, hgap=10)
        grid_sizer_parametres.Add(self.radio_btn_1, 0, 0, 0)
        grid_sizer_parametres.Add(self.radio_btn_2, 0, 0, 0)
        grid_sizer_manuel.Add(self.label_periode, 0,
                              wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_dates.Add(self.date_debut, 0, 0, 0)
        grid_sizer_dates.Add(self.label_au, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_dates.Add(self.date_fin, 0, 0, 0)
        grid_sizer_manuel.Add(grid_sizer_dates, 1, wx.EXPAND, 0)
        grid_sizer_manuel.Add(self.label_personnes, 0,
                              wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_manuel.Add(self.list_ctrl_personnes, 1, wx.EXPAND, 0)
        grid_sizer_manuel.AddGrowableCol(1)
        grid_sizer_parametres.Add(grid_sizer_manuel, 1, wx.LEFT | wx.EXPAND,
                                  30)
        grid_sizer_parametres.AddGrowableCol(0)
        sizer_parametres.Add(grid_sizer_parametres, 1, wx.ALL | wx.EXPAND, 10)
        grid_sizer_base.Add(sizer_parametres, 1, wx.EXPAND, 0)
        grid_sizer_modeles.Add(self.list_ctrl_modeles, 1, wx.EXPAND, 0)
        grid_sizer_boutons_modeles.Add(self.bouton_ajouter, 0, 0, 0)
        grid_sizer_boutons_modeles.Add(self.bouton_modifier, 0, 0, 0)
        grid_sizer_boutons_modeles.Add(self.bouton_dupliquer, 0, 0, 0)
        grid_sizer_boutons_modeles.Add(self.bouton_supprimer, 0, 0, 0)
        grid_sizer_modeles.Add(grid_sizer_boutons_modeles, 1, wx.EXPAND, 0)
        grid_sizer_modeles.AddGrowableRow(0)
        grid_sizer_modeles.AddGrowableCol(0)
        sizer_modeles.Add(grid_sizer_modeles, 1, wx.ALL | wx.EXPAND, 10)
        grid_sizer_base.Add(sizer_modeles, 1, wx.EXPAND, 0)
        grid_sizer_boutons.Add(self.bouton_aide, 0, 0, 0)
        grid_sizer_boutons.Add((20, 20), 0, 0, 0)
        grid_sizer_boutons.Add(self.bouton_ok, 0, 0, 0)
        grid_sizer_boutons.Add(self.bouton_annuler, 0, 0, 0)
        grid_sizer_boutons.AddGrowableCol(1)
        grid_sizer_base.Add(grid_sizer_boutons, 1, wx.EXPAND, 0)
        self.panel_base_2.SetSizer(grid_sizer_base)
        grid_sizer_base.AddGrowableRow(1)
        grid_sizer_base.AddGrowableCol(0)
        sizer_base_2.Add(self.panel_base_2, 1, wx.ALL | wx.EXPAND, 10)
        self.panel_base_1.SetSizer(sizer_base_2)
        sizer_base_1.Add(self.panel_base_1, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_base_1)
        sizer_base_1.Fit(self)
        self.Layout()
        self.grid_sizer_manuel = grid_sizer_manuel

    def SetLabelRadio1(self):
        """ Assigne un label au radio1 """
        if self.parent.GetName() == "panel_applicModele_FicheInd":
            if len(self.selectionLignes) == 0:
                txt = _(u"Selon les dates sélectionnées dans le calendrier")
            elif len(self.selectionLignes) == 1:
                txt = _(u"Selon la date sélectionnée dans le calendrier")
            else:
                txt = _(u"Selon les ") + str(len(self.selectionLignes)) + _(
                    u" dates sélectionnées dans le calendrier")
        else:
            if len(self.selectionLignes) == 0:
                txt = _(u"Selon les lignes sélectionnées dans le planning")
            elif len(self.selectionLignes) == 1:
                txt = _(u"Selon la ligne sélectionnée dans le planning")
            else:
                txt = _(u"Selon les ") + str(len(self.selectionLignes)) + _(
                    u" lignes sélectionnées dans le planning")
        self.radio_btn_1.SetLabel(txt)
        if len(self.selectionLignes) == 0:
            self.radio_btn_1.Enable(False)
            self.radio_btn_2.SetValue(True)
            self.date_debut.Enable(True)
            self.date_fin.Enable(True)
        else:
            self.radio_btn_1.Enable(True)
            self.radio_btn_1.SetValue(True)
            self.date_debut.Enable(False)
            self.date_fin.Enable(False)

    def OnClose(self, event):
        self.Fermer()
        event.Skip()

    def OnRadio1(self, event):
        self.ParamEnabled(False)

    def OnRadio2(self, event):
        self.ParamEnabled(True)

    def ParamEnabled(self, etat):
        self.label_periode.Enable(etat)
        self.date_debut.Enable(etat)
        self.label_au.Enable(etat)
        self.date_fin.Enable(etat)
        self.label_personnes.Enable(etat)
        self.list_ctrl_personnes.Enable(etat)

    def boutonsEnabled(self, ajouter=True, modifier=True, supprimer=True):
        self.bouton_ajouter.Enable(ajouter)
        self.bouton_modifier.Enable(modifier)
        self.bouton_supprimer.Enable(supprimer)
        self.bouton_dupliquer.Enable(supprimer)

    def OnBoutonAide(self, event):
        from Utils import UTILS_Aide
        UTILS_Aide.Aide("Appliquerunmodledeprsences")

    def OnBoutonAnnuler(self, event):
        self.Fermer()

    def Fermer(self):
        if self.parent.GetName() == "panel_applicModele_FicheInd":
            # Si appellée à partir de la fiche individuelle
            self.parent.GetParent().Fermer()
        else:
            # Sinon...
            self.parent.Fermer()

    def OnBoutonOk(self, event):
        """ Bouton Ok """
        # Vérifie qu'au moins un modèle a été coché
        selectionModeles = self.list_ctrl_modeles.selections
        if len(selectionModeles) == 0:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez cocher au moins un modèle dans la liste proposée."
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            return

        DB = GestionDB.DB()
        # Récupération des modèles
        if len(selectionModeles) == 1:
            selectionModelesTmp = "(%d)" % selectionModeles[0]
        else:
            selectionModelesTmp = str(tuple(selectionModeles))
        req = "SELECT * FROM modeles_planning WHERE IDmodele IN %s" % selectionModelesTmp
        DB.ExecuterReq(req)
        listeModeles = DB.ResultatReq()
        dictModeles = {}
        inclureFeries = False
        for modele in listeModeles:
            dictModeles[modele[0]] = (modele[1], modele[2], modele[3],
                                      modele[4], modele[5])
            if modele[5] == 1:
                inclureFeries = True
        # Récupération des tâches
        req = "SELECT * FROM modeles_taches WHERE IDmodele IN %s" % selectionModelesTmp
        DB.ExecuterReq(req)
        listeTaches = DB.ResultatReq()
        DB.Close()

        # On enlève les taches non utiles (d'autres périodes)
        listeExclusions = []
        for tache in listeTaches:
            typeModele = dictModeles[tache[1]][1]
            periodesModele = dictModeles[tache[1]][3]
            # Comparaison du type
            if typeModele != tache[2]:
                if tache[0] not in listeExclusions:
                    listeExclusions.append(tache[0])
            else:
                if tache[3] == 1 and periodesModele[0] != "1":
                    if tache[0] not in listeExclusions:
                        listeExclusions.append(tache[0])
                if tache[3] == 2 and periodesModele[1] != "1":
                    if tache[0] not in listeExclusions:
                        listeExclusions.append(tache[0])
                if tache[3] == 3 and periodesModele[2] != "1":
                    if tache[0] not in listeExclusions:
                        listeExclusions.append(tache[0])

        for exclusion in listeExclusions:
            index = 0
            for tache in listeTaches:
                if tache[0] == exclusion:
                    listeTaches.pop(index)
                    break
                index += 1

        # Creation du schéma d'application
        periodeEcole = {1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: []}
        periodeVacs = {1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: []}

        for tache in listeTaches:
            IDtache = tache[0]
            type = tache[2]
            periode = tache[3]
            jour = tache[4]
            heure_debut = tache[5]
            heure_fin = tache[6]
            IDcategorie = tache[7]
            intitule = tache[8]

            # Application periodeEcole :
            if periode == 1 or periode == 2:
                if type == "journ":
                    for numJour in range(1, 8):
                        detailTache = (IDtache, heure_debut, heure_fin,
                                       IDcategorie, intitule)
                        periodeEcole[numJour].append(detailTache)
                if type == "hebdo":
                    detailTache = (IDtache, heure_debut, heure_fin,
                                   IDcategorie, intitule)
                    periodeEcole[jour].append(detailTache)

            # Application periodeVacs :
            if periode == 1 or periode == 3:
                if type == "journ":
                    for numJour in range(1, 8):
                        detailTache = (IDtache, heure_debut, heure_fin,
                                       IDcategorie, intitule)
                        periodeVacs[numJour].append(detailTache)
                if type == "hebdo":
                    detailTache = (IDtache, heure_debut, heure_fin,
                                   IDcategorie, intitule)
                    periodeVacs[jour].append(detailTache)

        # On vérifie que des taches ne se chevauchent pas dans le schéma d'application
        chevauchement = 0

        for numJour in range(1, 8):
            for tacheRef in periodeEcole[numJour]:
                for tacheComp in periodeEcole[numJour]:
                    if tacheComp[0] != tacheRef[0]:
                        # Comparaison des horaires
                        ##                        if tacheComp[1] < tacheRef[1] < tacheComp[2] :
                        ##                            chevauchement += 1
                        ##                        if tacheComp[1] < tacheRef [2]< tacheComp[2] :
                        ##                            chevauchement += 1
                        if (tacheComp[1] < tacheRef[2]) and (tacheComp[2] >
                                                             tacheRef[1]):
                            chevauchement += 1

        for numJour in range(1, 8):
            for tacheRef in periodeVacs[numJour]:
                for tacheComp in periodeVacs[numJour]:
                    if tacheComp[0] != tacheRef[0]:
                        # Comparaison des horaires
                        ##                        if tacheComp[1] < tacheRef[1] < tacheComp[2] :
                        ##                            chevauchement += 1
                        ##                        if tacheComp[1] < tacheRef [2]< tacheComp[2] :
                        ##                            chevauchement += 1
                        if (tacheComp[1] < tacheRef[2]) and (tacheComp[2] >
                                                             tacheRef[1]):
                            chevauchement += 1

        if chevauchement > 0:
            nbreModelesCoches = len(selectionModeles)
            txt = _(u"Les ") + str(nbreModelesCoches) + _(
                u" modèles que vous avez sélectionnés ne sont pas compatibles entre eux : Des tâches se chevauchent. \n\nDéselectionnez ou modifiez les tâches de l'un des modèles."
            )
            dlg = wx.MessageDialog(self, txt, "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            return

        # Application du schéma d'application
        listeCreationsTaches = []

        if self.radio_btn_1.GetValue() == True:

            # Récupération des dates extremes de la sélection de lignes
            listeDatesSelection = []
            for ligne in self.selectionLignes:
                listeDatesSelection.append(ligne[1])
            listeDatesSelection.sort()
            dateMin = listeDatesSelection[0]
            dateMax = listeDatesSelection[-1]

            # Récupération des dates de jours de vacances
            listeJoursVacs = self.Importation_Jours_Vacances(dateMin, dateMax)

            # Création de la liste des taches à créer
            for ligne in self.selectionLignes:

                IDpersonne = ligne[0]
                date = ligne[1]
                jourSemaine = date.isoweekday()
                if date in listeJoursVacs: periode = "vacs"
                else: periode = "ecole"

                if periode == "vacs":
                    listTachesTemp = periodeVacs[jourSemaine]
                    for tache in listTachesTemp:
                        detailTache = (IDpersonne, date, tache[1], tache[2],
                                       tache[3], tache[4])
                        listeCreationsTaches.append(detailTache)

                if periode == "ecole":
                    listTachesTemp = periodeEcole[jourSemaine]
                    for tache in listTachesTemp:
                        detailTache = (IDpersonne, date, tache[1], tache[2],
                                       tache[3], tache[4])
                        listeCreationsTaches.append(detailTache)

        if self.radio_btn_2.GetValue() == True:

            # Vérifie que au moins 1 nom de personnes a été coché dans le listCtrl
            if len(self.selectionPersonnes) == 0:
                dlg = wx.MessageDialog(
                    self,
                    _(u"Vous devez cocher au moins un nom dans la liste des personnes."
                      ), "Erreur", wx.OK)
                dlg.ShowModal()
                dlg.Destroy()
                return

            # Vérifie que les dates données dans les datePickers sont correctes
            date_tmp = self.date_debut.GetValue()
            date_debut = datetime.date(date_tmp.GetYear(),
                                       date_tmp.GetMonth() + 1,
                                       date_tmp.GetDay())
            date_tmp = self.date_fin.GetValue()
            date_fin = datetime.date(date_tmp.GetYear(),
                                     date_tmp.GetMonth() + 1,
                                     date_tmp.GetDay())

            if date_debut > date_fin:
                dlg = wx.MessageDialog(
                    self,
                    _(u"La date de début doit être inférieure à la date de fin."
                      ), "Erreur de saisie", wx.OK)
                dlg.ShowModal()
                dlg.Destroy()
                return

            # Création de la liste de dates
            listeDatesSelection = []
            nbreJours = (date_fin - date_debut).days + 1
            dateTemp = date_debut
            for date in range(nbreJours):
                listeDatesSelection.append(dateTemp)
                dateTemp = dateTemp + datetime.timedelta(days=1)
            listeDatesSelection.sort()
            dateMin = listeDatesSelection[0]
            dateMax = listeDatesSelection[-1]

            # Récupération des dates de jours de vacances
            listeJoursVacs = self.Importation_Jours_Vacances(dateMin, dateMax)

            # Création de la liste des taches à créer
            for IDpersonne in self.selectionPersonnes:
                for date in listeDatesSelection:
                    jourSemaine = date.isoweekday()
                    if date in listeJoursVacs: periode = "vacs"
                    else: periode = "ecole"

                    if periode == "vacs":
                        listTachesTemp = periodeVacs[jourSemaine]
                        for tache in listTachesTemp:
                            detailTache = [
                                IDpersonne, date, tache[1], tache[2], tache[3],
                                tache[4]
                            ]
                            listeCreationsTaches.append(detailTache)

                    if periode == "ecole":
                        listTachesTemp = periodeEcole[jourSemaine]
                        for tache in listTachesTemp:
                            detailTache = [
                                IDpersonne, date, tache[1], tache[2], tache[3],
                                tache[4]
                            ]
                            listeCreationsTaches.append(detailTache)

        if len(listeCreationsTaches) == 0:
            dlg = wx.MessageDialog(
                self,
                _(u"Selon les paramètres que vous avez saisis, aucune tâche n'est à créer..."
                  ), "Information", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            return

        # Création de la liste formatée de confirmation
        dictCategories = self.Importation_categories_presences()

        ##        listeConfirmations = []
        ##        for tache in listeCreationsTaches :
        ##            nomPersonne = self.list_ctrl_personnes.dictPersonnes[tache[0]][0] + " " + self.list_ctrl_personnes.dictPersonnes[tache[0]][1]
        ##            date = DatetimeDateEnStr(tache[1])
        ##            horaires = tache[2][:2] + "h" + tache[2][3:] + "-" + tache[3][:2] + "h" + tache[3][3:]
        ##            categorie = dictCategories[tache[4]]
        ##            intitule = tache[5]
        ##            detailTache = (nomPersonne, date, horaires, categorie, intitule)
        ##            listeConfirmations.append(detailTache)

        dictConfirmations = {}
        for IDpersonne in self.selectionPersonnes:
            nomPersonne = self.list_ctrl_personnes.dictPersonnes[IDpersonne][
                0] + " " + self.list_ctrl_personnes.dictPersonnes[IDpersonne][1]
            dictConfirmations[(IDpersonne, nomPersonne)] = {}

        list(dictConfirmations.keys()).sort(reverse=True)

        for tache in listeCreationsTaches:
            IDpersonne = tache[0]
            nomPersonne = self.list_ctrl_personnes.dictPersonnes[IDpersonne][
                0] + " " + self.list_ctrl_personnes.dictPersonnes[IDpersonne][1]
            key = (IDpersonne, nomPersonne)
            date = tache[1]
            horaires = (
                tache[2], tache[3]
            )  #(tache[2][:2] + "h" + tache[2][3:] + "-" + tache[3][:2] + "h" + tache[3][3:]
            categorie = dictCategories[tache[4]]
            intitule = tache[5]
            #if len(dictConfirmations[nomPersonne]) == 0 :
            if date in dictConfirmations[key]:
                dictConfirmations[key][date].append(
                    [horaires, categorie, intitule])
                dictConfirmations[key][date].sort()
            else:
                dictConfirmations[key][date] = [
                    [horaires, categorie, intitule],
                ]

        nbreTaches = len(listeCreationsTaches)

        # Fenêtre de demande de confirmation
        dlg = DLG_Confirm_appli_modele.Dialog(
            self,
            nbreTaches=nbreTaches,
            dictTaches=dictConfirmations,
            listeCreationsTaches=listeCreationsTaches,
            inclureFeries=inclureFeries)
        dlg.ShowModal()
        etat = dlg.etat
        dlg.Destroy()
        if etat == "termine":
            if self.parent.GetName() == "panel_applicModele_FicheInd":
                self.GetGrandParent().EndModal(wx.ID_OK)
            else:
                self.GetParent().EndModal(wx.ID_OK)

    def EnregistrementTaches(self, listeCreationsTaches):
        """ Enregistrement des taches dans la base de données """
        listeExceptions = []

        # Récupération des dates de jours fériés
        self.listeFeriesFixes, self.listeFeriesVariables = self.Importation_Feries(
        )

        # Initialisation de la connexion avec la Base de données
        DB = GestionDB.DB()
        for tache in listeCreationsTaches:

            IDpersonne = tache[0]
            date = tache[1]
            heure_debut = tache[2]
            heure_fin = tache[3]
            IDcategorie = tache[4]
            intitule = tache[5]

            valide = True

            # Vérifie qu'aucune tâche n'existe déjà à ce moment dans la base de données
            req = """
            SELECT IDpresence, date, heure_debut, heure_fin
            FROM presences
            WHERE (date='%s' AND IDpersonne=%d)  AND
            (heure_debut<'%s' And heure_fin>'%s');
            """ % (str(date), IDpersonne, heure_fin, heure_debut)
            DB.ExecuterReq(req)
            listePresences = DB.ResultatReq()
            nbreResultats = len(listePresences)

            # Un ou des présences existent à ce moment, donc pas d'enregistrement
            if nbreResultats != 0:
                valide = False

            # Vérifie que ce n'est pas un jour férié
            #print date, type(date)
            if (date.day, date.month) in self.listeFeriesFixes:
                valide = False
            else:
                if date in self.listeFeriesVariables:
                    valide = False

            # Enregistrement si la date est bien valide
            if valide == True:
                listeDonnees = [
                    ("IDpersonne", IDpersonne),
                    ("date", str(date)),
                    ("heure_debut", heure_debut),
                    ("heure_fin", heure_fin),
                    ("IDcategorie", IDcategorie),
                    ("intitule", intitule),
                ]
                # Enregistrement dans la base
                ID = DB.ReqInsert("presences", listeDonnees)
                DB.Commit()
            else:

                # Si date non valide : on crée un rapport
                dictPersonnes = self.list_ctrl_personnes.dictPersonnes
                nomPersonne = dictPersonnes[IDpersonne][
                    0] + " " + dictPersonnes[IDpersonne][1]
                listeExceptions.append((nomPersonne, DatetimeDateEnStr(date),
                                        (heure_debut, heure_fin)))

        # Fermeture de la base de données
        DB.Close()

        # Lecture de la liste des exceptions
        nbreInvalides = len(listeExceptions)
        nbreValides = len(listeCreationsTaches) - nbreInvalides

        if nbreInvalides != 0:
            message = ""
            if nbreValides == 0:
                message += _(
                    u"Aucune tâche n'a été correctement enregistrée.\n\nL")
            elif nbreValides == 1:
                message += str(nbreValides) + _(
                    u" tâche a été correctement enregistrée.\n\nMais l")
            else:
                message += str(nbreValides) + _(
                    u" tâches ont été correctement enregistrées.\n\nMais l"
                )
            if nbreInvalides == 1:
                message += _(
                    u"a tâche de la liste suivante n'a pas pu être saisie car elle chevauchait une ou plusieurs des tâches existantes. "
                )
                message += _(
                    u"Vous devrez donc d'abord supprimer ou modifier les horaires de ces tâches existantes avant de pouvoir saisir celle-ci.\n\n"
                )
            else:
                message += _(u"es ") + str(nbreInvalides) + _(
                    u" tâches de la liste suivante n'ont pas pu être saisies car elles chevauchaient des tâches existantes. "
                )
                message += _(
                    u"Vous devrez donc d'abord supprimer ou modifier les horaires de ces tâches existantes avant de pouvoir saisir celles-ci.\n\n"
                )
            for exception in listeExceptions:
                message += "   > Le " + exception[1] + " pour " + exception[
                    0] + " de " + exception[2][0] + u" à " + exception[2][
                        1] + ".\n"
            dlg = wx.lib.dialogs.ScrolledMessageDialog(self, message,
                                                       _(u"Rapport d'erreurs"))
            dlg.ShowModal()

        #print "fin de la procedure d'enregistrement !!!"

    def Importation_Jours_Vacances(self, dateMin=None, dateMax=None):
        """ Importation des dates d'ouverture de la structure """

        ##        # Anciennce version :
        ##        conditions = ""
        ##        if dateMin != None and dateMax != None :
        ##            conditions = " WHERE date_ouverture >= '" + str(dateMin) + "' AND date_ouverture <= '" + str(dateMax)  + "'"
        ##        DB = GestionDB.DB()
        ##        req = "SELECT * FROM dates_ouverture" + conditions + ";"
        ##        DB.ExecuterReq(req)
        ##        listeVacs1 = DB.ResultatReq()
        ##        DB.Close()
        ##
        ##        # Formatage des dates pour la liste
        ##        listeVacs2 = []
        ##        for date in listeVacs1:
        ##            dateTemp = datetime.date(int(date[1][:4]), int(date[1][5:7]), int(date[1][8:10]))
        ##            listeVacs2.append(dateTemp)
        ##        listeVacs2.sort()
        ##        return listeVacs2

        req = "SELECT * FROM periodes_vacances ORDER BY date_debut;"
        DB = GestionDB.DB()
        DB.ExecuterReq(req)
        listeVacances1 = DB.ResultatReq()
        DB.Close()

        listeVacances2 = []
        for id, nom, annee, date_debut, date_fin in listeVacances1:
            datedebut = datetime.date(int(date_debut[:4]),
                                      int(date_debut[5:7]),
                                      int(date_debut[8:10]))
            datefin = datetime.date(int(date_fin[:4]), int(date_fin[5:7]),
                                    int(date_fin[8:10]))
            listeVacances2.append(datedebut)
            for x in range((datefin - datedebut).days):
                datedebut = datedebut + datetime.timedelta(days=1)
                listeVacances2.append(datedebut)

        return listeVacances2

    def Importation_Feries(self):
        """ Importation des dates des jours fériés """

        req = "SELECT * FROM jours_feries;"
        DB = GestionDB.DB()
        DB.ExecuterReq(req)
        listeFeriesTmp = DB.ResultatReq()
        DB.Close()

        listeFeriesFixes = []
        listeFeriesVariables = []
        for ID, type, nom, jour, mois, annee in listeFeriesTmp:
            if type == "fixe":
                date = (jour, mois)
                listeFeriesFixes.append(date)
            else:
                date = datetime.date(annee, mois, jour)
                listeFeriesVariables.append(date)
        return listeFeriesFixes, listeFeriesVariables

    def Importation_categories_presences(self):
        DB = GestionDB.DB()
        req = "SELECT IDcategorie, nom_categorie FROM cat_presences"
        DB.ExecuterReq(req)
        listeCategories = DB.ResultatReq()
        DB.Close()
        # Transformation en dictionnaire
        dictCategories = {}
        for ID, nom in listeCategories:
            dictCategories[ID] = nom
        return dictCategories

    def OnBoutonAjouter(self, event):
        """ Créer un nouveau modèle """
        dlg = DLG_Saisie_modele.Dialog(self, IDmodele=0)
        dlg.ShowModal()
        dlg.Destroy()

    def OnBoutonModifier(self, event):
        """ Modifier un modèle """
        index = self.list_ctrl_modeles.GetFirstSelected()
        if index == -1:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez sélectionner un modèle dans la liste proposée"
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            return
        IDmodele = self.list_ctrl_modeles.GetItemData(index)
        dlg = DLG_Saisie_modele.Dialog(self, IDmodele=IDmodele)
        dlg.ShowModal()
        dlg.Destroy()

    def OnBoutonSupprimer(self, event):
        """ Suppression d'un modèle """
        index = self.list_ctrl_modeles.GetFirstSelected()
        if index == -1:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez sélectionner un modèle dans la liste proposée"
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            return
        IDmodele = self.list_ctrl_modeles.GetItemData(index)
        nomModele = self.list_ctrl_modeles.dictModeles[IDmodele][0]
        dlg = wx.MessageDialog(
            self,
            _(u"Souhaitez-vous vraiment supprimer le modèle '") + nomModele +
            "' ?", _(u"Suppression d'un modèle"),
            wx.ICON_QUESTION | wx.YES_NO | wx.NO_DEFAULT)
        if dlg.ShowModal() == wx.ID_NO:
            dlg.Destroy()
            return
        dlg.Destroy()

        if IDmodele in self.list_ctrl_modeles.selections:
            self.list_ctrl_modeles.selections.remove(IDmodele)

        DB = GestionDB.DB()
        # Suppression des taches associées au modèle
        DB.ReqDEL("modeles_taches", "IDmodele", IDmodele)
        # Suppression du modèle
        DB.ReqDEL("modeles_planning", "IDmodele", IDmodele)
        DB.Close()

        # MAJ listCtrl Modeles
        self.list_ctrl_modeles.Remplissage()
        self.boutonsEnabled(True, False, False)

    def OnBoutonDupliquer(self, event):
        """ Dupliquer un modèle """
        # Demande de confirmation
        index = self.list_ctrl_modeles.GetFirstSelected()
        if index == -1:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez sélectionner un modèle dans la liste proposée"
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            return
        IDmodele = self.list_ctrl_modeles.GetItemData(index)
        nomModele = self.list_ctrl_modeles.dictModeles[IDmodele][0]
        dlg = wx.MessageDialog(
            self,
            _(u"Souhaitez-vous vraiment dupliquer le modèle '") + nomModele +
            u"' ?", _(u"Duplication d'un modèle"),
            wx.ICON_QUESTION | wx.YES_NO | wx.NO_DEFAULT)
        if dlg.ShowModal() == wx.ID_NO:
            dlg.Destroy()
            return
        dlg.Destroy()

        # Duplication du modèle
        dlg = DLG_Saisie_modele.Dialog(self, IDmodele=IDmodele)
        dlg.IDmodele = 0
        dlg.text_nom.SetValue(_(u"Copie de %s") % nomModele)
        dlg.ShowModal()
        dlg.Destroy()
Пример #4
0
class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, parent=None, title='量化软件', size=(1100, 700))
        # 创建显示区面板
        self.DispPanel = MPL_Panel_Base(self)  # 展示
        self.BackPanel = Loop_Panel_Base(self)  # 回测
        self.am = self.DispPanel.am
        self.vol = self.DispPanel.vol
        self.devol = self.DispPanel.devol
        self.macd = self.DispPanel.macd

        # 创建参数区面板
        self.ParaPanel = wx.Panel(self, -1)

        paraInput_Box = wx.StaticBox(self.ParaPanel, -1, '参数输入')
        paraInput_Sizer = wx.StaticBoxSizer(paraInput_Box, wx.VERTICAL)
        self.StNameCodedict = {
            "开山股份": "300257",
            "浙大网新": "600797",
            "水晶光电": "002273",
            "高鸿股份": "000851"
        }

        # 初始化股票代码变量
        self.stockName_Val = "开山股份"
        self.stockCode_Val = self.StNameCodedict[self.stockName_Val]

        self.stockName_CMBO = wx.ComboBox(
            self.ParaPanel,
            -1,
            self.stockName_Val,
            choices=list(self.StNameCodedict.keys()),
            style=wx.CB_READONLY | wx.CB_DROPDOWN)  # 股票名称
        stockCode_Text = wx.StaticText(self.ParaPanel, -1, '股票名称')

        # 策略选取
        strate_Text = wx.StaticText(self.ParaPanel, -1, '策略名称')
        strate_Combo_Val = ["双趋势融合", "待添加策略"]  # 策略
        self.pickstrate_Val = "双趋势融合"
        self.pickstrate_CMBO = wx.ComboBox(self.ParaPanel,
                                           -1,
                                           self.pickstrate_Val,
                                           choices=strate_Combo_Val,
                                           style=wx.CB_READONLY
                                           | wx.CB_DROPDOWN)  # 策略名称

        # 日历控件选择数据周期
        self.dpcEndTime = DatePickerCtrl(self.ParaPanel,
                                         -1,
                                         style=DP_DROPDOWN | DP_SHOWCENTURY
                                         | DP_ALLOWNONE)  # 结束时间
        self.dpcStartTime = DatePickerCtrl(self.ParaPanel,
                                           -1,
                                           style=DP_DROPDOWN | DP_SHOWCENTURY
                                           | DP_ALLOWNONE)  # 起始时间
        DateTimeNow = wx.DateTime.Now()  # wx.DateTime格式"03/03/18 00:00:00"
        self.dpcEndTime.SetValue(DateTimeNow)
        DateTimeNow.SetYear(DateTimeNow.year - 1)
        self.dpcStartTime.SetValue(DateTimeNow)
        stockData_Text = wx.StaticText(self.ParaPanel, -1, '日期(Start-End)')

        # 初始化时间变量
        # print('start----------')
        dateVal = self.dpcStartTime.GetValue()
        # print("dateVal ---> ", dateVal)
        # print("dateVal.year ----->", dateVal.year)
        # print("dateVal.month ---->", dateVal.month)
        # print("dateVal.day ----->", dateVal.day)
        self.stockSdate_Val = datetime.datetime(dateVal.year,
                                                dateVal.month + 1, dateVal.day)
        # print('self.stockSdate_Val----->', self.stockSdate_Val)
        dateVal = self.dpcEndTime.GetValue()
        # print("dateVal ---> ", dateVal)
        self.stockEdate_Val = datetime.datetime(dateVal.year,
                                                dateVal.month + 1, dateVal.day)
        # print('self.stockEdate_Val ------>', self.stockEdate_Val)
        # print('end----------')

        paraInput_Sizer.Add(stockCode_Text,
                            proportion=0,
                            flag=wx.EXPAND | wx.ALL,
                            border=2)
        paraInput_Sizer.Add(self.stockName_CMBO, 0,
                            wx.EXPAND | wx.ALL | wx.CENTER, 2)
        paraInput_Sizer.Add(stockData_Text,
                            proportion=0,
                            flag=wx.EXPAND | wx.ALL,
                            border=2)
        paraInput_Sizer.Add(self.dpcStartTime, 0,
                            wx.EXPAND | wx.ALL | wx.CENTER, 2)
        paraInput_Sizer.Add(self.dpcEndTime, 0, wx.EXPAND | wx.ALL | wx.CENTER,
                            2)
        paraInput_Sizer.Add(strate_Text, 0, wx.EXPAND | wx.ALL | wx.CENTER, 2)
        paraInput_Sizer.Add(self.pickstrate_CMBO, 0,
                            wx.EXPAND | wx.ALL | wx.CENTER, 2)

        RadioList = ["不显示", "跳空缺口", "金叉/死叉", "N日突破"]
        self.StratInputBox = wx.RadioBox(self.ParaPanel,
                                         -1,
                                         label='指标提示',
                                         choices=RadioList,
                                         majorDimension=4,
                                         style=wx.RA_SPECIFY_ROWS)
        self.StratInputBox.Bind(wx.EVT_RADIOBOX, self.OnRadioBox_Indicator)

        # 初始化指标变量
        self.IndicatInput_Val = self.StratInputBox.GetStringSelection()

        self.TextAInput = wx.TextCtrl(self.ParaPanel,
                                      -1,
                                      "交易信息提示:",
                                      size=(180, 200),
                                      style=wx.TE_MULTILINE
                                      | wx.TE_READONLY)  # 多行|只读

        vboxnetA = wx.BoxSizer(wx.VERTICAL)  # 纵向box
        vboxnetA.Add(paraInput_Sizer,
                     proportion=0,
                     flag=wx.EXPAND | wx.BOTTOM,
                     border=2)  # proportion参数控制容器尺寸比例
        vboxnetA.Add(self.StratInputBox,
                     proportion=0,
                     flag=wx.EXPAND | wx.BOTTOM,
                     border=2)
        vboxnetA.Add(self.TextAInput,
                     proportion=1,
                     flag=wx.EXPAND | wx.ALL,
                     border=2)
        self.ParaPanel.SetSizer(vboxnetA)

        # 创建Right面板
        self.CtrlPanel = wx.Panel(self, -1)
        # 创建FlexGridSizer布局网格
        self.FlexGridSizer = wx.FlexGridSizer(rows=3, cols=1, vgap=3, hgap=3)

        # 行情按钮
        self.Firmoffer = wx.Button(self.CtrlPanel, -1, "行情")
        self.Firmoffer.Bind(wx.EVT_BUTTON, self.FirmEvent)  # 绑定行情按钮事件

        # 回测按钮
        self.Backtrace = wx.Button(self.CtrlPanel, -1, "回测")
        self.Backtrace.Bind(wx.EVT_BUTTON, self.BackEvent)  # 绑定回测按钮事件

        # 选股按钮
        self.Stockpick = wx.Button(self.CtrlPanel, -1, "选股")
        self.Stockpick.Bind(wx.EVT_BUTTON, self.PstockpEvent)  # 绑定选股按钮事件

        # 加入Sizer中
        self.FlexGridSizer.Add(self.Firmoffer,
                               proportion=1,
                               border=5,
                               flag=wx.ALL | wx.EXPAND)
        self.FlexGridSizer.Add(self.Backtrace,
                               proportion=1,
                               border=5,
                               flag=wx.ALL | wx.EXPAND)
        self.FlexGridSizer.Add(self.Stockpick,
                               proportion=1,
                               border=5,
                               flag=wx.ALL | wx.EXPAND)
        self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)

        self.CtrlPanel.SetSizer(self.FlexGridSizer)

        self.HBoxPanel = wx.BoxSizer()
        self.HBoxPanel.Add(self.ParaPanel,
                           proportion=1.5,
                           border=2,
                           flag=wx.EXPAND | wx.ALL)
        self.HBoxPanel.Add(self.DispPanel,
                           proportion=8,
                           border=2,
                           flag=wx.EXPAND | wx.ALL)
        self.HBoxPanel.Add(self.CtrlPanel,
                           proportion=1,
                           border=2,
                           flag=wx.EXPAND | wx.ALL)
        self.SetSizer(self.HBoxPanel)

        self.Centre()

    def ProcessStock(self):
        # df_stockload = web.DataReader("600797.SS", "yahoo", datetime.datetime(2017,1,1), datetime.date.today())
        df_stockload = GetStockDatPro(self.stockCode_Val, self.stockSdate_Val,
                                      self.stockEdate_Val)
        """ 绘制移动平均线图 """
        # self.am.plot(self.numic[0:self.butNum],self.close[0:self.butNum],'#0f0ff0',linewidth=1.0)

        dispCont_List = []

        examp_trade = Excave_Indic_Base()
        if self.IndicatInput_Val == "金叉/死叉":
            dispCont_pd, dispCont_List = examp_trade.plot_Aver_Cross(
                df_stockload)
            self.DispPanel.draw_avercross(df_stockload, dispCont_pd)
        elif self.IndicatInput_Val == "跳空缺口":
            dispCont_pd, dispCont_List = examp_trade.plot_Jump_Thrd(
                df_stockload)
            self.DispPanel.draw_jumpgap(df_stockload, dispCont_pd)
        elif self.IndicatInput_Val == "N日突破":
            dispCont_pd, dispCont_List = examp_trade.plot_Ndays_Break(
                df_stockload)
            self.DispPanel.draw_ndaysbreak(df_stockload, dispCont_pd)
        else:
            dispCont_List = dispCont_List

        self.TextAInput.SetValue("指标提示信息如下:" + '\n')
        for i in dispCont_List:
            self.TextAInput.AppendText(i)

        numic = np.arange(0, len(df_stockload.index))
        butNum = len(df_stockload.index)
        self.DispPanel.xylabel_tick_lim(self.stockName_Val, df_stockload.index)
        self.DispPanel.draw_subgraph(df_stockload, numic)

    def ProcessLoop(self):

        df_stockload = GetStockDatPro(self.stockCode_Val, self.stockSdate_Val,
                                      self.stockEdate_Val)
        dispCont_List = []
        if self.pickstrate_Val == "双趋势融合":
            # 多趋势融合策略执行 """
            examp_trade = QuantPickTimeSys(df_stockload)
            dispCont_List = examp_trade.run_factor_plot(
                self.BackPanel.trade, self.BackPanel.total,
                self.BackPanel.profit)
        else:

            # 执行其他策略
            # 扩展其他策略

            pass

        self.TextAInput.SetValue(u"策略提示信息如下:" + '\n')
        for i in dispCont_List:
            self.TextAInput.AppendText(i)
        self.BackPanel.xylabel_tick_lim(self.stockName_Val)

    def reFlashLoop(self):
        self.BackPanel.clear_subgraph()  # 必须清理图形才能显示下一幅图
        self.ProcessLoop()
        self.BackPanel.update_subgraph()  # 必须刷新才能显示下一幅图

    def reFlashFrame(self):
        self.DispPanel.clear_subgraph()  # 必须清理图形才能显示下一幅图
        self.ProcessStock()
        self.DispPanel.update_subgraph()  # 必须刷新才能显示下一幅图

    def FirmEvent(self, event):
        # 显示行情面板
        self.HBoxPanel.Hide(self.BackPanel)
        self.HBoxPanel.Replace(self.BackPanel, self.DispPanel)
        self.HBoxPanel.Show(self.DispPanel)
        # self.HBoxPanel.Remove(self.BackPanel)
        self.SetSizer(self.HBoxPanel)
        self.HBoxPanel.Layout()

        # 获取列表股票代码和起始时间
        self.stockName_Val = self.stockName_CMBO.GetString(
            self.stockName_CMBO.GetSelection())
        self.stockCode_Val = self.StNameCodedict[self.stockName_Val]

        dateVal = self.dpcStartTime.GetValue()
        # print('------------')
        # print('dateVal:', dateVal, type(dateVal))
        # print('dateVal.Year:', dateVal.Year, type(dateVal.Year))
        self.stockSdate_Val = datetime.datetime(dateVal.year,
                                                dateVal.month + 1, dateVal.day)
        dateVal = self.dpcEndTime.GetValue()
        self.stockEdate_Val = datetime.datetime(dateVal.year,
                                                dateVal.month + 1, dateVal.day)

        self.reFlashFrame()

    def BackEvent(self, event):
        # 显示回测面板
        self.HBoxPanel.Hide(self.DispPanel)
        self.HBoxPanel.Replace(self.DispPanel, self.BackPanel)
        self.HBoxPanel.Show(self.BackPanel)
        # self.HBoxPanel.Remove(self.DispPanel)
        self.SetSizer(self.HBoxPanel)
        self.HBoxPanel.Layout()

        # 获取策略名称
        self.pickstrate_Val = self.pickstrate_CMBO.GetString(
            self.pickstrate_CMBO.GetSelection())
        self.reFlashLoop()

    def PstockpEvent(self, event):
        """选股事件触发"""
        dlg = wx.TextEntryDialog(self, '输入需要查询的股票代码', '自选窗')

        if dlg.ShowModal() == wx.ID_OK:
            # 获取代码编号
            code = dlg.GetValue()
            # 获取名称
            stockName = format_code_name(code)
            print('股票名称为', stockName)
            self.StNameCodedict[stockName] = dlg.GetValue()
            self.stockName_CMBO.Append(stockName)  # 添加数据
            self.stockName_CMBO.Update()
            self.stockName_CMBO.Refresh()
            self.ParaPanel.Update()

        # print("股票池:", self.StNameCodedict)
        dlg.Destroy()
        # print('销毁对话')

    def OnRadioBox_Indicator(self, event):
        self.IndicatInput_Val = self.StratInputBox.GetStringSelection()
Пример #5
0
class Page(wx.Panel):
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.TAB_TRAVERSAL
        wx.Panel.__init__(self, *args, **kwds)

        self.dictTypes = {}

        self.sizer_dates_staticbox = wx.StaticBox(self, -1, "Dates du contrat")
        self.sizer_caract_staticbox = wx.StaticBox(
            self, -1, _(u"Caractéristiques générales"))
        self.sizer_essai_staticbox = wx.StaticBox(self, -1,
                                                  _(u"Période d'essai"))
        self.label_titre = wx.StaticText(
            self, -1, _(u"2. Caractéristiques générales du contrat"))
        self.label_intro = wx.StaticText(
            self, -1,
            _(u"Saisissez les caractéristiques générales du contrat :"))

        self.label_type = wx.StaticText(self, -1, "Type de contrat :")
        self.choice_type = wx.Choice(self, -1, choices=[])
        self.Importation_Type()
        self.bouton_type = wx.Button(self, -1, "...", style=wx.BU_EXACTFIT)

        self.label_class = wx.StaticText(self, -1, "Classification :")
        self.choice_class = wx.Choice(self, -1, choices=[])
        self.Importation_classifications()
        self.bouton_class = wx.Button(self, -1, "...", style=wx.BU_EXACTFIT)

        self.label_valpoint = wx.StaticText(self, -1, "Valeur du point :")
        self.choice_valpoint = wx.Choice(self, -1, choices=[])
        self.Importation_valPoint()
        self.bouton_valpoint = wx.Button(self, -1, "...", style=wx.BU_EXACTFIT)

        self.label_date_debut = wx.StaticText(self, -1, "       A partir du :")
        self.datepicker_date_debut = DatePickerCtrl(self,
                                                    -1,
                                                    style=DP_DROPDOWN)
        self.label_date_fin = wx.StaticText(self, -1, "Jusqu'au :")
        self.datepicker_date_fin = DatePickerCtrl(self, -1, style=DP_DROPDOWN)
        self.datepicker_date_debut.Enable(False)
        self.datepicker_date_fin.Enable(False)

        self.check_rupture = wx.CheckBox(
            self, -1, _(u" Rupture anticipée du contrat au :"))
        self.datepicker_rupture = DatePickerCtrl(self, -1, style=DP_DROPDOWN)
        self.datepicker_rupture.Enable(False)

        self.label_essai = wx.StaticText(self, -1, _(u"    Nbre de jours :"))
        self.periode_essai = wx.SpinCtrl(self, -1, "", size=(60, -1))
        self.periode_essai.SetRange(0, 99)
        self.periode_essai.SetValue(0)
        self.aide_essai = wx.StaticText(
            self, -1, _(u"  (1 jour par semaine travaillée)"))
        self.aide_essai.SetForegroundColour('Grey')

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.OnBoutonClassifications,
                  self.bouton_class)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonValPoint, self.bouton_valpoint)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonType, self.bouton_type)
        self.Bind(wx.EVT_CHOICE, self.OnChoiceType, self.choice_type)
        self.Bind(wx.EVT_CHECKBOX, self.OnCheckRupture, self.check_rupture)

        self.Affichage_dateFin()
        # Importation des données
        if self.GetGrandParent().dictContrats["IDcontrat"] != 0:
            self.Importation()

    def __set_properties(self):
        self.label_titre.SetFont(
            wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
        self.bouton_type.SetMinSize((20, 20))
        self.bouton_type.SetToolTip(
            wx.ToolTip(
                _(u"Cliquez ici pour ajouter, modifier ou supprimer des types de contrat"
                  )))
        self.bouton_class.SetMinSize((20, 20))
        self.bouton_class.SetToolTip(
            wx.ToolTip(
                _(u"Cliquez ici pour ajouter, modifier ou supprimer des classifications"
                  )))
        self.bouton_valpoint.SetMinSize((20, 20))
        self.bouton_valpoint.SetToolTip(
            wx.ToolTip(
                _(u"Cliquez ici pour ajouter, modifier ou supprimer des valeurs de points"
                  )))
        self.check_rupture.SetToolTip(
            wx.ToolTip(
                _(u"Cliquez ici pour saisir une date de fin de contrat si l'employeur ou le salarié ont mis fin prématurément au contrat."
                  )))

    def __do_layout(self):
        grid_sizer_base = wx.FlexGridSizer(rows=5, cols=1, vgap=10, hgap=10)
        sizer_dates = wx.StaticBoxSizer(self.sizer_dates_staticbox,
                                        wx.VERTICAL)
        grid_sizer_dates = wx.FlexGridSizer(rows=1, cols=4, vgap=10, hgap=10)
        grid_sizer_rupture = wx.FlexGridSizer(rows=1, cols=3, vgap=5, hgap=5)

        sizer_caract = wx.StaticBoxSizer(self.sizer_caract_staticbox,
                                         wx.VERTICAL)
        grid_sizer_caract = wx.FlexGridSizer(rows=3, cols=3, vgap=5, hgap=5)
        grid_sizer_base.Add(self.label_titre, 0, 0, 0)
        grid_sizer_base.Add(self.label_intro, 0, wx.LEFT, 20)
        grid_sizer_caract.Add(self.label_type, 0,
                              wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_caract.Add(self.choice_type, 0, wx.EXPAND, 0)
        grid_sizer_caract.Add(self.bouton_type, 0, 0, 0)
        grid_sizer_caract.Add(self.label_class, 0,
                              wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_caract.Add(self.choice_class, 0, wx.EXPAND, 0)
        grid_sizer_caract.Add(self.bouton_class, 0, 0, 0)
        grid_sizer_caract.Add(self.label_valpoint, 0,
                              wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_caract.Add(self.choice_valpoint, 0, wx.EXPAND, 0)
        grid_sizer_caract.Add(self.bouton_valpoint, 0, 0, 0)
        grid_sizer_caract.AddGrowableCol(1)
        sizer_caract.Add(grid_sizer_caract, 1, wx.ALL | wx.EXPAND, 5)
        grid_sizer_base.Add(sizer_caract, 1, wx.LEFT | wx.EXPAND, 20)

        grid_sizer_dates.Add(self.label_date_debut, 0,
                             wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_dates.Add(self.datepicker_date_debut, 0, 0, 0)
        grid_sizer_dates.Add(self.label_date_fin, 0, wx.ALIGN_CENTER_VERTICAL,
                             0)
        grid_sizer_dates.Add(self.datepicker_date_fin, 0, 0, 0)
        sizer_dates.Add(grid_sizer_dates, 1, wx.ALL | wx.EXPAND, 5)

        grid_sizer_rupture.Add((90, 10), 1, wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_rupture.Add(self.check_rupture, 0, wx.ALIGN_CENTER_VERTICAL,
                               0)
        grid_sizer_rupture.Add(self.datepicker_rupture, 0,
                               wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_dates.Add(grid_sizer_rupture, 1, wx.EXPAND, 0)

        grid_sizer_base.Add(sizer_dates, 1, wx.LEFT | wx.EXPAND, 20)

        sizer_essai = wx.StaticBoxSizer(self.sizer_essai_staticbox,
                                        wx.VERTICAL)
        grid_sizer_essai = wx.FlexGridSizer(rows=1, cols=3, vgap=5, hgap=5)
        grid_sizer_essai.Add(self.label_essai, 0,
                             wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_essai.Add(self.periode_essai, 0, wx.ALIGN_CENTER_VERTICAL,
                             0)
        grid_sizer_essai.Add(self.aide_essai, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_essai.Add(grid_sizer_essai, 1, wx.ALL | wx.EXPAND, 5)
        grid_sizer_base.Add(sizer_essai, 1, wx.LEFT | wx.EXPAND, 20)

        self.SetSizer(grid_sizer_base)
        grid_sizer_base.Fit(self)
        grid_sizer_base.AddGrowableCol(0)

    def Importation(self):
        """ Remplit les controles avec les données importées si c'est une modification """
        dictContrats = self.GetGrandParent().dictContrats

        # Controles Choice
        type = dictContrats["IDtype"]
        self.SelectChoice(self.choice_type, data=type)
        classification = dictContrats["IDclassification"]
        self.SelectChoice(self.choice_class, data=classification)
        valeur_point = dictContrats["valeur_point"]
        self.SelectChoice(self.choice_valpoint, data=valeur_point)

        # Radio et Date de Rupture
        if dictContrats["date_rupture"] != "":
            self.check_rupture.SetValue(True)
            self.datepicker_rupture.Enable(True)
            self.SetDatePicker(self.datepicker_rupture,
                               dictContrats["date_rupture"])
        else:
            self.check_rupture.SetValue(False)
            self.datepicker_rupture.Enable(False)

        # Dates de début et de fin
        date_debut = dictContrats["date_debut"]
        date_fin = dictContrats["date_fin"]
        if date_debut != "":
            self.SetDatePicker(self.datepicker_date_debut,
                               dictContrats["date_debut"])
        if date_fin != "" and date_fin != "2999-01-01":
            self.SetDatePicker(self.datepicker_date_fin,
                               dictContrats["date_fin"])
        self.datepicker_date_debut.Enable(True)
        self.datepicker_date_fin.Enable(True)

        if self.dictTypes[type] == "non":
            self.label_date_fin.Show(True)
            self.datepicker_date_fin.Show(True)
        else:
            self.label_date_fin.Show(False)
            self.datepicker_date_fin.Show(False)

        # Période d'essai
        essai = dictContrats["essai"]
        self.periode_essai.SetValue(essai)

    def CalcEssai(self):
        """ Calcule la durée de la période d'essai en fonction des dates du contrat """
        essai = 0

        # Si CDI
        if self.dictTypes[self.choice_type.GetClientData(
                self.choice_type.GetSelection())] == "oui":
            self.periode_essai.SetValue(30)
            return

        # Si CDD

        # Calcul de la durée du contrat
        date_tmp = self.datepicker_date_debut.GetValue()
        date_debut = datetime.date(date_tmp.GetYear(),
                                   date_tmp.GetMonth() + 1, date_tmp.GetDay())
        date_tmp = self.datepicker_date_fin.GetValue()
        date_fin = datetime.date(date_tmp.GetYear(),
                                 date_tmp.GetMonth() + 1, date_tmp.GetDay())

        if date_debut > date_fin:
            self.periode_essai.SetValue(0)
            return

        nbreJours = (date_fin - date_debut).days
        nbreSemaines = nbreJours // 7

        print(nbreJours, nbreSemaines)

        self.periode_essai.SetValue(essai)

    def SetDatePicker(self, controle, date):
        """ Met une date dans un datePicker donné """
        annee = int(date[:4])
        mois = int(date[5:7]) - 1
        jour = int(date[8:10])
        date = wx.DateTime()
        date.Set(jour, mois, annee)
        controle.SetValue(date)

    def OnCheckRupture(self, event):
        if self.check_rupture.GetValue() == True:
            self.datepicker_rupture.Enable(True)
        else:
            self.datepicker_rupture.Enable(False)

    def OnChoiceType(self, event):
        self.datepicker_date_debut.Enable(True)
        self.datepicker_date_fin.Enable(True)
        self.Affichage_dateFin()
        self.CalcEssai()

    def Affichage_dateFin(self):
        """ Faire apparaitre ou disparaitre le controle DateFin en fonction du type de contrat choisi """
        selection = self.choice_type.GetSelection()
        if selection != -1:
            IDselection = self.choice_type.GetClientData(selection)
        else:
            return
        if self.dictTypes[IDselection] == "non":
            self.label_date_fin.Show(True)
            self.datepicker_date_fin.Show(True)
        else:
            self.label_date_fin.Show(False)
            self.datepicker_date_fin.Show(False)

    def OnBoutonClassifications(self, event):
        dlg = DLG_Config_classifications.Dialog(self)
        dlg.ShowModal()
        dlg.Destroy()
        self.MAJ_choice_Class()

    def OnBoutonValPoint(self, event):
        dlg = DLG_Config_val_point.Dialog(self)
        dlg.ShowModal()
        dlg.Destroy()
        self.MAJ_choice_ValPoint()

    def OnBoutonType(self, event):
        dlg = DLG_Config_types_contrats.Dialog(self)
        dlg.ShowModal()
        dlg.Destroy()
        self.MAJ_choice_Type()

    def MAJ_choice_Class(self):
        self.Importation_classifications()

    def Importation_classifications(self):
        controle = self.choice_class
        selection = controle.GetSelection()
        IDselection = None
        if selection != -1: IDselection = controle.GetClientData(selection)
        # Récupération des données
        DB = GestionDB.DB()
        req = """SELECT * FROM contrats_class """
        DB.ExecuterReq(req)
        liste = DB.ResultatReq()
        DB.Close()
        # Placement de la liste dans le Choice
        controle.Clear()
        x = 0
        for key, valeur in liste:
            controle.Append(valeur, key)
            if IDselection == key: controle.SetSelection(x)
            x += 1

    def MAJ_choice_ValPoint(self):
        self.Importation_valPoint()

    def Importation_valPoint(self):
        controle = self.choice_valpoint
        selection = controle.GetSelection()
        IDselection = None
        if selection != -1: IDselection = controle.GetClientData(selection)
        # Récupération des données
        DB = GestionDB.DB()
        req = """SELECT * FROM valeurs_point ORDER BY date_debut """
        DB.ExecuterReq(req)
        liste = DB.ResultatReq()
        DB.Close()

        # Recherche de la valeur actuelle
        dateJour = str(datetime.date.today())
        valeurActuelle = None
        for ID, valeur, dateDebut in liste:
            if dateJour >= dateDebut:
                valeurActuelle = ID

        # Placement de la liste dans le Choice
        controle.Clear()
        x = 0
        for ID, valeur, dateDebut in liste:
            txt = str(valeur) + _(u" ¤  (à partir du "
                                  ) + FonctionsPerso.DateEngFr(dateDebut) + ")"
            controle.Append(txt, ID)
            # Sélection de l'ancienne valeur sélectionnée
            if IDselection == ID: controle.SetSelection(x)
            # Sélection de la valeur actuelle si rien n'a été sélectionnée
            if IDselection == None and valeurActuelle == ID:
                controle.SetSelection(x)
            x += 1

        self.listeValPoint = liste

    def MAJ_choice_Type(self):
        self.Importation_Type()

    def Importation_Type(self):
        controle = self.choice_type
        selection = controle.GetSelection()
        IDselection = None
        if selection != -1: IDselection = controle.GetClientData(selection)
        # Récupération des données
        DB = GestionDB.DB()
        req = """SELECT * FROM contrats_types """
        DB.ExecuterReq(req)
        liste = DB.ResultatReq()
        DB.Close()
        # Placement de la liste dans le Choice
        controle.Clear()
        self.dictTypes = {}
        x = 0
        for key, nom, nom_abrege, duree_indeterminee in liste:
            self.dictTypes[key] = duree_indeterminee
            controle.Append(nom, key)
            if IDselection == key: controle.SetSelection(x)
            x += 1

        if selection != -1: self.Affichage_dateFin()

    def GetDatePickerValue(self, controle):
        date_tmp = controle.GetValue()
        return str(
            datetime.date(date_tmp.GetYear(),
                          date_tmp.GetMonth() + 1, date_tmp.GetDay()))

    def GetChoiceData(self, controle):
        selection = controle.GetSelection()
        if selection != -1:
            IDselection = controle.GetClientData(selection)
        else:
            IDselection = None
        return IDselection

    def SelectChoice(self, controle, data):
        nbreItems = controle.GetCount()
        index = 0
        for item in range(nbreItems):
            if controle.GetClientData(index) == data:
                controle.SetSelection(index)
                return
            index += 1

    def Validation(self):

        # Récupération des valeurs saisies
        type = self.GetChoiceData(self.choice_type)
        classification = self.GetChoiceData(self.choice_class)
        valPoint = self.GetChoiceData(self.choice_valpoint)
        date_debut = self.GetDatePickerValue(self.datepicker_date_debut)
        date_fin = self.GetDatePickerValue(self.datepicker_date_fin)
        rupture = self.check_rupture.GetValue()
        date_rupture = self.GetDatePickerValue(self.datepicker_rupture)
        essai = self.periode_essai.GetValue()

        # Vérifie que des valeurs ont été saisies
        if type == None:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez sélectionner un type de contrat dans la liste proposée."
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.choice_type.SetFocus()
            return False

        if classification == None:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez sélectionner une classification dans la liste proposée."
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.choice_class.SetFocus()
            return False

        if valPoint == None:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez sélectionner une valeur de point dans la liste proposée."
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.choice_valpoint.SetFocus()
            return False

        # Vérifie que la date de fin est supérieure à la date de début de contrat
        if date_debut > date_fin and self.datepicker_date_fin.IsShown():
            dlg = wx.MessageDialog(
                self,
                _(u"La date de fin de contrat que vous avez saisie est inférieure à la date de début !"
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.datepicker_date_fin.SetFocus()
            return False

        # Vérifie que la date de rupture est supérieure à la date de début de contrat
        if date_debut > date_rupture and rupture == True:
            dlg = wx.MessageDialog(
                self,
                _(u"La date de rupture de contrat que vous avez saisie est inférieure à la date de début !"
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.datepicker_date_fin.SetFocus()
            return False

        # Vérifie que la date de rupture est supérieure à la date de début de contrat et inférieure à la date de fin si contrat à durée déterminée :
        if self.datepicker_date_fin.IsShown(
        ) and date_rupture >= date_fin and rupture == True:
            dlg = wx.MessageDialog(
                self,
                _(u"La date de rupture de contrat que vous avez saisie est égale ou supérieure à la date de fin de contrat !"
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.datepicker_date_fin.SetFocus()
            return False

        # Vérifie que la valeur du point correspondant bien à la date de début de contrat
        valeurNecessaire = None
        for ID, valeur, dateValeur in self.listeValPoint:
            if date_debut >= dateValeur:
                valeurNecessaire = ID

        if valeurNecessaire == None:
            dlg = wx.MessageDialog(
                self,
                _(u"La valeur du point n'est pas correcte. Il n'existe pas dans la liste proposée de valeur correspondante à la date de début de contrat. \n\nVous devez donc créer une nouvelle valeur. \n\nSouhaitez-vous le faire maintenant ?"
                  ), "Erreur", wx.ICON_QUESTION | wx.YES_NO | wx.NO_DEFAULT)
            if dlg.ShowModal() == wx.ID_NO:
                dlg.Destroy()
                return False
            else:
                dlg.Destroy()
                self.OnBoutonValPoint(None)
                return False

        if valeurNecessaire != valPoint:
            dlg = wx.MessageDialog(
                self,
                _(u"La valeur du point ne correspond pas à la date de début du contrat. Vous devez sélectionner une autre valeur de points dans la liste proposée.\n\nVoulez-vous que je le fasse à votre place ?"
                  ), "Erreur", wx.ICON_QUESTION | wx.YES_NO | wx.NO_DEFAULT)
            if dlg.ShowModal() == wx.ID_NO:
                dlg.Destroy()
                return False
            else:
                dlg.Destroy()
                # Sélection automatique de la bonne valeur de point
                for index in range(self.choice_valpoint.GetCount()):
                    if self.choice_valpoint.GetClientData(
                            index) == valeurNecessaire:
                        self.choice_valpoint.SetSelection(index)
                        return False

        # Période d'essai
        if essai == "":
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez saisir un nombre de jours pour période d'essai."
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            return False

        if essai == 0:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous n'avez pas défini de période d'essai. \n\nSouhaitez-vous quand même continuer ? \n(Sinon cliquez 'non' ou 'annuler')"
                  ), "Erreur de saisie",
                wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL | wx.NO_DEFAULT)
            if dlg.ShowModal() == wx.ID_YES:
                dlg.Destroy()
            else:
                dlg.Destroy()
                return False

        # Mémorisation des données
        dictContrats = self.GetGrandParent().dictContrats
        dictContrats["IDtype"] = type
        dictContrats["IDclassification"] = classification
        dictContrats["valeur_point"] = valPoint
        dictContrats["date_debut"] = date_debut
        if self.datepicker_date_fin.IsShown():
            dictContrats["date_fin"] = date_fin
        else:
            dictContrats["date_fin"] = "2999-01-01"
        if rupture == True:
            dictContrats["date_rupture"] = date_rupture
        else:
            dictContrats["date_rupture"] = ""
        dictContrats["essai"] = essai

        return True
Пример #6
0
class Dialog(wx.Dialog):
    def __init__(self, parent, title="", IDperiode=0):
        wx.Dialog.__init__(self,
                           parent,
                           -1,
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
                           | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX)
        self.parent = parent
        self.panel_base = wx.Panel(self, -1)

        self.sizer_periode_staticbox = wx.StaticBox(self.panel_base, -1,
                                                    _(u"Nom de la période"))
        choices = [
            _(u"Février"),
            _(u"Pâques"),
            _(u"Eté"),
            _(u"Toussaint"),
            _(u"Noël")
        ]
        self.label_nom = wx.StaticText(self.panel_base, -1, _(u"Nom :"))
        self.choice_nom = wx.Choice(self.panel_base,
                                    -1,
                                    choices=choices,
                                    size=(100, -1))
        self.label_annee = wx.StaticText(self.panel_base, -1, _(u"Année :"))
        self.text_annee = wx.TextCtrl(self.panel_base,
                                      -1,
                                      "",
                                      style=wx.TE_CENTRE,
                                      size=(50, -1))

        self.sizer_dates_staticbox = wx.StaticBox(self.panel_base, -1,
                                                  _(u"Dates de la période"))
        self.label_dateDebut = wx.StaticText(self.panel_base, -1, u"Du")
        self.datepicker_dateDebut = DatePickerCtrl(self.panel_base,
                                                   -1,
                                                   style=DP_DROPDOWN)
        self.label_dateFin = wx.StaticText(self.panel_base, -1, _(u"au"))
        self.datepicker_dateFin = DatePickerCtrl(self.panel_base,
                                                 -1,
                                                 style=DP_DROPDOWN)

        self.bouton_aide = CTRL_Bouton_image.CTRL(
            self.panel_base,
            texte=_(u"Aide"),
            cheminImage=Chemins.GetStaticPath("Images/32x32/Aide.png"))
        self.bouton_ok = CTRL_Bouton_image.CTRL(
            self.panel_base,
            texte=_(u"Ok"),
            cheminImage=Chemins.GetStaticPath("Images/32x32/Valider.png"))
        self.bouton_annuler = CTRL_Bouton_image.CTRL(
            self.panel_base,
            texte=_(u"Annuler"),
            cheminImage=Chemins.GetStaticPath("Images/32x32/Annuler.png"))

        self.IDperiode = IDperiode
        if IDperiode != 0:
            self.Importation()

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.OnBoutonAide, self.bouton_aide)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonOk, self.bouton_ok)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonAnnuler, self.bouton_annuler)

    def __set_properties(self):
        self.SetTitle(_(u"Gestion des périodes de vacances"))
        if 'phoenix' in wx.PlatformInfo:
            _icon = wx.Icon()
        else:
            _icon = wx.EmptyIcon()
        _icon.CopyFromBitmap(
            wx.Bitmap(Chemins.GetStaticPath("Images/16x16/Logo.png"),
                      wx.BITMAP_TYPE_ANY))
        self.SetIcon(_icon)
        self.choice_nom.SetToolTip(
            wx.ToolTip(_(u"Choisissez ici le nom de la période")))
        self.text_annee.SetToolTip(
            wx.ToolTip(
                _(u"Saisissez ici l'année de la période. Ex. : '2008'")))
        self.datepicker_dateDebut.SetToolTip(
            wx.ToolTip(_(u"Saisissez ici la date de début de la période")))
        self.datepicker_dateFin.SetToolTip(
            wx.ToolTip(_(u"Saisissez ici la date de fin de la période")))
        self.bouton_aide.SetToolTip(
            wx.ToolTip(_(u"Cliquez ici pour obtenir de l'aide")))
        self.bouton_aide.SetSize(self.bouton_aide.GetBestSize())
        self.bouton_ok.SetToolTip(wx.ToolTip(_(u"Cliquez ici pour valider")))
        self.bouton_ok.SetSize(self.bouton_ok.GetBestSize())
        self.bouton_annuler.SetToolTip(
            wx.ToolTip(_(u"Cliquez ici pour annuler la saisie")))
        self.bouton_annuler.SetSize(self.bouton_annuler.GetBestSize())

    def __do_layout(self):
        sizer_base = wx.BoxSizer(wx.VERTICAL)
        grid_sizer_base = wx.FlexGridSizer(rows=3, cols=1, vgap=10, hgap=10)
        grid_sizer_boutons = wx.FlexGridSizer(rows=1, cols=4, vgap=10, hgap=10)

        sizer_contenu_1 = wx.StaticBoxSizer(self.sizer_periode_staticbox,
                                            wx.VERTICAL)
        grid_sizer_contenu_1 = wx.FlexGridSizer(rows=1,
                                                cols=6,
                                                vgap=10,
                                                hgap=10)
        grid_sizer_contenu_1.Add(self.label_nom, 0,
                                 wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_contenu_1.Add(self.choice_nom, 0, 0, 0)
        grid_sizer_contenu_1.Add(self.label_annee, 0,
                                 wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_contenu_1.Add(self.text_annee, 0, 0, 0)
        sizer_contenu_1.Add(grid_sizer_contenu_1, 1, wx.ALL | wx.EXPAND, 10)

        sizer_contenu_2 = wx.StaticBoxSizer(self.sizer_dates_staticbox,
                                            wx.VERTICAL)
        grid_sizer_contenu_2 = wx.FlexGridSizer(rows=1,
                                                cols=6,
                                                vgap=10,
                                                hgap=10)
        grid_sizer_contenu_2.Add(self.label_dateDebut, 0,
                                 wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_contenu_2.Add(self.datepicker_dateDebut, 0, 0, 0)
        grid_sizer_contenu_2.Add(self.label_dateFin, 0,
                                 wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_contenu_2.Add(self.datepicker_dateFin, 0, 0, 0)
        sizer_contenu_2.Add(grid_sizer_contenu_2, 1, wx.ALL | wx.EXPAND, 10)

        grid_sizer_base.Add(sizer_contenu_1, 1,
                            wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND, 10)
        grid_sizer_base.Add(sizer_contenu_2, 1,
                            wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.EXPAND, 10)

        grid_sizer_boutons.Add(self.bouton_aide, 0, 0, 0)
        grid_sizer_boutons.Add((20, 20), 0, wx.EXPAND, 0)
        grid_sizer_boutons.Add(self.bouton_ok, 0, 0, 0)
        grid_sizer_boutons.Add(self.bouton_annuler, 0, 0, 0)
        grid_sizer_boutons.AddGrowableCol(1)
        grid_sizer_base.Add(grid_sizer_boutons, 1,
                            wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 10)
        self.panel_base.SetSizer(grid_sizer_base)
        sizer_base.Add(self.panel_base, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_base)
        sizer_base.Fit(self)
        self.Layout()
        self.CenterOnScreen()

    def Importation(self):
        DB = GestionDB.DB()
        req = "SELECT * FROM periodes_vacances WHERE IDperiode=%d" % self.IDperiode
        DB.ExecuterReq(req)
        donnees = DB.ResultatReq()[0]
        DB.Close()
        if len(donnees) == 0: return
        # Place la valeur dans le controle nom période
        self.SelectChoice(self.choice_nom, donnees[1])
        # Place la valeur dans le controle annee
        self.text_annee.SetValue(str(donnees[2]))
        # Place la date de début dans le cdatePicker
        jour = int(donnees[3][8:10])
        mois = int(donnees[3][5:7]) - 1
        annee = int(donnees[3][:4])
        date = wx.DateTime()
        date.Set(jour, mois, annee)
        self.datepicker_dateDebut.SetValue(date)
        # Place la date de fin dans le cdatePicker
        jour = int(donnees[4][8:10])
        mois = int(donnees[4][5:7]) - 1
        annee = int(donnees[4][:4])
        date = wx.DateTime()
        date.Set(jour, mois, annee)
        self.datepicker_dateFin.SetValue(date)

    def SelectChoice(self, controle, data):
        nbreItems = controle.GetCount()
        index = 0
        for item in range(nbreItems):
            if controle.GetString(index) == data:
                controle.SetSelection(index)
                return
            index += 1

    def GetChoiceValue(self, controle):
        selection = controle.GetSelection()
        if selection != -1:
            IDselection = controle.GetString(selection)
        else:
            IDselection = None
        return IDselection

    def Sauvegarde(self):
        """ Sauvegarde des données dans la base de données """

        # Récupération ds valeurs saisies
        varNom = self.GetChoiceValue(self.choice_nom)
        varAnnee = self.text_annee.GetValue()
        varDateDebut = self.datepicker_dateDebut.GetValue()
        varTxtDateDebut = str(
            datetime.date(varDateDebut.GetYear(),
                          varDateDebut.GetMonth() + 1, varDateDebut.GetDay()))
        varDateFin = self.datepicker_dateFin.GetValue()
        varTxtDateFin = str(
            datetime.date(varDateFin.GetYear(),
                          varDateFin.GetMonth() + 1, varDateFin.GetDay()))

        DB = GestionDB.DB()
        # Création de la liste des données
        listeDonnees = [
            ("nom", varNom),
            ("annee", varAnnee),
            ("date_debut", varTxtDateDebut),
            ("date_fin", varTxtDateFin),
        ]
        if self.IDperiode == 0:
            # Enregistrement d'une nouvelle valeur
            newID = DB.ReqInsert("periodes_vacances", listeDonnees)
            ID = newID
        else:
            # Modification des valeurs
            DB.ReqMAJ("periodes_vacances", listeDonnees, "IDperiode",
                      self.IDperiode)
            ID = self.IDperiode
        DB.Commit()
        DB.Close()
        return ID

    def OnBoutonAide(self, event):
        from Utils import UTILS_Aide
        UTILS_Aide.Aide("Lespriodesdevacances")

    def OnBoutonAnnuler(self, event):
        self.EndModal(wx.ID_CANCEL)

    def OnBoutonOk(self, event):
        """ Validation des données saisies """

        # Vérifie que des valeurs ont été saisies
        valeur = self.GetChoiceValue(self.choice_nom)
        if valeur == None:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez sélectionner un nom de période dans la liste proposée !"
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.choice_nom.SetFocus()
            return

        valeur = self.text_annee.GetValue()
        if valeur == "":
            dlg = wx.MessageDialog(self,
                                   _(u"Vous devez saisir une année valide."),
                                   "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.text_annee.SetFocus()
            return
        # Vérifie que la valeur est bien constituée de chiffres uniquement
        incoherences = ""
        for lettre in valeur:
            if lettre not in "0123456789.":
                incoherences += "'" + lettre + "', "
        if len(incoherences) != 0:
            dlg = wx.MessageDialog(
                self, _(u"L'année que vous avez saisie n'est pas correcte."),
                "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.text_annee.SetFocus()
            return
        valeur = int(valeur)
        if valeur < 1000 or valeur > 3000:
            dlg = wx.MessageDialog(
                self, _(u"L'année que vous avez saisie n'est pas correcte."),
                "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.text_annee.SetFocus()
            return

        date_debut = self.datepicker_dateDebut.GetValue(
        )  # self.GetDatePickerValue(self.datepicker_date_debut)
        date_fin = self.datepicker_dateFin.GetValue(
        )  # self.GetDatePickerValue(self.datepicker_date_fin)
        # Vérifie que la date de fin est supérieure à la date de début de contrat
        if date_debut > date_fin:
            dlg = wx.MessageDialog(
                self,
                _(u"La date de fin de vacances doit être supérieure à la date de début !"
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.datepicker_dateFin.SetFocus()
            return

        # Sauvegarde
        self.Sauvegarde()
        # MAJ du listCtrl des valeurs de points
        if FonctionsPerso.FrameOuverte("panel_config_periodes_vacs") != None:
            self.GetParent().MAJ_ListCtrl()

        # Fermeture
        self.EndModal(wx.ID_OK)
Пример #7
0
class GamemasterWindow(wx.Panel):
    def __init__(self, parent):
        #wx.Frame.__init__(self,None,title="QJM Game Master")
        wx.Panel.__init__(self, parent)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.SetMinSize((850, 400))
        self.SetSize((800, 600))

        frame_sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(frame_sizer)
        # create a panel
        main_panel = wx.ScrolledWindow(self)
        frame_sizer.Add(main_panel, 1, wx.ALL | wx.EXPAND)
        main_panel.SetScrollRate(0, 5)
        #main_panel = wx.Panel(self)
        main_sizer = wx.BoxSizer(wx.VERTICAL)
        side_sizer = wx.BoxSizer(wx.HORIZONTAL)
        main_sizer.Add(side_sizer, 1, wx.EXPAND | wx.ALL)
        main_panel.SetSizer(main_sizer)

        ### create a menu
        #menubar = wx.MenuBar()
        #filemenu = wx.Menu()
        #editmenu = wx.Menu()
        #reloadmenu = filemenu.Append(wx.ID_ANY,"&Load state")
        #filemenu.AppendSeparator()
        #quitmenu = filemenu.Append(wx.ID_EXIT, "&Quit", "Quit application")
        #dbmenu = editmenu.Append(wx.ID_ANY,"&Database Editor")
        #menubar.Append(filemenu,"&File")
        #menubar.Append(editmenu,"&Edit")
        #self.SetMenuBar(menubar)

        ## menu binds
        #self.Bind(wx.EVT_MENU,self.OnLoad,reloadmenu)
        #self.Bind(wx.EVT_MENU,self.OnClose,quitmenu)
        #self.Bind(wx.EVT_MENU,self.OnDbEdit,dbmenu)

        sides = ["", "NATO", "Warsaw Pact"]
        # attacker info
        attacker_sizer = wx.StaticBoxSizer(wx.VERTICAL, main_panel,
                                           "Attacker:")
        side_sizer.Add(attacker_sizer, 1, wx.ALL | wx.EXPAND, 5)
        # attacker side selecton
        self.attacker_side = wx.Choice(main_panel, -1, choices=sides)
        self.attacker_side.Bind(wx.EVT_CHOICE, self.OnAttackerSide)
        attacker_sizer.Add(self.attacker_side, 0, wx.EXPAND, 3)
        # attacker listctrl
        self.attacker_list = CheckListCtrl(main_panel)
        attacker_sizer.Add(self.attacker_list, 1, wx.EXPAND, 3)
        self.attacker_list.InsertColumn(0, "Formation", width=180)
        self.attacker_list.InsertColumn(1, "Strength")
        self.attacker_list.Bind(EVT_CHECKLISTCTRL, self.OnAttackerCheck)
        # TLI output
        self.oli_atk = 0  # tracker
        self.attacker_oli = wx.StaticText(
            main_panel,
            -1,
            "Total attacker OLI: {:>9,.0f}".format(0),
        )
        attacker_sizer.Add(self.attacker_oli, 0,
                           wx.CENTRE | wx.EXPAND | wx.ALL, 3)

        # defender info
        defender_sizer = wx.StaticBoxSizer(wx.VERTICAL, main_panel,
                                           "Defender:")
        side_sizer.Add(defender_sizer, 1, wx.ALL | wx.EXPAND, 5)
        # defender side selecton
        self.defender_side = wx.Choice(main_panel, -1, choices=sides)
        self.defender_side.Bind(wx.EVT_CHOICE, self.OnDefenderSide)
        defender_sizer.Add(self.defender_side, 0, wx.EXPAND, 3)
        # defender listctrl
        self.defender_list = CheckListCtrl(main_panel)
        defender_sizer.Add(self.defender_list, 1, wx.EXPAND, 3)
        self.defender_list.InsertColumn(0, "Formation", width=180)
        self.defender_list.InsertColumn(1, "Strength")
        self.defender_list.Bind(EVT_CHECKLISTCTRL, self.OnDefenderCheck)
        # TLI output
        self.oli_def = 0  # tracker
        self.defender_oli = wx.StaticText(
            main_panel,
            -1,
            "Total defender OLI: {:>9,.0f}".format(0),
        )
        defender_sizer.Add(self.defender_oli, 0,
                           wx.CENTRE | wx.EXPAND | wx.ALL, 3)

        # bind double click for SITREP
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.ShowSITREP,
                  self.attacker_list)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.ShowSITREP,
                  self.defender_list)

        # battle data #########################
        data_sizer = wx.BoxSizer(wx.HORIZONTAL)
        main_sizer.Add(data_sizer, 0, wx.EXPAND | wx.ALL)
        # duration
        duration_sizer = wx.StaticBoxSizer(wx.VERTICAL, main_panel,
                                           "Duration (hrs):")
        self.duration = wx.SpinCtrl(main_panel, -1, min=4, max=48, initial=4)
        duration_sizer.Add(self.duration, 1, wx.EXPAND | wx.ALL, 3)
        data_sizer.Add(duration_sizer, 0, wx.EXPAND | wx.ALL, 5)
        # terrain
        terrain_sizer = wx.StaticBoxSizer(wx.VERTICAL, main_panel, "Terrain:")
        roughness = [
            "rugged, heavily wooded", "rugged, mixed", "rugged, bare",
            "rolling, heavily wooded", "rolling, mixed", "rolling, bare",
            "flat, heavily wooded", "flat, mixed", "flat, bare, hard",
            "flat, desert", "desert, sandy dunes", "swamp, jungled",
            "swamp, mixed or open", "urban"
        ]
        self.terrain = wx.Choice(main_panel, -1, choices=roughness)
        self.terrain.SetSelection(0)
        terrain_sizer.Add(self.terrain, 1, wx.EXPAND | wx.ALL, 3)
        data_sizer.Add(terrain_sizer, 1, wx.EXPAND | wx.ALL, 5)
        # weather
        weather_types = [
            "dry, sunshine, extreme heat",
            "dry, sunshine, temperate",
            "dry, sunshine, extreme cold",
            "dry, overcast, extreme heat",
            "dry, overcast, temperate",
            "dry, overcast, extreme cold",
            "wet, light, extreme heat",
            "wet, light, temperate",
            "wet, light, extreme cold",
            "wet, heavy, extreme heat",
            "wet, heavy, temperate",
            "wet, heavy, extreme cold",
        ]
        weather_sizer = wx.StaticBoxSizer(wx.VERTICAL, main_panel, "Weather:")
        self.weather = wx.Choice(main_panel, -1, choices=weather_types)
        self.weather.SetSelection(0)
        weather_sizer.Add(self.weather, 1, wx.EXPAND | wx.ALL, 3)
        data_sizer.Add(weather_sizer, 1, wx.EXPAND | wx.ALL, 5)

        # 2nd row
        datar2_sizer = wx.BoxSizer(wx.HORIZONTAL)
        main_sizer.Add(datar2_sizer, 0, wx.EXPAND | wx.ALL)
        # season
        season_sizer = wx.StaticBoxSizer(wx.HORIZONTAL, main_panel, "Season:")
        season_choices = [
            "winter, jungle", "winter, desert", "winter, temperate",
            "spring, jungle", "spring, desert", "spring, temperate",
            "summer, jungle", "summer, desert", "summer, temperate",
            "fall, jungle", "fall, desert", "fall, temperate"
        ]
        seasons_choices = ["spring", "summer", "fall", "winter"]
        seasonloc_choices = ["temperate", "jungle", "desert"]
        self.season = wx.Choice(main_panel, -1, choices=seasons_choices)
        self.seasonloc = wx.Choice(main_panel, -1, choices=seasonloc_choices)
        self.season.SetSelection(0)
        self.seasonloc.SetSelection(0)
        season_sizer.Add(self.season, 1, wx.EXPAND | wx.ALL, 3)
        season_sizer.Add(self.seasonloc, 1, wx.EXPAND | wx.ALL, 3)
        datar2_sizer.Add(season_sizer, 1, wx.EXPAND | wx.ALL, 5)
        # roads
        road_density_choices = [
            "dense network", "medium network", "sparse network"
        ]
        road_quality_choices = ["good roads", "mediocre roads", "poor roads"]
        roads_sizer = wx.StaticBoxSizer(wx.HORIZONTAL, main_panel, "Roads:")
        self.road_density = wx.Choice(main_panel,
                                      -1,
                                      choices=road_density_choices)
        self.road_density.SetSelection(0)
        self.road_quality = wx.Choice(main_panel,
                                      -1,
                                      choices=road_quality_choices)
        self.road_quality.SetSelection(0)
        roads_sizer.Add(self.road_density, 1, wx.EXPAND | wx.ALL, 3)
        roads_sizer.Add(self.road_quality, 1, wx.EXPAND | wx.ALL, 3)
        datar2_sizer.Add(roads_sizer, 1, wx.EXPAND | wx.ALL, 5)
        # posture
        def_pos_choices = ["hasty", "prepared", "fortified", "delay", "attack"]
        posture_sizer = wx.StaticBoxSizer(wx.VERTICAL, main_panel,
                                          "Defender posture:")
        self.posture = wx.Choice(main_panel, -1, choices=def_pos_choices)
        self.posture.SetSelection(0)
        posture_sizer.Add(self.posture, 1, wx.EXPAND | wx.ALL, 3)
        datar2_sizer.Add(posture_sizer, 1, wx.EXPAND | wx.ALL, 5)

        # date and name
        mdata_sizer = wx.BoxSizer(wx.HORIZONTAL)
        main_sizer.Add(mdata_sizer, 0, wx.EXPAND | wx.ALL, 0)
        datesizer = wx.StaticBoxSizer(wx.HORIZONTAL, main_panel,
                                      "Date and location:")
        self.date = DatePickerCtrl(main_panel, -1, style=wx.adv.DP_DROPDOWN)
        self.date.SetValue(wx.DateTime(1, 10, 1983))  # default is 1 Nov 1983
        #self.time = TimePickerCtrl(main_panel,-1)
        self.time = TimeCtrl(main_panel, -1, value='00:00', format='24HHMM')
        self.location = wx.TextCtrl(main_panel, -1, "")
        datesizer.Add(self.date, 0, wx.EXPAND | wx.ALL, 3)
        datesizer.Add(self.time, 0, wx.EXPAND | wx.ALL, 3)
        datesizer.Add(self.location, 1, wx.EXPAND | wx.ALL, 3)
        mdata_sizer.Add(datesizer, 1, wx.EXPAND | wx.ALL, 3)
        # river
        river_sizer = wx.StaticBoxSizer(wx.HORIZONTAL, main_panel, "River:")
        river_choices = [
            "no river",
            "fordable, 20m",
            "fordable, 50m",
            "fordable, 100m",
            "fordable, 500m",
            "unfordable, 20m",
            "unfordable, 50m",
            "unfordable, 100m",
            "unfordable, 500m",
        ]
        self.river = wx.Choice(main_panel, -1, choices=river_choices)
        self.river.SetSelection(0)
        river_sizer.Add(self.river, 1, wx.EXPAND | wx.ALL, 3)
        mdata_sizer.Add(river_sizer, 1, wx.EXPAND | wx.ALL, 3)

        # frontage
        frontage_sizer = wx.StaticBoxSizer(wx.HORIZONTAL, main_panel,
                                           "Frontage:")
        self.frontage = wx.Slider(main_panel,
                                  -1,
                                  100,
                                  0,
                                  100,
                                  style=wx.SL_HORIZONTAL | wx.SL_LABELS)
        frontage_sizer.Add(self.frontage, 1, wx.EXPAND | wx.ALL, 3)
        mdata_sizer.Add(frontage_sizer, 1, wx.EXPAND | wx.ALL, 3)

        # buttons
        button_panel = wx.Panel(self, style=wx.BORDER_THEME)
        frame_sizer.Add(button_panel, 0, wx.ALL | wx.EXPAND)
        button_sizer = wx.BoxSizer(wx.HORIZONTAL)
        button_panel.SetSizer(button_sizer)
        #main_sizer.Add(button_sizer,0,wx.EXPAND|wx.ALL,)
        self.simulate_btn = wx.Button(button_panel, -1, "Simulate")
        self.simulate_btn.Bind(wx.EVT_BUTTON, self.OnSimulate)
        self.save_btn = wx.Button(button_panel, -1, "Save State")
        self.save_btn.Bind(wx.EVT_BUTTON, self.OnSave)
        self.load_btn = wx.Button(button_panel, -1, "Load State")
        self.load_btn.Bind(wx.EVT_BUTTON, self.OnLoad)
        button_sizer.Add(self.simulate_btn, 1, wx.EXPAND | wx.ALL, 3)
        button_sizer.Add(self.save_btn, 1, wx.EXPAND | wx.ALL, 3)
        button_sizer.Add(self.load_btn, 1, wx.EXPAND | wx.ALL, 3)

    def OnAttackerCheck(self, event):
        idx = event.idx
        name = self.attacker_list.GetItemText(idx, col=0)
        form = self.GetTopLevelParent().gdb.gm_forms_db.formation_by_name(name)
        flag = event.flg
        if flag:  # if checked, add the OLI value
            self.oli_atk += form.OLI
        else:  # if unchecked, remove it
            self.oli_atk += -form.OLI
        # update the OLI display
        self.attacker_oli.SetLabel("Total attacker OLI: {:>9,.0f}".format(
            self.oli_atk))

    def OnDefenderCheck(self, event):
        idx = event.idx
        name = self.defender_list.GetItemText(idx, col=0)
        form = self.GetTopLevelParent().gdb.gm_forms_db.formation_by_name(name)
        flag = event.flg
        if flag:  # if checked, add the OLI value
            self.oli_def += form.OLI
        else:  # if unchecked, remove it
            self.oli_def += -form.OLI
        # update the OLI display
        self.defender_oli.SetLabel("Total defender OLI: {:>9,.0f}".format(
            self.oli_def))

    def OnAttackerSide(self, event):
        # set both OLI values to zero
        self.attacker_oli.SetLabel("Total attacker OLI: {:>9,.0f}".format(0))
        self.defender_oli.SetLabel("Total defender OLI: {:>9,.0f}".format(0))
        self.attacker_list.DeleteAllItems()  # clear items
        side = self.attacker_side.GetString(self.attacker_side.GetSelection())
        if side == "":
            return
        faction_search = side_dict[side]
        formations = self.GetTopLevelParent().gdb.gm_forms_db.forms
        for form in formations:
            if form.faction in faction_search:
                entry = [form.name, "{:,.0f}".format(form.OLI)]
                self.attacker_list.Append(entry)

    def OnDefenderSide(self, event):
        self.defender_list.DeleteAllItems()  # clear items
        side = self.defender_side.GetString(self.defender_side.GetSelection())
        if side == "":
            return
        faction_search = side_dict[side]
        formations = self.GetTopLevelParent().gdb.gm_forms_db.forms
        for form in formations:
            if form.faction in faction_search:
                entry = [form.name, "{:,.0f}".format(form.OLI)]
                self.defender_list.Append(entry)

    def OnSimulate(self, event):
        # Multiply force strength by operational variables - overall forms a big ugly equation
        # force strength is shown by:
        # S = [(ws+Wmg+Whw)*rn]+(wgi*rn)+[(Wg+Wgy)*(rwg*hwg*zwg*wyg)]+(Wi*rwi*hwi)+ ...
        #        ...(Wy*rwy*hwy*zyw*wyy) + Wgi + Wgy
        #   note Wgi is included up to enemy armour OLI, then only half excess is added
        #   same applies for Wfgy for air defense weapons, up to hostile Close Air Support (Wey)
        # Air firepower (Wy) over sum of all ground firepower is not fully effective
        # Wy > Ws + Wmy + Whw + Wgi + Wg + Wgy + Wi, only half of excess Wy is applied
        #       maximum Wy is 3x ground weapons firepower
        #
        # operational factors are given by:
        # [Ma-(1-rm*hm)(Ma-1)]*le*t*o*b*us*ru*hu*zu*v
        #       where v = 1-(N*uv/ru*(Se/Sf)**.5 * vy*vr)/Sf
        # Following are degredation factors
        # le: leadership - typically 1
        # t: training/experience - typically 1
        # o: morale - typically 1
        # b: logistical capability - typically 1

        # Get OLI values from checked attackers
        attackers = list()
        attackers_forms = list()
        for idx in range(self.attacker_list.GetItemCount()):
            if self.attacker_list.IsChecked(idx):
                attackers.append(self.attacker_list.GetItemText(idx))
        for form in attackers:
            attackers_forms.append(
                self.GetTopLevelParent().gdb.gm_forms_db.formation_by_name(
                    form))
        attacker_oli = self.GetTopLevelParent().gdb.gm_forms_db.oli_by_names(
            attackers)
        N_attacker = self.GetTopLevelParent().gdb.gm_forms_db.pers_by_names(
            attackers)
        J_attacker = self.GetTopLevelParent(
        ).gdb.gm_forms_db.vehicles_by_names(
            attackers,
            self.GetTopLevelParent().gdb.equip_db)

        # Get OLI values from checked defenders
        defenders = list()
        defenders_forms = list()
        for idx in range(self.defender_list.GetItemCount()):
            if self.defender_list.IsChecked(idx):
                defenders.append(self.defender_list.GetItemText(idx))
        defender_oli = self.GetTopLevelParent().gdb.gm_forms_db.oli_by_names(
            defenders)
        for form in defenders:
            defenders_forms.append(
                self.GetTopLevelParent().gdb.gm_forms_db.formation_by_name(
                    form))

        N_defender = self.GetTopLevelParent().gdb.gm_forms_db.pers_by_names(
            defenders)
        J_defender = self.GetTopLevelParent(
        ).gdb.gm_forms_db.vehicles_by_names(
            defenders,
            self.GetTopLevelParent().gdb.equip_db)

        # get environment data from the forms
        terrain = self.terrain.GetString(self.terrain.GetSelection())
        weather = self.weather.GetString(self.weather.GetSelection())
        season_sel = self.season.GetString(self.season.GetSelection())
        season_locale = self.seasonloc.GetString(self.seasonloc.GetSelection())
        river = self.river.GetString(self.river.GetSelection())
        time_day = self.time.GetValue()
        print(time_day)
        # determine if it is day or night
        if time_day > "06:00" and time_day < "20:00":
            daytime = True
        else:
            daytime = False

        # get the frontage of the attack (% of defenders)
        frontage = self.frontage.GetValue() / 100

        seasonstr = season_sel + ', ' + season_locale
        #print(seasonstr)

        # get the posture from the form
        def_posture = self.posture.GetString(self.posture.GetSelection())

        # Terrain effectiveness values (r) and weather effectiveness (h)
        # infantry & antitank
        rn = mc.terrain(terrain, 'inf')
        # artillery & air defence
        rwg = mc.terrain(terrain, 'arty')
        hwg = mc.weather(weather, 'arty')
        zwg = mc.season(seasonstr, 'arty')
        # tanks
        rwi = mc.terrain(terrain, 'tank')
        hwi = mc.weather(weather, 'tank')
        # aircraft
        rwy = mc.terrain(terrain, 'air')
        hwy = mc.weather(weather, 'air')
        zwy = mc.season(seasonstr, 'air')

        # these constants are for air superiority
        wyg = 1
        wyy = 1

        print(attacker_oli.air, attacker_oli.ad)
        print(defender_oli.air, defender_oli.ad)

        # attacker data:
        Wain = attacker_oli.inf
        Waat = attacker_oli.at
        Watn = attacker_oli.afv
        Waar = attacker_oli.arty
        Waad = attacker_oli.ad
        Waai = attacker_oli.air

        # defender data
        Wdin = defender_oli.inf
        Wdat = defender_oli.at
        Wdtn = defender_oli.afv
        Wdar = defender_oli.arty
        Wdad = defender_oli.ad
        Wdai = defender_oli.air

        # deal with overmatches in at and ad OLIs
        Waat = overmatch(Waat, Wdtn)
        Wdat = overmatch(Wdat, Watn)
        Waad = overmatch(Waad, Wdai, cap=3)
        Wdad = overmatch(Wdad, Waai, cap=3)

        # using my "simplified" formula
        S_attacker = ((Wain + Waat) * rn +
                      (Waar + Waad * wyg) * rwg * hwg * zwg +
                      Watn * rwi * hwi + Waai * rwy * hwy * zwy * wyy)
        S_defender = (
            (Wdin + Wdat) * rn + (Wdar + Wdad * wyg) * rwg * hwg * zwg +
            Wdtn * rwi * hwi + Wdai * rwy * hwy * zwy * wyy) * frontage

        # get the combat power
        Faj = 1  # judgement degrading factor for attacker
        Fdj = 1  # judgement degrading factor for defender
        uas = mc.stren_posture_factor('attack')  # posture for attacker
        uds = mc.stren_posture_factor(def_posture)  # posture for defender
        rau = 1  # terrain for attacker - attacker is always 1
        rdu = mc.terrain(
            terrain, 'defpos')  # terrain for defender - uses terrain defpos
        hau = mc.weather(weather, 'attack')  # weather for attacker
        hdu = 1  # weather for defender - defender is always 1
        zau = mc.season(seasonstr, 'attack')  # season for attacker
        zdu = 1  # season for defender - defender is always 1

        # mobility factors
        road_quality = self.road_quality.GetString(
            self.road_quality.GetSelection())
        road_density = self.road_density.GetString(
            self.road_density.GetSelection())
        rma = mc.terrain(terrain, 'mobility')
        hma = mc.weather(weather, 'mobility')
        mya = 1  # don't know what this factor is
        myd = 1  # don't know what this factor is either

        # vulnerability factors
        uav = mc.vuln_posture_factor('attack')
        udv = mc.vuln_posture_factor(def_posture)
        vay = 1  # air superiority vulnerability
        vdy = 1  # air superiority vulnerability
        var = 1  # shoreline vulnerability
        vdr = 1  # shoreline vulnerability

        # mobility
        MFactor = 12  # 20 for WWII
        M_attacker = ((
            (N_attacker + MFactor * J_attacker + Waar) * mya / N_attacker) /
                      ((N_defender + MFactor * J_defender + Wdar) * myd /
                       N_defender))**0.5
        M_defender = 1  # always 1

        ma_operational = M_attacker - (1 - rma * hma) * (M_attacker - 1)
        md_operational = M_defender

        # vulnerability
        Vuln_attacker = N_attacker * uav / rau * (S_defender /
                                                  S_attacker)**0.5 * vay * var
        print("Vulnerability calcs:", N_attacker, uav, rau, S_defender,
              S_attacker, vay, var)
        Vuln_defender = N_defender * udv / rdu * (S_attacker /
                                                  S_defender)**0.5 * vdy * vdr
        va_operational = (1 - Vuln_attacker / S_attacker)
        vd_operational = (1 - Vuln_defender / S_defender)

        if va_operational > 0.8:
            va_operational = 0.8
        elif va_operational > 0.3:
            va_operational = 0.3 + 0.1 * (va_operational - 0.3)
        else:
            va_operational = 0.3
        if vd_operational > 0.8:
            vd_operational = 0.8
        elif vd_operational > 0.3:
            vd_operational = 0.3 + 0.1 * (vd_operational - 0.3)
        else:
            vd_operational = 0.3

        # note that the CEV is already contained in the OLI output
        Op_attacker = Faj * uas * rau * hau * zau
        Op_defender = Fdj * uds * rdu * hdu * zdu

        P_attacker = S_attacker * ma_operational * Op_attacker * va_operational
        P_defender = S_defender * md_operational * Op_defender * vd_operational
        P_ratio = P_attacker / P_defender

        dateval = self.date.GetValue().FormatISODate()
        #timeval = self.time.GetValue().FormatISOTime()
        timeval = self.time.GetWxDateTime().FormatISOTime()
        location = self.location.GetValue()

        print("*** START REPORT ***\n")

        print("{} engages {}\n".format(attackers, defenders))

        print(
            "Base OLI data: (W) || Attacker: {:9,.0f} | Defender: {:9,.0f} | Ratio {:.1f}"
            .format(attacker_oli.total, defender_oli.total,
                    attacker_oli.total / defender_oli.total))

        print(
            "Strength data (S): || Attacker: {:9,.0f} | Defender: {:9,.0f} | Ratio {:.1f}"
            .format(S_attacker, S_defender, S_attacker / S_defender))

        print(
            "Combat Power (P):  || Attacker: {:9,.0f} | Defender: {:9,.0f} | Ratio {:.1f}"
            .format(P_attacker, P_defender, P_attacker / P_defender))

        print(
            "\n Key factors: |  Attacker | Defender\n",
            "Strength     | {:9,.0f} | {:9,.0f}\n".format(
                S_attacker, S_defender),
            "Mobility     | {:9,.2f} | {:9,.2f}\n".format(
                M_attacker, M_defender),
            "Vulnerability| {:9,.0f} | {:9,.0f}\n".format(
                Vuln_attacker, Vuln_defender),
            "Op. Vuln     | {:9,.3f} | {:9,.3f}\n".format(
                va_operational, vd_operational),
        )

        # advance rate - probably need to run for each individual formation?
        for name in attackers:
            index = self.GetTopLevelParent().gdb.gm_forms_db.names.index(name)
            unittype = self.GetTopLevelParent(
            ).gdb.gm_forms_db.forms[index].type
            adv_base = mc.advance_rate_base(P_ratio, unittype, def_posture)
            adv_roads = mc.advance_rate_road(road_quality, road_density)
            adv_terr = mc.advance_rate_terr(terrain, unittype)
            adv_river = mc.river_obstacle_factor(river)
            adv_rate = adv_base * adv_roads * adv_terr * adv_river
            atk_losses = self.GetTopLevelParent(
            ).gdb.gm_forms_db.forms[index].casualties(
                P_ratio,
                'attack',
                day=daytime,
                duration=self.duration.GetValue(),
                pers=N_attacker)
            print("{} advance rate: {:.1f} km/day".format(
                self.GetTopLevelParent().gdb.gm_forms_db.forms[index].name,
                adv_rate))
            print("---")
            print(self.GetTopLevelParent().gdb.gm_forms_db.forms[index].SITREP(
                atk_losses,
                activity='Attacking',
                datestr="{} {}".format(dateval, timeval),
                location=location,
                writefolder=gmdir + "\\reports"))

        for name in defenders:
            index = self.GetTopLevelParent().gdb.gm_forms_db.names.index(name)
            def_losses = self.GetTopLevelParent(
            ).gdb.gm_forms_db.forms[index].casualties(
                P_ratio,
                def_posture,
                day=daytime,
                duration=self.duration.GetValue(),
                exposure=frontage,
                pers=N_defender)
            print("---")
            print(self.GetTopLevelParent().gdb.gm_forms_db.forms[index].SITREP(
                def_losses,
                activity=def_posture + ' defense',
                datestr="{} {}".format(dateval, timeval),
                location=location,
                writefolder=gmdir + "\\reports"))

        # finish the report
        print("*** END REPORT ***")

    def ShowSITREP(self, event):
        # get the list that was clicked
        formlist = event.GetEventObject()
        # get the item from the list
        item = formlist.GetItemText(event.GetIndex(), col=0)
        # print a sitrep for the item
        form = self.GetTopLevelParent().gdb.gm_forms_db.formation_by_name(item)
        infoframe = formation_info_form(
            self,
            form.SITREP(activity='None') +
            "\nNo TLI data for:\n{}".format(form.NoTLIData), item)
        infoframe.Show()

    def OnDbEdit(self, event):
        eqp = equip_gui.equipment_gui_frame()
        eqp.Show()

    def OnSave(self, event):
        dlg = wx.DirDialog(self,
                           message="Master folder for formations to save",
                           defaultPath=gmdir)
        result = dlg.ShowModal()
        path = dlg.GetPath()
        dlg.Destroy()
        if result == wx.ID_OK:
            for form in self.GetTopLevelParent().gdb.gm_forms_db.forms:
                form.output(path)

    def OnLoad(self, event):
        dlg = wx.DirDialog(self,
                           message="Master folder for formations to load",
                           defaultPath=gmdir)
        result = dlg.ShowModal()
        path = dlg.GetPath()
        dlg.Destroy()
        if result == wx.ID_OK:
            self.GetTopLevelParent().gdb.load_gm_formations(path)

    def OnClose(self, event):
        dlg = wx.MessageDialog(self, "Are you sure you want to close?",
                               "Confirm exit",
                               wx.OK | wx.CANCEL | wx.ICON_QUESTION)
        result = dlg.ShowModal()
        dlg.Destroy()
        if result == wx.ID_OK:
            self.Destroy()
Пример #8
0
class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, parent=None, title=u'量化交易软件', size=(1500, 800),
                          style=wx.DEFAULT_FRAME_STYLE ^ wx.MAXIMIZE_BOX)
        # 创建显示区面板
        self.DispPanel = MPL_Panel_Base(self)
        self.BackPanel = Loop_Panel_Base(self)
        self.am = self.DispPanel.am
        self.vol = self.DispPanel.vol
        self.devol = self.DispPanel.devol
        self.macd = self.DispPanel.macd

        # 创建参数区面板
        self.ParaPanel = wx.Panel(self, -1)
        paraInput_Box = wx.StaticBox(self.ParaPanel, -1, u'参数输入')
        paraInput_Sizer = wx.StaticBoxSizer(paraInput_Box, wx.VERTICAL)

        self.StNameCodedict = {u"开山股份": "300257.SZ", u"浙大网新": "600797.SS",
                               u"水晶光电": "002273.SZ", u"高鸿股份": "000851.SZ"}

        # 初始化股票代码变量
        self.stockName_Val = u"开山股份"
        self.stockCode_Val = self.StNameCodedict[self.stockName_Val]

        self.stockName_CMBO = wx.ComboBox(self.ParaPanel, -1, self.stockName_Val,
                                          choices=list(self.StNameCodedict.keys()),
                                          style=wx.CB_READONLY | wx.CB_DROPDOWN)
        stockCode_Text = wx.StaticText(self.ParaPanel, -1, u'股票名称')

        # 策略选择
        strate_Text = wx.StaticText(self.ParaPanel, -1, u"策略选择")
        strate_Combo_Val = [u"双趋势融合", u"阿尔法", u"布林带"]
        self.pickstrate_Val = u"双趋势融合"
        self.pickstrate_CMBO = wx.ComboBox(self.ParaPanel, -1, self.pickstrate_Val,
                                           choices=strate_Combo_Val,
                                           style=wx.CB_READONLY | wx.CB_DROPDOWN)  # 策略名称

        # 日历控件选择数据周期
        # 结束时间
        self.dpcEndTime = DatePickerCtrl(self.ParaPanel, -1,
                                                style=DP_DROPDOWN | DP_SHOWCENTURY | DP_ALLOWNONE)
        # 起始时间
        self.dpcStartTime = DatePickerCtrl(self.ParaPanel, -1,
                                                  style=DP_DROPDOWN | DP_SHOWCENTURY | DP_ALLOWNONE)
        DateTimeNow = wx.DateTime.Now()
        self.dpcEndTime.SetValue(DateTimeNow)
        DateTimeNow.SetYear(DateTimeNow.GetYear() - 1)
        self.dpcStartTime.SetValue(DateTimeNow)
        stockData_Text = wx.StaticText(self.ParaPanel, -1, u'日期(Start-End)')

        # 初始化时间变量
        dateVal = self.dpcStartTime.GetValue()
        self.stockSdate_Val = datetime.datetime(dateVal.year, dateVal.month + 1, dateVal.day)
        # print(self.stockSdate_Val)
        dateVal = self.dpcEndTime.GetValue()
        self.stockEdate_Val = datetime.datetime(dateVal.year, dateVal.month + 1, dateVal.day)
        # print(self.stockEdate_Val)

        paraInput_Sizer.Add(stockCode_Text, proportion=0, flag=wx.EXPAND | wx.ALL, border=2)
        paraInput_Sizer.Add(self.stockName_CMBO, proportion=0, flag=wx.EXPAND | wx.ALL | wx.CENTER, border=2)
        paraInput_Sizer.Add(stockData_Text, proportion=0, flag=wx.EXPAND | wx.ALL, border=2)
        paraInput_Sizer.Add(self.dpcStartTime, proportion=0, flag=wx.EXPAND | wx.ALL | wx.CENTER, border=2)
        paraInput_Sizer.Add(self.dpcEndTime, proportion=0, flag=wx.EXPAND | wx.ALL | wx.CENTER, border=2)
        paraInput_Sizer.Add(strate_Text, proportion=0, flag=wx.EXPAND | wx.ALL | wx.CENTER, border=2)
        paraInput_Sizer.Add(self.pickstrate_CMBO, proportion=0, flag=wx.EXPAND | wx.ALL | wx.CENTER, border=2)

        # RadioList = ["跳空缺口", "金叉\死叉", "N日突破", "均线突破"]
        RadioList = ["不显示", "跳空缺口", "金叉/死叉", "N日突破"]
        self.StratInputBox = wx.RadioBox(self.ParaPanel, -1, label=u"指标提示", choices=RadioList,
                                         majorDimension=4, style=wx.RA_SPECIFY_ROWS)
        self.StratInputBox.Bind(wx.EVT_RADIOBOX, self.OnRadioBox_Indicator)
        # 初始化指标变量
        self.IndicatInput_Val = self.StratInputBox.GetStringSelection()

        self.TextAInput = wx.TextCtrl(self.ParaPanel, -1, "交易信息提示:",
                                      style=wx.TE_MULTILINE | wx.TE_READONLY)

        # 纵向box
        vboxnetA = wx.BoxSizer(wx.VERTICAL)
        vboxnetA.Add(paraInput_Sizer, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=2)
        vboxnetA.Add(self.StratInputBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=2)
        vboxnetA.Add(self.TextAInput, proportion=1, flag=wx.EXPAND | wx.ALL, border=2)
        self.ParaPanel.SetSizer(vboxnetA)

        # 创建Right面板
        self.CtrlPanel = wx.Panel(self, -1)
        # 创建FlexGridSizer布局网络
        self.FlexGridSizer = wx.FlexGridSizer(rows=3, cols=1, vgap=3, hgap=3)

        # 实盘按钮
        self.Firmoffer = wx.Button(self.CtrlPanel, -1, "行情")
        self.Firmoffer.Bind(wx.EVT_BUTTON, self.FirmEvent)  # 绑定行情按钮事件
        # 选股按钮
        self.Stockpick = wx.Button(self.CtrlPanel, -1, "选股")
        self.Stockpick.Bind(wx.EVT_BUTTON, self.PstockpEvent)  # 绑定选股按钮事件
        # 回测按钮
        self.Backtrace = wx.Button(self.CtrlPanel, -1, "回测")
        self.Backtrace.Bind(wx.EVT_BUTTON, self.BackEvent)  # 绑定回测按钮事件

        # 加入Sizer中
        self.FlexGridSizer.Add(self.Firmoffer, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
        self.FlexGridSizer.Add(self.Stockpick, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
        self.FlexGridSizer.Add(self.Backtrace, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
        self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)

        self.CtrlPanel.SetSizer(self.FlexGridSizer)

        self.HBoxPanel = wx.BoxSizer(wx.HORIZONTAL)
        self.HBoxPanel.Add(self.ParaPanel, proportion=1.5, border=2, flag=wx.EXPAND | wx.ALL)
        self.HBoxPanel.Add(self.DispPanel, proportion=8, border=2, flag=wx.EXPAND | wx.ALL)
        self.HBoxPanel.Add(self.CtrlPanel, proportion=1, border=2, flag=wx.EXPAND | wx.ALL)
        self.SetSizer(self.HBoxPanel)

        self.SetSizer(self.DispPanel.TopBoxSizer)

    def ProcessStock(self):
        df_stockload = GetStockDatPro(self.stockCode_Val, self.stockSdate_Val, self.stockEdate_Val)

        dispCont_List = []

        examp_trade = Excave_Indic_Base()
        if self.IndicatInput_Val == u"金叉\死叉":
            dispCont_pd, dispCont_List = examp_trade.plot_Aver_Cross(df_stockload)
            self.DispPanel.draw_avercross(df_stockload, dispCont_pd)
        elif self.IndicatInput_Val == u'跳空缺口':
            dispCont_pd, dispCont_List = examp_trade.plot_Jump_Thrd(df_stockload)
            self.DispPanel.draw_jumpgap(df_stockload, dispCont_pd)
        elif self.IndicatInput_Val == u'N日突破':
            dispCont_pd, dispCont_List = examp_trade.plot_Ndays_Break(df_stockload)
            self.DispPanel.draw_ndaysbreak(df_stockload)
        else:
            dispCont_List = dispCont_List

        self.TextAInput.SetValue(u'指标提示信息如下:' + '\n')
        for i in dispCont_List:
            self.TextAInput.AppendText(i)

        numic = np.arange(0, len(df_stockload.index))
        butNum = len(df_stockload.index)
        self.DispPanel.xylabel_tick_lim(self.stockName_Val, df_stockload.index)
        self.DispPanel.draw_subgraph(df_stockload, numic)

    def ProcessLoop(self):
        df_stockload = GetStockDatPro(self.stockCode_Val, self.stockSdate_Val, self.stockEdate_Val)

        dispCont_List = []
        if self.pickstrate_Val == u"双趋势融合":
            # 多趋势融合策略执行 """
            examp_trade = QuantPickTimeSys(df_stockload)
            dispCont_List = examp_trade.run_factor_plot(self.BackPanel.trade,
                                                        self.BackPanel.total,
                                                        self.BackPanel.profit)
        else:
            # 执行其他策略
            pass

        self.TextAInput.SetValue(u"策略提示信息如下:" + '\n')
        for i in dispCont_List:
            self.TextAInput.AppendText(i)

        self.BackPanel.xylabel_tick_lim(self.stockName_Val)

    # reFlashFrame和reFlashLoop为刷新一幅新的页面
    # clear_subgraph()方法和update_subgraph()方法在RedefPanelMod.py的Panel类中建立
    def reFlashLoop(self):
        # 清理当前图形,显示下一幅图
        self.BackPanel.clear_subgraph()
        self.ProcessLoop()
        self.BackPanel.update_subgraph()

    def reFlashFrame(self):
        self.DispPanel.clear_subgraph()
        self.ProcessStock()
        self.DispPanel.update_subgraph()

    def FirmEvent(self, event):
        self.HBoxPanel.Hide(self.BackPanel)
        self.HBoxPanel.Replace(self.BackPanel, self.DispPanel)
        self.HBoxPanel.Show(self.DispPanel)
        # self.HBoxPanel.Remove(self.BackPanel)
        self.SetSizer(self.HBoxPanel)
        self.HBoxPanel.Layout()

        # 获取列表股票代码和起始时间
        self.stockName_Val = self.stockName_CMBO.GetString(self.stockName_CMBO.GetSelection())
        self.stockCode_Val = self.StNameCodedict[self.stockName_Val]

        dateVal = self.dpcStartTime.GetValue()
        self.stockSdate_Val = datetime.datetime(dateVal.Year, dateVal.Month + 1, dateVal.Day)
        dateVal = self.dpcEndTime.GetValue()
        self.stockEdate_Val = datetime.datetime(dateVal.Year, dateVal.Month + 1, dateVal.Day)

        self.reFlashFrame()

    # 绑定行情按钮的事件,点击触发
    def BackEvent(self, event):
        self.HBoxPanel.Hide(self.DispPanel)
        self.HBoxPanel.Replace(self.DispPanel, self.BackPanel)
        self.HBoxPanel.Show(self.BackPanel)
        # self.HBoxPanel.Remove(self.DispPanel)
        self.SetSizer(self.HBoxPanel)
        self.HBoxPanel.Layout()

        # 获取策略名称
        self.pickstrate_Val = self.pickstrate_CMBO.GetString(self.pickstrate_CMBO.GetSelection())
        self.reFlashLoop()

    # 绑定选股按钮的事件,点击触发
    def PstockpEvent(self, event):
        dispCont_List = []

        # 执行选股策略
        examp_trade = FactorPickStockAng()
        for index, stockName in enumerate(self.StNameCodedict.keys()):
            print("stockName", stockName, self.StNameCodedict[stockName])

            df_stockload = GetStockDatPro(self.StNameCodedict[stockName],
                                          self.stockSdate_Val, self.stockEdate_Val)
            # 后一个数据填充
            df_stockload.fillna(method='bfill', inplace=True)
            dispCont_List.append(stockName + '\n' + examp_trade.fit_pick(df_stockload.Close) + '\n')
        print(dispCont_List)

        # 自定义提示框
        myPickStock = UserDialog(self, dispCont_List)

        # wx.Dialog类中ShowModal()方法用于显示模态方式对话框。
        if myPickStock.ShowModal() == wx.ID_OK:
            pass
        else:
            pass

    def OnRadioBox_Indicator(self, event):
        self.IndicatInput_Val = self.StratInputBox.GetStringSelection()
Пример #9
0
class Moria(wx.Frame):
    """
    Main window
    """
    def __init__(self, *args, **kw):
        super(Moria, self).__init__(*args, **kw)
        self.initFrame()

    def initFrame(self):
        #Create title in top bar.
        self.SetTitle("Moria")
        self.Center()
        #Make the panel larger than any screen to allow free positioning.
        self.panel = wx.Panel(self, size=(3000, 3000))
        #Paint background every time the window changes.
        self.panel.Bind(wx.EVT_PAINT, self.OnPaint)
        #Load titlepage on startup.
        self.page0()
        #What page is displayed?
        self.page = 0

    def OnPaint(self, event):
        #The background image depending on screen.
        if self.page == 0:
            backgroundimage = "Images/MoriaGateBlank.jpg"
        elif self.page == 1 or self.page == 2 or self.page == 4:
            backgroundimage = "Images/MoriaGateBoxed.jpg"

        if self.page != 3:
            image = wx.Bitmap(backgroundimage)
            image = wx.Bitmap.ConvertToImage(image)
            #Call screensizer function
            screensizing = self.screensizer()
            #Unpack result screensizer function
            width, height = screensizing
            #Set the program size to a fraction of the screen size in the right proportions
            self.SetSize(screensizing)
            #Make image the right size as background and draw it.
            image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)
            image = image.ConvertToBitmap()
            dc = wx.PaintDC(self.panel)
            dc.DrawBitmap(image, 0, 0)

    def page0(self):
        #Set page and refresh
        self.page = 0
        self.Refresh()
        #Call screensizer function
        screensizing = self.screensizer()
        #Unpack result screensizer function
        width, height = screensizing
        #Calculate position for button.
        wpos = width
        hpos = height
        wpos = int(wpos / 2 - 40)
        hpos = int(hpos / 10 * 7)
        #Make button
        orderbutton = wx.Button(self.panel,
                                id=wx.ID_ANY,
                                label="Order Tickets",
                                pos=(wpos, hpos))
        orderbutton.Bind(wx.EVT_BUTTON, self.page1)
        #Make background black and letters white.
        orderbutton.SetBackgroundColour("black")
        orderbutton.SetForegroundColour("white")
        #Calculate position for Banner.
        wpos = width
        hpos = height
        wpos = int(wpos / 2 - 90)
        hpos = int(hpos / 10 * 1)
        #Make Banner
        title = wx.StaticText(self.panel,
                              id=wx.ID_ANY,
                              label="Welcome to Moria",
                              pos=(wpos, hpos))
        #Make font larger.
        font = wx.Font(18, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        title.SetBackgroundColour("black")
        title.SetForegroundColour("white")
        #Set Font to banner
        title.SetFont(font)

    def page1(self, event):
        #Write data depending on source page.
        if self.page == 0:
            self.num17tick = 0
            self.num64tick = 0
            self.num65tick = 0
            #Set default price to 0
            self.price = 0
            #self.date = wx.DateTime.Now()
            returning = False
        elif self.page == 2:
            returning = True

        #Set page and refresh
        self.page = 1
        self.Refresh()
        #Call screensizer function
        screensizing = self.screensizer()
        #Unpack result screensizer function
        width, height = screensizing
        #Empty last page
        for child in self.panel.GetChildren():
            child.Destroy()

        #Position banner
        wpos = width
        hpos = height
        wpos = int(wpos / 2 - 90)
        hpos = int(hpos / 10 * 1)
        #Make Banner
        title = wx.StaticText(self.panel,
                              id=wx.ID_ANY,
                              label="Order your tickets",
                              pos=(wpos, hpos))
        #Make font larger.
        font = wx.Font(18, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        title.SetBackgroundColour("black")
        title.SetForegroundColour("white")
        #Set Font to banner
        title.SetFont(font)

        #Position text
        wpos = width
        hpos = height
        wpos = int(wpos / 2 - 70)
        hpos = int(hpos / 10 * 4)
        #Make Banner
        text = wx.StaticText(self.panel,
                             id=wx.ID_ANY,
                             label="How many tickets?",
                             pos=(wpos, hpos))
        #Make font larger.
        font = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        text.SetBackgroundColour("#030303")
        text.SetForegroundColour("white")
        #Set Font to banner
        text.SetFont(font)

        #Create panel for ticket ordering. Make sure to set parent correctly if UI immutable.
        wpos = width
        hpos = height
        wpos = int(wpos / 4)
        hpos = int(hpos / 10 * 4.5)
        pwith = int(width / 16 * 9)
        pheight = int(height / 10 * 4)

        orderpanel = wx.Panel(parent=self.panel,
                              size=(pwith, pheight),
                              pos=(wpos, hpos),
                              style=wx.TRANSPARENT_WINDOW)

        #Create sizer
        gridbox = wx.GridBagSizer(8, 5)

        #Make age3
        self.text = wx.StaticText(orderpanel, label="Age 0-3 are free:")
        #Make font larger.
        font = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        self.text.SetBackgroundColour("#030303")
        self.text.SetForegroundColour("white")
        #Set Font to age3
        self.text.SetFont(font)

        #Make age17
        self.text1 = wx.StaticText(orderpanel, label="Age 4-17:")
        #Make font larger.
        font = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        self.text1.SetBackgroundColour("#030303")
        self.text1.SetForegroundColour("white")
        #Set Font to age17
        self.text1.SetFont(font)

        #Make age64
        self.text2 = wx.StaticText(orderpanel, label="Age 18-64:")
        #Make font larger.
        font = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        self.text2.SetBackgroundColour("#030303")
        self.text2.SetForegroundColour("white")
        #Set Font to age64
        self.text2.SetFont(font)

        #Make age65+
        self.text3 = wx.StaticText(orderpanel, label="Age 65+:")
        #Make font larger.
        font = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        self.text3.SetBackgroundColour("#030303")
        self.text3.SetForegroundColour("white")
        #Set Font to age65+
        self.text3.SetFont(font)

        #counter17
        self.counter17 = wx.SpinCtrl(orderpanel, initial=0)
        self.counter17.SetRange(0, 100)
        #counter64
        self.counter64 = wx.SpinCtrl(orderpanel, initial=0)
        self.counter64.SetRange(0, 100)
        #counter65+
        self.counter65 = wx.SpinCtrl(orderpanel, initial=0)
        self.counter65.SetRange(0, 100)

        #Make discount
        self.text4 = wx.StaticText(orderpanel,
                                   label="If you buy 5 tickets or "
                                   "more you get a €5,- discount.",
                                   style=wx.TE_MULTILINE,
                                   size=(-1, -1))
        self.text4.Wrap(int(width / 16 * 5))
        #Make font larger.
        font = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        self.text4.SetBackgroundColour("#030303")
        self.text4.SetForegroundColour("white")
        #Set Font to age65+
        self.text4.SetFont(font)

        #Detect change in amount tickets and calculate price.
        self.counter17.Bind(wx.EVT_SPINCTRL, self.calcprice)
        self.counter64.Bind(wx.EVT_SPINCTRL, self.calcprice)
        self.counter65.Bind(wx.EVT_SPINCTRL, self.calcprice)

        #Make price
        self.text5 = wx.StaticText(orderpanel,
                                   label="The total price will be €" +
                                   str(self.price) + ",-")
        #Make font larger.
        font = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        self.text5.SetBackgroundColour("#030303")
        self.text5.SetForegroundColour("white")
        #Set Font to price+
        self.text5.SetFont(font)

        #Make DateLabel
        self.text6 = wx.StaticText(orderpanel,
                                   label="When will you "
                                   "descend into the depths?")
        #Make font larger.
        font = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        self.text6.SetBackgroundColour("#030303")
        self.text6.SetForegroundColour("white")
        #Set Font to age65+
        self.text6.SetFont(font)

        #Create Date widget
        self.calendar = DatePickerCtrl(orderpanel, style=wx.adv.DP_DROPDOWN)
        self.calendar.SetRange(wx.DateTime.Now(),
                               (wx.DateTime.FromDMY(5, 5, 3000)))
        #Create control date to check if date has changed later.
        self.controldate = wx.DateTime.Now()
        self.controldate = self.controldate.GetDateOnly()

        #Create ticket button
        self.ticketbutton = wx.Button(orderpanel,
                                      id=wx.ID_ANY,
                                      label="Order Tickets")
        #Make background black and letters white.
        self.ticketbutton.SetBackgroundColour("black")
        self.ticketbutton.SetForegroundColour("white")
        #Add button function
        self.ticketbutton.Bind(wx.EVT_BUTTON, self.page2)

        #Add age3 to sizer
        gridbox.Add(self.text, pos=(0, 0), span=(1, 2))
        #Add age17 to sizer
        gridbox.Add(self.text1, pos=(1, 0))
        #Add age64 to sizer
        gridbox.Add(self.text2, pos=(2, 0))
        #Add age65+ to sizer
        gridbox.Add(self.text3, pos=(3, 0))
        #Add counter17 to sizer
        gridbox.Add(self.counter17, pos=(1, 1), flag=wx.ALIGN_CENTER)
        #Add counter64 to sizer
        gridbox.Add(self.counter64, pos=(2, 1), flag=wx.ALIGN_CENTER)
        #Add counter65 to sizer
        gridbox.Add(self.counter65, pos=(3, 1), flag=wx.ALIGN_CENTER)
        #Add discount to sizer
        gridbox.Add(self.text4, pos=(1, 2), span=(3, 3))
        #Add price to sizer
        gridbox.Add(self.text5, pos=(4, 1), span=(1, 5))
        #Add DataLabel to sizer
        gridbox.Add(self.text6,
                    pos=(6, 0),
                    span=(1, 5),
                    flag=wx.ALIGN_CENTER,
                    border=20)
        #Add Calander to sizer
        gridbox.Add(self.calendar, pos=(7, 1), span=(1, 5))
        #Add ticketbutton to sizer
        gridbox.Add(self.ticketbutton,
                    pos=(8, 0),
                    span=(1, 5),
                    flag=wx.ALIGN_CENTER)

        if returning == True:
            #Set the counters to old values
            self.counter17.SetValue(self.num17tick)
            self.counter64.SetValue(self.num64tick)
            self.counter65.SetValue(self.num65tick)
            #Set date to old value
            if self.date != self.controldate:
                self.calendar.SetValue(self.date)

        orderpanel.SetSizer(gridbox)
        orderpanel.Layout()

    def page2(self, event):
        #Save the selected date.
        self.date = self.calendar.GetValue()
        #Set page and refresh
        self.page = 2
        self.Refresh()
        #Call screensizer function
        screensizing = self.screensizer()
        #Unpack result screensizer function
        width, height = screensizing
        #Empty last page
        for child in self.panel.GetChildren():
            child.Destroy()
        #Position banner
        wpos = width
        hpos = height
        wpos = int(wpos / 2 - 90)
        hpos = int(hpos / 10 * 1)
        #Make Banner
        title = wx.StaticText(self.panel,
                              id=wx.ID_ANY,
                              label="Please confirm "
                              "your order.",
                              pos=(wpos, hpos))
        #Make font larger.
        font = wx.Font(18, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        title.SetBackgroundColour("black")
        title.SetForegroundColour("white")
        #Set Font to banner
        title.SetFont(font)

        #Create panel for bounding confirmation information.
        wpos = width
        hpos = height
        wpos = int(wpos / 40 * 9)
        hpos = int(hpos / 20 * 7)
        pwith = int(width / 16 * 9)
        pheight = int(height / 10 * 4)
        confirmpanel = wx.Panel(parent=self.panel,
                                size=(pwith, pheight),
                                pos=(wpos, hpos),
                                style=wx.TRANSPARENT_WINDOW)

        #Made date more readable.
        self.displaydate = str(self.date)
        self.displaydate = self.displaydate.split()
        #Confirmation text
        confirmationtext = (
            "Thank you for braving the deapths of Moria please "
            "confirm all information has been entered correctly. \n\n"
            "You're welcome on: " + str(self.displaydate[0]) + "\n" +
            str(self.num17tick) + " tickets for people under 18.\n" +
            str(self.num64tick) + " tickets for people under 65.\n" +
            str(self.num65tick) + " tickets for people at or over 65.\n" +
            "The total cost will come to €" + str(self.price) + ",-\n\n"
            "If this all is correct we hope to see you soon, "
            "If not please return to the previous page.")
        #Make conformation information
        self.text7 = wx.StaticText(confirmpanel,
                                   label=confirmationtext,
                                   style=wx.TE_MULTILINE,
                                   size=(-1, -1))
        self.text7.Wrap(int(width / 16 * 8))
        #Make font larger.
        font = wx.Font(10, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
        #Make background black and letters white.
        self.text7.SetBackgroundColour("#030303")
        self.text7.SetForegroundColour("white")
        #Set Font to confirmation text+
        self.text7.SetFont(font)

        wpos = int(10)
        hpos = int(height / 20 * 7)
        #Create return button
        self.returnbutton = wx.Button(confirmpanel,
                                      id=wx.ID_ANY,
                                      label="Change Tickets",
                                      pos=(wpos, hpos))
        #Make background black and letters white.
        self.returnbutton.SetBackgroundColour("black")
        self.returnbutton.SetForegroundColour("white")
        #Add button function
        self.returnbutton.Bind(wx.EVT_BUTTON, self.page1)

        bwidth = self.returnbutton.Size.GetWidth()
        wpos = int(bwidth + 20)
        hpos = int(height / 20 * 7)
        #Create pay button
        self.paybutton = wx.Button(confirmpanel,
                                   id=wx.ID_ANY,
                                   label="Go to Payments",
                                   pos=(wpos, hpos))
        #Make background black and letters white.
        self.paybutton.SetBackgroundColour("black")
        self.paybutton.SetForegroundColour("white")
        #Add button function
        self.paybutton.Bind(wx.EVT_BUTTON, self.page3)

        confirmpanel.Layout()

    def page3(self, event):
        #Set page and refresh
        self.page = 3
        self.Refresh()
        #Call screensizer function
        screensizing = self.screensizer()
        #Unpack result screensizer function
        width, height = screensizing
        #Save the order to file.

        #Empty last page
        for child in self.panel.GetChildren():
            child.Destroy()

        #Create fakepaying button
        self.fakepaybutton = wx.Button(self.panel,
                                       id=wx.ID_ANY,
                                       label="'pay' Tickets",
                                       pos=(width / 2, height / 2))
        #Make background black and letters white.
        self.fakepaybutton.SetBackgroundColour("white")
        self.fakepaybutton.SetForegroundColour("black")
        #Add button function
        self.fakepaybutton.Bind(wx.EVT_BUTTON, self.page4)

    def page4(self, event):
        #Create dictionary for order.
        order = {
            "dateordered": self.controldate,
            "price": self.price,
        }
        #Add up number of tickets
        self.numticks = self.num17tick + self.num64tick + self.num65tick
        self.tick = 0
        while self.tick != self.numticks:
            if self.tick < self.num17tick:
                age = 17
            elif self.tick < (self.num17tick + self.num64tick):
                age = 64
            else:
                age = 65

            order[self.tick] = {
                "datevisit": self.displaydate,
                "age": age,
                "qr": ""
            }
            self.tick += 1
        #Set page and refresh
        self.page = 4
        self.Refresh()
        #Call screensizer function
        screensizing = self.screensizer()
        #Unpack result screensizer function
        width, height = screensizing
        #Empty last page
        for child in self.panel.GetChildren():
            child.Destroy()

    def screensizer(self):
        #Get size of the screen.
        screensize = wx.DisplaySize()
        #If screen ration > 0.5625 limit width, < limit height
        if (screensize[0] / screensize[1]) <= 0.5625:
            screensizing = (int((screensize[0] - 100) * 0.9),
                            int((screensize[0] - 100) / 0.562 * 0.9))
        else:
            screensizing = (int(
                (screensize[1] / 16 * 9) * 0.9), int(screensize[1] * 0.9))
        #Return the width and height for other functions.
        return screensizing

    def calcprice(self, event):
        #Calculate price
        #Retrieve amount of tickets
        self.num17tick = self.counter17.GetValue()
        self.num64tick = self.counter64.GetValue()
        self.num65tick = self.counter65.GetValue()
        #Calculate price
        self.price = self.num17tick * 5 + self.num64tick * 10 + self.num65tick * 8
        if (self.num17tick + self.num64tick + self.num65tick) >= 5:
            self.price -= 5
        #Make price
        self.text5.SetLabel("The total price will be €" + str(self.price) +
                            ",-")
Пример #10
0
class Dialog(wx.Dialog):
    def __init__(self, parent, title="", IDferie=0, type=""):
        wx.Dialog.__init__(self,
                           parent,
                           -1,
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
                           | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX)
        self.typeJour = type

        self.panel_base = wx.Panel(self, -1)
        self.staticBox_staticbox = wx.StaticBox(self.panel_base, -1, "")
        self.label_nom = wx.StaticText(self.panel_base, -1, "Nom :")
        self.text_ctrl_nom = wx.TextCtrl(self.panel_base, -1, "")
        self.label_jour_fixe = wx.StaticText(self.panel_base, -1, "Jour :")
        choices = []
        for x in range(1, 32):
            choices.append(str(x))
        self.choice_jour_fixe = wx.Choice(self.panel_base, -1, choices=choices)
        self.label_mois_fixe = wx.StaticText(self.panel_base, -1, "Mois :")
        self.choice_mois_fixe = wx.Choice(self.panel_base,
                                          -1,
                                          choices=[
                                              "Janvier",
                                              _(u"Février"), "Mars", "Avril",
                                              "Mai", "Juin", "Juillet",
                                              _(u"Août"), "Septembre",
                                              "Octobre", "Novembre",
                                              _(u"Décembre")
                                          ])
        self.label_date_variable = wx.StaticText(self.panel_base, -1, "Date :")
        self.datepicker_date_variable = DatePickerCtrl(self.panel_base,
                                                       -1,
                                                       style=DP_DROPDOWN)

        self.bouton_aide = CTRL_Bouton_image.CTRL(
            self.panel_base,
            texte=_(u"Aide"),
            cheminImage=Chemins.GetStaticPath("Images/32x32/Aide.png"))
        self.bouton_ok = CTRL_Bouton_image.CTRL(
            self.panel_base,
            texte=_(u"Ok"),
            cheminImage=Chemins.GetStaticPath("Images/32x32/Valider.png"))
        self.bouton_annuler = CTRL_Bouton_image.CTRL(
            self.panel_base,
            texte=_(u"Annuler"),
            cheminImage=Chemins.GetStaticPath("Images/32x32/Annuler.png"))

        self.IDferie = IDferie
        if IDferie != 0:
            self.Importation()

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.OnBoutonAide, self.bouton_aide)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonOk, self.bouton_ok)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonAnnuler, self.bouton_annuler)

    def __set_properties(self):
        self.SetTitle(_(u"Saisie d'un jour férié"))
        if 'phoenix' in wx.PlatformInfo:
            _icon = wx.Icon()
        else:
            _icon = wx.EmptyIcon()
        _icon.CopyFromBitmap(
            wx.Bitmap(Chemins.GetStaticPath("Images/16x16/Logo.png"),
                      wx.BITMAP_TYPE_ANY))
        self.SetIcon(_icon)
        self.choice_jour_fixe.SetMinSize((50, -1))
        self.choice_mois_fixe.SetMinSize((130, 21))
        self.bouton_aide.SetToolTip(
            wx.ToolTip("Cliquez ici pour obtenir de l'aide"))
        self.bouton_aide.SetSize(self.bouton_aide.GetBestSize())
        self.bouton_ok.SetToolTip(wx.ToolTip("Cliquez ici pour valider"))
        self.bouton_ok.SetSize(self.bouton_ok.GetBestSize())
        self.bouton_annuler.SetToolTip(
            wx.ToolTip("Cliquez ici pour annuler la saisie"))
        self.bouton_annuler.SetSize(self.bouton_annuler.GetBestSize())

    def __do_layout(self):
        sizer_base = wx.BoxSizer(wx.VERTICAL)
        sizer_base_2 = wx.BoxSizer(wx.VERTICAL)
        grid_sizer_base = wx.FlexGridSizer(rows=2, cols=1, vgap=0, hgap=0)
        grid_sizer_boutons = wx.FlexGridSizer(rows=1, cols=4, vgap=10, hgap=10)
        staticBox = wx.StaticBoxSizer(self.staticBox_staticbox, wx.VERTICAL)
        grid_sizer_staticBox = wx.FlexGridSizer(rows=3,
                                                cols=1,
                                                vgap=10,
                                                hgap=10)
        grid_sizer_variable = wx.FlexGridSizer(rows=1, cols=2, vgap=5, hgap=5)
        grid_sizer_fixe = wx.FlexGridSizer(rows=1, cols=5, vgap=5, hgap=5)
        grid_sizer_nom = wx.FlexGridSizer(rows=1, cols=2, vgap=5, hgap=5)
        grid_sizer_nom.Add(self.label_nom, 0,
                           wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_nom.Add(self.text_ctrl_nom, 0, wx.EXPAND, 0)
        grid_sizer_nom.AddGrowableCol(1)
        grid_sizer_staticBox.Add(grid_sizer_nom, 1, wx.EXPAND, 0)
        grid_sizer_fixe.Add(self.label_jour_fixe, 0,
                            wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_fixe.Add(self.choice_jour_fixe, 0, wx.RIGHT, 10)
        grid_sizer_fixe.Add(self.label_mois_fixe, 0,
                            wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_fixe.Add(self.choice_mois_fixe, 0, wx.EXPAND, 0)
        grid_sizer_fixe.AddGrowableCol(4)
        grid_sizer_staticBox.Add(grid_sizer_fixe, 1, wx.EXPAND, 0)
        grid_sizer_variable.Add(self.label_date_variable, 0,
                                wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_variable.Add(self.datepicker_date_variable, 0, 0, 0)
        grid_sizer_staticBox.Add(grid_sizer_variable, 1, wx.EXPAND, 0)
        grid_sizer_staticBox.AddGrowableCol(0)
        staticBox.Add(grid_sizer_staticBox, 1, wx.ALL | wx.EXPAND, 10)
        grid_sizer_base.Add(staticBox, 1, wx.ALL | wx.EXPAND, 10)
        grid_sizer_boutons.Add(self.bouton_aide, 0, 0, 0)
        grid_sizer_boutons.Add((20, 20), 0, 0, 0)
        grid_sizer_boutons.Add(self.bouton_ok, 0, 0, 0)
        grid_sizer_boutons.Add(self.bouton_annuler, 0, 0, 0)
        grid_sizer_boutons.AddGrowableCol(1)
        grid_sizer_base.Add(grid_sizer_boutons, 1,
                            wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 10)
        sizer_base_2.Add(grid_sizer_base, 1, wx.EXPAND, 0)
        self.panel_base.SetSizer(sizer_base_2)
        sizer_base.Add(self.panel_base, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_base)

        # Affiche en fonction du type de de jour férié
        if self.typeJour == "fixe":
            self.label_date_variable.Show(False)
            self.datepicker_date_variable.Show(False)
        else:
            self.label_jour_fixe.Show(False)
            self.choice_jour_fixe.Show(False)
            self.label_mois_fixe.Show(False)
            self.choice_mois_fixe.Show(False)

        sizer_base.Fit(self)
        self.Layout()
        self.CenterOnScreen()

    def Importation(self):
        DB = GestionDB.DB()
        req = "SELECT * FROM jours_feries WHERE IDferie=%d" % self.IDferie
        DB.ExecuterReq(req)
        donnees = DB.ResultatReq()[0]
        DB.Close()
        if len(donnees) == 0: return
        # Récupération des données
        type = donnees[1]
        nom = donnees[2]
        jour = donnees[3]
        mois = donnees[4]
        annee = donnees[5]

        # Place le nom
        self.text_ctrl_nom.SetValue(nom)
        # Place le jour et le mois si c'est un jour fixe
        if type == "fixe":
            self.choice_jour_fixe.SetSelection(jour - 1)
            self.choice_mois_fixe.SetSelection(mois - 1)

        # Place la date dans le cdatePicker si c'est une date variable
        else:
            date = wx.DateTime()
            date.Set(jour, mois - 1, annee)
            self.datepicker_date_variable.SetValue(date)

    def Sauvegarde(self):
        """ Sauvegarde des données dans la base de données """

        # Récupération ds valeurs saisies
        varNom = self.text_ctrl_nom.GetValue()
        if self.typeJour == "fixe":
            varJour = self.choice_jour_fixe.GetSelection() + 1
            varMois = self.choice_mois_fixe.GetSelection() + 1
            varAnnee = 0
        else:
            date_tmp = self.datepicker_date_variable.GetValue()
            varJour = date_tmp.GetDay()
            varMois = date_tmp.GetMonth() + 1
            varAnnee = date_tmp.GetYear()

        DB = GestionDB.DB()
        # Création de la liste des données
        listeDonnees = [
            ("type", self.typeJour),
            ("nom", varNom),
            ("jour", varJour),
            ("mois", varMois),
            ("annee", varAnnee),
        ]
        if self.IDferie == 0:
            # Enregistrement d'une nouvelle valeur
            newID = DB.ReqInsert("jours_feries", listeDonnees)
            ID = newID
        else:
            # Modification de la valeur
            DB.ReqMAJ("jours_feries", listeDonnees, "IDferie", self.IDferie)
            ID = self.IDferie
        DB.Commit()
        DB.Close()
        return ID

    def OnBoutonAide(self, event):
        from Utils import UTILS_Aide
        UTILS_Aide.Aide("Lesjoursfris")

    def OnBoutonAnnuler(self, event):
        self.EndModal(wx.ID_CANCEL)

    def OnBoutonOk(self, event):
        """ Validation des données saisies """

        varNom = self.text_ctrl_nom.GetValue()
        if varNom == "":
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez saisir un nom pour ce jour férié. Par exemple : 'Lundi de Pâques'..."
                  ), "Erreur", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()
            self.text_ctrl_nom.SetFocus()
            return

        if self.typeJour == "fixe":
            varJour = self.choice_jour_fixe.GetSelection()
            if varJour == -1 or varJour == None:
                dlg = wx.MessageDialog(
                    self,
                    _(u"Vous devez sélectionner un jour pour ce jour férié !"
                      ), "Erreur", wx.OK)
                dlg.ShowModal()
                dlg.Destroy()
                self.choice_jour_fixe.SetFocus()
                return
            varMois = self.choice_mois_fixe.GetSelection()
            if varMois == -1 or varMois == None:
                dlg = wx.MessageDialog(
                    self,
                    _(u"Vous devez sélectionner un mois pour ce jour férié !"
                      ), "Erreur", wx.OK)
                dlg.ShowModal()
                dlg.Destroy()
                self.choice_mois_fixe.SetFocus()
                return

        # Sauvegarde
        self.Sauvegarde()

        # MAJ du listCtrl des valeurs de points
        if FonctionsPerso.FrameOuverte("Config_jours_feries_" +
                                       self.typeJour) != None:
            self.GetParent().MAJ_ListCtrl()

        # Fermeture
        self.EndModal(wx.ID_OK)
Пример #11
0
class Dialog(wx.Dialog):
    def __init__(self, parent, title="" , IDvaleur=0):
        wx.Dialog.__init__(self, parent, -1, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.MAXIMIZE_BOX|wx.MINIMIZE_BOX)
        self.parent = parent
        self.panel_base = wx.Panel(self, -1)
        self.sizer_contenu_staticbox = wx.StaticBox(self.panel_base, -1, "")
        self.label_valeur = wx.StaticText(self.panel_base, -1, _(u"Valeur :"))
        self.text_valeur = wx.TextCtrl(self.panel_base, -1, "", style=wx.TE_CENTRE)
        self.label_euro = wx.StaticText(self.panel_base, -1, u"¤")
        self.label_dateDebut = wx.StaticText(self.panel_base, -1, _(u"A partir du :"))
        self.datepicker_dateDebut = DatePickerCtrl(self.panel_base, -1, style=DP_DROPDOWN)
        self.bouton_aide = CTRL_Bouton_image.CTRL(self.panel_base, texte=_(u"Aide"), cheminImage=Chemins.GetStaticPath("Images/32x32/Aide.png"))
        self.bouton_ok = CTRL_Bouton_image.CTRL(self.panel_base, texte=_(u"Ok"), cheminImage=Chemins.GetStaticPath("Images/32x32/Valider.png"))
        self.bouton_annuler = CTRL_Bouton_image.CTRL(self.panel_base, texte=_(u"Annuler"), cheminImage=Chemins.GetStaticPath("Images/32x32/Annuler.png"))
        
        self.IDvaleur = IDvaleur
        if IDvaleur != 0 : 
            self.Importation()

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.OnBoutonAide, self.bouton_aide)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonOk, self.bouton_ok)
        self.Bind(wx.EVT_BUTTON, self.OnBoutonAnnuler, self.bouton_annuler)

    def __set_properties(self):
        self.SetTitle(_(u"Gestion de la valeur du point"))
        if 'phoenix' in wx.PlatformInfo:
            _icon = wx.Icon()
        else :
            _icon = wx.EmptyIcon()
        _icon.CopyFromBitmap(wx.Bitmap(Chemins.GetStaticPath("Images/16x16/Logo.png"), wx.BITMAP_TYPE_ANY))
        self.SetIcon(_icon)
        self.text_valeur.SetMinSize((60, -1))
        self.text_valeur.SetToolTip(wx.ToolTip("Saisissez ici une valeur"))
        self.bouton_aide.SetToolTip(wx.ToolTip("Cliquez ici pour obtenir de l'aide"))
        self.bouton_aide.SetSize(self.bouton_aide.GetBestSize())
        self.bouton_ok.SetToolTip(wx.ToolTip("Cliquez ici pour valider"))
        self.bouton_ok.SetSize(self.bouton_ok.GetBestSize())
        self.bouton_annuler.SetToolTip(wx.ToolTip("Cliquez ici pour annuler la saisie"))
        self.bouton_annuler.SetSize(self.bouton_annuler.GetBestSize())

    def __do_layout(self):
        sizer_base = wx.BoxSizer(wx.VERTICAL)
        grid_sizer_base = wx.FlexGridSizer(rows=3, cols=1, vgap=10, hgap=10)
        grid_sizer_boutons = wx.FlexGridSizer(rows=1, cols=4, vgap=10, hgap=10)
        sizer_contenu = wx.StaticBoxSizer(self.sizer_contenu_staticbox, wx.VERTICAL)
        grid_sizer_contenu = wx.FlexGridSizer(rows=1, cols=6, vgap=10, hgap=10)
        grid_sizer_contenu.Add(self.label_valeur, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_contenu.Add(self.text_valeur, 0, 0, 0)
        grid_sizer_contenu.Add(self.label_euro, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_contenu.Add((20, 20), 0, wx.EXPAND, 0)
        grid_sizer_contenu.Add(self.label_dateDebut, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_contenu.Add(self.datepicker_dateDebut, 0, 0, 0)
        sizer_contenu.Add(grid_sizer_contenu, 1, wx.ALL|wx.EXPAND, 10)
        grid_sizer_base.Add(sizer_contenu, 1, wx.ALL|wx.EXPAND, 10)
        grid_sizer_boutons.Add(self.bouton_aide, 0, 0, 0)
        grid_sizer_boutons.Add((20, 20), 0, wx.EXPAND, 0)
        grid_sizer_boutons.Add(self.bouton_ok, 0, 0, 0)
        grid_sizer_boutons.Add(self.bouton_annuler, 0, 0, 0)
        grid_sizer_boutons.AddGrowableCol(1)
        grid_sizer_base.Add(grid_sizer_boutons, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)
        self.panel_base.SetSizer(grid_sizer_base)
        sizer_base.Add(self.panel_base, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_base)
        sizer_base.Fit(self)
        self.Layout()
        self.CenterOnScreen()

    def Importation(self):
        DB = GestionDB.DB()
        req = "SELECT * FROM valeurs_point WHERE IDvaleur_point=%d" % self.IDvaleur
        DB.ExecuterReq(req)
        donnees = DB.ResultatReq()[0]
        DB.Close()
        if len(donnees) == 0: return
        # Place la valeur dans le controle
        self.text_valeur.SetValue(str(donnees[1]))
        # Place la date dans le cdatePicker 
        jour = int(donnees[2][8:10])
        mois = int(donnees[2][5:7])-1
        annee = int(donnees[2][:4])
        date = wx.DateTime()
        date.Set(jour, mois, annee)
        self.datepicker_dateDebut.SetValue(date)

    def Sauvegarde(self):
        """ Sauvegarde des données dans la base de données """
        
        # Récupération ds valeurs saisies
        varValeur = self.text_valeur.GetValue()
        date_tmp = self.datepicker_dateDebut.GetValue()
        varDate = str(datetime.date(date_tmp.GetYear(), date_tmp.GetMonth()+1, date_tmp.GetDay()))

        DB = GestionDB.DB()
        # Création de la liste des données
        listeDonnees = [    ("valeur",   varValeur),  
                                    ("date_debut",    varDate), ]
        if self.IDvaleur == 0:
            # Enregistrement d'une nouvelle coordonnée
            newID = DB.ReqInsert("valeurs_point", listeDonnees)
            ID = newID
        else:
            # Modification de la coordonnée
            DB.ReqMAJ("valeurs_point", listeDonnees, "IDvaleur_point", self.IDvaleur)
            ID = self.IDvaleur
        DB.Commit()
        DB.Close()
        return ID

    def OnBoutonAide(self, event):
        from Utils import UTILS_Aide
        UTILS_Aide.Aide("Lesvaleursdepoints")

    def OnBoutonAnnuler(self, event):
        self.EndModal(wx.ID_CANCEL)

    def OnBoutonOk(self, event):
        """ Validation des données saisies """
        # Vérifie que une valeur a été saisie
        valeur = self.text_valeur.GetValue()
        if valeur == "" :
            dlg = wx.MessageDialog(self, _(u"Vous devez saisir une valeur de point."), "Erreur", wx.OK)  
            dlg.ShowModal()
            dlg.Destroy()
            self.text_valeur.SetFocus()
            return
        # Vérifie que la valeur est bien constituée de chiffres uniquement
        incoherences = ""
        for lettre in valeur :
            if lettre not in "0123456789." : incoherences += "'"+ lettre + "', "
        if len(incoherences) != 0 :
            txt = _(u"Caractères incorrects : ") + incoherences[:-2]
            dlg = wx.MessageDialog(self, _(u"La valeur de point que vous avez saisie n'est pas correcte.\n\n") + txt, "Erreur", wx.OK)  
            dlg.ShowModal()
            dlg.Destroy()
            self.text_valeur.SetFocus()
            return
        # Sauvegarde
        self.Sauvegarde()

        # MAJ du listCtrl des valeurs de points
        if FonctionsPerso.FrameOuverte("config_val_point") != None :
            self.GetParent().MAJ_ListCtrl()

        # Fermeture
        self.EndModal(wx.ID_OK)