Exemplo n.º 1
0
        public void btnSendPrice_Click(Object sender, EventArgs e)
        {
            var id = Page.Request.Params["id"];

            //читаем старый файл
            if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Temp/SendedPrices/")))
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Temp/SendedPrices/"));
            }
            var fileName = "Прайс " + BackendHelper.TagToValue("official_name") + " (" + OtherMethods.CreateUniqId(id + DateTime.Now.ToString("hh:mm:ssttzz")) + ").xls";
            var dataFile = HttpContext.Current.Server.MapPath("~/Temp/SendedPrices/" + fileName);
            var dm       = new DataManager();

            //получаем данные отправителя прайса из сотрудников
            var userInSession   = (Users)Session["userinsession"];
            var emailSenderData = new Users()
            {
                ID = userInSession.ID
            };

            emailSenderData.GetById();

            var ds = new DataSet();
            var ifUserHaveAssignSection = dm.QueryWithReturnDataSet(String.Format("SELECT * FROM `userstocategory` WHERE `UserID` = {0}", id));

            if (ifUserHaveAssignSection.Tables[0].Rows.Count == 0)
            {
                ds = dm.QueryWithReturnDataSet(
                    "SELECT Name as 'Наименование', " +
                    "MarginCoefficient as 'Юр. лицо', " +
                    "MarginCoefficient as 'Физ. лицо', " +
                    "MarginCoefficient as 'Физ. лица в скид.' " +
                    "FROM `titles` ORDER BY `Name`");
            }
            else
            {
                ds = dm.QueryWithReturnDataSet(String.Format(
                                                   "SELECT C.Name as 'Наименование', " +
                                                   "C.MarginCoefficient as 'Юр. лицо', " +
                                                   "C.MarginCoefficient as 'Физ. лицо', " +
                                                   "C.MarginCoefficient as 'Физ. лица в скид.' " +
                                                   "FROM `titles` C WHERE C.`CategoryID` IN (SELECT `CategoryID` FROM `userstocategory` WHERE `UserID` = {0})  ORDER BY C.`Name`", id));
            }
            var goodList    = new List <GoodsFromAPI>();
            var goods       = new GoodsFromAPI();
            var tableToSend = "<table class='table' style='width: 100%; border-collapse: collapse;'><tr>" +
                              "<th style='border: 1px solid #666666; padding: 3px 6px; text-align: left;'>Наименование</th>" +
                              "<th style='border: 1px solid #666666; padding: 3px 6px;'>ЮЛ/ТТН</th>" +
                              "<th style='border: 1px solid #666666; padding: 3px 6px;'>ФЛ/Регион</th>" +
                              "<th style='border: 1px solid #666666; padding: 3px 6px;'>ФИЗ. Л. регион/область</th>" +
                              "</tr>";

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                goodList.Clear();
                goods.Description   = row[0].ToString();
                goods.Number        = 1;
                goods.IsAdditional  = 0;
                goods.WithoutAkciza = 0;
                goods.Coefficient   = 0;
                goodList.Add(goods);


                row[1]       = Calculator.Calculate(goodList, 187, Convert.ToInt32(id), null, "2"); //за обычный город берем Петриков
                row[2]       = Calculator.Calculate(goodList, 187, Convert.ToInt32(id), null, "1"); //за обычный город берем Петриков
                row[3]       = Calculator.Calculate(goodList, 16, Convert.ToInt32(id), null, "1");  //за скидочный город берем Гродно
                tableToSend += string.Format("<tr>" +
                                             "<td style='border: 1px solid #666666; padding: 3px 6px; text-align: left;'>{0}</td>" +
                                             "<td style='border: 1px solid #666666; padding: 3px 6px;'>{1}</td>" +
                                             "<td style='border: 1px solid #666666; padding: 3px 6px;'>{2}</td>" +
                                             "<td style='border: 1px solid #666666; padding: 3px 6px;'>{3}</td>" +
                                             "</tr>", row[0], MoneyMethods.MoneySeparator(row[1].ToString()), MoneyMethods.MoneySeparator(row[2].ToString()), MoneyMethods.MoneySeparator(row[3].ToString()));
            }
            tableToSend += "</table>";
            DataRow emptyRow = ds.Tables[0].NewRow();
            DataRow newRow   = ds.Tables[0].NewRow();

            newRow[0] = String.Format("Наш {5}: {1} {2}, тел.: {0}, email: {3}, skype: {4}", emailSenderData.PhoneWorkOne, emailSenderData.Name, emailSenderData.Family, emailSenderData.Email, emailSenderData.Skype, userInSession.RussRole.ToLower());
            ds.Tables[0].Rows.Add(emptyRow);
            ds.Tables[0].Rows.Add(newRow);
            ds.Tables[0].TableName = "Прайс " + BackendHelper.TagToValue("not_official_name");

            Workbook book = Workbook.Load(HttpContext.Current.Server.MapPath("~/" + BackendHelper.TagToValue("comprop_tpl_file_name")));

            AddDataTableToWorkBook(ds.Tables[0], ref book);
            var user = new Users()
            {
                ID = Convert.ToInt32(id)
            };

            user.GetById();
            book.Save(dataFile);
            var emailNotification = new EmailNotifications {
                Name = "comprop_message"
            };

            emailNotification.GetByName();
            EmailMethods.MailSendHTML(
                string.Format(emailNotification.Title, BackendHelper.TagToValue("not_official_name")),
                string.Format(emailNotification.Body,
                              emailSenderData.PhoneWorkOne,
                              emailSenderData.Name,
                              emailSenderData.Family,
                              emailSenderData.Email,
                              emailSenderData.Skype,
                              tableToSend,
                              userInSession.RussRole.ToLower(),
                              BackendHelper.TagToValue("official_name"),
                              BackendHelper.TagToValue("current_app_address"),
                              BackendHelper.TagToValue("not_official_name")),
                user.Email,
                dataFile,
                true);

            Session["flash:now"] = "<span style='color: green; font-size: bold'>Прайс отправлен!</span>";
            Page.Response.Redirect("~/ManagerUI/Menu/Souls/ClientEdit.aspx?id=" + id);
        }
Exemplo n.º 2
0
        protected void ImportXLS_Click(object sender, EventArgs e)
        {
            DataSet result = new DataSet();
            string  message;

            if (FileUploader.HasFile)
            {
                result = ReadXLSMethods.ReadXLS(FileUploader.PostedFile.InputStream);
                if (result.Tables.Count == 0)
                {
                    labelStatus.Text = "Неверный тип файла";
                    return;
                }

                var    id            = Page.Request.Params["id"];
                var    userInSession = (Users)Session["userinsession"];
                string userDiscount;
                int    userID;

                int rowsCount        = 0;
                int rowsSuccessCount = 0;

                var user = new Users
                {
                    ID       = UserID,
                    Login    = userInSession.Login,
                    Email    = userInSession.Email,
                    Name     = userInSession.Name,
                    Family   = userInSession.Family,
                    Role     = userInSession.Role,
                    RussRole = UsersHelper.RoleToRuss(userInSession.Role),
                    IsCourse = userInSession.IsCourse
                };
                userID = user.ID;

                if (user.Role != Users.Roles.User.ToString())
                {
                    userDiscount = "0";
                    userID       = 1;
                }
                else
                {
                    userDiscount = user.Discount.ToString();
                }

                int i = 0;
                result.Tables[0].Columns.Add(new DataColumn());
                result.Tables[0].Columns.Add(new DataColumn());
                foreach (DataColumn column in result.Tables[0].Columns)
                {
                    column.ColumnName = i++.ToString();
                }

                if (result.Tables[0].Columns.Count < 22)
                {
                    labelStatus.Text = "Недостаточное количество колонок в таблице";
                    return;
                }

                if (result.Tables[0].Rows.Count == 0)
                {
                    labelStatus.Text = "Пустая таблица";
                    return;
                }

                rowsCount = result.Tables[0].Rows.Count;

                foreach (DataRow row in result.Tables[0].Rows)
                {
                    bool          norm        = true;
                    List <string> errors      = new List <string>();
                    Tickets       ticket      = new Tickets();
                    int?          profileType = null;

                    /// проверка профиля
                    foreach (DataRow rowProfile in selectProfilesDataSet.Rows)
                    {
                        string selectProfileName = String.IsNullOrEmpty(rowProfile["CompanyName"].ToString())
                            ? String.Format("{0} {1}", rowProfile["FirstName"], rowProfile["LastName"])
                            : rowProfile["CompanyName"].ToString();
                        if (selectProfileName == row.ItemArray[0].ToString())
                        {
                            ticket.UserProfileID = Convert.ToInt32(rowProfile["ID"].ToString());
                            ticket.UserID        =
                                UsersHelper.GetUserIdByUserProfileId(Convert.ToInt32(ticket.UserProfileID));

                            profileType = Convert.ToInt32(rowProfile["TypeID"].ToString());
                            if (profileType == 2)
                            {
                                ticket.PrintNaklInMap = 1;
                                ticket.PrintNakl      = 0;
                            }
                            else
                            {
                                ticket.PrintNaklInMap = 0;
                                ticket.PrintNakl      = 1;
                            }

                            break;
                        }
                    }
                    if (ticket.UserProfileID == null)
                    {
                        norm = false;
                        errors.Add("неверный профиль");
                    }
                    /// проверка ID города
                    ///
                    int cityId;
                    if (Int32.TryParse(row.ItemArray[1].ToString(), out cityId) != false)
                    {
                        if (CityHelper.CityIDToCityName(row.ItemArray[1].ToString()) != null)
                        {
                            ticket.CityID = Convert.ToInt32(row.ItemArray[1].ToString());
                        }
                        else
                        {
                            norm = false;
                            errors.Add("неверный ID города");
                        }
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверный ID города");
                    }
                    ///
                    /// Проверка типа улицы
                    if (RecipientStreetPrefixes.Contains(row.ItemArray[2].ToString()))
                    {
                        ticket.RecipientStreetPrefix = row.ItemArray[2].ToString();
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверный префикс улицы");
                    }

                    ///
                    /// Проверка района
                    if (row.ItemArray[3].ToString() != string.Empty)
                    {
                        ticket.RecipientStreet = row.ItemArray[3].ToString();
                    }
                    else
                    {
                        norm = false;
                        errors.Add("не введена улица");
                    }
                    ///
                    ///
                    int houseNumber;
                    if (Int32.TryParse(row.ItemArray[4].ToString(), out houseNumber) == true)
                    {
                        ticket.RecipientStreetNumber = houseNumber.ToString();
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверный номер дома");
                    }
                    /// Заполнение корпуса и квартиры
                    if (row.ItemArray[5].ToString() != string.Empty)
                    {
                        ticket.RecipientKorpus = row.ItemArray[5].ToString();
                    }
                    if (row.ItemArray[6].ToString() != string.Empty)
                    {
                        ticket.RecipientKvartira = row.ItemArray[6].ToString();
                    }
                    ///
                    /// Проверка фамилии, имени и отчества
                    if (row.ItemArray[7].ToString().Length < 2 || row.ItemArray[8].ToString().Length < 2 || row.ItemArray[9].ToString().Length < 2)
                    {
                        norm = false;
                        errors.Add("неверные ФИО");
                    }
                    else
                    {
                        ticket.RecipientFirstName = row.ItemArray[7].ToString();
                        ticket.RecipientLastName  = row.ItemArray[8].ToString();
                        ticket.RecipientThirdName = row.ItemArray[9].ToString();
                    }
                    ///
                    /// Проверка номеров телефона
                    string input1 = row.ItemArray[10].ToString();
                    string input2 = row.ItemArray[11].ToString();

                    int numMatches1 = 0;
                    foreach (Match m in Regex.Matches(input1, patternPhone))
                    {
                        numMatches1++;
                    }
                    int numMatches2 = 0;
                    foreach (Match m in Regex.Matches(input2, patternPhone))
                    {
                        numMatches2++;
                    }

                    if (row.ItemArray[10].ToString() == string.Empty || numMatches1 != 1)
                    {
                        norm = false;
                        errors.Add("неверный 1 номер телефона");
                    }
                    else
                    {
                        ticket.RecipientPhone = row.ItemArray[10].ToString();
                    }

                    if (row.ItemArray[11].ToString() != string.Empty && numMatches2 != 1)
                    {
                        norm = false;
                        errors.Add("неверный 2 номер телефона");
                    }
                    else
                    {
                        if (row.ItemArray[11].ToString() != string.Empty)
                        {
                            ticket.RecipientPhoneTwo = row.ItemArray[11].ToString();
                        }
                    }
                    ///
                    /// Проверка стоимости доставки для получателя
                    string patternCost = @"^\d+,\d{2}$";

                    if (row.ItemArray[12].ToString() != string.Empty)
                    {
                        //if (Regex.Matches(row.ItemArray[12].ToString(), patternCost).Count == 1)
                        try
                        {
                            ticket.DeliveryCost = Convert.ToDecimal(row.ItemArray[12].ToString());
                        }
                        catch
                        {
                            norm = false;
                            errors.Add("неверная стоимость для получателя");
                        }
                    }
                    else
                    {
                        ticket.DeliveryCost = 0;
                    }
                    ///
                    /// Проверка товаров
                    List <Goods>  goods    = new List <Goods>();
                    List <string> goodsStr = row.ItemArray[13].ToString().Split(';').ToList();
                    if (goodsStr.Count == 0)
                    {
                        norm = false;
                        errors.Add("не введены товары");
                    }
                    foreach (string goodStr in goodsStr)
                    {
                        List <string> goodParams = goodStr.Split('|').ToList();
                        if (goodParams.Count != 4)
                        {
                            norm = false;
                            errors.Add("неверно заполнены товары");
                            goods = new List <Goods>();
                            break;
                        }
                        string goodDesc  = goodParams[0];
                        string goodModel = goodParams[1];
                        string goodCost  = goodParams[2];
                        string goodCount = goodParams[3];
                        ///
                        var titleForCheck = new Titles();
                        titleForCheck.Name = goodDesc.Trim();
                        titleForCheck.GetByName();
                        if (titleForCheck.ID == 0)
                        {
                            norm = false;
                            errors.Add("неверно заполнены товары");
                            goods = new List <Goods>();
                            break;
                        }

                        int count;
                        if (Int32.TryParse(goodCount, out count) == false)
                        {
                            norm = false;
                            errors.Add("неверно заполнены товары");
                            goods = new List <Goods>();
                            break;
                        }

                        if (Regex.Matches(goodCost, patternCost).Count != 1)
                        {
                            norm = false;
                            errors.Add("неверно заполнены товары");
                            goods = new List <Goods>();
                            break;
                        }

                        Goods good = new Goods()
                        {
                            Description = OtherMethods.BeInUseReplace(goodDesc).Trim(),
                            Model       = goodModel.Trim(),
                            Number      = Convert.ToInt32(goodCount),
                            Cost        = Convert.ToDecimal(goodCost)
                        };
                        goods.Add(good);
                    }
                    ///
                    /// Получение стоимости за товары
                    ticket.AssessedCost = 0;
                    foreach (Goods good in goods)
                    {
                        ticket.AssessedCost += good.Number * good.Cost;
                    }
                    ///
                    /// Проверка количества грузовых мест
                    int boxesNumber;
                    if (row.ItemArray[14].ToString() != string.Empty)
                    {
                        if (Int32.TryParse(row.ItemArray[14].ToString(), out boxesNumber) != false)
                        {
                            ticket.BoxesNumber = boxesNumber;
                        }
                        else
                        {
                            norm = false;
                            errors.Add("неверно введено количество коробок");
                        }
                    }
                    else
                    {
                        ticket.BoxesNumber = 1;
                    }
                    ///
                    /// Проверка даты отправки
                    //if (Regex.Matches(row.ItemArray[15].ToString(), patternDate).Count == 1)
                    //{
                    DateTime date1;
                    try
                    {
                        date1 = Convert.ToDateTime(Convert.ToDateTime(row.ItemArray[15].ToString()).ToString("dd-MM-yyyy"));

                        DateTime date2 = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("dd-MM-yyyy"));

                        if (ticket.CityID != null)
                        {
                            var allCity  = Application["CityList"] as List <City>;
                            var city     = allCity.First(u => u.ID == Convert.ToInt32(ticket.CityID));
                            var district = new Districts {
                                ID = Convert.ToInt32(city.DistrictID)
                            };
                            district.GetById();
                            var selectDayOfWeek = Convert.ToDateTime(Convert.ToDateTime(row.ItemArray[15].ToString()).ToString("dd-MM-yyyy")).DayOfWeek;
                            if ((selectDayOfWeek == DayOfWeek.Monday && district.Monday != 1) ||
                                (selectDayOfWeek == DayOfWeek.Tuesday && district.Tuesday != 1) ||
                                (selectDayOfWeek == DayOfWeek.Wednesday && district.Wednesday != 1) ||
                                (selectDayOfWeek == DayOfWeek.Thursday && district.Thursday != 1) ||
                                (selectDayOfWeek == DayOfWeek.Friday && district.Friday != 1) ||
                                (selectDayOfWeek == DayOfWeek.Saturday && district.Saturday != 1) ||
                                (selectDayOfWeek == DayOfWeek.Sunday && district.Sunday != 1))
                            {
                                norm = false;
                                errors.Add("отправка возможна только в дни отправки");
                            }

                            if (date1 < date2 && ticket.CityID != 11)
                            {
                                norm = false;
                                errors.Add("отправка в города отличные от Минска возможна только на следующий день после создания заявки!");
                            }

                            if (date1 < Convert.ToDateTime(DateTime.Now.ToString("dd-MM-yyyy")) && ticket.CityID == 11)
                            {
                                norm = false;
                                errors.Add("доставка по Минску возможна только с текущего дня и далее!");
                            }

                            ticket.DeliveryDate = date1;
                        }
                    }
                    catch (Exception)
                    {
                        norm = false;
                        errors.Add("неверная дата");
                    }
                    //}
                    //else
                    //{
                    //norm = false;
                    //errors.Add("неверный формат даты отправки");
                    //}
                    ///
                    /// Комментарии
                    if (row.ItemArray[16].ToString() != string.Empty)
                    {
                        ticket.Note = row.ItemArray[16].ToString();
                    }
                    ///
                    /// Проверка данных документов
                    if (profileType == 2 || profileType == 3)
                    {
                        if (Regex.Matches(row.ItemArray[17].ToString(), patternTTNSeria).Count == 1)
                        {
                            ticket.TtnSeria = row.ItemArray[17].ToString();
                        }
                        else
                        {
                            norm = false;
                            errors.Add("неверно введена ТТН серия");
                        }

                        if (Regex.Matches(row.ItemArray[18].ToString(), patternTTNNumber).Count == 1)
                        {
                            ticket.TtnNumber = row.ItemArray[18].ToString();
                        }
                        else
                        {
                            norm = false;
                            errors.Add("неверно введен ТТН номер");
                        }
                    }
                    else
                    {
                        ticket.TtnNumber = string.Empty;
                        ticket.TtnSeria  = string.Empty;
                    }

                    ticket.OtherDocuments = row.ItemArray[19].ToString();
                    ///
                    /// Проверка серии и номера паспорта
                    if (Regex.Matches(row.ItemArray[20].ToString(), patternTTNSeria).Count == 1)
                    {
                        ticket.PassportSeria = row.ItemArray[20].ToString();
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверно введена серия паспорта");
                    }

                    if (Regex.Matches(row.ItemArray[21].ToString(), patternTTNNumber).Count == 1)
                    {
                        ticket.PassportNumber = row.ItemArray[21].ToString();
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверно введен номер паспорта");
                    }
                    ///
                    /// Подсчет стоимости за услугу
                    List <GoodsFromAPI> goodsAPI = new List <GoodsFromAPI>();
                    foreach (Goods good in goods)
                    {
                        GoodsFromAPI goodAPI = new GoodsFromAPI()
                        {
                            Description = good.Description,
                            Number      = good.Number
                        };
                        goodsAPI.Add(goodAPI);
                    }

                    if (goodsAPI.Count > 0)
                    {
                        var gruzobozCost = Calculator.Calculate(goodsAPI, Convert.ToInt32(ticket.CityID), userID, Convert.ToInt32(ticket.UserProfileID), profileType.ToString(), ticket.AssessedCost.ToString(), Convert.ToInt32(userDiscount));
                        //если стоимость за услугу не конвертируется в decimal - значит записываем 0
                        try
                        {
                            ticket.GruzobozCost = Decimal.Parse(gruzobozCost);
                        }
                        catch (Exception)
                        {
                            ticket.GruzobozCost = 0;
                        }
                        ///
                        /// Расчет веса
                        ticket.Weight = GoodsHelper.GoodsWeight(goodsAPI);
                    }

                    ///
                    /// Заполнение полей склада
                    if (warehouses.Rows.Count == 0)
                    {
                        norm = false;
                        errors.Add("ошибка склада");
                    }
                    DataRow rowWareHouses = warehouses.Rows[0];

                    ticket.SenderApartmentNumber = rowWareHouses["ApartmentNumber"].ToString();
                    ticket.SenderCityID          = Convert.ToInt32(rowWareHouses["CityID"].ToString());
                    ticket.SenderHousing         = rowWareHouses["Housing"].ToString();
                    ticket.SenderStreetName      = rowWareHouses["StreetName"].ToString();
                    ticket.SenderStreetNumber    = rowWareHouses["StreetNumber"].ToString();
                    ticket.SenderStreetPrefix    = rowWareHouses["StreetPrefix"].ToString();
                    ///
                    /// СОЗДАНИЕ ЗАЯВКИ
                    ///

                    string error = string.Empty;
                    foreach (string errorMsg in errors)
                    {
                        error += errorMsg;
                        error += ", ";
                    }
                    rowsError.Add(error);

                    string color;
                    if (errors.Count != 0)
                    {
                        color = "redRow";
                    }
                    else
                    {
                        color = "greenRow";
                    }
                    rowsColor.Add(color);

                    if (norm == true)
                    {
                        if (id == null)
                        {
                            rowsSuccessCount++;

                            //записываем хеши для заявки
                            if (user.Role != Users.Roles.User.ToString())
                            {
                                ticket.SecureID     = OtherMethods.CreateUniqId("1" + DateTime.Now.ToString("yyMdHms"));
                                ticket.FullSecureID = OtherMethods.CreateFullUniqId("1" + DateTime.Now.ToString("yyMdHms"));
                            }
                            else
                            {
                                ticket.SecureID     = OtherMethods.CreateUniqId(user.ID + DateTime.Now.ToString("yyMdHms"));
                                ticket.FullSecureID = OtherMethods.CreateFullUniqId(user.ID + DateTime.Now.ToString("yyMdHms"));
                            }

                            for (int j = 0; j < goods.Count; j++) //сохраняем заявки
                            {
                                goods[j].TicketFullSecureID = ticket.FullSecureID;
                                goods[j].Create();
                            }
                            ticket.Create();
                            #region Отправка емейла логистам

                            var logistRb      = BackendHelper.TagToValue("logist_rb_email");
                            var logistMinsk   = BackendHelper.TagToValue("logist_minsk_email");
                            var isMinskRegion = BackendHelper.TagToValue("logist_minsk_region");
                            var senderCity    = new City {
                                ID = Convert.ToInt32(ticket.SenderCityID)
                            };
                            senderCity.GetById();

                            if (isMinskRegion != "true")
                            {
                                if (!string.IsNullOrEmpty(logistRb) && senderCity.DistrictID != 10)
                                {
                                    try
                                    {
                                        EmailMethods.MailSend("Создана новая заявка с забором в РБ",
                                                              String.Format("Заявка #{0}, {1}", ticket.SecureID, senderCity.Name), logistRb, true);
                                    }
                                    catch (Exception)
                                    {
                                        // ignored
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(logistMinsk) && !(ticket.SenderCityID == 11 && ticket.SenderStreetName.ToLower() == BackendHelper.TagToValue("loading_point_street").ToLower() &&
                                                                                ticket.SenderStreetNumber == BackendHelper.TagToValue("loading_point_street_number")))
                                    {
                                        try
                                        {
                                            EmailMethods.MailSend("Создана новая заявка с забором в Минске и районе",
                                                                  String.Format("Заявка #{0}, {1}", ticket.SecureID, senderCity.Name), logistMinsk, true);
                                        }
                                        catch (Exception)
                                        {
                                            // ignored
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(logistRb) && senderCity.RegionID != 1)
                                {
                                    try
                                    {
                                        EmailMethods.MailSend("Создана новая заявка с забором в РБ",
                                                              String.Format("Заявка #{0}, {1}", ticket.SecureID, senderCity.Name), logistRb, true);
                                    }
                                    catch (Exception)
                                    {
                                        // ignored
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(logistMinsk) && !(ticket.SenderCityID == 11 && ticket.SenderStreetName.ToLower() == BackendHelper.TagToValue("loading_point_street") &&
                                                                                ticket.SenderStreetNumber == BackendHelper.TagToValue("loading_point_street_number")))
                                    {
                                        try
                                        {
                                            EmailMethods.MailSend("Создана новая заявка с забором в Минске и области",
                                                                  String.Format("Заявка #{0}, {1}", ticket.SecureID, senderCity.Name), logistMinsk, true);
                                        }
                                        catch (Exception)
                                        {
                                            // ignored
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                    }
                }

                for (int j = 0; j < result.Tables[0].Rows.Count; j++)
                {
                    result.Tables[0].Rows[j][22] = rowsError[j];
                    result.Tables[0].Rows[j][23] = rowsColor[j];
                }

                labelStatus.Text = "Успешно импортировано " + rowsSuccessCount.ToString() +
                                   " из " + rowsCount.ToString() + " заявок";
                ListXML.DataSource = result.Tables[0];
                ListXML.DataBind();
            }
        }
Exemplo n.º 3
0
        public List <TicketsCreateResult> CreateTickets(List <TicketToCreate> tickets, int id)
        {
            List <TicketsCreateResult> result = new List <TicketsCreateResult>();

            selectProfilesDataSet = dm.QueryWithReturnDataSet(string.Format("SELECT * FROM `usersprofiles` WHERE `UserID` = {0} AND `StatusID` = 1", id)).Tables[0];
            ////////////////

            string userDiscount;
            int    userID;

            int rowsCount        = 0;
            int rowsSuccessCount = 0;

            var user = new Users
            {
                ID = id
            };

            user.GetById();

            userID = user.ID;

            if (user.Role != Users.Roles.User.ToString())
            {
                userDiscount = "0";
                userID       = 1;
            }
            else
            {
                userDiscount = user.Discount.ToString();
            }

            int num = 0;

            foreach (TicketToCreate row in tickets)
            {
                bool          norm        = true;
                List <string> errors      = new List <string>();
                Tickets       ticket      = new Tickets();
                int?          profileType = null;

                TicketsCreateResult resultTicket = new TicketsCreateResult();
                resultTicket.number = num.ToString();
                num++;

                /// проверка профиля
                foreach (DataRow rowProfile in selectProfilesDataSet.Rows)
                {
                    string selectProfileName = String.IsNullOrEmpty(rowProfile["CompanyName"].ToString())
                        ? String.Format("{0} {1}", rowProfile["FirstName"], rowProfile["LastName"])
                        : rowProfile["CompanyName"].ToString();
                    if (selectProfileName == row.ProfileName)
                    {
                        ticket.UserProfileID = Convert.ToInt32(rowProfile["ID"].ToString());
                        ticket.UserID        =
                            UsersHelper.GetUserIdByUserProfileId(Convert.ToInt32(ticket.UserProfileID));

                        profileType = Convert.ToInt32(rowProfile["TypeID"].ToString());
                        if (profileType == 2)
                        {
                            ticket.PrintNaklInMap = 1;
                            ticket.PrintNakl      = 0;
                        }
                        else
                        {
                            ticket.PrintNaklInMap = 0;
                            ticket.PrintNakl      = 1;
                        }

                        break;
                    }
                }
                if (ticket.UserProfileID == null)
                {
                    norm = false;
                    errors.Add("неверный профиль");
                }
                /// проверка ID города
                ///
                int cityId;
                if (Int32.TryParse(row.CityID, out cityId) != false)
                {
                    if (CityHelper.CityIDToCityName(row.CityID.ToString()) != null)
                    {
                        ticket.CityID = Convert.ToInt32(row.CityID.ToString());
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверный ID города");
                    }
                }
                else
                {
                    norm = false;
                    errors.Add("неверный ID города");
                }
                ///
                /// Проверка типа улицы
                if (row.StreetPrefix == null || RecipientStreetPrefixes.Contains(row.StreetPrefix))
                {
                    ticket.RecipientStreetPrefix = row.StreetPrefix;
                }
                else
                {
                    norm = false;
                    errors.Add("неверный префикс улицы");
                }

                ///
                /// Проверка района
                if (row.StreetName != string.Empty)
                {
                    ticket.RecipientStreet = row.StreetName;
                }
                else
                {
                    norm = false;
                    errors.Add("не введена улица");
                }
                ///
                ///
                int houseNumber;
                if (Int32.TryParse(row.HouseNumber, out houseNumber))
                {
                    ticket.RecipientStreetNumber = houseNumber.ToString();
                }
                else
                {
                    norm = false;
                    errors.Add("неверный номер дома");
                }
                /// Заполнение корпуса и квартиры
                if (row.Korpus != string.Empty)
                {
                    ticket.RecipientKorpus = row.Korpus;
                }
                if (row.Kvartira != string.Empty)
                {
                    ticket.RecipientKvartira = row.Kvartira;
                }
                ///
                /// Проверка фамилии, имени и отчества
                if (row.FirstName == null || row.SecondName == null || row.ThirdName == null ||
                    row.FirstName.Length < 2 || row.SecondName.Length < 2 || row.ThirdName.Length < 2)
                {
                    norm = false;
                    errors.Add("неверные ФИО");
                }
                else
                {
                    ticket.RecipientFirstName = row.FirstName;
                    ticket.RecipientLastName  = row.SecondName;
                    ticket.RecipientThirdName = row.ThirdName;
                }
                ///
                /// Проверка номеров телефона
                string input1 = row.FirstTelefonNumber;
                string input2 = row.SecondTelefonNumber;

                int numMatches1 = 0;
                if (input1 != null)
                {
                    foreach (Match m in Regex.Matches(input1, patternPhone))
                    {
                        numMatches1++;
                    }
                }
                int numMatches2 = 0;
                if (input2 != null)
                {
                    foreach (Match m in Regex.Matches(input2, patternPhone))
                    {
                        numMatches2++;
                    }
                }

                if (row.FirstTelefonNumber == string.Empty || numMatches1 != 1)
                {
                    norm = false;
                    errors.Add("неверный 1 номер телефона");
                }
                else
                {
                    ticket.RecipientPhone = row.FirstTelefonNumber;
                }

                if (row.SecondTelefonNumber != string.Empty && numMatches2 != 1)
                {
                    norm = false;
                    errors.Add("неверный 2 номер телефона");
                }
                else
                {
                    if (row.SecondTelefonNumber != string.Empty)
                    {
                        ticket.RecipientPhoneTwo = row.SecondTelefonNumber;
                    }
                }
                ///
                /// Проверка стоимости доставки для получателя
                string patternCost = @"^\d+,\d{2}$";

                if (row.RecieverCost != string.Empty)
                {
                    //if (Regex.Matches(row.ItemArray[12].ToString(), patternCost).Count == 1)
                    try
                    {
                        ticket.DeliveryCost = Convert.ToDecimal(row.RecieverCost);
                    }
                    catch
                    {
                        norm = false;
                        errors.Add("неверная стоимость для получателя");
                    }
                }
                else
                {
                    ticket.DeliveryCost = 0;
                }
                ///
                /// Проверка товаров
                List <Goods> goods = new List <Goods>();
                if (row.Goods == null || row.Goods.Count == 0)
                {
                    norm = false;
                    errors.Add("не введены товары");
                }
                else
                {
                    foreach (TicketGood good in row.Goods)
                    {
                        if (string.IsNullOrEmpty(good.GoodName) || string.IsNullOrEmpty(good.GoodModel) || string.IsNullOrEmpty(good.GoodCount) || string.IsNullOrEmpty(good.GoodCost))
                        {
                            norm = false;
                            errors.Add("неверно заполнены товары");
                            goods = new List <Goods>();
                            break;
                        }
                        string goodDesc  = good.GoodName;
                        string goodModel = good.GoodModel;
                        string goodCost  = good.GoodCost;
                        string goodCount = good.GoodCount;
                        ///
                        var titleForCheck = new Titles();
                        titleForCheck.Name = goodDesc.Trim();
                        titleForCheck.GetByName();
                        if (titleForCheck.ID == 0)
                        {
                            norm = false;
                            errors.Add("неверно заполнены товары: товар не найден");
                            goods = new List <Goods>();
                            break;
                        }

                        int count;
                        if (Int32.TryParse(goodCount, out count) == false)
                        {
                            norm = false;
                            errors.Add("неверно заполнены товары: не верное количество");
                            goods = new List <Goods>();
                            break;
                        }

                        if (Regex.Matches(goodCost, patternCost).Count != 1)
                        {
                            norm = false;
                            errors.Add("неверно заполнены товары: не верная цена");
                            goods = new List <Goods>();
                            break;
                        }

                        Goods goodCreate = new Goods()
                        {
                            Description = OtherMethods.BeInUseReplace(goodDesc).Trim(),
                            Model       = goodModel.Trim(),
                            Number      = Convert.ToInt32(goodCount),
                            Cost        = Convert.ToDecimal(goodCost)
                        };
                        goods.Add(goodCreate);
                    }
                    ///
                    /// Получение стоимости за товары
                    ticket.AssessedCost = 0;
                    foreach (Goods good in goods)
                    {
                        ticket.AssessedCost += good.Number * good.Cost;
                    }
                    ///
                    /// Проверка количества грузовых мест
                    int boxesNumber;
                    if (row.BoxCount != string.Empty)
                    {
                        if (Int32.TryParse(row.BoxCount, out boxesNumber) != false)
                        {
                            ticket.BoxesNumber = boxesNumber;
                        }
                        else
                        {
                            norm = false;
                            errors.Add("неверно введено количество коробок");
                        }
                    }
                    else
                    {
                        ticket.BoxesNumber = 1;
                    }
                }
                ///
                /// Проверка даты отправки
                //if (Regex.Matches(row.ItemArray[15].ToString(), patternDate).Count == 1)
                //{
                DateTime date1;
                try
                {
                    date1 = Convert.ToDateTime(Convert.ToDateTime(row.SendDate).ToString("dd-MM-yyyy"));

                    DateTime date2 = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("dd-MM-yyyy"));

                    if (ticket.CityID != null)
                    {
                        var city = new City()
                        {
                            ID = Convert.ToInt32(row.CityID)
                        };
                        city.GetById();

                        //var city = allCity.First(u => u.ID == Convert.ToInt32(ticket.CityID));
                        var district = new Districts {
                            ID = Convert.ToInt32(city.DistrictID)
                        };
                        district.GetById();
                        var selectDayOfWeek = Convert.ToDateTime(Convert.ToDateTime(row.SendDate).ToString("dd-MM-yyyy")).DayOfWeek;
                        if ((selectDayOfWeek == DayOfWeek.Monday && district.Monday != 1) ||
                            (selectDayOfWeek == DayOfWeek.Tuesday && district.Tuesday != 1) ||
                            (selectDayOfWeek == DayOfWeek.Wednesday && district.Wednesday != 1) ||
                            (selectDayOfWeek == DayOfWeek.Thursday && district.Thursday != 1) ||
                            (selectDayOfWeek == DayOfWeek.Friday && district.Friday != 1) ||
                            (selectDayOfWeek == DayOfWeek.Saturday && district.Saturday != 1) ||
                            (selectDayOfWeek == DayOfWeek.Sunday && district.Sunday != 1))
                        {
                            norm = false;
                            errors.Add("отправка возможна только в дни отправки");
                        }

                        if (date1 < date2 && ticket.CityID != 11)
                        {
                            norm = false;
                            errors.Add("отправка в города отличные от Минска возможна только на следующий день после создания заявки!");
                        }

                        if (date1 < Convert.ToDateTime(DateTime.Now.ToString("dd-MM-yyyy")) && ticket.CityID == 11)
                        {
                            norm = false;
                            errors.Add("доставка по Минску возможна только с текущего дня и далее!");
                        }

                        ticket.DeliveryDate = date1;
                    }
                }
                catch (Exception)
                {
                    norm = false;
                    errors.Add("неверная дата");
                }
                //}
                //else
                //{
                //norm = false;
                //errors.Add("неверный формат даты отправки");
                //}
                ///
                /// Комментарии
                if (row.Comments != string.Empty)
                {
                    ticket.Note = row.Comments;
                }
                ///
                /// Проверка данных документов
                if (profileType == 2 || profileType == 3)
                {
                    if (Regex.Matches(row.TTNSeria, patternTTNSeria).Count == 1)
                    {
                        ticket.TtnSeria = row.TTNSeria;
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверно введена ТТН серия");
                    }

                    if (Regex.Matches(row.TTNNmber, patternTTNNumber).Count == 1)
                    {
                        ticket.TtnNumber = row.TTNNmber;
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверно введен ТТН номер");
                    }
                }
                else
                {
                    ticket.TtnNumber = string.Empty;
                    ticket.TtnSeria  = string.Empty;
                }

                ticket.OtherDocuments = row.OtherDocuments;
                ///
                /// Проверка серии и номера паспорта
                if (!string.IsNullOrEmpty(ticket.PassportNumber) || !string.IsNullOrEmpty(ticket.PassportSeria))
                {
                    if (Regex.Matches(row.PassportSeria, patternTTNSeria).Count == 1)
                    {
                        ticket.PassportSeria = row.PassportSeria;
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверно введена серия паспорта");
                    }

                    if (Regex.Matches(row.PassportNumber, patternTTNNumber).Count == 1)
                    {
                        ticket.PassportNumber = row.PassportNumber;
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверно введен номер паспорта");
                    }
                }
                ///
                /// Подсчет стоимости за услугу
                List <GoodsFromAPI> goodsAPI = new List <GoodsFromAPI>();
                foreach (Goods good in goods)
                {
                    GoodsFromAPI goodAPI = new GoodsFromAPI()
                    {
                        Description = good.Description,
                        Number      = good.Number
                    };
                    goodsAPI.Add(goodAPI);
                }

                if (goodsAPI.Count > 0)
                {
                    var gruzobozCost = Calculator.Calculate(goodsAPI, Convert.ToInt32(ticket.CityID), userID, Convert.ToInt32(ticket.UserProfileID), profileType.ToString(), ticket.AssessedCost.ToString(), Convert.ToInt32(userDiscount));
                    //если стоимость за услугу не конвертируется в decimal - значит записываем 0
                    try
                    {
                        ticket.GruzobozCost = Decimal.Parse(gruzobozCost);
                    }
                    catch (Exception)
                    {
                        ticket.GruzobozCost = 0;
                    }
                    ///
                    /// Расчет веса
                    ticket.Weight = GoodsHelper.GoodsWeight(goodsAPI);
                }

                ///
                /// Заполнение полей склада
                if (warehouses.Rows.Count == 0)
                {
                    norm = false;
                    errors.Add("ошибка склада");
                }
                DataRow rowWareHouses = warehouses.Rows[0];

                if (ticket.SenderCityID != null || !string.IsNullOrEmpty(ticket.SenderHousing) || !string.IsNullOrEmpty(ticket.SenderStreetName) ||
                    !string.IsNullOrEmpty(ticket.SenderStreetNumber) || !string.IsNullOrEmpty(ticket.SenderStreetPrefix) || !string.IsNullOrEmpty(ticket.SenderApartmentNumber))
                {
                    ticket.SenderApartmentNumber = rowWareHouses["ApartmentNumber"].ToString();
                    ticket.SenderCityID          = Convert.ToInt32(rowWareHouses["CityID"].ToString());
                    ticket.SenderHousing         = rowWareHouses["Housing"].ToString();
                    ticket.SenderStreetName      = rowWareHouses["StreetName"].ToString();
                    ticket.SenderStreetNumber    = rowWareHouses["StreetNumber"].ToString();
                    ticket.SenderStreetPrefix    = rowWareHouses["StreetPrefix"].ToString();
                }
                else
                {
                    if (Int32.TryParse(row.SenderCityID, out cityId) != false)
                    {
                        if (CityHelper.CityIDToCityName(row.SenderCityID.ToString()) != null)
                        {
                            ticket.SenderCityID = Convert.ToInt32(row.SenderCityID.ToString());
                        }
                        else
                        {
                            norm = false;
                            errors.Add("неверный ID города отправки");
                        }
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверный ID города");
                    }
                    ///
                    /// Проверка типа улицы
                    if (RecipientStreetPrefixes.Contains(row.SenderStreetPrefix))
                    {
                        ticket.SenderStreetPrefix = row.SenderStreetPrefix;
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверный префикс улицы отправки");
                    }

                    ///
                    /// Проверка района
                    if (row.SenderStreetName != string.Empty)
                    {
                        ticket.SenderStreetName = row.SenderStreetName;
                    }
                    else
                    {
                        norm = false;
                        errors.Add("не введена улица отправки");
                    }
                    ///
                    ///
                    if (Int32.TryParse(row.SenderHouseNumber, out houseNumber))
                    {
                        ticket.SenderStreetNumber = houseNumber.ToString();
                    }
                    else
                    {
                        norm = false;
                        errors.Add("неверный номер дома отправки");
                    }
                    /// Заполнение корпуса и квартиры
                    if (row.SenderKorpus != string.Empty)
                    {
                        ticket.SenderHousing = row.SenderKorpus;
                    }
                    if (row.Kvartira != string.Empty)
                    {
                        ticket.SenderApartmentNumber = row.SenderKvartira;
                    }
                }


                ///
                /// СОЗДАНИЕ ЗАЯВКИ
                ///

                string error = string.Empty;
                foreach (string errorMsg in errors)
                {
                    error += errorMsg;
                    error += ", ";
                }
                rowsError.Add(error);

                if (norm == true)
                {
                    try
                    {
                        rowsSuccessCount++;

                        //записываем хеши для заявки
                        if (user.Role != Users.Roles.User.ToString())
                        {
                            ticket.SecureID     = OtherMethods.CreateUniqId("1" + DateTime.Now.ToString("yyMdHms") + tickets.IndexOf(row));
                            ticket.FullSecureID = OtherMethods.CreateFullUniqId("1" + DateTime.Now.ToString("yyMdHms") + tickets.IndexOf(row));
                        }
                        else
                        {
                            ticket.SecureID     = OtherMethods.CreateUniqId(user.ID + DateTime.Now.ToString("yyMdHms") + tickets.IndexOf(row));
                            ticket.FullSecureID = OtherMethods.CreateFullUniqId(user.ID + DateTime.Now.ToString("yyMdHms") + tickets.IndexOf(row));
                        }

                        resultTicket.ID = ticket.SecureID;


                        for (int j = 0; j < goods.Count; j++) //сохраняем заявки
                        {
                            goods[j].TicketFullSecureID = ticket.FullSecureID;
                            goods[j].Create();
                        }
                        ticket.Create();
                        #region Отправка емейла логистам

                        var logistRb      = BackendHelper.TagToValue("logist_rb_email");
                        var logistMinsk   = BackendHelper.TagToValue("logist_minsk_email");
                        var isMinskRegion = BackendHelper.TagToValue("logist_minsk_region");
                        var senderCity    = new City {
                            ID = Convert.ToInt32(ticket.SenderCityID)
                        };
                        senderCity.GetById();

                        if (isMinskRegion != "true")
                        {
                            if (!string.IsNullOrEmpty(logistRb) && senderCity.DistrictID != 10)
                            {
                                try
                                {
                                    EmailMethods.MailSend("Создана новая заявка с забором в РБ",
                                                          String.Format("Заявка #{0}, {1}", ticket.SecureID, senderCity.Name), logistRb, true);
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(logistMinsk) && !(ticket.SenderCityID == 11 && ticket.SenderStreetName.ToLower() == BackendHelper.TagToValue("loading_point_street").ToLower() &&
                                                                            ticket.SenderStreetNumber == BackendHelper.TagToValue("loading_point_street_number")))
                                {
                                    try
                                    {
                                        EmailMethods.MailSend("Создана новая заявка с забором в Минске и районе",
                                                              String.Format("Заявка #{0}, {1}", ticket.SecureID, senderCity.Name), logistMinsk, true);
                                    }
                                    catch (Exception)
                                    {
                                        // ignored
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(logistRb) && senderCity.RegionID != 1)
                            {
                                try
                                {
                                    EmailMethods.MailSend("Создана новая заявка с забором в РБ",
                                                          String.Format("Заявка #{0}, {1}", ticket.SecureID, senderCity.Name), logistRb, true);
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(logistMinsk) && !(ticket.SenderCityID == 11 && ticket.SenderStreetName.ToLower() == BackendHelper.TagToValue("loading_point_street") &&
                                                                            ticket.SenderStreetNumber == BackendHelper.TagToValue("loading_point_street_number")))
                                {
                                    try
                                    {
                                        EmailMethods.MailSend("Создана новая заявка с забором в Минске и области",
                                                              String.Format("Заявка #{0}, {1}", ticket.SecureID, senderCity.Name), logistMinsk, true);
                                    }
                                    catch (Exception)
                                    {
                                        // ignored
                                    }
                                }
                            }
                        }
                        #endregion

                        resultTicket.desc = "Заявка создана";
                    }
                    catch (Exception ex)
                    {
                        resultTicket.desc = "Заявка не создана";
                    }
                }
                else
                {
                    resultTicket.desc = error;
                }

                result.Add(resultTicket);
            }


            ////////////////

            return(result);
        }
Exemplo n.º 4
0
        public void btnSendComProp_Click(Object sender, EventArgs e)
        {
            //читаем старый файл
            if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Temp/SendedPrices/")))
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Temp/SendedPrices/"));
            }
            var fileName = "Прайс " + BackendHelper.TagToValue("not_official_name") + " (" + OtherMethods.CreateUniqId(tbEmail.Text + DateTime.Now.ToString("hh:mm:ssttzz")) + ").xls";
            var dataFile = HttpContext.Current.Server.MapPath("~/Temp/SendedPrices/" + fileName);
            var dm       = new DataManager();

            //получаем данные отправителя прайса из сотрудников
            var userInSession   = (Users)Session["userinsession"];
            var emailSenderData = new Users()
            {
                ID = userInSession.ID
            };

            emailSenderData.GetById();

            var categoryIds         = string.Empty;
            var haveCheckedCategory = false;

            foreach (var items in lvAllCategory.Items)
            {
                var hfCategoryId = (HiddenField)items.FindControl("hfCategoryId");
                var cbCategory   = (CheckBox)items.FindControl("cbCategory");
                if (cbCategory.Checked)
                {
                    categoryIds        += string.Format("{0},", hfCategoryId.Value);
                    haveCheckedCategory = true;
                }
            }

            DataSet ds;

            if (!haveCheckedCategory)
            {
                ds = dm.QueryWithReturnDataSet(
                    "SELECT Name as 'Наименование', " +
                    "MarginCoefficient as 'Юр. лицо', " +
                    "MarginCoefficient as 'Физ. лицо', " +
                    "MarginCoefficient as 'Физ. лица в скид.' " +
                    "FROM `titles` ORDER BY `Name`");
            }
            else
            {
                categoryIds = categoryIds.Remove(categoryIds.Length - 1, 1);
                ds          = dm.QueryWithReturnDataSet(String.Format(
                                                            "SELECT C.Name as 'Наименование', " +
                                                            "C.MarginCoefficient as 'Юр. лицо', " +
                                                            "C.MarginCoefficient as 'Физ. лицо', " +
                                                            "C.MarginCoefficient as 'Физ. лица в скид.' " +
                                                            "FROM `titles` C WHERE C.`CategoryID` IN ({0})  ORDER BY C.`Name`", categoryIds));
            }
            var goodList    = new List <GoodsFromAPI>();
            var goods       = new GoodsFromAPI();
            var tableToSend = "<table class='table' style='width: 100%; border-collapse: collapse;'><tr>" +
                              "<th style='border: 1px solid #666666; padding: 3px 6px; text-align: left;'>Наименование</th>" +
                              "<th style='border: 1px solid #666666; padding: 3px 6px;'>По РБ</th>" +
                              "<th style='border: 1px solid #666666; padding: 3px 6px;'>По Минску</th>" +
                              "</tr>";

            List <ModelSortingCosts> table_list = new List <ModelSortingCosts>();
            DataTable sortedDS = new DataTable();

            sortedDS.Columns.Add(string.Format("Наименование", 0), typeof(string));
            sortedDS.Columns.Add(string.Format("Дверь/Дверь", 1), typeof(string));
            sortedDS.Columns.Add(string.Format("Склад/Дверь", 2), typeof(string));
            sortedDS.Columns.Add(string.Format("По Минску", 3), typeof(string));

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                ModelSortingCosts row_list = new ModelSortingCosts();

                goodList.Clear();
                goods.Description   = row[0].ToString();
                goods.Number        = 1;
                goods.IsAdditional  = 0;
                goods.WithoutAkciza = 0;
                goods.Coefficient   = 0;
                goodList.Add(goods);

                row_list.name      = row[0].ToString();
                row_list.costDD    = Calculator.Calculate(goodList, 187, 1, 239, "1", null, null, true);
                row_list.costSD    = Calculator.Calculate(goodList, 187, 1, 239, "1");
                row_list.costMinsk = Calculator.Calculate(goodList, 11, 1, 239, "1");

                table_list.Add(row_list);
            }
            table_list = table_list.OrderBy(x => x.costSD).ToList();
            foreach (ModelSortingCosts model in table_list)
            {
                DataRow dsRow = sortedDS.NewRow();
                dsRow[0] = model.name;
                dsRow[1] = model.costDD;
                dsRow[2] = model.costSD;
                dsRow[3] = model.costMinsk;
                sortedDS.Rows.Add(dsRow);
            }

            foreach (ModelSortingCosts row in table_list)
            {
                tableToSend += string.Format("<tr>" +
                                             "<td style='border: 1px solid #666666; padding: 3px 6px; text-align: left;'>{0}</td>" +
                                             "<td style='border: 1px solid #666666; padding: 3px 6px;'>{1}</td>" +
                                             "<td style='border: 1px solid #666666; padding: 3px 6px;'>{2}</td>" +
                                             "</tr>", row.name, MoneyMethods.MoneySeparator(row.costDD.ToString()), MoneyMethods.MoneySeparator(row.costSD.ToString()), MoneyMethods.MoneySeparator(row.costMinsk.ToString()));
            }
            tableToSend += "</table>";
            DataRow emptyRow = sortedDS.NewRow();
            DataRow newRow   = sortedDS.NewRow();

            newRow[0] = String.Format("тел.: {0}, email: {3}, skype: {4}", emailSenderData.PhoneWorkOne, emailSenderData.Name, emailSenderData.Family, emailSenderData.Email, emailSenderData.Skype, userInSession.RussRole.ToLower());
            sortedDS.Rows.Add(emptyRow);
            sortedDS.Rows.Add(newRow);
            sortedDS.TableName = "Прайс" + BackendHelper.TagToValue("not_official_name");

            Workbook book = Workbook.Load(HttpContext.Current.Server.MapPath("~/OtherFiles/" + BackendHelper.TagToValue("comprop_tpl_file_name")));

            AddDataTableToWorkBook(sortedDS, ref book);
            book.Save(dataFile);
            var emailNotification = new EmailNotifications {
                Name = "comprop_guest_message"
            };

            emailNotification.GetByName();
            EmailMethods.MailSendHTML(tbSubject.Text, string.Format(emailNotification.Body,
                                                                    emailSenderData.PhoneWorkOne,
                                                                    emailSenderData.Name,
                                                                    emailSenderData.Family,
                                                                    emailSenderData.Email,
                                                                    emailSenderData.Skype,
                                                                    tableToSend,
                                                                    userInSession.RussRole.ToLower(),
                                                                    BackendHelper.TagToValue("official_name"),
                                                                    BackendHelper.TagToValue("current_app_address"),
                                                                    BackendHelper.TagToValue("not_official_name")),
                                      tbEmail.Text,
                                      dataFile,
                                      false);

            Session["flash:now"] = "<span style='color: white;'>Комерческое предложение успешно отправлено на e-mail <b>" + tbEmail.Text + "</b>!</span>";
            Page.Response.Redirect("~/ManagerUI/Menu/Documents/SendComProp.aspx");
        }