Beispiel #1
0
        private bool check_exists()
        {
            NpgsqlConnection conn = null;

            try
            {
                conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                string query = "SELECT COUNT(*) FROM checks_header WHERE checks_header.date_time_write BETWEEN '" + DateTime.Now.Date +
                               "' and '" + DateTime.Now.Date.AddDays(1) + "'";
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                if (Convert.ToInt32(command.ExecuteScalar()) != 0)
                {
                    conn.Close();
                    return(true);
                }
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            return(false);
        }
Beispiel #2
0
        private void to_change_the_document_status()
        {
            NpgsqlConnection conn         = null;
            string           myQuery      = "";
            string           update_value = "";

            try
            {
                conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                if (listView1.Items[listView1.SelectedIndices[0]].Text == "0")
                {
                    update_value = "1";
                }
                else
                {
                    update_value = "0";
                }
                myQuery = "UPDATE checks_header   SET its_deleted=" + update_value + " where date_time_write = '" + listView1.Items[listView1.SelectedIndices[0]].SubItems[1].Text + "'";
                NpgsqlCommand command = new NpgsqlCommand(myQuery, conn);
                object        result  = command.ExecuteScalar();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message, "Ошибка при работе с базой данных");
            }
            finally
            {
                conn.Close();
            }
        }
Beispiel #3
0
        /// <summary>
        /// Возвращает ид Роли
        /// </summary>
        /// <param name="user_code"></param>
        /// <returns></returns>
        private int find_user_role(string user_code)
        {
            int rezult = 0;

            try
            {
                NpgsqlConnection conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                //string query = "SELECT users._right_,nick FROM users left join clients on users.client_code=clients.code where clients.barcode='" + user_code + "'";
                string           query   = "SELECT users._right_,nick,client_code FROM users left join clients on users.client_code=clients.code where clients.code='" + user_code + "'";
                NpgsqlCommand    command = new NpgsqlCommand(query, conn);
                NpgsqlDataReader reader  = command.ExecuteReader();
                while (reader.Read())
                {
                    rezult = Convert.ToInt32(reader.GetInt16(0));
                    if (!not_change_Cash_Operator)
                    {
                        MainStaticClass.Cash_Operator             = reader.GetString(1);
                        MainStaticClass.Cash_Operator_Client_Code = reader.GetString(2);
                    }
                }
                //object result = command.ExecuteScalar();
                //if (result != null)
                //{
                //    rezult = Convert.ToInt32(result);
                //}
                conn.Close();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }

            return(rezult);
        }
        private void write_error(string error)
        {
            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                string query = "INSERT INTO errors_on_send_portions(" +
                               "time_event," +
                               "errors_text," +
                               ")VALUES('" +
                               DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" +
                               error + "')";
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                command.ExecuteNonQuery();
                conn.Close();
            }
            catch
            {
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Beispiel #5
0
        private string get_num_doc_on_date_time_write(string date_time_write)
        {
            string result = "";

            NpgsqlConnection conn = null;

            try
            {
                conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                string        query   = "SELECT document_number FROM checks_header WHERE date_time_write='" + date_time_write + "'";
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                result = command.ExecuteScalar().ToString();
                conn.Close();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            return(result);
        }
Beispiel #6
0
        private void update_execute_addcolumn()
        {
            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                string        query   = " UPDATE constants SET execute_addcolumn = 2 ";
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                command.ExecuteNonQuery();
                conn.Close();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(" Ошибка при обновлении значения константы " + ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(" Ошибка при обновлении значения константы " + ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
        /// <summary>
        /// Получаем строку код сертификата и его номинал
        /// </summary>
        /// <returns></returns>
        private string get_not_sent_sertificates()
        {
            string result = "";

            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                string query = "SELECT " +
                               " checks_table.document_number" + "," +
                               " tovar_code" + "," +
                               " price" + "," +
                               " checks_header.cash_desk_number" + "," +
                               " sertificates.code AS sertificates_code" + "," +
                               " checks_header.date_time_write " +
                               " FROM checks_table LEFT JOIN tovar ON checks_table.tovar_code = tovar.code " +
                               " LEFT JOIN checks_header ON checks_header.document_number = checks_table.document_number " +
                               " LEFT JOIN sertificates ON checks_table.tovar_code = sertificates.code_tovar " +
                               " where checks_table.document_number in (" +
                               document_number_list.ToString() +
                               ") AND tovar.its_certificate = 1 AND checks_header.its_deleted = 0 ";//сертификаты только из проведенных документов
                NpgsqlCommand    command = new NpgsqlCommand(query, conn);
                NpgsqlDataReader reader  = command.ExecuteReader();
                while (reader.Read())
                {
                    result += reader["document_number"].ToString() + "," +
                              reader["tovar_code"].ToString() + "," +
                              reader["price"].ToString().Replace(",", ".") + "," +
                              reader["cash_desk_number"].ToString() + "," +
                              reader["sertificates_code"].ToString() + "," +
                              reader.GetDateTime(5).ToString("dd-MM-yyyy HH:mm:ss") + "|";
                }
                if (result != "")
                {
                    result = result.Substring(0, result.Length - 1);
                }
                reader.Close();
                conn.Close();
            }
            catch (NpgsqlException)
            {
                result = "-1";
            }
            catch (Exception)
            {
                result = "-1";
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }


            return(result);
        }
Beispiel #8
0
        public bool fill_items(BuyReturnRequest buyReturnRequest, string document_number, string client)
        {
            bool             result = true;
            NpgsqlConnection conn   = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                string           query   = "SELECT numstr, tovar_code, quantity, price,price_at_a_discount,sum_at_a_discount FROM checks_table where document_number =" + document_number + " order by numstr desc";
                NpgsqlCommand    command = new NpgsqlCommand(query, conn);
                NpgsqlDataReader reader  = command.ExecuteReader();
                buyReturnRequest.items = new Items();
                Items items = new Items();
                //List<Item> list_items= new List<Item>();// items2 = new items.item();
                items.item = new List <Item>();// items2 = new items.item();
                while (reader.Read())
                {
                    Item item = new Item();
                    item.pos = (Convert.ToInt32(reader["numstr"]) + 1).ToString();
                    //item.pos = Convert.ToInt32(reader["numstr"]).ToString();
                    item.SKU = reader["tovar_code"].ToString();
                    item.qty = reader["quantity"].ToString();
                    if (client == "")
                    {
                        item.price = Convert.ToInt32((Convert.ToDecimal(reader["price_at_a_discount"]) * 100)).ToString();
                    }
                    else
                    {
                        item.price = Convert.ToInt32((Convert.ToDecimal(reader["price"]) * 100)).ToString();
                    }
                    //item.discount = Convert.ToInt32(((Convert.ToDecimal(reader["sum_at_a_discount"]) - Convert.ToDecimal(reader["quantity"]) * Convert.ToDecimal(reader["price"]))*100)*-1).ToString();
                    //item.discount = Convert.ToInt32(((Convert.ToDecimal(reader["price_at_a_discount"])- Convert.ToDecimal(reader["price"])) * 100)*-1).ToString();
                    items.item.Add(item);
                    //list_items.Add(item);
                    //buyNewrequest.items.Add(item);
                }
                //items.item = list_items;
                buyReturnRequest.items = items;
            }
            catch (NpgsqlException ex)
            {
                result = false;
            }
            catch (Exception ex)
            {
                result = false;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
            return(result);
        }
Beispiel #9
0
        private void get_phone_client()
        {
            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                string query = "SELECT clients.phone AS phone, coalesce(temp_phone_clients.phone,'') AS phone1 FROM clients " +
                               " left join temp_phone_clients ON clients.code = temp_phone_clients.barcode " +
                               " WHERE clients.code='" + client_code + "'";
                NpgsqlCommand    command = new NpgsqlCommand(query, conn);
                NpgsqlDataReader reader  = command.ExecuteReader();
                while (reader.Read())
                {
                    if ((reader["phone"].ToString().Trim().Length >= 10))
                    {
                        txtB_phone.Text = reader["phone"].ToString().Trim();
                    }
                    else if ((reader["phone1"].ToString().Trim().Length >= 10))
                    {
                        txtB_phone.Text = reader["phone1"].ToString().Trim();
                    }
                }
                reader.Close();
                conn.Close();

                if (txtB_phone.Text.Trim().Length > 10)
                {
                    txtB_phone.Text = txtB_phone.Text.Substring(0, 2) + " " + txtB_phone.Text.Substring(2, 3) + " " + txtB_phone.Text.Substring(5, 3) + " " + txtB_phone.Text.Substring(8, 2) + " " + txtB_phone.Text.Substring(10, 2);
                }
                else if (txtB_phone.Text.Trim().Length == 10)
                {
                    txtB_phone.Text = txtB_phone.Text.Substring(0, 3) + " " + txtB_phone.Text.Substring(3, 3) + " " + txtB_phone.Text.Substring(6, 2) + " " + txtB_phone.Text.Substring(8, 2);
                }
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show("Ошибка при проверка наличия телефона " + ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка при проверка наличия телефона " + ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Возвращает ид Роли
        /// </summary>
        /// <param name="user_code"></param>
        /// <returns></returns>
        private int find_user_role_new(string password)
        {
            int rezult = 0;

            string password_Md5Hash = MainStaticClass.getMd5Hash(password).ToUpper();

            try
            {
                NpgsqlConnection conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                string           query   = "SELECT rights,name,code,inn FROM users where password_m='" + password_Md5Hash.Trim() + "' or password_b='" + password_Md5Hash.Trim() + "'";
                NpgsqlCommand    command = new NpgsqlCommand(query, conn);
                NpgsqlDataReader reader  = command.ExecuteReader();
                while (reader.Read())
                {
                    rezult = Convert.ToInt32(reader.GetInt16(0));
                    if (!not_change_Cash_Operator)
                    {
                        MainStaticClass.Cash_Operator             = reader["name"].ToString().Trim();
                        MainStaticClass.Cash_Operator_Client_Code = reader["code"].ToString();
                        MainStaticClass.cash_operator_inn         = reader["inn"].ToString();
                    }
                }
                conn.Close();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }

            if (MainStaticClass.Cash_Operator.Trim().ToUpper() == "К9")
            {
                //MessageBox.Show("                                                                              "+MainStaticClass.CashDeskNumber.ToString());
                //MessageBox.Show("                                                                              "+MainStaticClass.get_unloading_interval().ToString());

                if ((MainStaticClass.CashDeskNumber != 9) || (MainStaticClass.get_unloading_interval() != 0))//Это пользователь для центрального компьютера 9 касса, пользователь не может зайти если стоит период синхронизации отличный от нуля или если номер кассы не 9
                {
                    rezult = 0;
                    MainStaticClass.Cash_Operator             = "";
                    MainStaticClass.Cash_Operator_Client_Code = "";
                }
            }

            return(rezult);
        }
Beispiel #11
0
        private void Constants_Load(object sender, EventArgs e)
        {
            NpgsqlConnection conn = null;

            try
            {
                conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                string query = "SELECT nick_shop,cash_desk_number,use_debug,code_shop," +
                               " path_for_web_service,currency,unloading_period,last_date_download_bonus_clients," +
                               " envd,pass_promo,print_m,system_taxation FROM constants";
                NpgsqlCommand    command = new NpgsqlCommand(query, conn);
                NpgsqlDataReader reader  = command.ExecuteReader();
                while (reader.Read())
                {
                    this.nick_shop.Text        = reader["nick_shop"].ToString();
                    this.cash_desk_number.Text = reader["cash_desk_number"].ToString();
                    m_cash_desk_number         = Convert.ToInt32(reader["cash_desk_number"]);
                    if (Convert.ToBoolean(reader["use_debug"]))
                    {
                        this.use_debug.CheckState = CheckState.Checked;
                    }
                    //this.code_shop.Text = reader["code_shop"].ToString();
                    this.path_for_web_service.Text = reader["path_for_web_service"].ToString();
                    this.currency.Text             = reader["currency"].ToString();
                    this.unloading_period.Text     = reader["unloading_period"].ToString();
                    this.txtB_last_date_download_bonus_clients.Text = (reader["last_date_download_bonus_clients"].ToString() == "" ? new DateTime(2000, 1, 1).ToString("dd-MM-yyyy") : Convert.ToDateTime(reader["last_date_download_bonus_clients"]).ToString("dd-MM-yyyy"));
                    //this.checkBox_envd.CheckState = (reader["envd"].ToString().ToLower() == "false" ? CheckState.Unchecked : CheckState.Checked);
                    this.checkBox_print_m.CheckState = (reader["print_m"].ToString().ToLower() == "false" ? CheckState.Unchecked : CheckState.Checked);
                    //this.checkBox_osn_usnIncomeOutcome.CheckState = (reader["usn_income_out_come"].ToString().ToLower() == "false" ? CheckState.Unchecked : CheckState.Checked);
                    this.comboBox_system_taxation.SelectedIndex = Convert.ToInt16(reader["system_taxation"]);
                }
                reader.Close();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
            }
        }
Beispiel #12
0
        private void btn_execute_Click(object sender, EventArgs e)
        {
            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                string        query   = "INSERT INTO public.client_with_changed_status_to_send(client,date_change,new_phone_number)VALUES(@client,@date_change,@new_phone_number);";
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                command.Parameters.AddWithValue("@client", client_code);
                command.Parameters.AddWithValue("@date_change", (DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss")));
                string new_phone = maskedTxtB_new_phone_number.Text.Trim().Replace(" ", "").Replace("+7", "");
                if ((new_phone.Length != 10) && (new_phone.Length != 0))
                {
                    MessageBox.Show("Неверная длина номера телефона");
                    return;
                }
                command.Parameters.AddWithValue("@new_phone_number", maskedTxtB_new_phone_number.Text.Trim().Replace(" ", "").Replace("+7", ""));

                command.ExecuteNonQuery();
                command.Dispose();
                conn.Close();
                MessageBox.Show("Заявка на изменение статуса успешно создана");
                this.Close();
                this.DialogResult = DialogResult.OK;
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(" Ошибка при изменении статуса  " + ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(" Ошибка при изменении статуса  " + ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
        /// <summary>
        /// Обновим статусы после успешной отправки документов
        /// </summary>
        private void update_status_is_sent()
        {
            NpgsqlConnection  conn  = MainStaticClass.NpgsqlConn();
            NpgsqlTransaction trans = null;

            try
            {
                conn.Open();
                trans = conn.BeginTransaction();
                string query = "UPDATE checks_header SET is_sent=1 WHERE document_number in (" +
                               document_number_list.ToString() + ")";
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                command.Transaction = trans;
                command.ExecuteNonQuery();
                trans.Commit();
                command.Dispose();
                trans.Dispose();
                conn.Close();
                MainStaticClass.Last_Send_Last_Successful_Sending = DateTime.Now;
            }
            catch (NpgsqlException)
            {
                if (trans != null)
                {
                    trans.Rollback();
                }
            }
            catch (Exception)
            {
                if (trans != null)
                {
                    trans.Rollback();
                }
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Beispiel #14
0
        private void load_actions()
        {
            NpgsqlConnection conn    = null;
            NpgsqlCommand    command = null;

            try
            {
                conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                string query = "SELECT action_header.date_started, action_header.date_end, action_header.num_doc, action_header.tip, action_header.barcode, action_header.persent, action_header.sum,action_header.comment,tovar.name   FROM action_header left join tovar on action_header.code_tovar=tovar.code ;";
                command = new NpgsqlCommand(query, conn);
                NpgsqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    ListViewItem lvi = new ListViewItem(reader.GetInt32(2).ToString());
                    lvi.Tag = reader.GetInt32(2).ToString();
                    lvi.SubItems.Add(reader.GetDateTime(0).ToString());
                    lvi.SubItems.Add(reader.GetDateTime(1).ToString());
                    lvi.SubItems.Add(reader.GetInt16(3).ToString());
                    lvi.SubItems.Add(reader.GetString(4).ToString());
                    lvi.SubItems.Add(reader.GetDecimal(5).ToString());
                    lvi.SubItems.Add(reader.GetDecimal(6).ToString());
                    lvi.SubItems.Add(reader.GetString(7).ToString());
                    //lvi.SubItems.Add(reader.GetString(8).ToString());
                    lvi.SubItems.Add(reader[8].ToString());
                    listView_doc.Items.Add(lvi);
                }
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Beispiel #15
0
        private void insert_record_failed_input_phone()
        {
            bool errors = false;

            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                string        query   = "INSERT INTO failed_input_phone(client_code, datetime_input)  VALUES ('" + caller.client.Tag.ToString() + "','" + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + "');";
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                command.ExecuteNonQuery();
                conn.Close();
                command.Dispose();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show("Ошибка при определении количества попыток ввода неправильного номера телефона " + ex.Message);
                errors = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка при определении количества попыток ввода неправильного номера телефона " + ex.Message);
                errors = true;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
            if (errors)
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
        }
Beispiel #16
0
        private bool this_check_the_last(string datetime)
        {
            bool result = false;


            NpgsqlConnection conn = null;

            try
            {
                conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                string        query   = "SELECT date_time_write  FROM checks_header order by date_time_write desc";
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                //object result_query = command.ExecuteScalar();
                if (datetime.Trim() == Convert.ToDateTime(command.ExecuteScalar()).ToString("yyyy-MM-dd HH:mm:ss").Trim())
                {
                    result = true;
                }
                conn.Close();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            return(result);
        }
Beispiel #17
0
        private int count_users()
        {
            int rezult = 0;

            try
            {
                NpgsqlConnection conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                string        query   = "SELECT COUNT(*)FROM users ";
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                object        result  = command.ExecuteScalar();
                if (result != null)
                {
                    rezult = Convert.ToInt32(result);
                }
                conn.Close();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }

            return(rezult);
        }
Beispiel #18
0
        private void print_control_check()
        {
            StringBuilder print_string = new StringBuilder();

            int width_of_symbols = MainStaticClass.Width_Of_Symbols;

            if (width_of_symbols == 0)
            {
                MessageBox.Show("Не задана ширина печати, печать выполнена не будет ", "Ошибка настройки программы");
                return;
            }
            //using (StreamWriter sw = new StreamWriter(Application.StartupPath + "/PrintCheck.txt"))
            //{
            //sw.WriteLine("ЧИСТЫЙ ДОМ - Магазин низких цен №1");


            print_string.Append("ЧИСТЫЙ ДОМ - Магазин низких цен №1" + "\r\n");
            //sw.WriteLine("       << ЧИСТЫЙ ДОМ >>");
            //sw.WriteLine("бытовая химия - косметика - парфюмерия");
            print_string.Append("бытовая химия - косметика - парфюмерия" + "\r\n");
            //sw.WriteLine("_______________________________________");
            print_string.Append("---------------------------------------" + "\r\n");


            print_string.Append(MainStaticClass.Nick_Shop + " К №" + MainStaticClass.CashDeskNumber + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + MainStaticClass.Cash_Operator + "\r\n");

            string number = "";

            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                string query = "SELECT MAX(document_number)  FROM checks_header  where date_time_write<'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                conn.Open();
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                number = command.ExecuteScalar().ToString();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
                number = "Ошибка при получении номера";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                number = "Ошибка при получении номера";
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            print_string.Append("Предыдущий чек № " + number + "\r\n");


            //if (DialogResult.OK == MessageBox.Show("Печатать чек ?", "Печатать чек ?", MessageBoxButtons.OKCancel))
            //{
            PrintDocument pd = new PrintDocument();

            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            //pd.PrinterSettings.PrinterName = PrinterSettings.InstalledPrinters[0];
            pd.PrinterSettings.PrinterName = PrinterSettings.InstalledPrinters[MainStaticClass.get_num_text_pinter()];
            count_pages = -1;
            string TFF = print_string.ToString();

            TFF        = TFF.Replace("\r\n", "|");
            print_data = TFF.Split('|');
            pd.Print();
            //}
        }
Beispiel #19
0
        public void loaddocuments()
        {
            listView1.Items.Clear();
            NpgsqlConnection conn = null;

            try
            {
                conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                //string myQuery = "SELECT checks_header.date_time_write,clients.name,checks_header.cash,checks_header.remainder  FROM checks_header left join clients ON checks_header.client=clients.code WHERE checks_header.date_time_write BETWEEN '" + data_start.Text + "' and '" + data_finish.Text + "' order by checks_header.date_time_write  ";
                string myQuery = "SELECT checks_header.its_deleted," +
                                 "checks_header.date_time_write," +
                                 "clients.name," +
                                 "checks_header.cash," +
                                 "checks_header.remainder," +
                                 "checks_header.comment," +
                                 //"checks_header.inventory,"+
                                 "checks_header.its_print," +
                                 "checks_header.check_type,checks_header.document_number  FROM checks_header left join clients ON checks_header.client=clients.code WHERE checks_header.date_time_write BETWEEN '" + dateTimePicker1.Value.ToString("yyy-MM-dd") + " 00:00:00" + "' and '" + dateTimePicker1.Value.AddDays(1).ToString("yyy-MM-dd") + " 00:00:00" + "' AND its_deleted<2 order by checks_header.date_time_write  ";
                if (checkBox_show_3_last_checks.CheckState == CheckState.Checked)
                {
                    myQuery += " desc limit 3 ";
                }
                //MessageBox.Show(myQuery);
                NpgsqlCommand    command = new NpgsqlCommand(myQuery, conn);
                NpgsqlDataReader reader  = command.ExecuteReader();

                while (reader.Read())
                {
                    //ListViewItem lvi = new ListViewItem(reader.GetDateTime(0).ToString("yyy-MM-dd HH:mm:ss"));
                    ListViewItem lvi = new ListViewItem(reader.GetDecimal(0).ToString());
                    lvi.SubItems.Add(reader.GetDateTime(1).ToString("yyyy-MM-dd HH:mm:ss"));
                    lvi.SubItems.Add(reader[2].ToString());
                    lvi.SubItems.Add(reader.GetDecimal(3).ToString());
                    lvi.SubItems.Add(reader.GetDecimal(4).ToString());
                    lvi.SubItems.Add((reader["check_type"].ToString() == "0" ? "Продажа" : "Возврат"));
                    lvi.SubItems.Add(reader.GetString(5));

                    if (MainStaticClass.Use_Fiscall_Print)
                    {
                        if (!Convert.IsDBNull(reader[6]))
                        {
                            if (!reader.GetBoolean(6))
                            {
                                if (reader.GetDecimal(0) == 0)
                                {
                                    lvi.BackColor = Color.Pink;
                                }
                            }
                        }
                        else
                        {
                            if (reader.GetDecimal(0) == 0)
                            {
                                lvi.BackColor = Color.Pink;
                            }
                        }
                    }
                    lvi.SubItems.Add(reader["document_number"].ToString());

                    listView1.Items.Add(lvi);
                }
                reader.Close();
                conn.Close();
                command.Dispose();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            listView1.Focus();
            this.listView1.Select();
            if (checkBox_show_3_last_checks.CheckState == CheckState.Checked)
            {
                if (listView1.Items.Count > 0)
                {
                    this.listView1.Items[0].Selected = true;
                    this.listView1.Items[0].Focused  = true;
                    this.listView1.EnsureVisible(0);
                }
            }
            else
            {
                if (listView1.Items.Count > 0)
                {
                    this.listView1.Items[this.listView1.Items.Count - 1].Selected = true;
                    this.listView1.Items[this.listView1.Items.Count - 1].Focused  = true;
                    this.listView1.EnsureVisible(this.listView1.Items.Count - 1);
                }
            }
        }
        private void getdata_h()
        {
            salesPortions.ListSalesPortionsHeader = new List <SalesPortionsHeader>();
            StringBuilder    result = new StringBuilder();
            NpgsqlConnection conn   = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                string query = "SELECT document_number," +
                               " cash_desk_number," +
                               " client," +
                               " bonuses_it_is_counted," +
                               " discount," +
                               " cash," +
                               " check_type," +
                               " have_action," +
                               " date_time_start," +
                               " date_time_write," +
                               " its_deleted," +
                               " bonuses_it_is_written_off, " +
                               " action_num_doc, " +
                               " cash_money, " +
                               " non_cash_money, " +
                               " sertificate_money," +
                               //" sales_assistant,"+
                               " autor, " +
                               " comment, " +
                               " its_print, " +
                               "id_transaction," +
                               "id_transaction_sale" +
                               " FROM checks_header WHERE document_number in  (" + document_number_list.ToString() + ")";
                NpgsqlCommand    command = new NpgsqlCommand(query, conn);
                NpgsqlDataReader reader  = command.ExecuteReader();
                while (reader.Read())
                {
                    //Новое заполнение
                    SalesPortionsHeader salesPortionsHeader = new SalesPortionsHeader();
                    salesPortionsHeader.Shop             = nick_shop;
                    salesPortionsHeader.Num_doc          = reader["document_number"].ToString();
                    salesPortionsHeader.Num_cash         = reader["cash_desk_number"].ToString();
                    salesPortionsHeader.Client           = reader["client"].ToString();
                    salesPortionsHeader.Bonus_counted    = reader["bonuses_it_is_counted"].ToString().Replace(",", ".");
                    salesPortionsHeader.Discount         = reader["discount"].ToString().Replace(",", ".");
                    salesPortionsHeader.Sum              = reader["cash"].ToString().Replace(",", ".");
                    salesPortionsHeader.Check_type       = reader["check_type"].ToString();
                    salesPortionsHeader.Have_action      = Convert.ToBoolean(reader["have_action"]) ? "1" :"0"; //reader
                    salesPortionsHeader.Date_time_start  = Convert.ToDateTime(reader["date_time_start"]).ToString("dd-MM-yyyy HH:mm:ss");
                    salesPortionsHeader.Date_time_write  = Convert.ToDateTime(reader["date_time_write"]).ToString("dd-MM-yyyy HH:mm:ss");
                    salesPortionsHeader.Its_deleted      = reader["its_deleted"].ToString();
                    salesPortionsHeader.Bonus_writen_off = reader["bonuses_it_is_written_off"].ToString().Replace(",", ".");
                    salesPortionsHeader.Action           = reader["action_num_doc"].ToString();
                    salesPortionsHeader.Sum_cash         = reader["cash_money"].ToString().Replace(",", ".");
                    salesPortionsHeader.Sum_terminal     = reader["non_cash_money"].ToString().Replace(",", ".");
                    salesPortionsHeader.Sum_certificate  = reader["sertificate_money"].ToString().Replace(",", ".");
                    //salesPortionsHeader.Sales_assistant = reader["sales_assistant"].ToString();
                    salesPortionsHeader.Autor   = reader["autor"].ToString();
                    salesPortionsHeader.Comment = reader["comment"].ToString();
                    if (reader["its_print"].ToString() == "")
                    {
                        salesPortionsHeader.Its_print = "0";
                    }
                    else
                    {
                        salesPortionsHeader.Its_print = (Convert.ToBoolean(reader["its_print"]) == true ? "1" : "0");
                    }
                    salesPortionsHeader.Id_transaction      = reader["id_transaction"].ToString();
                    salesPortionsHeader.Id_transaction_sale = reader["id_transaction_sale"].ToString();
                    salesPortions.ListSalesPortionsHeader.Add(salesPortionsHeader);
                    //Конец Новое заполнение
                }
                conn.Close();
                reader.Close();
            }
            catch (NpgsqlException ex)
            {
                if (show_messages)
                {
                    MessageBox.Show(ex.Message);
                }
                were_mistakes = true;
            }
            catch (Exception ex)
            {
                if (show_messages)
                {
                    MessageBox.Show(ex.Message);
                }
                were_mistakes = true;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Beispiel #21
0
        public bool sent_documentbuyReturn(BuyReturnRequest buyReturnRequest, string document_number)
        {
            bool result = true;

            string json = JsonConvert.SerializeObject(buyReturnRequest, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            txtB_jason.Text = json;
            string url = "http://92.242.41.218/processing/v3/buyReturn/";

            byte[]         body         = Encoding.UTF8.GetBytes(json);
            HttpWebRequest request      = (HttpWebRequest)WebRequest.Create(url);
            string         shop_request = "";

            if (MainStaticClass.Nick_Shop.Substring(0, 1).ToUpper() == "A")
            {
                shop_request = MainStaticClass.Nick_Shop + MainStaticClass.CashDeskNumber;
            }
            else
            {
                shop_request = "1" + Convert.ToInt16(MainStaticClass.Nick_Shop.Substring(1, 2)).ToString() + MainStaticClass.CashDeskNumber;
            }

            //var authString = Convert.ToBase64String(Encoding.Default.GetBytes("A011" + ":" + "JpDkHs~AE%zS8Y7HDpVM"));
            var authString = Convert.ToBase64String(Encoding.Default.GetBytes(shop_request + ":" + MainStaticClass.PassPromo));

            request.Headers.Add("Authorization", "Basic " + authString);

            request.Method        = "POST";
            request.ContentType   = "application/json; charset=utf-8";
            request.ContentLength = body.Length;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(body, 0, body.Length);
                stream.Close();
            }

            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    byte[] buf   = new byte[10000];
                    int    count = -1;
                    String read  = "";
                    do
                    {
                        count = response.GetResponseStream().Read(buf, 0, buf.Length);
                        read += Encoding.UTF8.GetString(buf, 0, count);
                    } while (response.GetResponseStream().CanRead&& count != 0);
                    //txtB_json_response.Text = JsonConvert.DeserializeObject(read).ToString();
                    //string answer = JsonConvert.DeserializeObject(read.Replace("{}", @"""""")).ToString();//read.Replace("{}","\"\"")
                    BuynewResponse buynewResponse = JsonConvert.DeserializeObject <BuynewResponse>(read.Replace("{}", @""""""), new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    });
                    if (buynewResponse.res == "1")
                    {
                        conn.Open();
                        string        query        = "UPDATE checks_header SET sent_to_processing_center=1,id_transaction=" + buynewResponse.transactionId + " WHERE document_number =" + document_number;
                        NpgsqlCommand command      = new NpgsqlCommand(query, conn);
                        int           rowsaffected = command.ExecuteNonQuery();
                        conn.Close();
                        command.Dispose();
                    }
                    else //Куда то записать информацию о трудностях
                    {
                        get_description_errors_on_code(buynewResponse.res);
                    }
                    response.Close();
                }
            }
            catch (WebException ex)
            {
                if (!run_in_the_background)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            catch (NpgsqlException ex)
            {
                if (!run_in_the_background)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            catch (Exception ex)
            {
                if (!run_in_the_background)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            return(result);
        }
Beispiel #22
0
        void txtB_phone_number_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (e.KeyChar != 43)
            //{
            if (!(Char.IsDigit(e.KeyChar)))
            {
                if (e.KeyChar != (char)Keys.Back)
                {
                    e.Handled = true;
                }
            }
            //}

            if (e.KeyChar == (char)Keys.Enter)
            {
                //int lenght = 0;
                //if (MainStaticClass.get_currency() == "руб.")
                //{
                //    lenght = 12;
                //}
                //else
                //{
                //    lenght = 13;
                //}

                if (this.txtB_phone_number.Text.Trim().Length != 10)
                {
                    MessageBox.Show(" Телефонный номер должен состоять из 10 цифр ");
                    return;
                }
                //{
                //    MessageBox.Show(" Телефонный номер введен некорректно ");
                //    return;
                //}
                //if (MainStaticClass.get_currency() == "руб.")
                //{
                //if (this.txtB_phone_number.Text.Trim().Substring(0, 1) != "7")
                //{
                //    MessageBox.Show(" Телефонный номер введен некорректно, номер должен начинаться с +7 ");
                //    return;
                //}
                //}
                //else
                //{
                //    if (this.txtB_phone_number.Text.Trim().Substring(0, 3) != "+38")
                //    {
                //        MessageBox.Show(" Телефонный номер введен некорректно, номер должен начинаться с +38 ");
                //        return;
                //    }
                //}
            }
            else
            {
                return;
            }

            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                //string query = "SELECT COUNT(*) FROM clients WHERE phone LIKE'%"+ txtB_phone_number.Text.Trim() + "%'";
                string        query   = "SELECT COUNT(*) FROM clients where right(phone,10)='" + txtB_phone_number.Text.Trim() + "'";
                NpgsqlCommand command = new NpgsqlCommand(query, conn);
                if (Convert.ToInt32(command.ExecuteScalar()) == 0)
                {
                    query   = "DELETE FROM temp_phone_clients WHERE phone='" + this.txtB_phone_number.Text.Trim() + "'";
                    command = new NpgsqlCommand(query, conn);
                    command.ExecuteNonQuery();
                    if (barcode != "")
                    {
                        query = "INSERT INTO temp_phone_clients(barcode, phone)VALUES ('" + barcode + "','" + this.txtB_phone_number.Text.Trim() + "')";
                    }
                    else
                    {
                        query = "INSERT INTO temp_phone_clients(barcode, phone)VALUES ('" + this.txtB_phone_number.Text.Trim() + "','" + this.txtB_phone_number.Text.Trim() + "')";
                    }
                    command = new NpgsqlCommand(query, conn);
                    command.ExecuteNonQuery();
                    conn.Close();
                    if (barcode == "")
                    {
                        cash_Check.client.Tag  = this.txtB_phone_number.Text.Trim();
                        cash_Check.client.Text = this.txtB_phone_number.Text.Trim();
                        cash_Check.Discount    = Convert.ToDecimal(0.05);
                    }
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("У этого клиента уже есть дисконтная карта с привязанным номером телефона !!!");
                    //MessageBox.Show("Введите номер телефона в соответсвующее поле !!!");
                    this.DialogResult = DialogResult.Yes;
                    conn.Close();
                    this.Close();
                }
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(" Ошибки при записи номера телефона " + ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(" Ошибки при записи номера телефона " + ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            this.Close();
        }
Beispiel #23
0
        /// <summary>
        /// Главный вызываемый метод по отправке бонусов
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void sent_Click(object sender, EventArgs e)
        {
            if (MainStaticClass.PassPromo == "")
            {
                MessageBox.Show("Эта касса не учавствует в бонусной программе ");
                return;
            }

            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                string query = " SELECT document_number, client, cash_desk_number,date_time_start,bonuses_it_is_written_off,id_transaction,id_transaction_sale,check_type  " +
                               " FROM checks_header WHERE sent_to_processing_center = 0 and its_deleted=0";
                NpgsqlCommand    command       = new NpgsqlCommand(query, conn);
                NpgsqlDataReader reader        = command.ExecuteReader();
                BuyNewRequest    buyNewRequest = new BuyNewRequest();
                while (reader.Read())//Здесь перебираем документы
                {
                    //предварительно было отправлено buy_new, поэтому если нет оплаты бонусами то нужно отправить buycommit
                    //if ((reader["id_transaction"].ToString().Trim() != "")&&(Convert.ToInt32(reader["bonuses_it_is_written_off"]) == 0))
                    if (reader["id_transaction"].ToString().Trim() != "")
                    {
                        BuyCommit buyCommit = new BuyCommit();
                        buyCommit.transactionId = reader["id_transaction"].ToString().Trim();
                        sent_document_buyCommit(buyCommit, reader["document_number"].ToString().Trim());
                        continue;
                    }
                    if (reader["check_type"].ToString() == "0")
                    {
                        buyNewRequest.cashierName = MainStaticClass.Cash_Operator;
                        buyNewRequest.commit      = "1";
                        buyNewRequest.date        = Convert.ToDateTime(reader["date_time_start"]).ToString("yyyy-MM-dd HH:mm:ss");
                        //if (reader["client"].ToString().Trim().Length == 36)
                        //{
                        //    buyNewRequest.cardTrack2 = reader["client"].ToString();
                        //}
                        if (reader["client"].ToString().Trim().Length >= 10)
                        {
                            buyNewRequest.cardNum = reader["client"].ToString();
                        }

                        if ((Convert.ToInt32(reader["bonuses_it_is_written_off"]) != 0) && (reader["client"].ToString().Trim().Length == 10))
                        {
                            buyNewRequest.charge = (Convert.ToInt32(reader["bonuses_it_is_written_off"]) * 100).ToString();
                        }

                        //if (reader["client"].ToString().Trim().Length == 0)
                        //{
                        //    buyNewRequest.type = "6";
                        //}
                        //else
                        //{
                        buyNewRequest.type = "4";
                        //}
                        if (fill_items(buyNewRequest, reader["document_number"].ToString(), reader["client"].ToString()))
                        {
                            sent_document(buyNewRequest, reader["document_number"].ToString());
                        }
                    }
                    else if (reader["check_type"].ToString() == "1")
                    {
                        BuyReturnRequest buyReturnRequest = new BuyReturnRequest();
                        buyReturnRequest.cashierName = MainStaticClass.Cash_Operator;
                        buyReturnRequest.commit      = "1";
                        //buyReturnRequest.date = Convert.ToDateTime(reader["date_time_start"]).ToString("yyyy-MM-dd HH:mm:ss");
                        buyReturnRequest.transactionId = reader["id_transaction_sale"].ToString();
                        if (fill_items(buyReturnRequest, reader["document_number"].ToString(), reader["client"].ToString()))
                        {
                            sent_documentbuyReturn(buyReturnRequest, reader["document_number"].ToString());
                        }
                    }

                    //if (fill_items(buyNewRequest, reader["document_number"].ToString(),reader["client"].ToString()))
                    //{
                    //    if (reader["check_type"].ToString() == "0")
                    //    {

                    //    }
                    //    else if (reader["check_type"].ToString() == "1")
                    //    {
                    //        sent_documentbuyReturn(buyNewRequest, reader["document_number"].ToString());
                    //    }
                    //}
                }
                reader.Close();
                conn.Close();
            }
            catch (NpgsqlException ex)
            {
                if (!run_in_the_background)
                {
                    MyMessageBox mmb = new MyMessageBox(ex.Message, " Отправка неотправленных бонусов ");
                    mmb.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                if (!run_in_the_background)
                {
                    MyMessageBox mmb = new MyMessageBox(ex.Message, " Отправка неотправленных бонусов ");
                    mmb.ShowDialog();
                }
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Beispiel #24
0
        private void txtB_inpute_code_client_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 43)
            {
                if (!(Char.IsDigit(e.KeyChar)))
                {
                    if (e.KeyChar != (char)Keys.Back)
                    {
                        e.Handled = true;
                    }
                }
            }

            if (e.KeyChar == (char)Keys.Enter)
            {
                NpgsqlConnection conn      = MainStaticClass.NpgsqlConn();
                bool             thisclose = true;
                try
                {
                    conn.Open();
                    string query = "SELECT code FROM bonus_cards WHERE pin='" + this.txtB_inpute_code_client.Text.Trim() + "'";
                    this.txtB_inpute_code_client.Text = "";
                    NpgsqlCommand command      = new NpgsqlCommand(query, conn);
                    object        result_query = command.ExecuteScalar();
                    if (result_query == null)
                    {
                        MessageBox.Show("Бонусная карта с введенным кодом не найдена");
                        return;
                    }
                    string code = result_query.ToString();
                    if (code.Trim() == "")
                    {
                        MessageBox.Show("Бонусная карта не найдена");
                        txtB_inpute_code_client.Text = "";
                        thisclose = false;
                    }
                    else
                    {
                        //ПРЕДВАРИТЕЛЬНАЯ ПРОВЕРКА ТЧ НА НАЛИЧИЕ БОНУСНОЙ КАРТЫ
                        bool finded = false;
                        foreach (ListViewItem lvi in cc.listView1.Items)
                        {
                            if (lvi.SubItems[0].Text.Trim() == "3")
                            {
                                finded = true;
                                break;
                            }
                        }
                        if (finded)
                        {
                            MessageBox.Show("в Т.Ч. Уже есть бонусная карта ");
                            return;
                        }
                        //ДОБАВЛЕНИЕ БОНУСНОЙ КАРТЫ !!!
                        cc.client.Text = code;
                        cc.client.Tag  = code;

                        query   = "SELECT code,name, retail_price FROM tovar WHERE code = 3 and its_deleted=0";
                        command = new NpgsqlCommand(query, conn);
                        NpgsqlDataReader reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            finded = true;//Это значит, что запись найдена
                            ListViewItem item = new ListViewItem(reader[0].ToString());
                            item.Tag = reader[0].ToString();
                            item.SubItems.Add(reader[1].ToString());
                            item.SubItems.Add("");                   //Характеристика
                            item.SubItems.Add("1");
                            item.SubItems.Add(reader[2].ToString()); //Цена
                            item.SubItems.Add(reader[2].ToString()); //Сумма
                            item.SubItems.Add(reader[2].ToString()); //Цена со скидкой
                            item.SubItems.Add(reader[2].ToString()); //Сумма со кидкой
                            item.SubItems.Add("0");
                            item.SubItems.Add("0");
                            item.SubItems.Add("0");
                            item.SubItems.Add("0");
                            item.SubItems.Add("0");
                            item.SubItems.Add("0");
                            cc.listView1.Items.Add(item);
                            break;
                        }
                        if (!finded)//товар дисконтная карта не найден и не добавлен в ТЧ
                        {
                            return;
                        }
                    }
                    conn.Close();
                }
                catch (NpgsqlException ex)
                {
                    MessageBox.Show(" Ошибки при записи нового кода клиента  " + ex.Message);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(" Ошибки при записи нового кода клиента  " + ex.Message);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                }
                if (thisclose)
                {
                    this.Close();
                }
            }
        }
Beispiel #25
0
        private void btn_send_sms_Click(object sender, EventArgs e)
        {
            RequestSMSCode requestSMSCode = new RequestSMSCode();

            requestSMSCode.phone         = code_client;
            requestSMSCode.notRegistered = "0";

            string json = JsonConvert.SerializeObject(requestSMSCode, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });
            //txtB_jason.Text = json;
            string url = "http://92.242.41.218/processing/v3/requestSMSCode/";

            byte[]         body         = Encoding.UTF8.GetBytes(json);
            HttpWebRequest request      = (HttpWebRequest)WebRequest.Create(url);
            string         shop_request = "";

            if (MainStaticClass.Nick_Shop.Substring(0, 1).ToUpper() == "A")
            {
                shop_request = MainStaticClass.Nick_Shop + MainStaticClass.CashDeskNumber;
            }
            else
            {
                shop_request = "1" + Convert.ToInt16(MainStaticClass.Nick_Shop.Substring(1, 2)).ToString() + MainStaticClass.CashDeskNumber;
            }

            //var authString = Convert.ToBase64String(Encoding.Default.GetBytes("A011" + ":" + "JpDkHs~AE%zS8Y7HDpVM"));
            var authString = Convert.ToBase64String(Encoding.Default.GetBytes(shop_request + ":" + MainStaticClass.PassPromo));

            request.Headers.Add("Authorization", "Basic " + authString);

            request.Method        = "POST";
            request.ContentType   = "application/json; charset=utf-8";
            request.ContentLength = body.Length;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(body, 0, body.Length);
                stream.Close();
            }

            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    byte[] buf   = new byte[10000];
                    int    count = -1;
                    String read  = "";
                    do
                    {
                        count = response.GetResponseStream().Read(buf, 0, buf.Length);
                        read += Encoding.UTF8.GetString(buf, 0, count);
                    } while (response.GetResponseStream().CanRead&& count != 0);
                    //txtB_json_response.Text = JsonConvert.DeserializeObject(read).ToString();
                    //string answer = JsonConvert.DeserializeObject(read.Replace("{}", @"""""")).ToString();//read.Replace("{}","\"\"")
                    ResponceRequestSMSCode responceRequestSMSCode = JsonConvert.DeserializeObject <ResponceRequestSMSCode>(read.Replace("{}", @""""""), new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    });
                    if (responceRequestSMSCode.res == "1")
                    {
                        code_answer            = responceRequestSMSCode.code;
                        label1.Text            = "Проверочный код успешно получен";
                        btn_check_code.Enabled = true;
                        MessageBox.Show(code_answer);
                    }
                    else if (responceRequestSMSCode.res == "20") //Куда то записать информацию о трудностях
                    {
                        MessageBox.Show(" Номер телефона не найден ");
                    }
                    response.Close();
                }
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

            //return result;
        }
Beispiel #26
0
        void Discount_types_Load(object sender, System.EventArgs e)
        {
            // Set the view to show details.
            listView1.View = View.Details;

            // Allow the user to edit item text.
            listView1.LabelEdit = true;

            // Allow the user to rearrange columns.
            listView1.AllowColumnReorder = true;

            // Select the item and subitems when selection is made.
            listView1.FullRowSelect = true;

            // Display grid lines.
            listView1.GridLines = true;

            // Sort the items in the list in ascending order.
            //listView1.Sorting = SortOrder.Ascending;

            listView1.Columns.Add("Код", 100, HorizontalAlignment.Left);
            listView1.Columns.Add("Процент скидки", 200, HorizontalAlignment.Left);
            listView1.Columns.Add("Сумма перехода", 200, HorizontalAlignment.Right);
            //listView1.Columns.Add("Последняя зак. цена", 100, HorizontalAlignment.Right);

            //ListViewItemSorter _lvwItemComparer = new ListViewItemComparer();
            //this.listView1.ListViewItemSorter = _lvwItemComparer;


            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            conn.Open();
            string           myQuery   = "SELECT * FROM discount_types order by code";
            NpgsqlCommand    command   = new NpgsqlCommand(myQuery, conn);
            NpgsqlDataReader reader    = command.ExecuteReader();
            DataTable        dataTable = new DataTable();

            dataTable.Load(reader);
            conn.Close();
            // Get the table from the data set
            //DataTable dtable = _DataSet.Tables["barcode"];

            // Clear the ListView control
            listView1.Items.Clear();

            // Display items in the ListView control
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                DataRow drow = dataTable.Rows[i];

                // Only row that have not been deleted
                if (drow.RowState != DataRowState.Deleted)
                {
                    // Define the list items
                    ListViewItem lvi = new ListViewItem(drow["code"].ToString());
                    //lvi.SubItems.Add(drow["name"].ToString());
                    lvi.SubItems.Add(drow["discount_percent"].ToString());
                    lvi.SubItems.Add(drow["transition_sum"].ToString());

                    // Add the list items to the ListView
                    listView1.Items.Add(lvi);
                }
            }
        }
Beispiel #27
0
        private void write_Click(object sender, EventArgs e)
        {
            if (this.cash_desk_number.Text.Trim().Length == 0)
            {
                MessageBox.Show("Не заполнен номер кассы");
                return;
            }
            if (this.nick_shop.Text.Trim().Length == 0)
            {
                MessageBox.Show("Не заполнен код магазина");
                return;
            }

            //if (main_change_path.Text.Trim().Length == 0)
            //{
            //    MessageBox.Show("Не заполнен путь к папке обмена");
            //    return;
            //}


            if (m_cash_desk_number != 0)
            {
                if (Convert.ToInt16(this.cash_desk_number.Text) != m_cash_desk_number)
                {
                    if (check_exists())
                    {
                        MessageBox.Show("За сегодня существуют чеки , номер кассы изменить невозможно");
                        return;
                    }
                }
            }

            if (currency.Text.Trim().Length == 0)
            {
                MessageBox.Show(" Не заполнена валюта ", " Ошибка ввода !!!");
            }


            if (unloading_period.Text.Trim().Length == 0)
            {
                unloading_period.Text = "0";
            }
            else
            {
                if (Convert.ToInt32(unloading_period.Text) != 0)
                {
                    if (Convert.ToInt32(unloading_period.Text) > 10)
                    {
                        MessageBox.Show(" Период выгрузки может быть раным нулю или быть в диапазоне 1-10 ");
                        return;
                    }
                }
            }

            string print_m = (checkBox_print_m.CheckState == CheckState.Unchecked ? "false" : "true");

            //string usn_income_out_come = (checkBox_osn_usnIncomeOutcome.CheckState == CheckState.Unchecked ? "false" : "true");

            try
            {
                NpgsqlConnection conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                NpgsqlTransaction tran  = conn.BeginTransaction();
                string            query = "UPDATE constants SET " +
                                          "cash_desk_number =" + cash_desk_number.Text + "," +
                                          "nick_shop ='" + nick_shop.Text + "'," +
                                          "use_debug =" + get_use_debug() + "," +
                                          "path_for_web_service ='" + path_for_web_service.Text + "'," +
                                          "currency ='" + currency.Text + "'," +
                                          "unloading_period =" + unloading_period.Text + "," +
                                          "print_m ='" + print_m + "'," +
                                          "last_date_download_bonus_clients ='" + txtB_last_date_download_bonus_clients.Text + "'," +
                                          "system_taxation = '" + comboBox_system_taxation.SelectedIndex.ToString() + "'";

                NpgsqlCommand command      = new NpgsqlCommand(query, conn);
                int           resul_update = command.ExecuteNonQuery();
                if (resul_update == 0)
                {
                    query = "INSERT INTO constants(cash_desk_number," +
                            "nick_shop," +
                            "use_debug," +
                            "path_for_web_service," +
                            "currency," +
                            "unloading_period," +
                            "last_date_download_bonus_clients," +
                            //"envd,"+
                            "print_m," +
                            "system_taxation) VALUES(" +
                            cash_desk_number.Text + ",'" +
                            nick_shop.Text + "'," +
                            get_use_debug() + ",'" +
                            path_for_web_service.Text + "','" +
                            currency.Text + "','" +
                            unloading_period.Text + "','" +
                            txtB_last_date_download_bonus_clients.Text + "','" +
                            print_m + "','" +
                            comboBox_system_taxation.SelectedIndex.ToString() + "')";

                    command = new NpgsqlCommand(query, conn);
                    command.ExecuteNonQuery();
                }
                tran.Commit();
                conn.Close();
                this.Close();
                MessageBox.Show(" Для применения новых параметров программа будет закрыта");
                Application.Exit();
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #28
0
        private void execute_enter(string barcode)
        {
            fail_autorize.Text = "";
            int result = -1;

            if (MainStaticClass.Use_Usb_to_Com_Barcode_Scaner)
            {
                this.input_barcode.Text = barcode;
            }
            //Проверка наличия таблицы если не найдена то это первый запуск

            NpgsqlConnection conn = null;

            try
            {
                conn = MainStaticClass.NpgsqlConn();
                conn.Open();
                NpgsqlCommand command = new NpgsqlCommand();
                command.Connection  = conn;
                command.CommandText = "select COUNT(*) from information_schema.tables 		where table_schema='public' 	and table_name='users'	";
                if (Convert.ToInt16(command.ExecuteScalar()) == 0)
                {
                    //if (caller_type == 3)
                    //{

                    //    return;
                    //}
                    //else
                    //{
                    this.Close();
                    MainStaticClass.Code_right_of_user = 1;
                    MainStaticClass.Main.InitializeComponent1();
                    conn.Close();
                    return;
                    //}
                }
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
                conn.Close();
            }

            if ((count_users() == 0) && (input_barcode.Text.Trim() == "1"))
            {//Пользователей еще нет, это первый вход
                this.Close();
                MainStaticClass.Code_right_of_user = 1;
                MainStaticClass.Main.InitializeComponent1();
            }
            else
            {
                //if (barcode.Length < 10)
                //{
                //    MessageBox.Show("Неверный код входа");
                //    return;
                //}

                //Если версия программы < 18.12.2017 тогда вызываем старую процедуру
                //иначе если версия = 18.12.2017 тогда вызываем промежуточную
                //иначе если версия > 18.12.2017 тогда вызываем новую
                //string cash_version = MainStaticClass.version();
                //int year = int.Parse("" + cash_version.Substring(6, 5).Replace(".", ""));
                //int month = int.Parse("" + cash_version.Substring(3, 2).Replace(".", ""));
                //int day = int.Parse("" + cash_version.Substring(0, 2));
                //DateTime date_version_program = new DateTime(year, month, day);
                //if (new DateTime(2017, 12, 18) <= date_version_program)
                //{
                //проверим схему бд она старая или уже новая
                //if (MainStaticClass.check_new_shema_autenticate() == 0)
                //{
                //    result = find_user_role(input_barcode.Text);
                //}

                if (MainStaticClass.check_new_shema_autenticate() == 1)
                {
                    result = find_user_role_new(input_barcode.Text);
                }
                else
                {
                    MessageBox.Show(" Из за произошедших ошибок авторизация невозможна ");
                    result = 0;
                }
                //}
                //else
                //{
                //    //result = find_user_role(input_barcode.Text);
                //    result = find_user_role_new(input_barcode.Text);
                //}
            }
            if (result == 1)
            {
                if (MainStaticClass.Use_Usb_to_Com_Barcode_Scaner)
                {
                    result_execute_enter = true;
                    stop_com_barcode_scaner();
                }
                MainStaticClass.First_Login_Admin = true;
                this.Close();

                if ((caller_type == 3) && (cc != null))//Это авторизация на удаление чека
                {
                    cc.enable_delete = true;
                    return;
                }

                MainStaticClass.Code_right_of_user = 1;
                MainStaticClass.Main.InitializeComponent1();
                //MainStaticClass.write_event_dssl_in_log("POSNG_ADMIN_LOGIN","", MainStaticClass.Cash_Operator,DateTime.Now.Date, DateTime.Now.TimeOfDay,0,0,0,"","",MainStaticClass.CashDeskNumber.ToString(),"");
                //if (MainStaticClass.Use_Trassir > 0)
                //{
                //    string s = MainStaticClass.get_string_message_for_trassir("POSNG_ADMIN_LOGIN", "", MainStaticClass.Cash_Operator, DateTime.Now.Date.ToString("dd'/'MM'/'yyyy"), DateTime.Now.ToString("HH:mm:ss"), "", "", "", "", "", MainStaticClass.CashDeskNumber.ToString(), "");
                //    MainStaticClass.send_data_trassir(s);
                //}
            }
            else if (result == 2)
            {
                if (MainStaticClass.Use_Usb_to_Com_Barcode_Scaner)
                {
                    result_execute_enter = true;
                    stop_com_barcode_scaner();
                }
                if (!MainStaticClass.First_Login_Admin)
                {
                    MessageBox.Show(" Первая регистрация должна с правами администратора ");
                    return;
                }
                this.Close();
                MainStaticClass.Main.show_Cash_checks();
                //MainStaticClass.write_event_dssl_in_log("POSNG_CASHIER_LOGIN", "", MainStaticClass.Cash_Operator, DateTime.Now.Date, DateTime.Now.TimeOfDay, 0, 0, 0, "", "", MainStaticClass.CashDeskNumber.ToString(), "");
                //MainStaticClass.write_event_dssl_in_log("POSNG_CASHIER_LOGIN", MainStaticClass.Cash_Operator_Client_Code, DateTime.Now, 0);
            }
            else if (result == 13)
            {
                fail_autorize.Text = " У вас нет прав для входа в программу ";
                this.input_barcode.Focus();
            }
            else if (result == 0)
            {
                fail_autorize.Text = "Неудачная попытка авторизации";
                this.input_barcode.Focus();
            }

            this.input_barcode.Text = "";
        }
Beispiel #29
0
        private void find_sertificate_on_code(string code)
        {
            NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

            try
            {
                conn.Open();
                string query = "";
                if (input_sertificate.Text.Length > 6)
                {
                    query = "select tovar.code AS tovar_code,tovar.name AS tovar_name ,tovar.retail_price AS retail_price " +
                            " FROM  barcode left join tovar ON barcode.tovar_code=tovar.code " +
                            //" WHERE barcode='" + input_sertificate.Text + "' AND its_deleted=0  AND retail_price<>0 ";
                            " WHERE barcode='" + code + "' AND its_deleted=0  AND retail_price<>0 AND its_certificate=1 ";
                }
                else
                {
                    query = "select tovar.code AS tovar_code,tovar.name  AS tovar_name,tovar.retail_price  AS retail_price " +
                            " FROM tovar where tovar.its_deleted=0 AND retail_price<>0 " +
                            //" AND tovar.code='" + input_sertificate.Text + "'";
                            " AND tovar.code='" + code + "' AND its_certificate=1";
                }
                input_sertificate.Text = "";
                NpgsqlCommand    command = new NpgsqlCommand(query, conn);
                NpgsqlDataReader reader  = command.ExecuteReader();
                bool             have    = false;
                while (reader.Read())
                {
                    have = true;
                    //проверка есть ли такой уже сертификат
                    bool exist = false;
                    if (listView_sertificates.Items.Count > 0)
                    {
                        for (int i = 0; i < listView_sertificates.Items.Count; i++)
                        {
                            if (listView_sertificates.Items[i].Tag.ToString().Trim() == reader["tovar_code"].ToString().Trim())
                            {
                                exist = true;
                                break;
                            }
                        }
                    }
                    if (!exist)
                    {
                        ListViewItem lvi = new ListViewItem(reader["tovar_code"].ToString());
                        lvi.Tag = reader["tovar_code"].ToString();
                        lvi.SubItems.Add(reader["tovar_name"].ToString());   // Наименование
                        lvi.SubItems.Add(reader["retail_price"].ToString()); //Сумма
                        listView_sertificates.Items.Add(lvi);
                        listView_sertificates.Focus();
                        listView_sertificates.Items[listView_sertificates.Items.Count - 1].Focused  = true;
                        listView_sertificates.Items[listView_sertificates.Items.Count - 1].Selected = true;
                    }
                }
                reader.Close();
                command.Dispose();
                conn.Close();
                if (!have)
                {
                    MessageBox.Show(" Сертификат не найден ");
                }
            }
            catch (NpgsqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Beispiel #30
0
        private void btn_download_Click(object sender, EventArgs e)
        {
            check_and_update_npgsql();

            btn_close.Enabled = false;
            if (!MainStaticClass.service_is_worker())
            {
                return;
            }

            Cash8.DS.DS ds = MainStaticClass.get_ds();
            ds.Timeout = 50000;

            //Получить параметра для запроса на сервер
            string nick_shop = MainStaticClass.Nick_Shop.Trim();

            if (nick_shop.Trim().Length == 0)
            {
                return;
            }

            string code_shop = MainStaticClass.Code_Shop.Trim();

            if (code_shop.Trim().Length == 0)
            {
                return;
            }

            string count_day = CryptorEngine.get_count_day();

            string key = nick_shop.Trim() + count_day.Trim() + code_shop.Trim();
            //старая версия
            //string my_version = version.Substring(0, 2) + "-" + version.Substring(2, 2) + "-" + version.Substring(4, 4);
            string my_version = version;

            string data = code_shop.Trim() + "|" + version + "|" + code_shop.Trim();

            byte[] result_web_query = new byte[0];
            try
            {
                result_web_query = ds.GetUpdateProgram(nick_shop, CryptorEngine.Encrypt(data, true, key));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            if (result_web_query.Length > 10)
            {
                try
                {
                    if (!Directory.Exists(Application.StartupPath + "/Update"))
                    {
                        Directory.CreateDirectory(Application.StartupPath + "/Update");
                    }

                    File.WriteAllBytes(Application.StartupPath + "/Update/Cash.exe", result_web_query);

                    if (!Directory.Exists(Application.StartupPath + "/Previous"))
                    {
                        Directory.CreateDirectory(Application.StartupPath + "/Previous");
                    }

                    File.Copy(Application.StartupPath + "/Cash.exe", Application.StartupPath + "/Previous/Cash.exe", true);
                    //File.Copy(Application.StartupPath + "/Update/Cash.exe", Application.StartupPath + "/Cash.exe", true); При переходе на wine это не будет работать.
                    //update_execute_addcolumn();
                    //*********************************************************************** update_execute_addcolumn()
                    NpgsqlConnection conn = MainStaticClass.NpgsqlConn();

                    try
                    {
                        conn.Open();
                        string        query   = " UPDATE constants SET execute_addcolumn = 2 ";
                        NpgsqlCommand command = new NpgsqlCommand(query, conn);
                        command.ExecuteNonQuery();
                        conn.Close();
                    }
                    catch (NpgsqlException ex)
                    {
                        MessageBox.Show(" Ошибка при обновлении значения константы " + ex.Message);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(" Ошибка при обновлении значения константы " + ex.Message);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open)
                        {
                            conn.Close();
                        }
                    }
                    //*********************************************************************** КОНЕЦ update_execute_addcolumn()
                    MessageBox.Show(" Обновление успешно загружено, теперь необходимо перезапустить программу ");
                    this.DialogResult = DialogResult.Yes;
                    this.Close();
                    //this.Dispose();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(" При загрузке произошли ошибки " + ex.Message);
                }
            }

            btn_close.Enabled = true;
        }