public async Task <IHttpActionResult> DeleteDocServicePurch2Tab(int id)
        {
            #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

            //Получаем Куку
            System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"];

            // Проверяем Логин и Пароль
            Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true));

            if (!field.Access)
            {
                return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10)));
            }

            //Изменяем строку соединения
            db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true));

            //Права (1 - Write, 2 - Read, 3 - No Access)
            bool bRight = await Task.Run(() => accessRight.AccessCheck(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServiceWorkshopsTab2ReturnCheck"));

            if (!bRight)
            {
                return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))));
            }

            //Разные Функции
            function.NumberDecimalSeparator();

            //Получам настройки
            Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1);

            #endregion

            #region Удаление

            try
            {
                DocServicePurch2Tab docServicePurch2Tab = await db.DocServicePurch2Tabs.FindAsync(id);

                if (docServicePurch2Tab == null)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg99)));
                }

                //Проверка точки === === ===
                Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch2Tab.DocServicePurchID);

                if (field.DirEmployeeID != 1)
                {
                    int?DirWarehouseID = docServicePurch.DirWarehouseID;
                    var query          = await
                                         (
                        from x in db.DirEmployeeWarehouse
                        where x.DirEmployeeID == field.DirEmployeeID && x.DirWarehouseID == DirWarehouseID
                        select x
                                         ).ToListAsync();
                    if (query.Count() == 0)
                    {
                        return(Ok(returnServer.Return(false, "У Вас нет доступа к этой точке!")));
                    }
                }

                using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction())
                {
                    db.Configuration.AutoDetectChangesEnabled = false;

                    try
                    {
                        #region Лог

                        //Пишем в Лог о смене статуса и мастера, если такое было
                        logService.DocServicePurchID   = docServicePurch2Tab.DocServicePurchID;
                        logService.DirServiceLogTypeID = 6;
                        logService.DirEmployeeID       = field.DirEmployeeID;
                        logService.DirServiceStatusID  = null;
                        logService.Msg = "Удаление записи " + docServicePurch2Tab.DirNomenName + " на сумму " + docServicePurch2Tab.PriceCurrency;

                        await logServicesController.mPutPostLogServices(db, logService, EntityState.Added);

                        #endregion

                        #region Save

                        db.DocServicePurch2Tabs.Remove(docServicePurch2Tab);
                        await db.SaveChangesAsync();

                        #endregion


                        #region Партии

                        //Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch2Tab.DocServicePurchID);

                        //Models.Sklad.Rem.RemPartyMinus remPartyMinus = db.RemPartyMinuses.Where(x => x.DocID == docServicePurch.DocID && x.FieldID == id).ToList().First();
                        var query2 = await db.RemPartyMinuses.Where(x => x.DocID == docServicePurch.DocID && x.FieldID == id).ToListAsync();

                        if (query2.Count() > 0)
                        {
                            Models.Sklad.Rem.RemPartyMinus remPartyMinus = query2[0];
                            db.RemPartyMinuses.Remove(remPartyMinus);
                            await db.SaveChangesAsync();
                        }

                        #endregion


                        ts.Commit();
                    }
                    catch (Exception ex)
                    {
                        try { ts.Rollback(); ts.Dispose(); } catch { }
                        try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { }

                        return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
                    }
                }


                dynamic collectionWrapper = new
                {
                    ID  = docServicePurch2Tab.DocServicePurch2TabID,
                    Msg = Classes.Language.Sklad.Language.msg19
                };
                return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }

            #endregion
        }
        internal async Task <DocServicePurch2Tab> mPutPostDocServicePurch2Tab(
            DbConnectionSklad db,
            Models.Sklad.Doc.DocServicePurch docServicePurch,
            DocServicePurch2Tab docServicePurch2Tab,

            Classes.Account.Login.Field field //Дополнительные данные о сотруднике
            )
        {
            #region Лог

            //Пишем в Лог о смене статуса и мастера, если такое было
            logService.DocServicePurchID   = docServicePurch2Tab.DocServicePurchID;
            logService.DirServiceLogTypeID = 6;
            logService.DirEmployeeID       = field.DirEmployeeID;
            logService.DirServiceStatusID  = null;
            if (docServicePurch2Tab.DocServicePurch2TabID == null)
            {
                logService.Msg = "Создание записи " + docServicePurch2Tab.DirNomenName + " на сумму " + docServicePurch2Tab.PriceCurrency;
            }
            else
            {
                logService.Msg = "Изменение записи " + docServicePurch2Tab.DirNomenName + " на сумму " + docServicePurch2Tab.PriceCurrency;
            }

            await logServicesController.mPutPostLogServices(db, logService, EntityState.Added);

            #endregion


            #region Save

            docServicePurch2Tab.TabDate = DateTime.Now;

            if (docServicePurch2Tab.DocServicePurch2TabID > 0)
            {
                db.Entry(docServicePurch2Tab).State = EntityState.Modified;
            }
            else
            {
                db.Entry(docServicePurch2Tab).State = EntityState.Added;
            }
            await Task.Run(() => db.SaveChangesAsync());

            #endregion

            #region Партии *** *** *** *** *** *** *** ***


            Controllers.Sklad.Rem.RemPartyMinusesController remPartyMinuses = new Rem.RemPartyMinusesController();

            //Находим "DocServicePurch" по "docServicePurch2Tab.DocServicePurchID"
            //Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch2Tab.DocServicePurchID);
            Models.Sklad.Doc.Doc doc = await db.Docs.FindAsync(docServicePurch.DocID);


            #region Ищим в Возврате покупателя, если нет, то удаляем в RemPartyMinuses *** *** *** *** ***

            //Ищим в Возврате покупателя
            var queryRemPartyMinuses = await
                                       (
                from x in db.RemPartyMinuses
                where x.DocID == docServicePurch.DocID
                select x
                                       ).ToListAsync();

            for (int i = 0; i < queryRemPartyMinuses.Count(); i++)
            {
                int iRemPartyMinusID = Convert.ToInt32(queryRemPartyMinuses[i].RemPartyMinusID);

                var queryDocReturnsCustomerTab = await
                                                 (
                    from x in db.DocReturnsCustomerTabs
                    where x.RemPartyMinusID == iRemPartyMinusID
                    select x
                                                 ).ToListAsync();

                if (queryDocReturnsCustomerTab.Count() > 0)
                {
                    throw new System.InvalidOperationException(
                              Classes.Language.Sklad.Language.msg117 +

                              "<tr>" +
                              "<td>" + queryDocReturnsCustomerTab[0].RemPartyMinusID + "</td>" +                     //партия списания
                              "<td>" + queryDocReturnsCustomerTab[0].DocReturnsCustomerID + "</td>" +                //№ д-та
                              "<td>" + queryDocReturnsCustomerTab[0].DirNomenID + "</td>" +                          //Код товара
                              "<td>" + queryDocReturnsCustomerTab[0].Quantity + "</td>" +                            //списуемое к-во
                              "</tr>" +
                              "</table>" +

                              Classes.Language.Sklad.Language.msg117_1
                              );
                }

                //1.1. Удаляем "RemPartyMinuses" - не удаляем!!!
                //Models.Sklad.Rem.RemPartyMinus _remPartyMinus = await db.RemPartyMinuses.FindAsync(iRemPartyMinusID);
                //db.RemPartyMinuses.Remove(_remPartyMinus);
                //await db.SaveChangesAsync();
            }

            #endregion

            #region Удаляем все записи из таблицы "RemPartyMinuses" - не удаляем!!!
            //Удаляем все записи из таблицы "RemPartyMinuses"
            //Что бы правильно Проверяло на Остаток.
            //А то, товар уже списан, а я проверяю на остаток!

            //await Task.Run(() => remPartyMinuses.Delete(db, Convert.ToInt32(docServicePurch.DocID)));  //remPartyMinuses.Delete(db, Convert.ToInt32(doc.DocID)));

            #endregion


            #region Проверки и Списание с партий (RemPartyMinuses)


            #region Проверка

            //Переменные
            int    iRemPartyID = docServicePurch2Tab.RemPartyID;
            double dQuantity   = 1; // docServicePurch2Tab.Quantity;
                                    //Находим партию
            Models.Sklad.Rem.RemParty remParty = await db.RemParties.FindAsync(iRemPartyID);

            db.Entry(remParty).Reload(); // - Это Важно! Триггер изменил значения, то они НЕ видны в проекте, надо обновить значения!!!

            #region 1. Есть ли остаток в партии с которой списываем!
            if (remParty.Remnant < dQuantity)
            {
                throw new System.InvalidOperationException(
                          Classes.Language.Sklad.Language.msg104 +

                          "<tr>" +
                          "<td>" + docServicePurch2Tab.RemPartyID + "</td>" +    //партия
                          "<td>" + docServicePurch2Tab.DirNomenID + "</td>" +    //Код товара
                          "<td>1</td>" +                                         //"<td>" + docServicePurch2Tab.Quantity + "</td>"                                 //списуемое к-во
                          "<td>" + remParty.Remnant + "</td>" +                  //остаток партии
                          "<td>" + (1 - remParty.Remnant).ToString() + "</td>" + //"<td>" + (docServicePurch2Tab.Quantity - remParty.Remnant).ToString() + "</td>" //недостающее к-во
                          "</tr>" +
                          "</table>" +

                          Classes.Language.Sklad.Language.msg104_1
                          );
            }
            #endregion

            #region 2. Склад: склад документа должен соответствовать каждой списуемой партии!
            if (remParty.DirWarehouseID != docServicePurch.DirWarehouseID)
            {
                //Это нужно, т.к. к нам от клиента не пришли все значения модели: "docServicePurch.dirWarehouse.DirWarehouseName"
                Models.Sklad.Dir.DirWarehouse dirWarehouse = await db.DirWarehouses.FindAsync(docServicePurch.DirWarehouseID);

                throw new System.InvalidOperationException(
                          Classes.Language.Sklad.Language.msg105 +

                          "<tr>" +
                          "<td>" + docServicePurch2Tab.RemPartyID + "</td>" +         //партия
                          "<td>" + docServicePurch2Tab.DirNomenID + "</td>" +         //Код товара
                          "<td>" + dirWarehouse.DirWarehouseName + "</td>" +          //склад документа
                          "<td>" + remParty.dirWarehouse.DirWarehouseName + "</td>" + //склад партии
                          "</tr>" +
                          "</table>" +

                          Classes.Language.Sklad.Language.msg105_1
                          );
            }
            #endregion

            #region 3. Организация: организация документа должен соответствовать каждой списуемой партии!
            if (remParty.DirContractorIDOrg != doc.DirContractorIDOrg)
            {
                //Это нужно, т.к. к нам от клиента не пришли все значения модели: "docServicePurch.dirWarehouse.DirWarehouseName"
                Models.Sklad.Dir.DirContractor dirContractor = await db.DirContractors.FindAsync(doc.DirContractorIDOrg);

                throw new System.InvalidOperationException(
                          Classes.Language.Sklad.Language.msg106 +

                          "<tr>" +
                          "<td>" + docServicePurch2Tab.RemPartyID + "</td>" +              //партия
                          "<td>" + docServicePurch2Tab.DirNomenID + "</td>" +              //Код товара
                          "<td>" + dirContractor.DirContractorName + "</td>" +             //организация спецификации
                          "<td>" + remParty.dirContractorOrg.DirContractorName + "</td>" + //организация партии
                          "</tr>" +
                          "</table>" +

                          Classes.Language.Sklad.Language.msg106_1
                          );
            }
            #endregion

            #endregion


            #region Сохранение

            Models.Sklad.Rem.RemPartyMinus remPartyMinus = new Models.Sklad.Rem.RemPartyMinus();
            remPartyMinus.RemPartyMinusID         = null;
            remPartyMinus.RemPartyID              = docServicePurch2Tab.RemPartyID;
            remPartyMinus.DirNomenID              = Convert.ToInt32(docServicePurch2Tab.DirNomenID);
            remPartyMinus.Quantity                = 1; // docServicePurch2Tab.Quantity;
            remPartyMinus.DirCurrencyID           = docServicePurch2Tab.DirCurrencyID;
            remPartyMinus.DirCurrencyMultiplicity = docServicePurch2Tab.DirCurrencyMultiplicity;
            remPartyMinus.DirCurrencyRate         = docServicePurch2Tab.DirCurrencyRate;
            remPartyMinus.DirVatValue             = docServicePurch.DirVatValue;
            remPartyMinus.DirWarehouseID          = docServicePurch.DirWarehouseID;
            remPartyMinus.DirContractorIDOrg      = doc.DirContractorIDOrg;
            remPartyMinus.DirContractorID         = doc.DirContractorIDOrg;
            remPartyMinus.DocID         = Convert.ToInt32(docServicePurch.DocID);
            remPartyMinus.PriceCurrency = docServicePurch2Tab.PriceCurrency;
            remPartyMinus.PriceVAT      = docServicePurch2Tab.PriceVAT;
            remPartyMinus.FieldID       = Convert.ToInt32(docServicePurch2Tab.DocServicePurch2TabID);
            remPartyMinus.Reserve       = false; //docServicePurch.Reserve;

            remPartyMinus.DirEmployeeID = doc.DirEmployeeID;
            remPartyMinus.DocDate       = doc.DocDate;

            db.Entry(remPartyMinus).State = EntityState.Added;
            await db.SaveChangesAsync();

            #endregion


            #endregion


            #endregion


            return(docServicePurch2Tab);
        }
        public async Task <IHttpActionResult> PostDocServicePurch2Tab(DocServicePurch2Tab docServicePurch2Tab)
        {
            try
            {
                #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

                //Получаем Куку
                System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"];

                // Проверяем Логин и Пароль
                Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true));

                if (!field.Access)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10)));
                }

                //Изменяем строку соединения
                db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true));

                //Права (1 - Write, 2 - Read, 3 - No Access)
                int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServicePurch2Tabs"));

                if (iRight != 1)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))));
                }

                //Разные Функции
                function.NumberDecimalSeparator();

                //Получам настройки
                Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1);

                #endregion

                #region Параметры

                //Получаем колекцию "Спецификации"
                Models.Sklad.Doc.DocServicePurch2Tab[] DocServicePurch2TabCollection = null;
                if (!String.IsNullOrEmpty(docServicePurch2Tab.recordsDataX))
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    DocServicePurch2TabCollection = serializer.Deserialize <Models.Sklad.Doc.DocServicePurch2Tab[]>("[" + docServicePurch2Tab.recordsDataX + "]");
                }

                if (DocServicePurch2TabCollection.Length > 0)
                {
                    docServicePurch2Tab          = DocServicePurch2TabCollection[0];
                    docServicePurch2Tab.PriceVAT = docServicePurch2Tab.PriceCurrency;
                    //if (docServicePurch2Tab.DirServiceJobNomenID == 0) docServicePurch2Tab.DirServiceJobNomenID = null;
                    if (docServicePurch2Tab.DocServicePurch2TabID == null || docServicePurch2Tab.DocServicePurch2TabID < 1)
                    {
                        docServicePurch2Tab.DocServicePurch2TabID   = null;
                        docServicePurch2Tab.DirEmployeeID           = field.DirEmployeeID;
                        docServicePurch2Tab.DirCurrencyID           = sysSetting.DirCurrencyID;
                        docServicePurch2Tab.DirCurrencyRate         = 1;
                        docServicePurch2Tab.DirCurrencyMultiplicity = 1;
                    }
                }

                //Проверка точки === === ===
                Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch2Tab.DocServicePurchID);

                if (field.DirEmployeeID != 1)
                {
                    int?DirWarehouseID = docServicePurch.DirWarehouseID;
                    var query          = await
                                         (
                        from x in db.DirEmployeeWarehouse
                        where x.DirEmployeeID == field.DirEmployeeID && x.DirWarehouseID == DirWarehouseID
                        select x
                                         ).ToListAsync();
                    if (query.Count() == 0)
                    {
                        return(Ok(returnServer.Return(false, "У Вас нет доступа к этой точке!")));
                    }
                }

                #endregion


                #region Сохранение


                using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction())
                {
                    db.Configuration.AutoDetectChangesEnabled = false;

                    try
                    {
                        docServicePurch2Tab = await Task.Run(() => mPutPostDocServicePurch2Tab(db, docServicePurch, docServicePurch2Tab, field));

                        ts.Commit();
                    }
                    catch (Exception ex)
                    {
                        try { ts.Rollback(); ts.Dispose(); } catch { }
                        try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { }

                        return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
                    }
                }



                dynamic collectionWrapper = new
                {
                    DocServicePurch2TabID   = docServicePurch2Tab.DocServicePurch2TabID,
                    DirEmployeeID           = docServicePurch2Tab.DirEmployeeID,
                    DirCurrencyID           = docServicePurch2Tab.DirCurrencyID,
                    DirCurrencyRate         = docServicePurch2Tab.DirCurrencyRate,
                    DirCurrencyMultiplicity = docServicePurch2Tab.DirCurrencyMultiplicity
                };
                return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, ""));

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Пример #4
0
        //int ListObjectID = 53;

        #endregion


        #region Не рабочий метод!!!

        //Не рабочий метод!!!
        public async Task <IHttpActionResult> GetSms(int SmsTemplateID, int DocServicePurchID, HttpRequestMessage request)
        {
            try
            {
                #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

                //Получаем Куку
                System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"];

                // Проверяем Логин и Пароль
                Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true));

                if (!field.Access)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10)));
                }

                //Изменяем строку соединения
                db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true));

                //Права

                /*int Status = await Task.Run(() => accessRight.Access(db, field.DirEmployeeID, "DirBank"));
                 * if (Status >= 3) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)));*/

                //Права (1 - Write, 2 - Read, 3 - No Access)
                //int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDirBanks"));
                //if (iRight == 3) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)));

                //Разные Функции
                function.NumberDecimalSeparator();

                //Получам настройки
                Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1);

                #endregion


                string res = "";

                //Находим по "DocServicePurchID" номер телефона клиента
                Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(DocServicePurchID);

                // DirServiceContractorPhone == "79257711344"


                #region Проверки

                //Активны SMS
                if (sysSetting.SmsActive)
                {
                    return(Ok(returnServer.Return(false, "Активируйте в Настройках (верхнее меню) оповещение по SMS!")));
                }

                //Проверка номера телефона
                if (docServicePurch.DirServiceContractorPhone == null)
                {
                    return(Ok(returnServer.Return(false, "Номер телефоана клиента не корректный!")));
                }
                //Убираем + в самом начале
                docServicePurch.DirServiceContractorPhone = docServicePurch.DirServiceContractorPhone.Replace("+", "");
                //Проверка номера телефона
                if (docServicePurch.DirServiceContractorPhone.Length < 11)
                {
                    return(Ok(returnServer.Return(false, "Номер телефоана клиента не корректный!")));
                }

                #endregion


                if (sysSetting.SmsServiceID == 1)
                {
                    #region sms48_ru

                    PartionnyAccount.Classes.SMS.sms48_ru sms48_ru = new Classes.SMS.sms48_ru();
                    res = sms48_ru.Send(sysSetting, docServicePurch.DirServiceContractorPhone, "Apparat otremontirovan. Zaberite ego - 1200 RUR");

                    //Пишем в Лог + ещё куда-то
                    //Только, если успешно!
                    if (res == "8")
                    {
                        res = "Отправлено";
                    }
                    else if (res == "1")
                    {
                        res = "Доставлено";
                    }
                    else if (res == "2")
                    {
                        res = "Не удалось";
                    }
                    else
                    {
                        res = "Ошибка: " + res;
                    }

                    #endregion
                }
                else if (sysSetting.SmsServiceID == 2)
                {
                    #region sms4b_ru - не работает

                    /*
                     * PartionnyAccount.Classes.SMS.sms4b_ru sms4b_ru = new Classes.SMS.sms4b_ru();
                     * res = sms4b_ru.Send();
                     *
                     * //Пишем в Лог + ещё куда-то
                     * //Только, если успешно!
                     * if (res == "1")
                     * {
                     *
                     * }
                     */

                    #endregion
                }


                dynamic collectionWrapper = new
                {
                    Msg = res
                };
                return(Ok(returnServer.Return(true, collectionWrapper)));
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Пример #5
0
        public async Task <IHttpActionResult> PutSms(int id, DirSmsTemplate dirSmsTemplate, HttpRequestMessage request)
        {
            try
            {
                #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

                //Получаем Куку
                System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"];

                // Проверяем Логин и Пароль
                Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true));

                if (!field.Access)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10)));
                }

                //Изменяем строку соединения
                db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true));

                //Права

                /*int Status = await Task.Run(() => accessRight.Access(db, field.DirEmployeeID, "DirBank"));
                 * if (Status >= 3) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)));*/

                //Права (1 - Write, 2 - Read, 3 - No Access)
                //int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDirBanks"));
                //if (iRight == 3) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)));

                //Разные Функции
                function.NumberDecimalSeparator();

                //Получам настройки
                Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1);

                #endregion

                #region Параметры

                //paramList -список параметров
                var paramList = request.GetQueryNameValuePairs();
                //Параметры
                int ListObjectID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "ListObjectID", true) == 0).Value); //Записей на страницу

                #endregion


                #region Проверки

                //Активны SMS
                if (!sysSetting.SmsActive)
                {
                    return(Ok(returnServer.Return(false, "Активируйте в Настройках (верхнее меню) оповещение по SMS!")));
                }


                string Phone = "";
                if (ListObjectID == 40)
                {
                    //Находим по "DocServicePurchID" номер телефона клиента
                    Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(id); // DirServiceContractorPhone == "79257711344"

                    //Проверка номера телефона
                    if (docServicePurch.DirServiceContractorPhone == null)
                    {
                        return(Ok(returnServer.Return(false, "Номер телефоана клиента не корректный!")));
                    }
                    //Убираем + в самом начале
                    docServicePurch.DirServiceContractorPhone = docServicePurch.DirServiceContractorPhone.Replace("+", "");
                    //Проверка номера телефона
                    if (docServicePurch.DirServiceContractorPhone.Length < 11)
                    {
                        return(Ok(returnServer.Return(false, "Номер телефоана клиента не корректный!")));
                    }

                    Phone = docServicePurch.DirServiceContractorPhone;
                }
                else if (ListObjectID == 33)
                {
                    //Находим по "DocMovementID" документ
                    Models.Sklad.Doc.DocMovement docMovement = await db.DocMovements.FindAsync(id); // DirServiceContractorPhone == "79257711344"

                    //По документу находим курьера и его номер телефона
                    Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(docMovement.DirEmployeeIDCourier);

                    //Проверка номера телефона
                    if (dirEmployee.Phone == null)
                    {
                        return(Ok(returnServer.Return(false, "Номер телефоана клиента не корректный!")));
                    }
                    //Убираем + в самом начале
                    dirEmployee.Phone = dirEmployee.Phone.Replace("+", "");
                    //Проверка номера телефона
                    if (dirEmployee.Phone.Length < 11)
                    {
                        return(Ok(returnServer.Return(false, "Номер телефоана клиента не корректный!")));
                    }

                    Phone = dirEmployee.Phone;
                }

                #endregion


                #region OLD

                /*
                 *
                 * string res = "";
                 *
                 * if (sysSetting.SmsServiceID == 1)
                 * {
                 #region sms48_ru
                 *
                 *  //Отправка SMS
                 *  PartionnyAccount.Classes.SMS.sms48_ru sms48_ru = new Classes.SMS.sms48_ru();
                 *  res = sms48_ru.Send(sysSetting, Phone, dirSmsTemplate.DirSmsTemplateMsg);
                 *
                 *  //Результат
                 *  if (res == "8") res = "Отправлено";
                 *  else if (res == "1") res = "Доставлено";
                 *  else if (res == "2") res = "Не удалось";
                 *  else res = "Ошибка: " + res;
                 *
                 *  //Пишем в Лог
                 *  await RecordInLog(ListObjectID, id, "Номер тел.:" + Phone + "Текст SMS: " + dirSmsTemplate.DirSmsTemplateMsg + "<br /> Результат: " + res, field);
                 *
                 #endregion
                 * }
                 * else if (sysSetting.SmsServiceID == 2)
                 * {
                 #region sms4b_ru - не работает
                 *
                 #endregion
                 * }
                 * if (sysSetting.SmsServiceID == 3)
                 * {
                 #region infobip_com
                 *
                 *  //Отправка SMS
                 *  PartionnyAccount.Classes.SMS.infobip_com infobip_com = new Classes.SMS.infobip_com();
                 *  res = infobip_com.Send(sysSetting, Phone, dirSmsTemplate.DirSmsTemplateMsg);
                 *
                 *  //Пишем в Лог
                 *  await RecordInLog(ListObjectID, id, "Номер тел.:" + Phone + "Текст SMS: " + dirSmsTemplate.DirSmsTemplateMsg + "<br /> Результат: " + res, field);
                 *
                 #endregion
                 * }
                 */

                #endregion


                int DocID = 0;

                string res = await SenSms(
                    //res,
                    sysSetting,
                    ListObjectID,
                    id,
                    Phone,
                    dirSmsTemplate.DirSmsTemplateMsg,
                    field,
                    db,
                    id
                    );


                #region Меняем в таблице "DocServicePurches" поля: "AlertedCount" и "AlertedDate"

                PartionnyAccount.Models.Sklad.Doc.DocServicePurch docServicePurch1 = await db.DocServicePurches.FindAsync(id);

                docServicePurch1.AlertedCount   = Convert.ToInt32(docServicePurch1.AlertedCount) + 1;
                docServicePurch1.AlertedDateTxt = DateTime.Now.ToString("yyyy-MM-dd");
                docServicePurch1.AlertedDate    = DateTime.Now;

                db.Entry(docServicePurch1).State = EntityState.Modified;
                await db.SaveChangesAsync();

                #endregion


                dynamic collectionWrapper = new
                {
                    Msg = res
                };
                return(Ok(returnServer.Return(true, collectionWrapper)));
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
        public async Task <IHttpActionResult> DeleteDocServicePurch1Tab(int id, HttpRequestMessage request)
        {
            #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

            //Получаем Куку
            System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"];

            // Проверяем Логин и Пароль
            Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true));

            if (!field.Access)
            {
                return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10)));
            }

            //Изменяем строку соединения
            db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true));

            //Права (1 - Write, 2 - Read, 3 - No Access)
            int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServicePurch1Tabs"));

            if (iRight != 1)
            {
                return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))));
            }

            //Разные Функции
            function.NumberDecimalSeparator();

            //Получам настройки
            Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1);

            #endregion

            #region Параметры

            var    paramList           = request.GetQueryNameValuePairs();
            int    iDirServiceStatusID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceStatusID", true) == 0).Value);
            string sDiagnosticRresults = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "sDiagnosticRresults", true) == 0).Value;

            #endregion


            #region Удаление

            try
            {
                DocServicePurch1Tab docServicePurch1Tab = await db.DocServicePurch1Tabs.FindAsync(id);

                if (docServicePurch1Tab == null)
                {
                    //return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg99));

                    dynamic collectionWrapper2 = new
                    {
                        ID  = 0,
                        Msg = Classes.Language.Sklad.Language.msg99
                    };
                    return(Ok(returnServer.Return(true, collectionWrapper2)));
                }

                //Проверка точки === === ===
                Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch1Tab.DocServicePurchID);

                if (field.DirEmployeeID != 1)
                {
                    int?DirWarehouseID = docServicePurch.DirWarehouseID;
                    var query          = await
                                         (
                        from x in db.DirEmployeeWarehouse
                        where x.DirEmployeeID == field.DirEmployeeID && x.DirWarehouseID == DirWarehouseID
                        select x
                                         ).ToListAsync();
                    if (query.Count() == 0)
                    {
                        return(Ok(returnServer.Return(false, "У Вас нет доступа к этой точке!")));
                    }
                }


                using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction())
                {
                    db.Configuration.AutoDetectChangesEnabled = false;

                    try
                    {
                        #region Лог

                        //Пишем в Лог о смене статуса и мастера, если такое было
                        logService.DocServicePurchID   = docServicePurch1Tab.DocServicePurchID;
                        logService.DirServiceLogTypeID = 5;
                        logService.DirEmployeeID       = field.DirEmployeeID;
                        logService.DirServiceStatusID  = null;
                        logService.Msg  = "Удаление записи " + docServicePurch1Tab.DirServiceJobNomenName + " на сумму " + docServicePurch1Tab.PriceCurrency;
                        logService.Msg += "<br />Причина удаление: " + sDiagnosticRresults;

                        await logServicesController.mPutPostLogServices(db, logService, EntityState.Added);

                        #endregion

                        #region Save

                        db.DocServicePurch1Tabs.Remove(docServicePurch1Tab);
                        await db.SaveChangesAsync();

                        #endregion

                        ts.Commit();
                    }
                    catch (Exception ex)
                    {
                        try { ts.Rollback(); ts.Dispose(); } catch { }
                        try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { }

                        return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
                    }
                }


                dynamic collectionWrapper = new
                {
                    ID  = docServicePurch1Tab.DocServicePurch1TabID,
                    Msg = Classes.Language.Sklad.Language.msg19
                };
                return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, "")
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }

            #endregion
        }
        public async Task <IHttpActionResult> PostDocServicePurch1Tab(DocServicePurch1Tab docServicePurch1Tab, HttpRequestMessage request)
        {
            try
            {
                #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

                //Получаем Куку
                System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"];

                // Проверяем Логин и Пароль
                Classes.Account.Login.Field field = await Task.Run(() => login.Return(authCookie, true));

                if (!field.Access)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg10)));
                }

                //Изменяем строку соединения
                db = new DbConnectionSklad(connectionString.Return(field.DirCustomersID, null, true));

                //Права (1 - Write, 2 - Read, 3 - No Access)
                int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServicePurch1Tabs"));

                if (iRight != 1)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))));
                }


                //Разные Функции
                function.NumberDecimalSeparator();

                //Получам настройки
                Models.Sklad.Sys.SysSetting sysSetting = await db.SysSettings.FindAsync(1);

                #endregion

                #region Параметры

                var    paramList           = request.GetQueryNameValuePairs();
                int    iDirServiceStatusID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceStatusID", true) == 0).Value);
                string sDiagnosticRresults = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "sDiagnosticRresults", true) == 0).Value;

                //Получаем колекцию "Спецификации"
                Models.Sklad.Doc.DocServicePurch1Tab[] DocServicePurch1TabCollection = null;
                if (!String.IsNullOrEmpty(docServicePurch1Tab.recordsDataX))
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    DocServicePurch1TabCollection = serializer.Deserialize <Models.Sklad.Doc.DocServicePurch1Tab[]>("[" + docServicePurch1Tab.recordsDataX + "]");
                }

                if (DocServicePurch1TabCollection.Length > 0)
                {
                    docServicePurch1Tab          = DocServicePurch1TabCollection[0];
                    docServicePurch1Tab.PriceVAT = docServicePurch1Tab.PriceCurrency;
                    if (docServicePurch1Tab.DirServiceJobNomenID == 0)
                    {
                        docServicePurch1Tab.DirServiceJobNomenID = null;
                    }
                    if (docServicePurch1Tab.DocServicePurch1TabID == null || docServicePurch1Tab.DocServicePurch1TabID < 1)
                    {
                        docServicePurch1Tab.DocServicePurch1TabID   = null;
                        docServicePurch1Tab.DirEmployeeID           = field.DirEmployeeID;
                        docServicePurch1Tab.DirCurrencyID           = sysSetting.DirCurrencyID;
                        docServicePurch1Tab.DirCurrencyRate         = 1;
                        docServicePurch1Tab.DirCurrencyMultiplicity = 1;

                        if (docServicePurch1Tab.DirServiceJobNomenID == null)
                        {
                            bool bRight = await Task.Run(() => accessRight.AccessCheck(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDocServiceWorkshopsTab1AddCheck"));

                            if (!bRight)
                            {
                                return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0))));
                            }
                        }
                    }
                }

                //Проверка точки === === ===
                Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch1Tab.DocServicePurchID);

                if (field.DirEmployeeID != 1)
                {
                    int?DirWarehouseID = docServicePurch.DirWarehouseID;
                    var query          = await
                                         (
                        from x in db.DirEmployeeWarehouse
                        where x.DirEmployeeID == field.DirEmployeeID && x.DirWarehouseID == DirWarehouseID
                        select x
                                         ).ToListAsync();
                    if (query.Count() == 0)
                    {
                        return(Ok(returnServer.Return(false, "У Вас нет доступа к этой точке!")));
                    }
                }

                #endregion


                #region Сохранение


                using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction())
                {
                    db.Configuration.AutoDetectChangesEnabled = false;

                    try
                    {
                        #region Save docServicePurch

                        //Models.Sklad.Doc.DocServicePurch docServicePurch = await db.DocServicePurches.FindAsync(docServicePurch1Tab.DocServicePurchID);
                        int?DirServiceStatusIDOLD = docServicePurch.DirServiceStatusID;
                        docServicePurch.DirServiceStatusID = iDirServiceStatusID;
                        db.Entry(docServicePurch).State    = EntityState.Modified;


                        #region Лог - если поменялся статус

                        if (DirServiceStatusIDOLD != iDirServiceStatusID)
                        {
                            //Пишем в Лог о смене статуса и мастера, если такое было
                            logService.DocServicePurchID   = docServicePurch1Tab.DocServicePurchID;
                            logService.DirServiceLogTypeID = 1;
                            logService.DirEmployeeID       = field.DirEmployeeID;
                            logService.DirServiceStatusID  = iDirServiceStatusID;
                            if (!String.IsNullOrEmpty(sDiagnosticRresults))
                            {
                                logService.Msg = sDiagnosticRresults;
                            }

                            await logServicesController.mPutPostLogServices(db, logService, EntityState.Added);
                        }

                        #endregion

                        #endregion


                        #region Save docServicePurch1Tab


                        #region Лог

                        //Пишем в Лог о смене статуса и мастера, если такое было
                        logService.DocServicePurchID   = docServicePurch1Tab.DocServicePurchID;
                        logService.DirServiceLogTypeID = 5;
                        logService.DirEmployeeID       = field.DirEmployeeID;
                        logService.DirServiceStatusID  = iDirServiceStatusID;

                        if (docServicePurch1Tab.DocServicePurch1TabID == null)
                        {
                            logService.Msg = "Создание записи " + docServicePurch1Tab.DirServiceJobNomenName + " на сумму " + docServicePurch1Tab.PriceCurrency;
                        }
                        else
                        {
                            logService.Msg = "Изменение записи " + docServicePurch1Tab.DirServiceJobNomenName + " на сумму " + docServicePurch1Tab.PriceCurrency;
                        }
                        if (!String.IsNullOrEmpty(sDiagnosticRresults))
                        {
                            logService.Msg += "<br /> Результат Диагностики: " + sDiagnosticRresults;
                        }

                        await logServicesController.mPutPostLogServices(db, logService, EntityState.Added);

                        #endregion

                        docServicePurch1Tab.DirServiceStatusID = iDirServiceStatusID;

                        if (docServicePurch1Tab.DocServicePurch1TabID > 0)
                        {
                            db.Entry(docServicePurch1Tab).State = EntityState.Modified;
                        }
                        else
                        {
                            docServicePurch1Tab.DiagnosticRresults = sDiagnosticRresults;
                            docServicePurch1Tab.TabDate            = DateTime.Now;

                            db.Entry(docServicePurch1Tab).State = EntityState.Added;
                        }
                        await Task.Run(() => db.SaveChangesAsync());

                        #endregion


                        ts.Commit();
                    }
                    catch (Exception ex)
                    {
                        try { ts.Rollback(); ts.Dispose(); } catch { }
                        try { db.Database.Connection.Close(); db.Database.Connection.Dispose(); } catch { }

                        return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
                    }
                }



                dynamic collectionWrapper = new
                {
                    DocServicePurch1TabID   = docServicePurch1Tab.DocServicePurch1TabID,
                    DirEmployeeID           = docServicePurch1Tab.DirEmployeeID,
                    DirCurrencyID           = docServicePurch1Tab.DirCurrencyID,
                    DirCurrencyRate         = docServicePurch1Tab.DirCurrencyRate,
                    DirCurrencyMultiplicity = docServicePurch1Tab.DirCurrencyMultiplicity
                };
                return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, ""));

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }