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> 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
        }