Beispiel #1
0
        private void AcceptButton_Click(object sender, EventArgs e)
        {
            //recuperation des valeurs des textbox
            string nom    = txtNom.Text;
            string prenom = txtPrenom.Text;
            string tel    = txtTel.Text.Replace(" ", "");

            OleDbConnection connec = DatabaseManager.GetConnection();

            //requete SQL pour recuperer le code personne le plus grand
            string sqlCodePersonne = "SELECT MAX(codePersonne) FROM Personne";
            //requete sql pour inserer la nouvelle personne dans la base de donnees
            string sqlAjoutPersonne = "INSERT INTO Personne ([codePersonne], [nomPersonne], [pnPersonne], [telMobile]) VALUES (?,?,?,?)";

            //recuperation et calcul du prochain codePersonne
            OleDbCommand cmd = new OleDbCommand(sqlCodePersonne, connec);

            try
            {
                connec.Open();
                int codePersonne = int.Parse(cmd.ExecuteScalar().ToString()) + 1;

                //insertion de la personne dans la base de donnees
                cmd.CommandText = sqlAjoutPersonne;
                cmd.Parameters.AddWithValue("@codePersonne", codePersonne);
                cmd.Parameters.AddWithValue("@nomPersonne", nom);
                cmd.Parameters.AddWithValue("@pnPersonne", prenom);
                cmd.Parameters.AddWithValue("@telMobile", string.IsNullOrEmpty(tel) ? (object)DBNull.Value : tel); //si jamais le telephone n'est pas renseigne, on insert null dans la colonne telMobile
                cmd.ExecuteNonQuery();

                ErrorManager.EntriesSuccessfullyAdded(this);
                this.DialogResult = DialogResult.OK;
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                this.Close();
            }
        }
        // Valider la transaction
        private void btnOK_Click(object sender, EventArgs e)
        {
            // Récupération des informations du formulaire
            string dateTransaction = calAjoutTransaction.Value.ToShortDateString();
            string description     = txtAjoutTransaction_desc.Text;
            double montant;
            int    type      = (int)cboAjoutTransaction_Type.SelectedValue;
            int    idTransac = GetNextIdTransac(); // Récupérer le numéro de la prochaine transaction

            int codeRetour;

            // Tente de convertir le montant en un double. Sinon : affiche une erreur et stop le traitement.
            if (!LocalizationManager.ConvertFloatingTo <double>(txtAjoutTransaction_montant.Text, double.TryParse, out montant))
            {
                ErrorManager.ShowNotANumberError(this);
                return;
            }

            // Ouverture de la connection
            OleDbConnection connec = DatabaseManager.CreateConnection();

            // Construction de la chaine de la requête
            string requeteTransac = @"INSERT INTO [Transaction]
                                        VALUES (?,?,?,?,?,?,?)";

            // Création de la requete INSERT de la transaction
            OleDbCommand cmdTransac = new OleDbCommand(requeteTransac, connec);

            cmdTransac.Parameters.AddWithValue("@codeTransaction", idTransac);
            cmdTransac.Parameters.AddWithValue("@dateTransaction", dateTransaction);

            // Si jamais la description n'est pas renseigne, on insert "NULL" dans la colonne description
            cmdTransac.Parameters.AddWithValue("@description", string.IsNullOrEmpty(description) ? (object)DBNull.Value : description);
            cmdTransac.Parameters.AddWithValue("@montant", montant > 0 ? montant : montant * -1);
            cmdTransac.Parameters.AddWithValue("@recetteON", ckbAjoutTransaction_recette.Checked);
            cmdTransac.Parameters.AddWithValue("@percuON", ckbAjoutTransaction_percu.Checked);
            cmdTransac.Parameters.AddWithValue("@type", type);

            try {
                // Execution de la requête
                connec.Open();
                codeRetour = cmdTransac.ExecuteNonQuery();

                // Création des requetes dans la table des bénéficiaires
                OleDbCommand cmdBenef = new OleDbCommand();
                cmdBenef.Connection = connec;
                string requeteBenef = @"INSERT INTO [Beneficiaires]([codeTransaction], [codePersonne])
                                            VALUES (?,?)";
                cmdBenef.CommandText = requeteBenef;
                string numPers = string.Empty;

                // Pour chaque personne sélectionnée dans la listbox,
                // ajouter la transaction avec le codePersonne correspondant
                foreach (DataRowView drw in listBoxAjoutTransaction_Personne.SelectedItems)
                {
                    cmdBenef.Parameters.Clear();
                    numPers = drw.Row[0].ToString();
                    cmdBenef.Parameters.AddWithValue("@codeTransaction", idTransac);
                    cmdBenef.Parameters.AddWithValue("@codePersonne", numPers);
                    cmdBenef.ExecuteNonQuery();
                }
                ///////// Envoi d'un SMS si la somme dépasse la totalité des revenus + 10 %
                // Recherche et calcul du revenu de la famille
                string       requeteSumRevenus = "SELECT SUM(montant) FROM [PosteRevenu]";
                OleDbCommand cmdSumRevenus     = new OleDbCommand(requeteSumRevenus, connec);

                double sumRevenus  = (double)cmdSumRevenus.ExecuteScalar();
                double sommeLimite = sumRevenus + 0.1 * sumRevenus;
                //MessageBox.Show("Revenu : " + sumRevenus + "\n" + "Somme limite : " + sommeLimite);
                List <string> numerosTel = new List <string>();

                // Si le montant de la transaction dépasse cette somme max, alors on envoi
                // un sms a tous les numéros renseignés dans la base
                if (montant > sommeLimite)
                {
                    // On récupère tous les numéros de téléphone de la table Personne
                    string          requeteAllNum = "SELECT telMobile FROM [Personne] WHERE telMobile IS NOT NULL";
                    OleDbCommand    cmdAllNum     = new OleDbCommand(requeteAllNum, connec);
                    OleDbDataReader drAllNum      = cmdAllNum.ExecuteReader();
                    while (drAllNum.Read())
                    {
                        string num = drAllNum[0].ToString();
                        if (num[0] == '0')
                        {
                            num = num.Substring(1, num.Length - 1);
                            num = "+33" + num;
                        }
                        //MessageBox.Show("Numéro : " + num);
                        numerosTel.Add(num);
                    }
                }

                // Envoi des SMS
                string message = "Message automatique de BreakingBudget\n" +
                                 "ATTENTION : Quelqu'un a saisi une transaction d'un montant anormalement élevé de " + montant;
                SMSManager.SendSMS(this, numerosTel.ToArray(), message);

                // Show message success
                ErrorManager.EntriesSuccessfullyAdded(this);

                // Clear formulaire
                btnClear_Click(null, null);
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                connec.Close();
            }

            // TODO: SMS API
        }
Beispiel #3
0
        // Valider la transaction
        private void btnOK_Click(object sender, EventArgs e)
        {
            // Récupération des informations du formulaire
            string  dateTransaction = calAjoutTransaction.Value.ToShortDateString();
            string  description     = txtDesc.Text;
            decimal montant;
            int     type      = (int)cboType.SelectedValue;
            int     idTransac = GetNextIdTransac(); // Récupérer le numéro de la prochaine transaction

            int codeRetour;

            // Tente de convertir le montant en un double. Sinon : affiche une erreur et stop le traitement.
            if (!LocalizationManager.ConvertFloatingTo <decimal>(txtMontant.Text, decimal.TryParse, out montant))
            {
                ErrorManager.ShowNotANumberError(this);
                return;
            }

            // Ouverture de la connection
            OleDbConnection connec = DatabaseManager.GetConnection();

            // Construction de la chaine de la requête
            string requeteTransac = @"INSERT INTO [Transaction]
                                        VALUES (?,?,?,?,?,?,?)";

            // Création de la requete INSERT de la transaction
            OleDbCommand cmdTransac = new OleDbCommand(requeteTransac, connec);

            cmdTransac.Parameters.AddWithValue("@codeTransaction", idTransac);
            cmdTransac.Parameters.AddWithValue("@dateTransaction", dateTransaction);

            // Si jamais la description n'est pas renseigne, on insert "NULL" dans la colonne description
            cmdTransac.Parameters.AddWithValue("@description", string.IsNullOrEmpty(description) ? (object)DBNull.Value : description);
            cmdTransac.Parameters.AddWithValue("@montant", montant);
            cmdTransac.Parameters.AddWithValue("@recetteON", ckbRecette.Checked);
            cmdTransac.Parameters.AddWithValue("@percuON", ckbPercu.Checked);
            cmdTransac.Parameters.AddWithValue("@type", type);

            try
            {
                // Execution de la requête
                connec.Open();
                codeRetour = cmdTransac.ExecuteNonQuery();

                // Création des requetes dans la table des bénéficiaires
                OleDbCommand cmdBenef = new OleDbCommand();
                cmdBenef.Connection = connec;
                string requeteBenef = @"INSERT INTO [Beneficiaires]([codeTransaction], [codePersonne])
                                            VALUES (?,?)";
                cmdBenef.CommandText = requeteBenef;
                string numPers = string.Empty;

                // Pour chaque personne sélectionnée dans la listbox,
                // ajouter la transaction avec le codePersonne correspondant
                foreach (DataRowView drw in listBoxAjoutTransaction_Personne.SelectedItems)
                {
                    cmdBenef.Parameters.Clear();
                    numPers = drw.Row[0].ToString();
                    cmdBenef.Parameters.AddWithValue("@codeTransaction", idTransac);
                    cmdBenef.Parameters.AddWithValue("@codePersonne", numPers);
                    cmdBenef.ExecuteNonQuery();
                }
                ErrorManager.EntriesSuccessfullyAdded(this);


                // if the amount is a expense
                if (montant < 0)
                {
                    ///////// Envoi d'un SMS si la somme dépasse la totalité des revenus + 10 %
                    // Recherche et calcul du revenu de la famille
                    string       requeteSumRevenus = "SELECT SUM(montant) FROM [PosteRevenu]";
                    OleDbCommand cmdSumRevenus     = new OleDbCommand(requeteSumRevenus, connec);

                    object _sumRevenus = cmdSumRevenus.ExecuteScalar();

                    // we put in decimal because of a bug from the VS compiler installed in rds's server
                    // (see https://github.com/dotnet/roslyn/issues/7148)
                    decimal sumRevenus = (_sumRevenus.GetType() != typeof(DBNull)) ? decimal.Parse(_sumRevenus.ToString()) : 0;

                    // put the sum Revenu to negative to compare the negative expense
                    decimal sommeLimite = (sumRevenus * -1) - 0.1M * sumRevenus;

                    List <string> numerosTel = new List <string>();

                    // Si le montant de la transaction dépasse cette somme max, alors on envoi
                    // un sms a tous les numéros renseignés dans la base
                    if (montant < sommeLimite)
                    {
                        // On récupère tous les numéros de téléphone de la table Personne
                        string          requeteAllNum = "SELECT telMobile FROM [Personne] WHERE telMobile IS NOT NULL";
                        OleDbCommand    cmdAllNum     = new OleDbCommand(requeteAllNum, connec);
                        OleDbDataReader drAllNum      = cmdAllNum.ExecuteReader();
                        while (drAllNum.Read())
                        {
                            string num = drAllNum[0].ToString();
                            if (num[0] == '0')
                            {
                                num = num.Substring(1, num.Length - 1);
                                num = "+33" + num;
                            }
                            numerosTel.Add(num);
                        }

                        // if there are num found
                        if (numerosTel.Count > 0)
                        {
                            // Envoi des SMS
                            string message = string.Format(Program.settings.localize.Translate("sms_big_expense_msg_{0}"), montant);
                            SMSManager.SendSMS(this, numerosTel.ToArray(), message);
                            ErrorManager.SMSSuccessfullySent(this);
                        }
                    }
                }

                // Clear formulaire
                btnClearAjoutTransaction_Click(null, null);

                this.Close();
            }
            catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
            }
            finally
            {
                connec.Close();
            }
        }
Beispiel #4
0
        private void btnValiderBudgetPonctuel_Click(object sender, EventArgs _ev)
        {
            OleDbConnection  dbConn;
            OleDbTransaction dbTransaction;

            // Will store the deadlines
            List <KeyValuePair <DateTime, decimal> > deadLines;

            // Retrieve the budget's title + comments and remove any leading whitespacess
            string budgetTitle    = this.txtBoxIntitulePonctuel.Text.Trim();
            string budgetComments = this.txtBoxCommentairePonctuel.Text.Trim();

            // if the comments are empty, set it to null (to avoid a OleDB Error)
            if (string.IsNullOrEmpty(budgetComments))
            {
                budgetComments = null;
            }

            // TODO: if set, check if the sum of the fields is equal to the input sum
            //		 if not, put a warning & ask for confirmation
            //    string.IsNullOrEmpty(this.txtBoxMontantPonctuel.Text)
            //    && float.TryParse(this.txtBoxMontantPonctuel.Text, out montantTotal)

            // - if:
            //     - the budget's title is null/empty
            //     - or only has spaces:
            //     - or if not every deadline is filled
            //   ---> show missing fields error and stop proceeding
            //
            // - otherwise: proceed and insert the data (if the title does not exist yet)

            if (string.IsNullOrWhiteSpace(budgetTitle) ||
                this.numberOfDeadlines < 1

                // try to retrieve every deadlines, store it to `deadLines` and return false
                // if there was a missing value
                || !CheckAndConvertDeadLinesToList(out deadLines))
            {
                ErrorManager.ShowMissingFieldsError(this);
                return;
            }

            // check if the budgetTitle is unique in the database
            // if not unique: show an error saying that it already exists and stop proceeding
            try {
                if (!PosteRepository.IsUnique(budgetTitle))
                {
                    // show a duplicate value error and specify the field
                    ErrorManager.ShowDuplicateError(this,
                                                    Program.settings.localize.Translate(this.lblIntitulePonctuel.Name));
                    return;
                }
            } catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
                return;
            }

            // otherwise: continue and insert the data
            dbConn = DatabaseManager.GetConnection();

            dbConn.Open();

            dbTransaction = dbConn.BeginTransaction();

            // Insert the data to the data base
            try {
                PostePonctuelRepository.Create(dbConn, dbTransaction,
                                               budgetTitle,
                                               budgetComments,
                                               deadLines.ToArray()
                                               );

                Console.WriteLine("<- Commit");
                dbTransaction.Commit();

                ErrorManager.EntriesSuccessfullyAdded(this);
                ClearPostePonctuelForm();
            } catch (OleDbException e)
            {
                // cancel the changes
                dbTransaction.Rollback();

                // handle the error (log it and report it to the user)
                ErrorManager.HandleOleDBError(e);
            }
            finally
            {
                dbConn.Close();
            }
        }
Beispiel #5
0
        private void btnValiderRevenu_Click(object _s, EventArgs _ev)
        {
            OleDbConnection  dbConn;
            OleDbTransaction dbTransaction;

            // Retrieve the budget's title + comments and remove any leading whitespacess
            string  revenuPoste = this.txtBoxPosteRevenu.Text.Trim();
            decimal revenuMontant;
            int     chaqueXDuMois;

            PersonneRepository.PersonneModel personne;

            // try to convert the user amount to a decimal and the day to a int,
            // if it fails, we trigger a "not a number" error and we stop proceeding
            if (!LocalizationManager.ConvertFloatingTo <decimal>(this.txtBoxMontantRevenu.Text, decimal.TryParse, out revenuMontant) ||
                !this.isDayOfTheMonth(this.txtTousLesXDuMoisRevenu.Text, out chaqueXDuMois))
            {
                ErrorManager.ShowNotANumberError(this);
                return;
            }

            // - if:
            //     - the poste is null/empty
            //     - or only has spaces:
            //     - or the beneficiary is not selected
            //   ---> show missing fields error and stop proceeding
            //
            // - otherwise: proceed and insert the data (if the poste does not exist yet)
            if (this.listBeneficiairesComboBox.SelectedItem == null ||
                string.IsNullOrWhiteSpace(revenuPoste))
            {
                ErrorManager.ShowMissingFieldsError(this);
                return;
            }

            // retrieve the selected beneficiary
            personne = (PersonneRepository.PersonneModel)listBeneficiairesComboBox.SelectedItem;

            // check if the budgetTitle is unique in the database
            // if not unique: show an error saying that it already exists and stop proceeding
            try {
                if (!PosteRepository.IsUnique(revenuPoste))
                {
                    // show a duplicate value error and specify the field
                    ErrorManager.ShowDuplicateError(this,
                                                    Program.settings.localize.Translate(this.lblPosteRevenu.Name));
                    return;
                }
            } catch (OleDbException ex)
            {
                ErrorManager.HandleOleDBError(ex);
                return;
            }

            // otherwise: continue and insert the data
            dbConn = DatabaseManager.GetConnection();

            dbConn.Open();

            dbTransaction = dbConn.BeginTransaction();

            // Insert the data to the data base
            try
            {
                PosteRevenuRepository.Create(dbConn, dbTransaction,
                                             revenuPoste,
                                             personne,
                                             revenuMontant,
                                             chaqueXDuMois
                                             );

                Console.WriteLine("<- Commit");
                dbTransaction.Commit();

                ErrorManager.EntriesSuccessfullyAdded(this);
                ClearPosteRevenuForm();
            }
            catch (OleDbException e)
            {
                // cancel the changes
                dbTransaction.Rollback();

                // handle the error (log it and report it to the user)
                ErrorManager.HandleOleDBError(e);
            }
            catch (ArgumentException e)
            {
                ErrorManager.ShowOperationFailed(this, Program.settings.localize.Translate(e.Message));
            }
            finally
            {
                dbConn.Close();
            }
        }
Beispiel #6
0
        private void BtnValiderBudgetFixe_Click(object _s, EventArgs e)
        {
            MetroButton sender = (MetroButton)_s;

            PosteRepository.PosteModel             SelectedPoste;
            PeriodiciteRepository.PeriodiciteModel SelectedPeriode;
            decimal montant;
            int     TousLesXDuMois;

            // disable submit button
            sender.Enabled = false;

            // Check if every field was filled
            if (
                this.ComboxBoxListePeriodicites.SelectedItem == null ||
                this.ComboxBoxListePostes.SelectedItem == null ||
                this.TxtBoxTousLesXMois.Text.Length < 1 ||
                this.TxtBoxMontantPosteFixe.Text.Length < 1
                )
            {
                MetroMessageBox.Show(this,
                                     Program.settings.localize.Translate("err_missing_fields_msg"),
                                     Program.settings.localize.Translate("err_missing_fields_caption"),
                                     MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            // try to convert the decimals and integers
            else if (!(LocalizationManager.ConvertFloatingTo <decimal>(TxtBoxMontantPosteFixe.Text, decimal.TryParse, out montant) &&
                       int.TryParse(TxtBoxTousLesXMois.Text, out TousLesXDuMois)))
            {
                MetroMessageBox.Show(this,
                                     Program.settings.localize.Translate("err_day_of_month_and_sum_not_number"),
                                     Program.settings.localize.Translate("err_uh_oh_caption"),
                                     MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                // retrieve the selected items
                SelectedPoste   = (PosteRepository.PosteModel) this.ComboxBoxListePostes.SelectedItem;
                SelectedPeriode = (PeriodiciteRepository.PeriodiciteModel) this.ComboxBoxListePeriodicites.SelectedItem;

                OleDbCommand cmd = DatabaseManager.InsertInto("PostePeriodique",
                                                              DatabaseManager.GetConnection(),
                                                              new KeyValuePair <string, object>("codePoste", SelectedPoste.codePoste),
                                                              new KeyValuePair <string, object>("typePer", SelectedPeriode.codePer),
                                                              new KeyValuePair <string, object>("montant", montant),
                                                              new KeyValuePair <string, object>("jourDuMois", TousLesXDuMois)
                                                              );

                try
                {
                    if (PosteRepository.IsAvailable(SelectedPoste.codePoste))
                    {
                        cmd.Connection.Open();
                        cmd.ExecuteNonQuery();  // insert data

                        ErrorManager.EntriesSuccessfullyAdded(this);
                        ClearPosteFixeForm();
                    }
                    else
                    {
                        ErrorManager.ShowAlreadyUsedError(this, this.lblCmbPostes.Text);
                    }
                }
                catch (OleDbException ex)
                {
                    ErrorManager.HandleOleDBError(ex);
                }
                finally
                {
                    cmd.Connection.Close();
                }

                this.FillPostesComboBox();
            }

            // re-enable the submit button
            sender.Enabled = true;
        }