//Сумма документа
        public string GenerateSQLSUM(Models.Sklad.Sys.SysSetting sysSettings)
        {
            string SQL =
                "SELECT Docs.Discount, " +
                "COUNT(*) CountRecord, " +
                "COUNT(*) CountRecord_NumInWords, " +
                "SUM(DocSecondHandRetailReturnTabs.Quantity) SumCount, " +

                //Сумма С НДС в текущей валюте
                "round( (SUM( (1 - Docs.Discount / 100) * (DocSecondHandRetailReturnTabs.Quantity * DocSecondHandRetailReturnTabs.PriceCurrency))), " + sysSettings.FractionalPartInSum + ") 'SumOfVATCurrency', " +
                "round( (SUM( (1 - Docs.Discount / 100) * (DocSecondHandRetailReturnTabs.Quantity * DocSecondHandRetailReturnTabs.PriceCurrency))), " + sysSettings.FractionalPartInSum + ") 'SumOfVATCurrency_InWords', " + //Приписью

                "round( (SUM( (1 - Docs.Discount / 100) * DocSecondHandRetailReturnTabs.Quantity * (DocSecondHandRetailReturnTabs.PriceCurrency - (DocSecondHandRetailReturnTabs.PriceCurrency)/(1 + (Docs.DirVatValue) / 100)))), " + sysSettings.FractionalPartInSum + ") 'SumVATCurrency', " +
                "round( (SUM( (1 - Docs.Discount / 100) * DocSecondHandRetailReturnTabs.Quantity * (DocSecondHandRetailReturnTabs.PriceCurrency - (DocSecondHandRetailReturnTabs.PriceCurrency)/(1 + (Docs.DirVatValue) / 100)))), " + sysSettings.FractionalPartInSum + ") 'SumVATCurrency_InWords', " + //Приписью

                "round( SUM( (1 - Docs.Discount / 100) * (DocSecondHandRetailReturnTabs.Quantity * DocSecondHandRetailReturnTabs.PriceCurrency)/(1 + (Docs.DirVatValue) / 100) ), " + sysSettings.FractionalPartInSum + ") 'SumOfNoVatCurrency', " +
                "round( SUM( (1 - Docs.Discount / 100) * (DocSecondHandRetailReturnTabs.Quantity * DocSecondHandRetailReturnTabs.PriceCurrency)/(1 + (Docs.DirVatValue) / 100) ), " + sysSettings.FractionalPartInSum + ") 'SumOfNoVatCurrency_InWords', " + //Приписью

                "Docs.DirVatValue 'DirVatValue' " +
                "FROM Docs, DocSecondHandRetailReturns, DocSecondHandRetailReturnTabs " +
                "WHERE " +
                "(Docs.DocID=DocSecondHandRetailReturns.DocID)and" +
                "(DocSecondHandRetailReturns.DocSecondHandRetailReturnID=DocSecondHandRetailReturnTabs.DocSecondHandRetailReturnID)and(Docs.DocID=@DocID)";

            return(SQL);
        }
        //Сумма документа
        public string GenerateSQLSUM(Models.Sklad.Sys.SysSetting sysSettings)
        {
            string SQL =
                "SELECT " +
                "[Docs].[DocDate] AS [DocDate], [Docs].[DocDate] AS [DocDate_InWords], " +
                "[DirEmployees].[DirEmployeeName] AS [DirEmployeeName], " +
                "Docs.Discount, " +
                "COUNT(*) CountRecord, " +
                "COUNT(*) CountRecord_NumInWords, " +
                "SUM(DocDomesticExpenseTabs.Quantity) SumCount, " +

                //Сумма С НДС в текущей валюте
                "round( (SUM( (1 - Docs.Discount / 100) * (DocDomesticExpenseTabs.Quantity * DocDomesticExpenseTabs.PriceCurrency))), " + sysSettings.FractionalPartInSum + ") 'SumOfVATCurrency', " +
                "round( (SUM( (1 - Docs.Discount / 100) * (DocDomesticExpenseTabs.Quantity * DocDomesticExpenseTabs.PriceCurrency))), " + sysSettings.FractionalPartInSum + ") 'SumOfVATCurrency_InWords', " + //Приписью

                "round( (SUM( (1 - Docs.Discount / 100) * DocDomesticExpenseTabs.Quantity * (DocDomesticExpenseTabs.PriceCurrency - (DocDomesticExpenseTabs.PriceCurrency)/(1 + (Docs.DirVatValue) / 100)))), " + sysSettings.FractionalPartInSum + ") 'SumVATCurrency', " +
                "round( (SUM( (1 - Docs.Discount / 100) * DocDomesticExpenseTabs.Quantity * (DocDomesticExpenseTabs.PriceCurrency - (DocDomesticExpenseTabs.PriceCurrency)/(1 + (Docs.DirVatValue) / 100)))), " + sysSettings.FractionalPartInSum + ") 'SumVATCurrency_InWords', " + //Приписью

                "round( SUM( (1 - Docs.Discount / 100) * (DocDomesticExpenseTabs.Quantity * DocDomesticExpenseTabs.PriceCurrency)/(1 + (Docs.DirVatValue) / 100) ), " + sysSettings.FractionalPartInSum + ") 'SumOfNoVatCurrency', " +
                "round( SUM( (1 - Docs.Discount / 100) * (DocDomesticExpenseTabs.Quantity * DocDomesticExpenseTabs.PriceCurrency)/(1 + (Docs.DirVatValue) / 100) ), " + sysSettings.FractionalPartInSum + ") 'SumOfNoVatCurrency_InWords', " + //Приписью

                "Docs.DirVatValue 'DirVatValue' " +
                "FROM Docs, DocDomesticExpenses, DocDomesticExpenseTabs, DirEmployees " +
                "WHERE " +
                "(Docs.DocID=DocDomesticExpenses.DocID)and" +
                "(DocDomesticExpenses.DocDomesticExpenseID=DocDomesticExpenseTabs.DocDomesticExpenseID)and(Docs.DocID=@DocID)and" +
                "(Docs.DirEmployeeID=DirEmployees.DirEmployeeID)";

            return(SQL);
        }
Esempio n. 3
0
        //Сумма документа
        public string GenerateSQLSUM(Models.Sklad.Sys.SysSetting sysSettings)
        {
            string SQL =
                "SELECT " +
                "COUNT(*) CountRecord, " +
                "COUNT(*) CountRecord_NumInWords, " +
                "SUM(DocInventoryTabs.Quantity) SumCount, " +

                //Сумма С НДС в текущей валюте
                "round((SUM((DocInventoryTabs.Quantity * DocInventoryTabs.PriceCurrency))), " + sysSettings.FractionalPartInSum + ") 'SumOfVATCurrency', " +
                "round((SUM((DocInventoryTabs.Quantity * DocInventoryTabs.PriceCurrency))), " + sysSettings.FractionalPartInSum + ") 'SumOfVATCurrency_InWords' " + //Приписью

                //"round((SUM( DocInventoryTabs.Quantity * (DocInventoryTabs.PriceCurrency - DocInventoryTabs.PriceCurrency))), " + sysSettings.FractionalPartInSum + ") 'SumVATCurrency', " +
                //"round((SUM(DocInventoryTabs.Quantity * (DocInventoryTabs.PriceCurrency - DocInventoryTabs.PriceCurrency))), " + sysSettings.FractionalPartInSum + ") 'SumVATCurrency_InWords' " + //Приписью

                //"round(SUM((DocInventoryTabs.Quantity * DocInventoryTabs.PriceCurrency)), " + sysSettings.FractionalPartInSum + ") 'SumOfNoVatCurrency', " +
                //"round(SUM((DocInventoryTabs.Quantity * DocInventoryTabs.PriceCurrency)), " + sysSettings.FractionalPartInSum + ") 'SumOfNoVatCurrency_InWords' " + //Приписью

                "FROM Docs, DocInventories, DocInventoryTabs " +
                "WHERE " +
                "(Docs.DocID=DocInventories.DocID)and" +
                "(DocInventories.DocInventoryID=DocInventoryTabs.DocInventoryID)and(Docs.DocID=@DocID)";

            return(SQL);
        }
Esempio n. 4
0
        //db, dbRead, sysSetting, docPurchTab, EntityState.Added, field
        internal async Task <DocPurchTab> mPutPostDocPurchTab(
            DbConnectionSklad db,
            DbConnectionSklad dbRead,
            Models.Sklad.Sys.SysSetting sysSetting,
            DocPurchTab docPurchTab,
            EntityState entityState,          //EntityState.Added, Modified

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

            db.Entry(docPurchTab).State = entityState;
            await db.SaveChangesAsync();

            #endregion


            #region n. Подтверждение транзакции

            //ts.Commit(); //.Complete();

            #endregion


            return(docPurchTab);
        }
Esempio n. 5
0
        internal string Send(Models.Sklad.Sys.SysSetting sysSetting, string TelTo, string Message)
        {
            /*
             * string checksum = ComputeChecksum(Login, Password, TelTo);
             * var requestUrl = String.Format(UrlFormat, Login, TelTo, TelFrom, Message, checksum);
             * var request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
             * var response = (HttpWebResponse)request.GetResponse();
             *
             * var res = response.GetResponseStream();
             *
             * var res2 = res;
             */



            //Строка соединения
            //string URI = "http://sms48.ru/send_sms.php";
            //Параметры
            string checksum   = ComputeChecksum(sysSetting.SmsLogin, sysSetting.SmsPassword, TelTo);
            var    requestUrl = String.Format(UrlFormat, sysSetting.SmsLogin, TelTo, sysSetting.SmsTelFrom, Message, checksum);

            using (WebClient wc = new WebClient())
            {
                //wc.Encoding = System.Text.Encoding.UTF8;
                //wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                return(wc.UploadString(requestUrl, ""));
            }
        }
Esempio n. 6
0
        internal async Task <string> mSms_DocServicePurches(
            DbConnectionSklad db,
            DirSmsTemplate dirSmsTemplate,
            DocServicePurch docServicePurch,
            Models.Sklad.Sys.SysSetting sysSetting
            )
        {
            string ret = dirSmsTemplate.DirSmsTemplateMsg;

            //Парсим текст

            //Ваш (тип устройства/марка/модель) Mob.tel/Nokia/535 принят в ремонт, номер ремонта 2005
            //Мастерская Сити-Мастер
            //тел (тут вставляем номер тел точки чтоб чел мог набрать)


            //1. DirServiceNomenName: надо получить полное наименование
            Controllers.Sklad.Doc.DocServicePurches.DocServicePurchesController docServicePurchesController = new Controllers.Sklad.Doc.DocServicePurches.DocServicePurchesController();
            string[] DirServiceNomenPatchFullarr = await Task.Run(() => docServicePurchesController.mPatchFull(db, docServicePurch.DirServiceNomenID));

            string DirServiceNomenPatchFull = DirServiceNomenPatchFullarr[0];

            ret = ret.Replace("[[[ТоварНаименование]]]", DirServiceNomenPatchFull);


            //2. DocServicePurchID
            ret = ret.Replace("[[[ДокументНомер]]]", docServicePurch.DocServicePurchID.ToString());


            //3. Организация: получаем из настроек
            Models.Sklad.Dir.DirContractor dirContractor = await db.DirContractors.FindAsync(sysSetting.DirContractorIDOrg);

            ret = ret.Replace("[[[Организация]]]", dirContractor.DirContractorName);


            //4. Телефон: получаем из "docServicePurch.DirWarehouseID"
            Models.Sklad.Dir.DirWarehouse dirWarehouse = await db.DirWarehouses.FindAsync(docServicePurch.DirWarehouseID);

            ret = ret.Replace("[[[ТочкаНаименование]]]", dirWarehouse.DirWarehouseName);
            ret = ret.Replace("[[[ТочкаАдрес]]]", dirWarehouse.DirWarehouseAddress);
            ret = ret.Replace("[[[ТочкаТелефон]]]", dirWarehouse.Phone);


            //5. [[[Сумма]]]
            ret = ret.Replace("[[[Сумма]]]", docServicePurch.Sums.ToString()); //SumsTotal



            return(ret);
        }
Esempio n. 7
0
        //Сумма документа
        public string GenerateSQLSUM(Models.Sklad.Sys.SysSetting sysSettings)
        {
            string SQL =
                "SELECT " +
                "COUNT(*) CountRecord, " +
                "COUNT(*) CountRecord_NumInWords, " +

                //Сумма С НДС в текущей валюте
                "round( SUM(DocSecondHandMovTabs.PriceRetailCurrency), " + sysSettings.FractionalPartInSum + ") 'SumOfVATCurrency', " +
                "round( SUM(DocSecondHandMovTabs.PriceRetailCurrency), " + sysSettings.FractionalPartInSum + ") 'SumOfVATCurrency_InWords' " + //Приписью

                "FROM Docs, DocSecondHandMovs, DocSecondHandMovTabs " +
                "WHERE " +
                "(Docs.DocID=DocSecondHandMovs.DocID)and" +
                "(DocSecondHandMovs.DocSecondHandMovID=DocSecondHandMovTabs.DocSecondHandMovID)and(Docs.DocID=@DocID)";

            return(SQL);
        }
Esempio n. 8
0
        public async Task <IHttpActionResult> GetDirBonus(int id, 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, "RightDirBonuses"));

                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 Параметры

                Params _params = new Params();

                //paramList -список параметров
                var paramList = request.GetQueryNameValuePairs();
                //Параметры
                _params.parSearch = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "parSearch", true) == 0).Value; if (_params.parSearch != null)
                {
                    _params.parSearch = _params.parSearch.ToLower();                                                                                                                                      //Поиск
                }
                #endregion


                #region Отправка JSON

                var query = await Task.Run(() =>
                                           (

                                               from x in db.DirBonuses

                                               where x.DirBonusID == id

                                               select new
                {
                    DirBonusID = x.DirBonusID,
                    Del = x.Del,
                    DirBonusName = x.DirBonusName,
                    Description = x.Description
                }

                                           ).ToListAsync());


                if (query.Count() > 0)
                {
                    return(Ok(returnServer.Return(true, query[0])));
                }
                else
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg89)));
                }

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Esempio n. 9
0
        public async Task <IHttpActionResult> PostDirBonus(DirBonus dirBonus)
        {
            #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, "RightDirBonuses"));

            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.Dir.DirBonusTab[] dirBonusTabCollection = null;
            if (!String.IsNullOrEmpty(dirBonus.recordsDirBonusTabsGrid))
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                dirBonusTabCollection = serializer.Deserialize <Models.Sklad.Dir.DirBonusTab[]>(dirBonus.recordsDirBonusTabsGrid);
            }

            #endregion

            #region Проверки

            if (!ModelState.IsValid)
            {
                return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91)));                     //return BadRequest(ModelState);
            }
            #endregion


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

            try
            {
                //Используем метод, что бы было всё в одном потоке
                await Task.Run(() => mPutPostDirBonus(sysSetting, dirBonus, EntityState.Added, dirBonusTabCollection));


                #region 6. JourDisp *** *** *** *** *** *** *** *** *** *

                Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp();
                sysJourDisp.DirDispOperationID = 3; //Добавление записи
                sysJourDisp.DirEmployeeID      = field.DirEmployeeID;
                sysJourDisp.ListObjectID       = ListObjectID;
                sysJourDisp.TableFieldID       = dirBonus.DirBonusID;
                sysJourDisp.Description        = "";
                try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { }

                #endregion


                dynamic collectionWrapper = new
                {
                    ID = dirBonus.DirBonusID
                };
                return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, ""));
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }

            #endregion
        }
Esempio n. 10
0
        //Спецификация
        public string GenerateSQLSelectCollection(Models.Sklad.Sys.SysSetting sysSettings, int Exist)
        {
            string SQL = "";

            SQL =
                "SELECT " +

                "[Docs].[DocDate] AS [DocDate], " +

                //Номер документа
                "[DocSecondHandInvTabs].DocSecondHandPurchID AS [DocSecondHandPurchID], " +


                //Товар *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                //"[DirServiceNomens].[DirServiceNomenName] AS [DirServiceNomenName], " +
                "CASE " +
                "WHEN ([dirServiceNomensGroup].[DirServiceNomenName] IS NULL) THEN [dirServiceNomensSubGroup].[DirServiceNomenName] " +

                "WHEN ([DirServiceNomens].[DirServiceNomenName] IS NULL) THEN " +

                "CASE WHEN ([dirServiceNomensSubGroup].[DirServiceNomenName] IS NULL) THEN '' ELSE [dirServiceNomensSubGroup].[DirServiceNomenName] END || ' / ' || " +
                "CASE WHEN ([dirServiceNomensGroup].[DirServiceNomenName] IS NULL) THEN '' ELSE [dirServiceNomensGroup].[DirServiceNomenName] END ELSE " +

                "CASE WHEN ([dirServiceNomensSubGroup].[DirServiceNomenName] IS NULL) THEN '' ELSE [dirServiceNomensSubGroup].[DirServiceNomenName] END || ' / ' || " +
                "CASE WHEN ([dirServiceNomensGroup].[DirServiceNomenName] IS NULL) THEN '' ELSE [dirServiceNomensGroup].[DirServiceNomenName] END || ' / ' || " +
                "CASE WHEN ([DirServiceNomens].[DirServiceNomenName] IS NULL) THEN '' ELSE [DirServiceNomens].[DirServiceNomenName] END END AS [DirServiceNomenName], " +
                //Товар *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

                "[DocSecondHandInvTabs].[DirServiceNomenID] AS [DirServiceNomenID], " +
                "[DocSecondHandInvTabs].[PriceVAT] AS [PriceVAT], " +
                "[DocSecondHandInvTabs].[DirCurrencyID] AS [DirCurrencyID], " +
                "[DocSecondHandInvTabs].[DirCurrencyRate] AS [DirCurrencyRate], " +
                "[DocSecondHandInvTabs].[DirCurrencyMultiplicity] AS [DirCurrencyMultiplicity], " +

                "[DirCurrencies].[DirCurrencyName] || ' (' || [DocSecondHandInvTabs].[DirCurrencyRate] || ', ' || [DocSecondHandInvTabs].[DirCurrencyMultiplicity] || ')' AS [DirCurrencyName], " +
                "[DirContractorOrg].[DirContractorName] AS [DirContractorNameOrg], " +

                //Цены и Суммы НДС=================================================================================
                //В валюте
                "ROUND([DocSecondHandInvTabs].[PriceVAT], " + sysSettings.FractionalPartInPrice + ") 'PriceVAT', " +         //"Цена с НДС"  в валюте
                "ROUND([DocSecondHandInvTabs].[PriceVAT], " + sysSettings.FractionalPartInPrice + ") 'PriceVAT_InWords', " + //"Цена с НДС"  в валюте (словами)
                "ROUND([DocSecondHandInvTabs].[PriceVAT], " + sysSettings.FractionalPartInSum + ") 'SUMPriceVAT', " +        //"Стоимость с НДС" в валюте


                //В текущей валюте
                "ROUND([DocSecondHandInvTabs].[PriceCurrency], " + sysSettings.FractionalPartInPrice + ") 'PriceCurrency', " +         //"Цена с НДС" в текущей валюте
                "ROUND([DocSecondHandInvTabs].[PriceCurrency], " + sysSettings.FractionalPartInPrice + ") 'PriceCurrency_InWords', " + //"Цена с НДС" в текущей валюте (словами)
                "ROUND([DocSecondHandInvTabs].[PriceCurrency], " + sysSettings.FractionalPartInSum + ") 'SUMPriceCurrency', " +        //Стоимость с НДС в текущей валюте
                //Цены и Суммы НДС=================================================================================


                //Прочерк
                "'-' AS FieldDash, " +
                //Пустое поле
                "' ' AS FieldEmpty " +


                "FROM [Docs], [DocSecondHandInvs], [DocSecondHandInvTabs] " +

                "INNER JOIN [DirCurrencies] ON [DocSecondHandInvTabs].[DirCurrencyID] = [DirCurrencies].[DirCurrencyID] " +
                "INNER JOIN [DirContractors] AS [DirContractorOrg] ON [Docs].[DirContractorIDOrg] = [DirContractorOrg].[DirContractorID] " +
                //"INNER JOIN [DirPriceTypes] ON [DocSecondHandInvTabs].[DirPriceTypeID] = [DirPriceTypes].[DirPriceTypeID] " +

                //Товар *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                "LEFT JOIN [DirServiceNomens] AS [DirServiceNomens] ON [DirServiceNomens].[DirServiceNomenID] = [DocSecondHandInvTabs].[DirServiceNomenID] " +
                "LEFT JOIN [DirServiceNomens] AS [dirServiceNomensGroup] ON [DirServiceNomens].[Sub] = [dirServiceNomensGroup].[DirServiceNomenID] " +
                "LEFT JOIN [DirServiceNomens] AS [dirServiceNomensSubGroup] ON [dirServiceNomensGroup].[Sub] = [dirServiceNomensSubGroup].[DirServiceNomenID] " +
                //Товар *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***


                "WHERE " +
                "([Docs].[DocID]=[DocSecondHandInvs].[DocID])and([DocSecondHandInvs].[DocSecondHandInvID]=[DocSecondHandInvTabs].[DocSecondHandInvID])and(Docs.DocID=@DocID)and(DocSecondHandInvTabs.Exist=" + Exist.ToString() + ") ";


            return(SQL);
        }
Esempio n. 11
0
        // GET: api/DocSecondHandInvTabs
        public async Task <IHttpActionResult> GetDocSecondHandInvTabs(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, "RightDocSecondHandInventories"));

                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 Параметры

                Params _params = new Params();

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

                #endregion



                #region Основной запрос *** *** ***

                var query =
                    (
                        from docSecondHandInvTabs in db.DocSecondHandInvTabs

                        join dirServiceNomens11 in db.DirServiceNomens on docSecondHandInvTabs.dirServiceNomen.Sub equals dirServiceNomens11.DirServiceNomenID into dirServiceNomens12
                        from dirServiceNomensSubGroup in dirServiceNomens12.DefaultIfEmpty()

                        join dirServiceNomens21 in db.DirServiceNomens on dirServiceNomensSubGroup.Sub equals dirServiceNomens21.DirServiceNomenID into dirServiceNomens22
                        from dirServiceNomensGroup in dirServiceNomens22.DefaultIfEmpty()

                        where docSecondHandInvTabs.DocSecondHandInvID == _params.DocSecondHandInvID

                        #region select

                        select new
                {
                    DocSecondHandPurchID = docSecondHandInvTabs.DocSecondHandPurchID,
                    DocDate = docSecondHandInvTabs.docSecondHandInv.doc.DocDate,


                    DocSecondHandInvTabID = docSecondHandInvTabs.DocSecondHandInvTabID,
                    DocSecondHandInvID = docSecondHandInvTabs.DocSecondHandInvID,
                    DirServiceNomenID = docSecondHandInvTabs.DirServiceNomenID,

                    //DirServiceNomenName = docSecondHandInvTabs.dirServiceNomen.DirServiceNomenName,
                    DirServiceNomenName =
                        dirServiceNomensSubGroup.DirServiceNomenName == null ? docSecondHandInvTabs.dirServiceNomen.DirServiceNomenName :
                        dirServiceNomensGroup.DirServiceNomenName == null ? dirServiceNomensSubGroup.DirServiceNomenName + " / " + docSecondHandInvTabs.dirServiceNomen.DirServiceNomenName :
                        dirServiceNomensGroup.DirServiceNomenName + " / " + dirServiceNomensSubGroup.DirServiceNomenName + " / " + docSecondHandInvTabs.dirServiceNomen.DirServiceNomenName,

                    PriceVAT = docSecondHandInvTabs.PriceVAT,
                    PriceRetailVAT = docSecondHandInvTabs.docSecondHandPurch.PriceRetailVAT,

                    DirCurrencyID = docSecondHandInvTabs.DirCurrencyID,
                    DirCurrencyRate = docSecondHandInvTabs.DirCurrencyRate,
                    DirCurrencyMultiplicity = docSecondHandInvTabs.DirCurrencyMultiplicity,
                    DirCurrencyName = docSecondHandInvTabs.dirCurrency.DirCurrencyName + " (" + docSecondHandInvTabs.DirCurrencyRate + ", " + docSecondHandInvTabs.DirCurrencyMultiplicity + ")",

                    Exist = docSecondHandInvTabs.Exist,


                    DirSecondHandStatusName = docSecondHandInvTabs.dirSecondHandStatus.DirSecondHandStatusName,

                    //Exist

                    /*
                     * ExistName = docSecondHandInvTabs.Exist == 1 ? "Присутствует"
                     * :
                     * docSecondHandInvTabs.Exist == 2 ? "Списывается с ЗП"
                     * :
                     * docSecondHandInvTabs.Exist == 4 ? "Отсутствует"
                     * :
                     * "На разбор",
                     */
                    ExistName = docSecondHandInvTabs.Exist == 1 ? "Присутствует"
                            :
                                docSecondHandInvTabs.Exist == 2 ? "Отсутствует"
                            :
                                "????????????????",

                    //Цена в т.в.
                    PriceRetailCurrency = docSecondHandInvTabs.docSecondHandPurch.PriceRetailCurrency,
                    PriceCurrency = docSecondHandInvTabs.PriceCurrency,
                    //Себестоимость
                    SUMSalePriceVATCurrency = docSecondHandInvTabs.PriceCurrency == null ? 0
                            :
                                              Math.Round(docSecondHandInvTabs.PriceCurrency, sysSetting.FractionalPartInSum)
                }

                        #endregion
                    );

                #endregion


                #region Отправка JSON

                dynamic collectionWrapper = new
                {
                    sucess = true,
                    total  = query.Count(),
                    DocSecondHandInvTab = query
                };
                return(await Task.Run(() => Ok(collectionWrapper)));

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
        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
        }
Esempio n. 13
0
        // GET: api/DocSecondHandRazbor2Tabs
        public async Task <IHttpActionResult> GetDocSecondHandRazbor2Tabs(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, "RightDocSecondHandRazbors"));

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

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

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

                #endregion


                #region Параметры

                Params _params = new Params();

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

                #endregion



                #region Основной запрос *** *** ***

                var query =
                    (
                        from docSecondHandRazbor2Tabs in db.DocSecondHandRazbor2Tabs

                        join dirNomens11 in db.DirNomens on docSecondHandRazbor2Tabs.dirNomen.Sub equals dirNomens11.DirNomenID into dirNomens12
                        from dirNomensSubGroup in dirNomens12.DefaultIfEmpty()

                        join dirNomens21 in db.DirNomens on dirNomensSubGroup.Sub equals dirNomens21.DirNomenID into dirNomens22
                        from dirNomensGroup in dirNomens22.DefaultIfEmpty()

                        where docSecondHandRazbor2Tabs.DocSecondHandPurchID == _params.DocSecondHandPurchID

                        #region select

                        select new
                {
                    //партия
                    //RemPartyID = remParties.RemPartyID,
                    //DocSecondHandPurchID = docSecondHandRazbor2Tabs.DocSecondHandPurchID,

                    DocSecondHandRazbor2TabID = docSecondHandRazbor2Tabs.DocSecondHandRazbor2TabID,
                    DocSecondHandPurchID = docSecondHandRazbor2Tabs.DocSecondHandPurchID,
                    DirNomenID = docSecondHandRazbor2Tabs.DirNomenID,

                    //DirNomenName = docSecondHandRazbor2Tabs.dirNomen.DirNomenName,

                    /*
                     * DirNomenName =
                     * dirNomensSubGroup1.DirNomenName == null ? docSecondHandRazbor2Tabs.dirNomen.DirNomenName
                     * :
                     * dirNomensSubGroup1.DirNomenName + " / " + docSecondHandRazbor2Tabs.dirNomen.DirNomenName,
                     */

                    //DirNomenName = dirNomensGroup.DirNomenName + " / " + dirNomensSubGroup.DirNomenName + " / " + docSecondHandRazbor2Tabs.dirNomen.DirNomenName,
                    DirNomenName =
                        dirNomensSubGroup.DirNomenName == null ? docSecondHandRazbor2Tabs.dirNomen.DirNomenName :
                        dirNomensGroup.DirNomenName == null ? dirNomensSubGroup.DirNomenName + " / " + docSecondHandRazbor2Tabs.dirNomen.DirNomenName :
                        dirNomensGroup.DirNomenName + " / " + dirNomensSubGroup.DirNomenName + " / " + docSecondHandRazbor2Tabs.dirNomen.DirNomenName,


                    Quantity = docSecondHandRazbor2Tabs.Quantity,

                    PriceVAT = docSecondHandRazbor2Tabs.PriceVAT,

                    DirCurrencyID = docSecondHandRazbor2Tabs.DirCurrencyID,
                    DirCurrencyRate = docSecondHandRazbor2Tabs.DirCurrencyRate,
                    DirCurrencyMultiplicity = docSecondHandRazbor2Tabs.DirCurrencyMultiplicity,
                    DirCurrencyName = docSecondHandRazbor2Tabs.dirCurrency.DirCurrencyName + " (" + docSecondHandRazbor2Tabs.DirCurrencyRate + ", " + docSecondHandRazbor2Tabs.DirCurrencyMultiplicity + ")",


                    //Характеристики
                    DirCharColourID = docSecondHandRazbor2Tabs.DirCharColourID,
                    DirCharColourName = docSecondHandRazbor2Tabs.dirCharColour.DirCharColourName,
                    DirCharMaterialID = docSecondHandRazbor2Tabs.DirCharMaterialID,
                    DirCharMaterialName = docSecondHandRazbor2Tabs.dirCharMaterial.DirCharMaterialName,
                    DirCharNameID = docSecondHandRazbor2Tabs.DirCharNameID,
                    DirCharNameName = docSecondHandRazbor2Tabs.dirCharName.DirCharNameName,
                    DirCharSeasonID = docSecondHandRazbor2Tabs.DirCharSeasonID,
                    DirCharSeasonName = docSecondHandRazbor2Tabs.dirCharSeason.DirCharSeasonName,
                    DirCharSexID = docSecondHandRazbor2Tabs.DirCharSexID,
                    DirCharSexName = docSecondHandRazbor2Tabs.dirCharSex.DirCharSexName,
                    DirCharSizeID = docSecondHandRazbor2Tabs.DirCharSizeID,
                    DirCharSizeName = docSecondHandRazbor2Tabs.dirCharSize.DirCharSizeName,
                    DirCharStyleID = docSecondHandRazbor2Tabs.DirCharStyleID,
                    DirCharStyleName = docSecondHandRazbor2Tabs.dirCharStyle.DirCharStyleName,
                    DirContractorID = docSecondHandRazbor2Tabs.DirContractorID,
                    DirContractorName = docSecondHandRazbor2Tabs.dirContractor.DirContractorName,
                    DirCharTextureID = docSecondHandRazbor2Tabs.DirCharTextureID,
                    DirCharTextureName = docSecondHandRazbor2Tabs.dirCharTexture.DirCharTextureName,
                    DirChar =
                        docSecondHandRazbor2Tabs.dirCharColour.DirCharColourName + " " +
                        docSecondHandRazbor2Tabs.dirCharMaterial.DirCharMaterialName + " " +
                        docSecondHandRazbor2Tabs.dirCharName.DirCharNameName + " " +
                        docSecondHandRazbor2Tabs.dirCharSeason.DirCharSeasonName + " " +
                        docSecondHandRazbor2Tabs.dirCharSex.DirCharSexName + " " +
                        docSecondHandRazbor2Tabs.dirCharSize.DirCharSizeName + " " +
                        docSecondHandRazbor2Tabs.dirCharStyle.DirCharStyleName + " " +
                        docSecondHandRazbor2Tabs.dirContractor.DirContractorName + " " +
                        docSecondHandRazbor2Tabs.dirCharTexture.DirCharTextureName,
                    SerialNumber = docSecondHandRazbor2Tabs.SerialNumber,
                    Barcode = docSecondHandRazbor2Tabs.Barcode,


                    //Цена в т.в.
                    PriceCurrency = docSecondHandRazbor2Tabs.PriceCurrency,
                    //Себестоимость
                    SUMPurchPriceVATCurrency = docSecondHandRazbor2Tabs.Quantity * docSecondHandRazbor2Tabs.PriceCurrency == null ? 0
                            :
                                               Math.Round(docSecondHandRazbor2Tabs.Quantity * docSecondHandRazbor2Tabs.PriceCurrency, sysSetting.FractionalPartInSum),

                    //Розница ***
                    //Наценка
                    MarkupRetail = 100 * (docSecondHandRazbor2Tabs.PriceRetailVAT - docSecondHandRazbor2Tabs.PriceVAT) / docSecondHandRazbor2Tabs.PriceVAT == null ? 0
                            :
                                   Math.Round(100 * (docSecondHandRazbor2Tabs.PriceRetailVAT - docSecondHandRazbor2Tabs.PriceVAT) / docSecondHandRazbor2Tabs.PriceVAT, sysSetting.FractionalPartInSum),
                    //Розничная цена
                    PriceRetailVAT = docSecondHandRazbor2Tabs.PriceRetailVAT,
                    //Розничная цена в текущей валюте
                    PriceRetailCurrency = docSecondHandRazbor2Tabs.PriceRetailCurrency,

                    //Опт ***
                    //Наценка
                    MarkupWholesale = 100 * (docSecondHandRazbor2Tabs.PriceWholesaleVAT - docSecondHandRazbor2Tabs.PriceVAT) / docSecondHandRazbor2Tabs.PriceVAT == null ? 0
                            : Math.Round(100 * (docSecondHandRazbor2Tabs.PriceWholesaleVAT - docSecondHandRazbor2Tabs.PriceVAT) / docSecondHandRazbor2Tabs.PriceVAT, sysSetting.FractionalPartInSum),
                    //Оптовая цена
                    PriceWholesaleVAT = docSecondHandRazbor2Tabs.PriceWholesaleVAT,
                    //Оптовая цена в текущей валюте
                    PriceWholesaleCurrency = docSecondHandRazbor2Tabs.PriceWholesaleCurrency,

                    //Интерне-Магазин ***
                    //Наценка
                    MarkupIM = 100 * (docSecondHandRazbor2Tabs.PriceIMVAT - docSecondHandRazbor2Tabs.PriceVAT) / docSecondHandRazbor2Tabs.PriceVAT == null ? 0
                            : Math.Round(100 * (docSecondHandRazbor2Tabs.PriceIMVAT - docSecondHandRazbor2Tabs.PriceVAT) / docSecondHandRazbor2Tabs.PriceVAT, sysSetting.FractionalPartInSum),
                    //Интернет-Магазин
                    PriceIMVAT = docSecondHandRazbor2Tabs.PriceIMVAT,
                    //Интернет-Магазин в текущей валюте
                    PriceIMCurrency = docSecondHandRazbor2Tabs.PriceIMCurrency,

                    DirNomenMinimumBalance = docSecondHandRazbor2Tabs.DirNomenMinimumBalance
                }

                        #endregion
                    );

                #endregion


                #region Отправка JSON

                dynamic collectionWrapper = new
                {
                    sucess = true,
                    total  = query.Count(),
                    DocSecondHandRazbor2Tab = query
                };
                return(await Task.Run(() => Ok(collectionWrapper)));

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Esempio n. 14
0
        public async Task <IHttpActionResult> GetDirBonus2Tab(int id)
        {
            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, "RightDirBonuses"));

                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 Отправка JSON

                var query =
                    (
                        from dirBonus2Tabs in db.DirBonus2Tabs
                        where dirBonus2Tabs.DirBonus2ID == id
                        select new
                {
                    DirBonus2ID = dirBonus2Tabs.DirBonus2ID,
                    SumBegin = dirBonus2Tabs.SumBegin,
                    Bonus = dirBonus2Tabs.Bonus
                }
                    ).OrderBy(x => x.SumBegin);


                //К-во
                int dirCount = await Task.Run(() => query.Count());

                dynamic collectionWrapper = new
                {
                    sucess       = true,
                    total        = dirCount,
                    DirBonus2Tab = query
                };
                return(await Task.Run(() => Ok(collectionWrapper)));

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Esempio n. 15
0
        //UpdateDirBonusBar
        //SaveAccountBasic
        private void mPutPostDirBonus(
            Models.Sklad.Sys.SysSetting sysSettings,
            DirBonus dirBonus,
            //bool InsertUpdate, //true - Insert, false - Update
            EntityState entityState, //EntityState.Added, Modified
            Models.Sklad.Dir.DirBonusTab[] dirBonusTabCollection
            )
        {
            //using (TransactionScope ts = new TransactionScope())
            using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction())
            {
                #region 1. DirBonus *** *** *** *** *** *** *** *** *** ***

                db.Entry(dirBonus).State = entityState;
                db.SaveChanges();

                #endregion


                #region 2. DirBonusTab *** *** *** *** *** *** *** *** *** ***


                //3.2. Удаляем все кроме существующих
                //3.2.1. Формируем запрос
                var query2 =
                    (
                        from dirBonusTabs in db.DirBonusTabs
                        where dirBonusTabs.DirBonusID == dirBonus.DirBonusID // == id
                        select dirBonusTabs
                    ).ToList();
                //3.2.2. Удаляем каждую запись отдельно
                foreach (var dirBonusTab in query2)
                {
                    try
                    {
                        db.Entry(dirBonusTab).State = EntityState.Deleted;
                        db.SaveChanges();
                    }
                    catch (Exception ex) { ts.Rollback(); db.Database.Connection.Close(); throw new System.InvalidOperationException(Classes.Language.Sklad.Language.msg93 + ex.Message); }
                }



                //3.3. Проверяем, что бы была строгая градация:
                //     Меньшая сумма - меньшая скидка, при росте суммы - ростёт и скидка
                for (int i = 0; i < dirBonusTabCollection.Length; i++)
                {
                    for (int j = i + 1; j < dirBonusTabCollection.Length; j++)
                    {
                        //Суммы равны
                        if (dirBonusTabCollection[i].SumBegin == dirBonusTabCollection[j].SumBegin)
                        {
                            ts.Rollback(); db.Database.Connection.Close();
                            throw new System.InvalidOperationException(Classes.Language.Sklad.Language.msg58);
                        }
                        //Сумма больше, а скидка меньше
                        if (
                            (dirBonusTabCollection[i].SumBegin > dirBonusTabCollection[j].SumBegin && dirBonusTabCollection[i].Bonus < dirBonusTabCollection[j].Bonus)
                            ||
                            (dirBonusTabCollection[i].SumBegin <dirBonusTabCollection[j].SumBegin && dirBonusTabCollection[i].Bonus> dirBonusTabCollection[j].Bonus)
                            )
                        {
                            ts.Rollback(); db.Database.Connection.Close();
                            throw new System.InvalidOperationException(Classes.Language.Sklad.Language.msg58_1 + " (" + dirBonusTabCollection[i].SumBegin + "; " + dirBonusTabCollection[i].Bonus + "),  (" + dirBonusTabCollection[j].SumBegin + "; " + dirBonusTabCollection[j].Bonus + ")");
                        }
                    }
                }



                //3.34 Сохраняем
                for (int i = 0; i < dirBonusTabCollection.Count(); i++)
                {
                    dirBonusTabCollection[i].DirBonusID      = Convert.ToInt32(dirBonus.DirBonusID);
                    db.Entry(dirBonusTabCollection[i]).State = EntityState.Added;
                    db.SaveChanges();
                }
                //db.SaveChanges();

                #endregion



                #region 4. Подтверждение транзакции *** *** *** *** *** *** *** *** *** ***

                ts.Commit(); //.Complete();

                #endregion
            }
        }
Esempio n. 16
0
        public async Task <IHttpActionResult> PostDirWarehouse(DirWarehouse dirWarehouse)
        {
            #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, "RightDirWarehouses"));

            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 Проверки

            if (!ModelState.IsValid)
            {
                return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91)));                     //return BadRequest(ModelState);
            }
            //Подстановки - некоторые поля надо заполнить, если они не заполены
            //dirWarehouse.Substitute();

            #endregion


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

            try
            {
                //Используем метод, что бы было всё в одном потоке
                //db.Entry(dirWarehouse).State = EntityState.Added;
                //await Task.Run(() => db.SaveChangesAsync());

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

                    try
                    {
                        //Используем метод, что бы было всё в одном потоке
                        dirWarehouse = await Task.Run(() => mPutPostDirWarehouse(db, dirWarehouse, EntityState.Added, field));

                        ts.Commit(); //.Complete();
                    }
                    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))));
                    }
                }



                #region 6. JourDisp *** *** *** *** *** *** *** *** *** *

                Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp();
                sysJourDisp.DirDispOperationID = 3; //Добавление записи
                sysJourDisp.DirEmployeeID      = field.DirEmployeeID;
                sysJourDisp.ListObjectID       = ListObjectID;
                sysJourDisp.TableFieldID       = dirWarehouse.DirWarehouseID;
                sysJourDisp.Description        = "";
                try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { }

                #endregion


                dynamic collectionWrapper = new
                {
                    ID = dirWarehouse.DirWarehouseID
                };
                return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, ""));
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }

            #endregion
        }
Esempio n. 17
0
        public async Task <IHttpActionResult> DeleteDirWarehouse(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)
            int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDirWarehouses"));

            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 Удаление

            try
            {
                DirWarehouse dirWarehouse = await db.DirWarehouses.FindAsync(id);

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

                db.DirWarehouses.Remove(dirWarehouse);
                await db.SaveChangesAsync();


                #region 6. JourDisp *** *** *** *** *** *** *** *** *** *

                Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp();
                sysJourDisp.DirDispOperationID = 5; //Удаление записи
                sysJourDisp.DirEmployeeID      = field.DirEmployeeID;
                sysJourDisp.ListObjectID       = ListObjectID;
                sysJourDisp.TableFieldID       = dirWarehouse.DirWarehouseID;
                sysJourDisp.Description        = "";
                try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { }

                #endregion


                dynamic collectionWrapper = new
                {
                    ID  = dirWarehouse.DirWarehouseID,
                    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
        }
Esempio n. 18
0
        // GET: api/DirWarehouses
        public async Task <IHttpActionResult> GetDirWarehouses(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, "RightDirWarehouses"));
                //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 Параметры

                Params _params = new Params();

                //paramList -список параметров
                var paramList = request.GetQueryNameValuePairs();
                //Параметры
                _params.limit     = 999999;                                                                                           // sysSetting.PageSizeDir; //Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "limit", true) == 0).Value); //Записей на страницу
                _params.page      = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "page", true) == 0).Value); //Номер страницы
                _params.Skip      = _params.limit * (_params.page - 1);
                _params.type      = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "type", true) == 0).Value;
                _params.parSearch = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "parSearch", true) == 0).Value; if (_params.parSearch != null)
                {
                    _params.parSearch = _params.parSearch.ToLower();                                                                                                                                      //Поиск
                }
                _params.Sub = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "Sub", true) == 0).Value); if (_params.Sub == 0)
                {
                    _params.Sub = null;
                }
                //_params.WarehouseAll = Convert.ToBoolean(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "WarehouseAll", true) == 0).Value);

                //для документа "DocMovements" показать все склады
                _params.ListObjectID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "ListObjectID", true) == 0).Value);   //Склад привязанный к сотруднику

                #endregion


                if (_params.type == "Grid")
                {
                    //Если привязка к сотруднику (для документа "DocMovements" показать все склады)
                    if (field.DirEmployeeID != 1 && _params.ListObjectID != 33)
                    {
                        #region Основной запрос *** *** ***

                        var query =
                            (
                                from dirWarehouses in db.DirWarehouses
                                from x in db.DirEmployeeWarehouse

                                where dirWarehouses.Sub == _params.Sub && x.DirWarehouseID == dirWarehouses.DirWarehouseID && x.DirEmployeeID == field.DirEmployeeID
                                select new
                        {
                            DirWarehouseID = dirWarehouses.DirWarehouseID,
                            Sub = dirWarehouses.Sub,
                            Del = dirWarehouses.Del,
                            SysRecord = dirWarehouses.SysRecord,
                            DirWarehouseName = dirWarehouses.DirWarehouseName,
                            DirWarehouseAddress = dirWarehouses.DirWarehouseAddress,
                            Phone = dirWarehouses.Phone,

                            DirCashOfficeID = dirWarehouses.dirCashOffice.DirCashOfficeID,
                            DirCashOfficeName = dirWarehouses.dirCashOffice.DirCashOfficeName,
                            DirCurrencyID = dirWarehouses.dirCashOffice.DirCurrencyID,
                            DirCurrencyRate = dirWarehouses.dirCashOffice.dirCurrency.DirCurrencyRate,
                            DirCurrencyMultiplicity = dirWarehouses.dirCashOffice.dirCurrency.DirCurrencyMultiplicity,
                            DirCashOfficeSum = dirWarehouses.dirCashOffice.DirCashOfficeSum,

                            //DirWarehouseLocName = dirWarehouses.DirWarehouseLoc
                            DirWarehouseLocName =
                                dirWarehouses.DirWarehouseLoc == 1 ? SubWar1 :
                                dirWarehouses.DirWarehouseLoc == 2 ? SubWar2 :
                                dirWarehouses.DirWarehouseLoc == 3 ? SubWar3 :
                                dirWarehouses.DirWarehouseLoc == 4 ? SubWar4 :
                                dirWarehouses.DirWarehouseLoc == 5 ? SubWar5 :
                                "Ошибка!",

                            IsAdmin = x.IsAdmin,

                            //SalaryPercentTrade = dirWarehouses.SalaryPercentTrade,
                            //SalaryPercentService1Tabs = dirWarehouses.SalaryPercentService1Tabs,
                            //SalaryPercentService2Tabs = dirWarehouses.SalaryPercentService2Tabs,
                            //SalaryPercentSecond = dirWarehouses.SalaryPercentSecond,

                            //ККМ
                            KKMSActive = dirWarehouses.KKMSActive,

                            //Автоматическое закрытие смены
                            SmenaClose = dirWarehouses.SmenaClose,
                            SmenaCloseTime = dirWarehouses.SmenaCloseTime,
                        }
                            );

                        #endregion


                        #region Условия (параметры) *** *** ***


                        #region Не показывать удалённые

                        if (!Convert.ToBoolean(sysSetting.DeletedRecordsShow))
                        {
                            query = query.Where(x => x.Del == sysSetting.DeletedRecordsShow);
                        }

                        #endregion


                        #region Поиск

                        if (!String.IsNullOrEmpty(_params.parSearch))
                        {
                            //Проверяем число ли это
                            Int32 iNumber32;
                            bool  bResult32 = Int32.TryParse(_params.parSearch, out iNumber32);


                            //Если число, то задействуем в поиске и числовые поля (_params.parSearch == iNumber)
                            if (bResult32)
                            {
                                query = query.Where(x => x.DirWarehouseID == iNumber32 || x.DirWarehouseName.Contains(_params.parSearch) || x.DirWarehouseAddress.Contains(_params.parSearch));
                            }
                            else
                            {
                                query = query.Where(x => x.DirWarehouseName.Contains(_params.parSearch) || x.DirWarehouseAddress.Contains(_params.parSearch));
                            }
                        }

                        #endregion


                        //Если привязка к сотруднику (для документа "DocMovements" показать все склады)

                        /*
                         * if (field.DirEmployeeID != 1 && _params.ListObjectID != 33)
                         * {
                         *  //1. Получаем все склады к которым у Сотрудника есть доступ
                         *  var queryW = await Task.Run(() =>
                         *      (
                         *          from x in db.DirEmployeeWarehouse
                         *          where x.DirEmployeeID == field.DirEmployeeID
                         *          select x.DirWarehouseID
                         *      ).ToListAsync());
                         *
                         *  if (queryW.Count() > 0)
                         *  {
                         *      query = query.Where(x => queryW.Contains(x.DirWarehouseID));
                         *  }
                         * }
                         */


                        #region OrderBy и Лимит

                        query = query.OrderBy(x => x.DirWarehouseName).Skip(_params.Skip).Take(_params.limit);

                        #endregion


                        #endregion


                        #region Отправка JSON

                        //К-во Номенклатуры
                        int dirCount = await Task.Run(() => db.DirWarehouses.CountAsync());

                        //А вдруг к-во меньше Лимита, тогда показать не общее к-во, а реальное!
                        int dirCount2 = query.Count();
                        if (dirCount2 < _params.limit)
                        {
                            dirCount = _params.limit * (_params.page - 1) + dirCount2;
                        }

                        dynamic collectionWrapper = new
                        {
                            sucess       = true,
                            total        = dirCount,
                            DirWarehouse = query
                        };
                        return(await Task.Run(() => Ok(collectionWrapper)));

                        #endregion
                    }
                    else
                    {
                        #region Основной запрос *** *** ***

                        var query =
                            (
                                from dirWarehouses in db.DirWarehouses
                                where dirWarehouses.Sub == _params.Sub
                                select new
                        {
                            DirWarehouseID = dirWarehouses.DirWarehouseID,
                            Sub = dirWarehouses.Sub,
                            Del = dirWarehouses.Del,
                            SysRecord = dirWarehouses.SysRecord,
                            DirWarehouseName = dirWarehouses.DirWarehouseName,
                            DirWarehouseAddress = dirWarehouses.DirWarehouseAddress,
                            Phone = dirWarehouses.Phone,

                            DirCashOfficeID = dirWarehouses.dirCashOffice.DirCashOfficeID,
                            DirCashOfficeName = dirWarehouses.dirCashOffice.DirCashOfficeName,
                            DirCurrencyID = dirWarehouses.dirCashOffice.DirCurrencyID,
                            DirCurrencyRate = dirWarehouses.dirCashOffice.dirCurrency.DirCurrencyRate,
                            DirCurrencyMultiplicity = dirWarehouses.dirCashOffice.dirCurrency.DirCurrencyMultiplicity,
                            DirCashOfficeSum = dirWarehouses.dirCashOffice.DirCashOfficeSum,

                            //DirWarehouseLocName = dirWarehouses.DirWarehouseLoc
                            DirWarehouseLocName =
                                dirWarehouses.DirWarehouseLoc == 1 ? SubWar1 :
                                dirWarehouses.DirWarehouseLoc == 2 ? SubWar2 :
                                dirWarehouses.DirWarehouseLoc == 3 ? SubWar3 :
                                dirWarehouses.DirWarehouseLoc == 4 ? SubWar4 :
                                dirWarehouses.DirWarehouseLoc == 4 ? SubWar5 :
                                "Ошибка!",

                            //Админ - всегда Админ!
                            //IsAdmin = x.IsAdmin,

                            //ККМ
                            KKMSActive = dirWarehouses.KKMSActive,

                            //Автоматическое закрытие смены
                            SmenaClose = dirWarehouses.SmenaClose,
                            SmenaCloseTime = dirWarehouses.SmenaCloseTime,
                        }
                            );

                        #endregion


                        #region Условия (параметры) *** *** ***


                        #region Не показывать удалённые

                        if (!Convert.ToBoolean(sysSetting.DeletedRecordsShow))
                        {
                            query = query.Where(x => x.Del == sysSetting.DeletedRecordsShow);
                        }

                        #endregion


                        #region Поиск

                        if (!String.IsNullOrEmpty(_params.parSearch))
                        {
                            //Проверяем число ли это
                            Int32 iNumber32;
                            bool  bResult32 = Int32.TryParse(_params.parSearch, out iNumber32);


                            //Если число, то задействуем в поиске и числовые поля (_params.parSearch == iNumber)
                            if (bResult32)
                            {
                                query = query.Where(x => x.DirWarehouseID == iNumber32 || x.DirWarehouseName.Contains(_params.parSearch) || x.DirWarehouseAddress.Contains(_params.parSearch));
                            }
                            else
                            {
                                query = query.Where(x => x.DirWarehouseName.Contains(_params.parSearch) || x.DirWarehouseAddress.Contains(_params.parSearch));
                            }
                        }

                        #endregion


                        #region OrderBy и Лимит

                        query = query.OrderBy(x => x.DirWarehouseName).Skip(_params.Skip).Take(_params.limit);

                        #endregion


                        #endregion


                        #region Отправка JSON

                        //К-во Номенклатуры
                        int dirCount = await Task.Run(() => db.DirWarehouses.CountAsync());

                        //А вдруг к-во меньше Лимита, тогда показать не общее к-во, а реальное!
                        int dirCount2 = query.Count();
                        if (dirCount2 < _params.limit)
                        {
                            dirCount = _params.limit * (_params.page - 1) + dirCount2;
                        }

                        dynamic collectionWrapper = new
                        {
                            sucess       = true,
                            total        = dirCount,
                            DirWarehouse = query
                        };
                        return(await Task.Run(() => Ok(collectionWrapper)));

                        #endregion
                    }
                }
                else //Tree
                {
                    #region Отобразить только "Руты" *** *** ***

                    var query =
                        (
                            from x in db.DirWarehouses
                            where x.Sub == null && x.DirWarehouseID != _params.XGroupID_NotShow
                            select new
                    {
                        id = x.DirWarehouseID,
                        text = x.DirWarehouseName,
                        leaf = true,
                        Del = x.Del
                    }
                        );

                    #endregion


                    #region Отправка JSON

                    //return Ok(await Task.Run(() => query));

                    dynamic collectionWrapper = new
                    {
                        query
                    };
                    return(Ok(await Task.Run(() => collectionWrapper)));

                    #endregion
                }
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Esempio n. 19
0
        public async Task<IHttpActionResult> PutDirWarehouse(HttpRequestMessage request) //HttpPostedFileBase upload
        {
            #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

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

            // Проверяем Логин и Пароль
            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));
            //dbRead = 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, "RightDocAccounts"));
            if (iRight == 3) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)));
            */
            if(field.DirEmployeeID != 1) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57(0)));

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

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

            //Получаем сотрудника: если к нему привязан Склад и/или Организация, то выбираем документы только по этим характеристикам
            Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(field.DirEmployeeID);

            #endregion

            #region Параметры

            //paramList -список параметров
            var paramList = request.GetQueryNameValuePairs();
            //Параметры
            sheetName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "sheetName", true) == 0).Value;
            DirContractorIDOrg = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorIDOrg", true) == 0).Value);
            DirContractorID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorID", true) == 0).Value);
            DirWarehouseID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseID", true) == 0).Value);

            #endregion


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

            OleDbConnection OleDbConn = null;
            try
            {
                //Алгоритм:
                //0. Проверка
                //1. Генерируем ID-шник "SysGens"
                //2. Получаем файл и сохраняем в папаке "Uploads" с именем: authCookie["CookieB"] + "_" + sysGen.SysGenID

                //3. Считываем Эксель файл
                //   [Код товара], [Категория], [Товар]

                //Получаем категорию "APPLE/ iPhone 4S/  Распродажа/  Распродажа Swarovski /"
                //Разделитель "/" и убираем первый пробел
                //Проверяем каждую получиную категорию: есть ли связка (Sub, Name)
                //Если нет - вносим категорию, а потом товар: ([Код товара], [Товар])
                //Если есть - вносим товар: ([Код товара], [Товар])


                // *** Важно *** *** ***
                //1.Находим максимальный код группы
                //2.Создаём коды групп (Макс + 1)
                //3.Создаём коды товаров(из Эксель)



                #region 0. Проверка *** *** *** *** *** *** ***

                if (!Request.Content.IsMimeMultipartContent()) Ok(returnServer.Return(false, "{" + "'msgType':'1', 'msg':'" + Classes.Language.Sklad.Language.msg57(0) + "'}"));

                #endregion


                #region 1. Генерируем ID-шник "SysGens" *** *** *** *** *** *** ***

                Models.Sklad.Sys.SysGen sysGen = new Models.Sklad.Sys.SysGen(); sysGen.SysGenDisc = ""; sysGen.SysGenID = null;
                //if (!ModelState.IsValid) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91)); //return BadRequest(ModelState);
                db.Entry(sysGen).State = EntityState.Added;
                await db.SaveChangesAsync();

                #endregion


                #region 2. Получаем файл и сохраняем в папаке "Uploads" с именем: authCookie["CookieB"] + "_" + sysGen.SysGenID *** *** *** *** *** *** *** 

                string filePatch = "";
                var provider = new MultipartMemoryStreamProvider();
                string root = System.Web.HttpContext.Current.Server.MapPath("~/UsersTemp/FileStock/");
                await Request.Content.ReadAsMultipartAsync(provider);
                foreach (var file in provider.Contents)
                {
                    if (file.Headers.ContentDisposition.FileName != null)
                    {
                        var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                        var ext = Path.GetExtension(filename);
                        filePatch = root + field.DirCustomersID + "_" + sysGen.SysGenID + ext;

                        byte[] fileArray = await file.ReadAsByteArrayAsync();

                        using (System.IO.FileStream fs = new System.IO.FileStream(filePatch, System.IO.FileMode.Create)) //root + filename
                        {
                            await fs.WriteAsync(fileArray, 0, fileArray.Length);
                        }
                    }
                }

                #endregion


                #region 3. Получаем максимальный код группы

                var queryMaxGroupID = await Task.Run(() =>
                    (
                        from x in db.DirNomens
                        where x.DirNomenCategoryID == null
                        select x
                    ).MaxAsync(x => x.DirNomenID));

                iMaxGroupID = queryMaxGroupID + 1;
                if (iMaxGroupID == null || iMaxGroupID == 0) iMaxGroupID = 1;

                #endregion


                #region 4. Считываем Эксель файл

                if (filePatch.Length > 0)
                {
                    //1. Получаем категорию "APPLE/ iPhone 4S/  Распродажа/  Распродажа Swarovski /"
                    //2. Разделитель "/" и убираем первый пробел
                    //3. Проверяем каждую получиную категорию: есть ли связка (Sub, Name)
                    //4. Если нет - вносим категорию, а потом товар: ([Код товара], [Товар])
                    //5. Если есть - вносим товар: ([Код товара], [Товар])

                    string sExcelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePatch + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;\""; //8.0
                    using (OleDbConn = new OleDbConnection(sExcelConnectionString))
                    {
                        OleDbConn.Open();

                        using (OleDbCommand OleDbCmd = new OleDbCommand("", OleDbConn))
                        {
                            #region 1. Таблица "Товар"

                            OleDbCmd.CommandText = "SELECT * FROM [" + sheetName + "$]";
                            OleDbCmd.Parameters.Clear();
                            using (OleDbDataReader dr = OleDbCmd.ExecuteReader())
                            {
                                using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction())
                                {
                                    while (dr.Read())
                                    {
                                        if (dr["Код товара"].ToString().Length == 5)
                                        {
                                            //Read
                                            string DirNomenID = dr["Код товара"].ToString();
                                            string GroupList = dr["Категория"].ToString();
                                            string DirNomenName = dr["Товар"].ToString();

                                            //Create Group in database
                                            await Task.Run(() => GroupCreate(Convert.ToInt32(DirNomenID), GroupList, DirNomenName));
                                        }
                                        else
                                        {
                                            alCodeNot.Add(dr["Код товара"].ToString() + "  -  " + dr["Категория"].ToString() + "  -  " + dr["Товар"].ToString());

                                            //...
                                        }
                                    }

                                    ts.Commit();
                                }
                            }

                            #endregion


                            #region 2. Таблицы: Характеристики, Приходная накладная (Шапка + Спецификация), Остатки, Партии. (Новый алгоритм алгоритм: одна приходная накладная)



                            //1. Надо получить все точки из Эксель (GROUP BY)
                            //2. И делать SELECT по точкам, что бы сформировать приходные накладные по точкам
                            OleDbCmd.CommandText = "SELECT [Точка] FROM [" + sheetName + "$] GROUP BY [Точка] ORDER BY [Точка]";
                            OleDbCmd.Parameters.Clear();
                            ArrayList alDirWarehouseID = new ArrayList();
                            using (OleDbDataReader dr = OleDbCmd.ExecuteReader())
                            {
                                while (dr.Read())
                                {
                                    alDirWarehouseID.Add(dr["Точка"].ToString());
                                }
                            }



                            //Формируем "Приходные накладные"
                            using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction())
                            {
                                for (int i = 0; i < alDirWarehouseID.Count; i++)
                                {
                                    Models.Sklad.Doc.DocPurch docPurch = new Models.Sklad.Doc.DocPurch();


                                    ArrayList alWrite = new ArrayList();
                                    //OleDbCmd.CommandText = "SELECT * FROM [" + sheetName + "$] WHERE Дата=@pDate";
                                    OleDbCmd.CommandText = "SELECT * FROM [" + sheetName + "$] WHERE Точка=@Точка"; // ORDER BY [Код товара], [Дата] DESC
                                    OleDbCmd.Parameters.Clear();
                                    OleDbCmd.Parameters.AddWithValue("@Точка", alDirWarehouseID[i].ToString());

                                    using (OleDbDataReader dr = OleDbCmd.ExecuteReader())
                                    {
                                        while (dr.Read())
                                        {
                                            if (dr["Код товара"].ToString().Length == 5)
                                            {
                                                Field1 field1 = new Field1();
                                                field1.DirNomenID = Convert.ToInt32(dr["Код товара"].ToString());
                                                field1.DocDate = dr["Дата"].ToString();
                                                //field1.DirWarehouseID = ReturnDirWarehouseID(dr["Точка"].ToString());
                                                field1.DirWarehouseID = await Task.Run(() => ReturnDirWarehouseID(dr["Точка"].ToString()));
                                                field1.Quantity = Convert.ToInt32(dr["Остаток"].ToString());

                                                field1.PriceVAT = Convert.ToDouble(dr["Закуп цена за ед"].ToString());
                                                field1.PriceCurrency = Convert.ToDouble(dr["Закуп цена за ед"].ToString());

                                                field1.PriceRetailVAT = Convert.ToDouble(dr["Цена-1"].ToString());
                                                field1.PriceRetailCurrency = Convert.ToDouble(dr["Цена-1"].ToString());

                                                field1.PriceWholesaleVAT = Convert.ToDouble(dr["Цена-2"].ToString());
                                                field1.PriceWholesaleCurrency = Convert.ToDouble(dr["Цена-2"].ToString());

                                                field1.PriceIMVAT = Convert.ToDouble(dr["Цена-3"].ToString());
                                                field1.PriceIMCurrency = Convert.ToDouble(dr["Цена-3"].ToString());

                                                field1.DirCharColourID = ReturnDirCharColourID(dr["Поставщик"].ToString());
                                                field1.DirCharTextureID = ReturnDirCharTextureID(dr["Примечание"].ToString());

                                                alWrite.Add(field1);
                                            }
                                            else
                                            {
                                                //alCodeNot.Add(dr["Код товара"].ToString() + "  -  " + dr["Категория"].ToString() + "  -  " + dr["Товар"].ToString());

                                                //...
                                            }
                                        }
                                    }


                                    //Create Purchase documents and Remnants of goods in stock
                                    docPurch = await Task.Run(() => DocsCreate(alWrite));


                                    #region Чистим пустые партии товара, но только соотвутствующие Номеру документа, что бы НЕ удалить все пустые (0, 0)

                                    SQLiteParameter parDocID = new SQLiteParameter("@DocID", System.Data.DbType.Int32) { Value = docPurch.DocID };
                                    await db.Database.ExecuteSqlCommandAsync("DELETE FROM RemParties WHERE DocID=@DocID and Remnant=0; ", parDocID);

                                    #endregion

                                }


                                ts.Commit();
                            }

                            #endregion
                        }

                        OleDbConn.Close();
                    }

                }

                #endregion


                #region 5. Send

                dynamic collectionWrapper = new
                {
                    Msg = "Файл загружен!"
                };
                return Ok(returnServer.Return(true, collectionWrapper));

                #endregion

            }
            catch (Exception ex)
            {
                try { OleDbConn.Close(); OleDbConn.Dispose(); } catch { }
                return Ok(returnServer.Return(false, exceptionEntry.Return(ex) + i777.ToString()));
            }

            #endregion
        }
Esempio n. 20
0
        //db, dbRead, sysSetting, docSecondHandRazbor2Tab, EntityState.Added, field
        internal async Task <DocSecondHandRazbor2Tab> mPutPostDocSecondHandRazbor2Tab(
            DbConnectionSklad db,
            DbConnectionSklad dbRead,
            Models.Sklad.Sys.SysSetting sysSetting,
            DocSecondHandRazbor2Tab docSecondHandRazbor2Tab,
            EntityState entityState,          //EntityState.Added, Modified

            Classes.Account.Login.Field field //Дополнительные данные о сотруднике
            )
        {
            //Алгоритм
            //1. DirNomens (ищим: находим (ничего), не находим (новый)) и заполняем DocSecondHandRazbor2Tabs.DirNomenID
            //2. DocSecondHandRazbor2Tabs (сохраняем)
            //3. RemParties (создаём партию)


            #region 1. DirNomens
            //Иищим: находим (ничего), не находим (новый)
            //и заполняем DocSecondHandRazbor2Tabs.DirNomenID

            #region  Категория товара

            if (docSecondHandRazbor2Tab.DirNomenCategoryID == null)
            {
                var queryDirNomenCategoryID = await
                                              (
                    from x in db.DirNomenCategories
                    where x.DirNomenCategoryName == docSecondHandRazbor2Tab.DirNomenCategoryName
                    select x
                                              ).ToListAsync();
                if (queryDirNomenCategoryID.Count() > 0)
                {
                    docSecondHandRazbor2Tab.DirNomenCategoryID   = queryDirNomenCategoryID[0].DirNomenCategoryID;
                    docSecondHandRazbor2Tab.DirNomenCategoryName = queryDirNomenCategoryID[0].DirNomenCategoryName;
                }
                else
                {
                    Models.Sklad.Dir.DirNomenCategory dirNomenCategory = new Models.Sklad.Dir.DirNomenCategory();
                    dirNomenCategory.DirNomenCategoryName = docSecondHandRazbor2Tab.DirNomenCategoryName;

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

                    docSecondHandRazbor2Tab.DirNomenCategoryID   = dirNomenCategory.DirNomenCategoryID;
                    docSecondHandRazbor2Tab.DirNomenCategoryName = dirNomenCategory.DirNomenCategoryName;
                }
            }
            else
            {
                Models.Sklad.Dir.DirNomenCategory dirNomenCategory = await db.DirNomenCategories.FindAsync(docSecondHandRazbor2Tab.DirNomenCategoryID);

                docSecondHandRazbor2Tab.DirNomenCategoryName = dirNomenCategory.DirNomenCategoryName;
            }

            #endregion


            var query = await
                        (
                from x in db.DirNomens
                where x.Sub == docSecondHandRazbor2Tab.DirNomen2ID && x.DirNomenCategoryID == docSecondHandRazbor2Tab.DirNomenCategoryID
                select x
                        ).ToListAsync();
            if (query.Count() > 0)
            {
                docSecondHandRazbor2Tab.DirNomenID = query[0].DirNomenID;
            }
            else
            {
                Models.Sklad.Dir.DirNomen dirNomen = new Models.Sklad.Dir.DirNomen();
                dirNomen.Sub                = docSecondHandRazbor2Tab.DirNomen2ID;
                dirNomen.DirNomenTypeID     = 1;
                dirNomen.DirNomenName       = docSecondHandRazbor2Tab.DirNomenCategoryName;
                dirNomen.DirNomenCategoryID = docSecondHandRazbor2Tab.DirNomenCategoryID;
                dirNomen.DirNomenNameFull   = docSecondHandRazbor2Tab.DirNomenCategoryName;

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

                docSecondHandRazbor2Tab.DirNomenID = dirNomen.DirNomenID;
            }

            #endregion


            #region 2. DocSecondHandRazbor2Tabs

            db.Entry(docSecondHandRazbor2Tab).State = entityState;
            await db.SaveChangesAsync();

            #endregion


            #region 3. RemParties

            Models.Sklad.Doc.DocSecondHandPurch docSecondHandPurch = await db.DocSecondHandPurches.FindAsync(docSecondHandRazbor2Tab.DocSecondHandPurchID);


            Models.Sklad.Rem.RemParty remParty = new Models.Sklad.Rem.RemParty();
            remParty.RemPartyID    = null;
            remParty.DirNomenID    = Convert.ToInt32(docSecondHandRazbor2Tab.DirNomenID);
            remParty.Quantity      = docSecondHandRazbor2Tab.Quantity;
            remParty.Remnant       = docSecondHandRazbor2Tab.Quantity;
            remParty.DirCurrencyID = docSecondHandRazbor2Tab.DirCurrencyID;
            //remParty.DirCurrencyMultiplicity = docSecondHandRazbor2Tab.DirCurrencyMultiplicity;
            //remParty.DirCurrencyRate = docSecondHandRazbor2Tab.DirCurrencyRate;
            remParty.DirVatValue         = 0;                                                         // docPurch.DirVatValue;
            remParty.DirWarehouseID      = docSecondHandPurch.DirWarehouseID;                         // docPurch.DirWarehouseID;
            remParty.DirWarehouseIDDebit = docSecondHandPurch.DirWarehouseID;                         // docPurch.DirWarehouseID;
            remParty.DirWarehouseIDPurch = Convert.ToInt32(docSecondHandPurch.DirWarehouseIDPurches); // docPurch.DirWarehouseID;
            remParty.DirContractorIDOrg  = docSecondHandPurch.doc.DirContractorIDOrg;

            //!!! Важно !!!
            //if (docSecondHandRazbor2Tab.DirContractorID != null) remParty.DirContractorID = Convert.ToInt32(docSecondHandRazbor2Tab.DirContractorID);
            //else remParty.DirContractorID = docSecondHandPurch.DirContractorID;
            remParty.DirContractorID = docSecondHandPurch.doc.DirContractorIDOrg;
            //!!! Важно !!!

            //Дата Приёмки товара
            remParty.DocDatePurches = docSecondHandPurch.doc.DocDate;

            remParty.DirCharColourID   = docSecondHandRazbor2Tab.DirCharColourID;
            remParty.DirCharMaterialID = docSecondHandRazbor2Tab.DirCharMaterialID;
            remParty.DirCharNameID     = docSecondHandRazbor2Tab.DirCharNameID;
            remParty.DirCharSeasonID   = docSecondHandRazbor2Tab.DirCharSeasonID;
            remParty.DirCharSexID      = docSecondHandRazbor2Tab.DirCharSexID;
            remParty.DirCharSizeID     = docSecondHandRazbor2Tab.DirCharSizeID;
            remParty.DirCharStyleID    = docSecondHandRazbor2Tab.DirCharStyleID;
            remParty.DirCharTextureID  = docSecondHandRazbor2Tab.DirCharTextureID;

            remParty.SerialNumber = docSecondHandRazbor2Tab.SerialNumber;
            remParty.Barcode      = docSecondHandRazbor2Tab.Barcode;

            remParty.DocID         = Convert.ToInt32(docSecondHandPurch.DocID);
            remParty.PriceCurrency = docSecondHandRazbor2Tab.PriceCurrency;
            remParty.PriceVAT      = docSecondHandRazbor2Tab.PriceVAT;
            remParty.FieldID       = Convert.ToInt32(docSecondHandRazbor2Tab.DocSecondHandRazbor2TabID);

            remParty.PriceRetailVAT         = docSecondHandRazbor2Tab.PriceRetailVAT;
            remParty.PriceRetailCurrency    = docSecondHandRazbor2Tab.PriceRetailCurrency;
            remParty.PriceWholesaleVAT      = docSecondHandRazbor2Tab.PriceWholesaleVAT;
            remParty.PriceWholesaleCurrency = docSecondHandRazbor2Tab.PriceWholesaleCurrency;
            remParty.PriceIMVAT             = docSecondHandRazbor2Tab.PriceIMVAT;
            remParty.PriceIMCurrency        = docSecondHandRazbor2Tab.PriceIMCurrency;

            //DirNomenMinimumBalance
            remParty.DirNomenMinimumBalance = sysSetting.DirNomenMinimumBalance;

            remParty.DirEmployeeID = docSecondHandPurch.doc.DirEmployeeID;
            remParty.DocDate       = docSecondHandPurch.doc.DocDate;


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


            #endregion


            #region 3. Лог: Пишем в Лог о смене статуса и мастера, если такое было

            logService.DocSecondHandPurchID   = docSecondHandRazbor2Tab.DocSecondHandPurchID;
            logService.DirSecondHandLogTypeID = 6; //Смена статуса
            logService.DirEmployeeID          = field.DirEmployeeID;
            //logService.DirSecondHandStatusID = DirSecondHandStatusID;
            logService.Msg = "Разборка: добавили запчасть: " + docSecondHandRazbor2Tab.dirNomen.DirNomenName;

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

            #endregion


            return(docSecondHandRazbor2Tab);
        }
Esempio n. 21
0
        public async Task <IHttpActionResult> DeleteDirBonus(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)
            int iRight = await Task.Run(() => accessRight.Access(connectionString.Return(field.DirCustomersID, null, true), field.DirEmployeeID, "RightDirBonuses"));

            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 Удаление

            try
            {
                DirBonus dirBonus = await db.DirBonuses.FindAsync(id);

                if (dirBonus == null)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg99)));
                }
                //if (dirBonus.SysRecord) return Ok(returnServer.Return(false, Classes.Language.Language.msg98));


                #region 6. JourDisp *** *** *** *** *** *** *** *** *** *

                Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp();
                sysJourDisp.DirDispOperationID = 5; //Удаление записи
                sysJourDisp.DirEmployeeID      = field.DirEmployeeID;
                sysJourDisp.ListObjectID       = ListObjectID;
                sysJourDisp.TableFieldID       = id;
                sysJourDisp.Description        = "";
                try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { }

                #endregion


                if (!dirBonus.Del)
                {
                    // === Удаляем === === === === ===

                    //2. Для каскадного удаления "Договора" (достаточно сделать выборку с ToList() в одном подключении)
                    var queryDirBonusTabs = await db.DirBonusTabs.Where(x => x.DirBonusID == id).ToListAsync();

                    //3. Удаляем
                    try
                    {
                        db.DirBonuses.Remove(dirBonus);
                        await db.SaveChangesAsync();

                        dynamic collectionWrapper = new
                        {
                            ID  = dirBonus.DirBonusID,
                            Msg = Classes.Language.Sklad.Language.msg19
                        };
                        return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, ""));
                    }
                    catch (Exception ex)
                    {
                        if (function.ExceptionFkExist(ex))
                        {
                            //2. Исключение - пометка на удаление
                            dirBonus.Del = true;

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

                            dynamic collectionWrapper = new
                            {
                                ID  = dirBonus.DirBonusID,
                                Msg = Classes.Language.Sklad.Language.msg96           //"Помечено на удаление, так как запись задействована в других объектах сервиса (напр. в документах)."
                            };
                            return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, ""));
                        }
                        else
                        {
                            return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
                        }
                    }
                }
                else
                {
                    // === Снимаем пометку на удаление === === === === ===

                    dirBonus.Del = false;

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

                    dynamic collectionWrapper = new
                    {
                        ID  = dirBonus.DirBonusID,
                        Msg = Classes.Language.Sklad.Language.msg97           //"Пометка на удаление снята."
                    };
                    return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, ""));
                }
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }

            #endregion
        }
        internal string GenerateSQLSelectCollection2(Models.Sklad.Sys.SysSetting sysSettings)
        {
            string SQL = "";

            //Используем оператор "UNION ALL"

            SQL =

                //DocServicePurch2Tabs *** *** ***

                "SELECT " +
                "'Работа' AS TabNum, " +
                "[Docs].[DirVatValue] AS [DirVatValue], " +
                //"[DirNomens].[DirNomenName] AS [DirNomenName], " +
                "[DirCurrencies].[DirCurrencyName] || ' (' || [DocServicePurch2Tabs].[DirCurrencyRate] || ', ' || [DocServicePurch2Tabs].[DirCurrencyMultiplicity] || ')' AS [DirCurrencyName], " +
                "[DocServicePurch2Tabs].[PriceVAT] AS [PriceVAT], " +
                "[DocServicePurch2Tabs].[PriceCurrency] AS [PriceCurrency], " +
                "[DocServicePurch2Tabs].[DirCurrencyRate] AS [DirCurrencyRate], " +
                "[DocServicePurch2Tabs].[DirCurrencyMultiplicity] AS [DirCurrencyMultiplicity], " +
                "[DirEmployees].[DirEmployeeName] AS [DirEmployeeName], " +

                //Прочерк
                "'-' AS FieldDash, " +
                //Пустое поле
                "' ' AS FieldEmpty, " +



                //Товар *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                "CASE " +
                "WHEN ([dirNomensGroup].[DirNomenName] IS NULL) THEN [dirNomensSubGroup].[DirNomenName] " +

                "WHEN ([DirNomens].[DirNomenName] IS NULL) THEN " +

                "CASE WHEN ([dirNomensSubGroup].[DirNomenName] IS NULL) THEN '' ELSE [dirNomensSubGroup].[DirNomenName] END || ' / ' || " +
                "CASE WHEN ([dirNomensGroup].[DirNomenName] IS NULL) THEN '' ELSE [dirNomensGroup].[DirNomenName] END ELSE " +

                "CASE WHEN ([dirNomensSubGroup].[DirNomenName] IS NULL) THEN '' ELSE [dirNomensSubGroup].[DirNomenName] END || ' / ' || " +
                "CASE WHEN ([dirNomensGroup].[DirNomenName] IS NULL) THEN '' ELSE [dirNomensGroup].[DirNomenName] END || ' / ' || " +
                "CASE WHEN ([DirNomens].[DirNomenName] IS NULL) THEN '' ELSE [DirNomens].[DirNomenName] END END AS [DirNomenName] " +
                //Товар *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***



                "FROM [Docs], [DocServicePurches] " +
                "INNER JOIN [DocServicePurch2Tabs] AS [DocServicePurch2Tabs] ON [DocServicePurch2Tabs].[DocServicePurchID] = [DocServicePurches].[DocServicePurchID]  and [DocServicePurch2Tabs].RemontN=(SELECT MAX(RemontN) FROM [DocServicePurch2Tabs] WHERE [DocServicePurch2Tabs].[DocServicePurchID] = [DocServicePurches].[DocServicePurchID]) " + // and [DocServicePurch2Tabs].PayDate>=(SELECT MAX(PayDate) FROM [DocServicePurch2Tabs] WHERE [DocServicePurch2Tabs].[DocServicePurchID] = [DocServicePurches].[DocServicePurchID])
                "INNER JOIN [DirCurrencies] ON [DocServicePurch2Tabs].[DirCurrencyID] = [DirCurrencies].[DirCurrencyID] " +
                "INNER JOIN [DirEmployees] ON [DocServicePurch2Tabs].[DirEmployeeID] = [DirEmployees].[DirEmployeeID] " +

                //Товар *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                "LEFT JOIN [DirNomens] AS [DirNomens] ON [DirNomens].[DirNomenID] = [DocServicePurch2Tabs].[DirNomenID] " +
                "LEFT JOIN [DirNomens] AS [dirNomensGroup] ON [DirNomens].[Sub] = [dirNomensGroup].[DirNomenID] " +
                "LEFT JOIN [DirNomens] AS [dirNomensSubGroup] ON [dirNomensGroup].[Sub] = [dirNomensSubGroup].[DirNomenID] " +
                //Товар *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

                "WHERE " +
                "([Docs].[DocID]=[DocServicePurches].[DocID])and" +
                "(Docs.DocID=@DocID)";
            //"( [DocServicePurch2Tabs].PayDate=(SELECT MAX(PayDate) FROM [DocServicePurch2Tabs] WHERE [DocServicePurch2Tabs].[DocServicePurchID] = [DocServicePurches].[DocServicePurchID]) )";


            return(SQL);
        }
Esempio n. 23
0
        // GET: api/DirBonuses
        public async Task <IHttpActionResult> GetDirBonuses(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, "RightDirBonuses"));

                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 Параметры

                Params _params = new Params();

                //paramList -список параметров
                var paramList = request.GetQueryNameValuePairs();
                //Параметры
                _params.limit     = 999999;                                                                                           // sysSetting.PageSizeDir; //Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "limit", true) == 0).Value); //Записей на страницу
                _params.page      = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "page", true) == 0).Value); //Номер страницы
                _params.Skip      = _params.limit * (_params.page - 1);
                _params.type      = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "type", true) == 0).Value;
                _params.parSearch = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "parSearch", true) == 0).Value; if (_params.parSearch != null)
                {
                    _params.parSearch = _params.parSearch.ToLower();                                                                                                                                      //Поиск
                }
                #endregion


                if (_params.type == "Grid")
                {
                    #region Основной запрос *** *** ***

                    var query =
                        (
                            from x in db.DirBonuses
                            select new
                    {
                        DirBonusID = x.DirBonusID,
                        Del = x.Del,
                        DirBonusName = x.DirBonusName
                    }
                        );

                    #endregion


                    #region Условия (параметры) *** *** ***


                    #region Не показывать удалённые

                    if (!Convert.ToBoolean(sysSetting.DeletedRecordsShow))
                    {
                        query = query.Where(x => x.Del == sysSetting.DeletedRecordsShow);
                    }

                    #endregion


                    #region Поиск

                    if (!String.IsNullOrEmpty(_params.parSearch))
                    {
                        //Проверяем число ли это
                        Int32 iNumber32;
                        bool  bResult32 = Int32.TryParse(_params.parSearch, out iNumber32);


                        //Если число, то задействуем в поиске и числовые поля (_params.parSearch == iNumber)
                        if (bResult32)
                        {
                            query = query.Where(x => x.DirBonusID == iNumber32 || x.DirBonusName.Contains(_params.parSearch));
                        }
                        else
                        {
                            query = query.Where(x => x.DirBonusName.Contains(_params.parSearch));
                        }
                    }

                    #endregion


                    #region OrderBy и Лимит

                    query = query.OrderBy(x => x.DirBonusName); //.Skip(_params.Skip).Take(_params.limit);

                    #endregion


                    #endregion


                    #region Отправка JSON

                    //К-во Номенклатуры
                    int dirCount = await Task.Run(() => db.DirBonuses.Count());

                    //А вдруг к-во меньше Лимита, тогда показать не общее к-во, а реальное!
                    int dirCount2 = query.Count();
                    //if (dirCount2 < _params.limit) dirCount = _params.limit * (_params.page - 1) + dirCount2;

                    dynamic collectionWrapper = new
                    {
                        sucess   = true,
                        total    = dirCount,
                        DirBonus = query
                    };
                    return(await Task.Run(() => Ok(collectionWrapper)));

                    #endregion
                }
                else //Tree
                {
                    #region Отобразить только "Руты" *** *** ***

                    var query =
                        (
                            from x in db.DirBonuses
                            select new
                    {
                        id = x.DirBonusID,
                        text = x.DirBonusName,
                        leaf = true,
                        Del = x.Del
                    }
                        );

                    #endregion


                    #region Отправка JSON

                    //return Ok(await Task.Run(() => query));

                    dynamic collectionWrapper = new
                    {
                        query
                    };
                    return(Ok(await Task.Run(() => collectionWrapper)));

                    #endregion
                }
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Esempio n. 24
0
        public async Task <IHttpActionResult> PostDocSecondHandRazbor2Tab(DocSecondHandRazbor2Tab docSecondHandRazbor2Tab, HttpRequestMessage request)
        {
            //Алгоритм
            //1. DirNomens (ищим: находим (ничего), не находим (новый)) и заполняем DocSecondHandRazbor2Tabs.DirNomenID
            //2. DocSecondHandRazbor2Tabs (сохраняем)
            //3. Партии (создаём партию)

            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));
                dbRead = 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, "RightDocSecondHandRazbors"));

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

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

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

                #endregion

                #region Параметры

                //save, save_close, held, held_cancel
                var paramList = request.GetQueryNameValuePairs();
                docSecondHandRazbor2Tab.DocSecondHandPurchID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocSecondHandPurchID", true) == 0).Value);

                #endregion

                #region Проверки

                if (!ModelState.IsValid)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91)));                     //return BadRequest(ModelState);
                }
                //Если документ "docSecondHandRazbor2Tab.DocSecondHandPurchID" проведён, то выдать Эксепшн

                /*
                 * Models.Sklad.Doc.DocSecondHandRazbor docSecondHandRazbor = await db.DocSecondHandRazbors.FindAsync(docSecondHandRazbor2Tab.DocSecondHandPurchID);
                 * //Models.Sklad.Doc.Doc doc = await db.Docs.FindAsync(docSecondHandRazbor.DocID);
                 * if (Convert.ToBoolean(docSecondHandRazbor.doc.Held)) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57_3));
                 */
                Models.Sklad.Doc.DocSecondHandPurch docSecondHandPurch = await db.DocSecondHandPurches.FindAsync(docSecondHandRazbor2Tab.DocSecondHandPurchID);

                if (docSecondHandPurch == null)
                {
                    return(Ok(returnServer.Return(false, "Документ (аппарат) не найден №" + docSecondHandRazbor2Tab.DocSecondHandPurchID)));
                }
                else
                {
                    if (docSecondHandPurch.DirSecondHandStatusID != 12)
                    {
                        return(Ok(returnServer.Return(false, "Для добавление запчастей, статус документа должен быть '12.В разборе'. А он " + docSecondHandPurch.DirSecondHandStatusID + "." + docSecondHandPurch.dirSecondHandStatus.DirSecondHandStatusName)));
                    }
                }

                //Подстановки - некоторые поля надо заполнить, если они не заполены (Юридические реквизиты)
                //docSecondHandRazbor2Tab.Substitute();

                #endregion


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

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

                    try
                    {
                        //Используем метод, что бы было всё в одном потоке
                        docSecondHandRazbor2Tab = await Task.Run(() => mPutPostDocSecondHandRazbor2Tab(db, dbRead, sysSetting, docSecondHandRazbor2Tab, EntityState.Added, field)); //sysSetting

                        ts.Commit();                                                                                                                                                //.Complete();
                    }
                    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))));
                    }
                }


                #region 6. JourDisp *** *** *** *** *** *** *** *** *** *

                Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp();
                sysJourDisp.DirDispOperationID = 3; //Добавление записи
                sysJourDisp.DirEmployeeID      = field.DirEmployeeID;
                sysJourDisp.ListObjectID       = ListObjectID;
                sysJourDisp.TableFieldID       = docSecondHandRazbor2Tab.DocSecondHandPurchID;
                sysJourDisp.Description        = "";
                try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { }

                #endregion


                dynamic collectionWrapper = new
                {
                    DocSecondHandRazbor2TabID = docSecondHandRazbor2Tab.DocSecondHandRazbor2TabID
                };
                return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, ""));

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
        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))));
            }
        }
        // GET: api/DocSecondHandRetailReturnTabs
        public async Task <IHttpActionResult> GetDocSecondHandRetailReturnTabs(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, "RightDocSecondHandRetailReturns"));

                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 Параметры

                Params _params = new Params();

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

                _params.DateS = Convert.ToDateTime(Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DateS", true) == 0).Value).ToString("yyyy-MM-dd 23:59:59"));
                if (_params.DateS < Convert.ToDateTime("01.01.1800"))
                {
                    _params.DateS = Convert.ToDateTime(sysSetting.JurDateS.ToString("yyyy-MM-dd 00:00:00")).AddDays(-1);
                }
                else
                {
                    _params.DateS = _params.DateS.Value.AddDays(-1);
                }

                _params.DatePo = Convert.ToDateTime(Convert.ToDateTime(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocDate", true) == 0).Value).ToString("yyyy-MM-dd 23:59:59"));
                if (_params.DatePo < Convert.ToDateTime("01.01.1800"))
                {
                    _params.DatePo = Convert.ToDateTime(sysSetting.JurDatePo.ToString("yyyy-MM-dd 23:59:59"));
                }

                _params.DirWarehouseID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseID", true) == 0).Value);

                #endregion



                #region Основной запрос *** *** ***

                var query =
                    (
                        from docSecondHandRetailReturnTabs in db.DocSecondHandRetailReturnTabs

                        join dirServiceNomens11 in db.DirServiceNomens on docSecondHandRetailReturnTabs.dirServiceNomen.Sub equals dirServiceNomens11.DirServiceNomenID into dirServiceNomens12
                        from dirServiceNomensSubGroup in dirServiceNomens12.DefaultIfEmpty()

                        join dirServiceNomens21 in db.DirServiceNomens on dirServiceNomensSubGroup.Sub equals dirServiceNomens21.DirServiceNomenID into dirServiceNomens22
                        from dirServiceNomensGroup in dirServiceNomens22.DefaultIfEmpty()

                        /*
                         * //Характеристики
                         * join dirCharColours1 in db.DirCharColours on docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharColourID equals dirCharColours1.DirCharColourID into dirCharColours2
                         * from dirCharColours in dirCharColours2.DefaultIfEmpty()
                         *
                         * join dirCharMaterials1 in db.DirCharMaterials on docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharMaterialID equals dirCharMaterials1.DirCharMaterialID into dirCharMaterials2
                         * from dirCharMaterials in dirCharMaterials2.DefaultIfEmpty()
                         *
                         * join dirCharNames1 in db.DirCharNames on docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharNameID equals dirCharNames1.DirCharNameID into dirCharNames2
                         * from dirCharNames in dirCharNames2.DefaultIfEmpty()
                         *
                         * join dirCharSeasons1 in db.DirCharSeasons on docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharSeasonID equals dirCharSeasons1.DirCharSeasonID into dirCharSeasons2
                         * from dirCharSeasons in dirCharSeasons2.DefaultIfEmpty()
                         *
                         * join dirCharSexes1 in db.DirCharSexes on docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharSexID equals dirCharSexes1.DirCharSexID into dirCharSexes2
                         * from dirCharSexes in dirCharSexes2.DefaultIfEmpty()
                         *
                         * join dirCharSizes1 in db.DirCharSizes on docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharSizeID equals dirCharSizes1.DirCharSizeID into dirCharSizes2
                         * from dirCharSizes in dirCharSizes2.DefaultIfEmpty()
                         *
                         * join dirCharStyles1 in db.DirCharStyles on docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharStyleID equals dirCharStyles1.DirCharStyleID into dirCharStyles2
                         * from dirCharStyles in dirCharStyles2.DefaultIfEmpty()
                         *
                         * join dirCharTextures1 in db.DirCharTextures on docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharTextureID equals dirCharTextures1.DirCharTextureID into dirCharTextures2
                         * from dirCharTextures in dirCharTextures2.DefaultIfEmpty()
                         */

                        //where docSecondHandRetailReturnTabs.DocSecondHandRetailReturnID == _params.DocSecondHandRetailReturnID

                        #region select

                        select new
                {
                    DocID = docSecondHandRetailReturnTabs.docSecondHandRetailReturn.DocID,
                    DocDate = docSecondHandRetailReturnTabs.docSecondHandRetailReturn.doc.DocDate,
                    Held = docSecondHandRetailReturnTabs.docSecondHandRetailReturn.doc.Held,
                    Discount = docSecondHandRetailReturnTabs.docSecondHandRetailReturn.doc.Discount,
                    DirWarehouseID = docSecondHandRetailReturnTabs.docSecondHandRetailReturn.DirWarehouseID,

                    //партия
                    Rem2PartyMinusID = docSecondHandRetailReturnTabs.rem2PartyMinus.Rem2PartyMinusID,

                    DocSecondHandRetailReturnTabID = docSecondHandRetailReturnTabs.DocSecondHandRetailReturnTabID,
                    DocSecondHandRetailReturnID = docSecondHandRetailReturnTabs.DocSecondHandRetailReturnID,
                    DirServiceNomenID = docSecondHandRetailReturnTabs.DirServiceNomenID,

                    //DirServiceNomenName = docSecondHandRetailReturnTabs.dirServiceNomen.DirServiceNomenName,
                    DirServiceNomenName =
                        dirServiceNomensSubGroup.DirServiceNomenName == null ? docSecondHandRetailReturnTabs.dirServiceNomen.DirServiceNomenName :
                        dirServiceNomensGroup.DirServiceNomenName == null ? dirServiceNomensSubGroup.DirServiceNomenName + " / " + docSecondHandRetailReturnTabs.dirServiceNomen.DirServiceNomenName :
                        dirServiceNomensGroup.DirServiceNomenName + " / " + dirServiceNomensSubGroup.DirServiceNomenName + " / " + docSecondHandRetailReturnTabs.dirServiceNomen.DirServiceNomenName,

                    Quantity = docSecondHandRetailReturnTabs.Quantity,
                    PriceVAT = docSecondHandRetailReturnTabs.PriceVAT,

                    DirCurrencyID = docSecondHandRetailReturnTabs.DirCurrencyID,
                    DirCurrencyRate = docSecondHandRetailReturnTabs.DirCurrencyRate,
                    DirCurrencyMultiplicity = docSecondHandRetailReturnTabs.DirCurrencyMultiplicity,
                    DirCurrencyName = docSecondHandRetailReturnTabs.dirCurrency.DirCurrencyName + " (" + docSecondHandRetailReturnTabs.DirCurrencyRate + ", " + docSecondHandRetailReturnTabs.DirCurrencyMultiplicity + ")",

                    DirEmployeeName = docSecondHandRetailReturnTabs.docSecondHandRetailReturn.doc.dirEmployee.DirEmployeeName,

                    //Характеристики

                    /*
                     * DirCharColourID = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharColourID,
                     * DirCharColourName = dirCharColours.DirCharColourName,
                     * DirCharMaterialID = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharMaterialID,
                     * DirCharMaterialName = dirCharMaterials.DirCharMaterialName,
                     * DirCharNameID = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharNameID,
                     * DirCharNameName = dirCharNames.DirCharNameName,
                     * DirCharSeasonID = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharSeasonID,
                     * DirCharSeasonName = dirCharSeasons.DirCharSeasonName,
                     * DirCharSexID = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharSexID,
                     * DirCharSexName = dirCharSexes.DirCharSexName,
                     * DirCharSizeID = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharSizeID,
                     * DirCharSizeName = dirCharSizes.DirCharSizeName,
                     * DirCharStyleID = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharStyleID,
                     * DirCharStyleName = dirCharStyles.DirCharStyleName,
                     * DirCharTextureID = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharTextureID,
                     * DirCharTextureName = dirCharTextures.DirCharTextureName,
                     * DirChar =
                     *  dirCharColours.DirCharColourName + " " +
                     *  dirCharMaterials.DirCharMaterialName + " " +
                     *  dirCharNames.DirCharNameName + " " +
                     *  dirCharSeasons.DirCharSeasonName + " " +
                     *  dirCharSexes.DirCharSexName + " " +
                     *  dirCharSizes.DirCharSizeName + " " +
                     *  dirCharStyles.DirCharStyleName + " " +
                     *  dirCharTextures.DirCharTextureName,
                     */
                    SerialNumber = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.SerialNumber,
                    Barcode = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.Barcode,


                    //Цена в т.в.
                    PriceCurrency = docSecondHandRetailReturnTabs.PriceCurrency,
                    //Себестоимость
                    SUMPurchPriceVATCurrency = docSecondHandRetailReturnTabs.Quantity * docSecondHandRetailReturnTabs.PriceCurrency == null ? 0
                            : Math.Round(docSecondHandRetailReturnTabs.Quantity * docSecondHandRetailReturnTabs.PriceCurrency, sysSetting.FractionalPartInSum),


                    //Розница ***
                    //Наценка
                    MarkupRetail = 100 * (docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceRetailVAT - docSecondHandRetailReturnTabs.PriceVAT) / docSecondHandRetailReturnTabs.PriceVAT == null ? 0
                            : Math.Round(100 * (docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceRetailVAT - docSecondHandRetailReturnTabs.PriceVAT) / docSecondHandRetailReturnTabs.PriceVAT, sysSetting.FractionalPartInSum),
                    //Розничная цена
                    PriceRetailVAT = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceRetailVAT,
                    //Розничная цена в текущей валюте
                    PriceRetailCurrency = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceRetailCurrency,

                    //Опт ***
                    //Наценка
                    MarkupWholesale = 100 * (docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceWholesaleVAT - docSecondHandRetailReturnTabs.PriceVAT) / docSecondHandRetailReturnTabs.PriceVAT == null ? 0
                            : Math.Round(100 * (docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceWholesaleVAT - docSecondHandRetailReturnTabs.PriceVAT) / docSecondHandRetailReturnTabs.PriceVAT, sysSetting.FractionalPartInSum)
                    ,
                    //Оптовая цена
                    PriceWholesaleVAT = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceWholesaleVAT,
                    //Оптовая цена в текущей валюте
                    PriceWholesaleCurrency = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceWholesaleCurrency,

                    //Интерне-Магазин ***
                    //Наценка
                    MarkupIM = 100 * (docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceIMVAT - docSecondHandRetailReturnTabs.PriceVAT) / docSecondHandRetailReturnTabs.PriceVAT == null ? 0
                            : Math.Round(100 * (docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceIMVAT - docSecondHandRetailReturnTabs.PriceVAT) / docSecondHandRetailReturnTabs.PriceVAT, sysSetting.FractionalPartInSum)
                    ,
                    //Интернет-Магазин
                    PriceIMVAT = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceIMVAT,
                    //Интернет-Магазин в текущей валюте
                    PriceIMCurrency = docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.PriceIMCurrency,
                }

                        #endregion
                    );


                //Параметры
                //1. По документу
                if (_params.DocSecondHandRetailReturnID > 0)
                {
                    query = query.Where(x => x.DocSecondHandRetailReturnID == _params.DocSecondHandRetailReturnID);
                }
                //2. По дате
                if (_params.DateS != null)
                {
                    query = query.Where(x => x.DocDate >= _params.DateS && x.DocDate <= _params.DatePo);
                }
                //3. Склад
                if (_params.DirWarehouseID > 0)
                {
                    query = query.Where(x => x.DirWarehouseID == _params.DirWarehouseID);
                }


                #endregion


                #region Отправка JSON

                dynamic collectionWrapper = new
                {
                    sucess = true,
                    total  = query.Count(),
                    DocSecondHandRetailReturnTab = query
                };
                return(await Task.Run(() => Ok(collectionWrapper)));

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
        // GET: api/DocServicePurch2Tabs
        public async Task <IHttpActionResult> GetDocServicePurch2Tabs(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, "RightDocServicePurches"));
                 * 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 Параметры

                Params _params = new Params();

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


                //Получаем Docs.DocIDBase
                int?_DocID         = 0;
                var queryDocIDBase = await
                                     (
                    from x in db.DocServicePurches
                    where x.DocServicePurchID == _params.DocServicePurchID
                    select x
                                     ).ToListAsync();
                if (queryDocIDBase.Count() > 0)
                {
                    _DocID = queryDocIDBase[0].doc.DocID;
                }

                #endregion



                #region Основной запрос *** *** ***
                var query =
                    (
                        from x in db.DocServicePurch2Tabs

                        join dirNomens11 in db.DirNomens on x.dirNomen.Sub equals dirNomens11.DirNomenID into dirNomens12
                        from dirNomensSubGroup in dirNomens12.DefaultIfEmpty()

                        where x.DocServicePurchID == _params.DocServicePurchID

                        #region select

                        select new
                {
                    IsZakaz = false,

                    DocServicePurch2TabID = x.DocServicePurch2TabID,
                    DocServicePurchID = x.DocServicePurchID,

                    DirEmployeeID = x.DirEmployeeID,
                    DirEmployeeName = x.dirEmployee.DirEmployeeName,

                    DirNomenID = x.DirNomenID,

                    //DirNomenName = x.dirNomen.DirNomenName,
                    DirNomenName =
                        dirNomensSubGroup.DirNomenName == null ? x.dirNomen.DirNomenName
                            :
                        dirNomensSubGroup.DirNomenName + " / " + x.dirNomen.DirNomenName,

                    RemPartyID = x.RemPartyID,
                    PriceVAT = x.PriceVAT,
                    PriceCurrency = x.PriceCurrency,

                    DirCurrencyID = x.DirCurrencyID,
                    DirCurrencyRate = x.DirCurrencyRate,
                    DirCurrencyMultiplicity = x.DirCurrencyMultiplicity,
                    DirCurrencyName = x.dirCurrency.DirCurrencyName + " (" + x.DirCurrencyRate + ", " + x.DirCurrencyMultiplicity + ")",

                    TabDate = x.TabDate,

                    PayDate = x.PayDate,
                    RemontN = x.RemontN,
                }

                        #endregion
                    );



                //Заказы !!!
                if (_DocID > 0)
                {
                    int?     DocServicePurch2TabID = null, RemontN = null;
                    int      DocServicePurchID = _params.DocServicePurchID;
                    DateTime?PayDate = null;

                    query = query.Concat
                            (
                        from x in db.DocOrderInts

                        //join dirNomens11 in db.DirNomens on x.dirNomen.Sub equals dirNomens11.DirNomenID into dirNomens12
                        //from dirNomensSubGroup in dirNomens12.DefaultIfEmpty()

                        where x.doc.DocIDBase == _DocID && x.DirOrderIntStatusID < 4

                        #region select

                        select new
                    {
                        IsZakaz = true,

                        DocServicePurch2TabID = DocServicePurch2TabID,         //x.DocServicePurch2TabID,
                        DocServicePurchID     = DocServicePurchID,

                        DirEmployeeID   = x.doc.DirEmployeeID,
                        DirEmployeeName = x.doc.dirEmployee.DirEmployeeName,

                        DirNomenID = x.DocOrderIntID,         //x.DirNomenID == null ? 0 : x.DirNomenID, //x.DirNomenCategoryID, //x.DirNomenID,  //===== !!! DirNomenCategoryID !!!

                        //DirNomenName = x.dirNomen.DirNomenName,
                        DirNomenName =
                            x.dirNomen1.DirNomenName + " / " + x.dirNomen2.DirNomenName + " / " + x.dirNomenCategory.DirNomenCategoryName,

                        RemPartyID    = 0,      //x.RemPartyID,
                        PriceVAT      = x.PriceVAT,
                        PriceCurrency = x.PriceCurrency,

                        DirCurrencyID           = x.DirCurrencyID,
                        DirCurrencyRate         = x.DirCurrencyRate,
                        DirCurrencyMultiplicity = x.DirCurrencyMultiplicity,
                        DirCurrencyName         = x.dirCurrency.DirCurrencyName + " (" + x.DirCurrencyRate + ", " + x.DirCurrencyMultiplicity + ")",

                        TabDate = x.doc.DocDate,   //x.TabDate,

                        PayDate = PayDate,         //x.PayDate,
                        RemontN = RemontN,
                    }

                        #endregion
                            );
                }

                #endregion


                #region Отправка JSON

                dynamic collectionWrapper = new
                {
                    sucess = true,
                    total  = query.Count(),
                    DocServicePurch2Tab = query
                };
                return(await Task.Run(() => Ok(collectionWrapper)));

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Esempio n. 28
0
        public async Task <IHttpActionResult> DeleteDocSecondHandRazbor2Tab(int id, 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));
                dbRead = 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, "RightDocSecondHandRazbors"));

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

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

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

                #endregion

                #region Параметры

                //save, save_close, held, held_cancel
                //var paramList = request.GetQueryNameValuePairs();
                //docSecondHandRazbor2Tab.DocSecondHandPurchID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocSecondHandPurchID", true) == 0).Value);

                #endregion

                #region Проверки

                if (!ModelState.IsValid)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91)));                     //return BadRequest(ModelState);
                }
                Models.Sklad.Doc.DocSecondHandRazbor2Tab docSecondHandRazbor2Tab = await db.DocSecondHandRazbor2Tabs.FindAsync(id);

                int?   DocSecondHandPurchID = docSecondHandRazbor2Tab.DocSecondHandPurchID; //Не трогать !!!
                string DirNomenName         = docSecondHandRazbor2Tab.dirNomen.DirNomenName;

                //1. Если проведён
                //if (Convert.ToBoolean(docSecondHandRazbor2Tab.docSecondHandPurch.doc.Held)) return Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57_3));
                //2. Если разобран (надо поменять статус)
                if (Convert.ToBoolean(docSecondHandRazbor2Tab.docSecondHandPurch.DirSecondHandStatusID != 12))
                {
                    return(Ok(returnServer.Return(false, "Для удаления запчасти (партии) статус аппарата должен быть 'В разборе'!")));
                }
                //3. Есть ли остаток
                int?DocID           = docSecondHandRazbor2Tab.docSecondHandPurch.DocID;
                var queryRemParties = await
                                      (
                    from x in db.RemParties
                    where x.DocID == DocID && x.FieldID == docSecondHandRazbor2Tab.DocSecondHandRazbor2TabID
                    select x
                                      ).ToListAsync();
                if (queryRemParties.Count() > 0)
                {
                    if (queryRemParties[0].Remnant < docSecondHandRazbor2Tab.Quantity)
                    {
                        return(Ok(returnServer.Return(false, "Партия уже продана! К-во на остатке: " + queryRemParties[0].Remnant)));
                    }
                }

                #endregion


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

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

                    try
                    {
                        #region 1. DocSecondHandRazbor2Tabs

                        db.Entry(docSecondHandRazbor2Tab).State = EntityState.Deleted;
                        await db.SaveChangesAsync();

                        #endregion


                        #region 2. RemParties

                        int?RemPartyID = queryRemParties[0].RemPartyID;
                        Models.Sklad.Rem.RemParty remParty = await db.RemParties.FindAsync(RemPartyID);

                        db.Entry(remParty).State = EntityState.Deleted;
                        await db.SaveChangesAsync();

                        #endregion


                        #region 3. Лог: Пишем в Лог о смене статуса и мастера, если такое было

                        logService.DocSecondHandPurchID   = DocSecondHandPurchID;
                        logService.DirSecondHandLogTypeID = 6; //Смена статуса
                        logService.DirEmployeeID          = field.DirEmployeeID;
                        //logService.DirSecondHandStatusID = DirSecondHandStatusID;
                        logService.Msg = "Разборка: удалили запчасть: " + DirNomenName;

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

                        #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))));
                    }
                }


                #region 6. JourDisp *** *** *** *** *** *** *** *** *** *

                Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp();
                sysJourDisp.DirDispOperationID = 5; //Удаление записи
                sysJourDisp.DirEmployeeID      = field.DirEmployeeID;
                sysJourDisp.ListObjectID       = ListObjectID;
                sysJourDisp.TableFieldID       = docSecondHandRazbor2Tab.DocSecondHandPurchID;
                sysJourDisp.Description        = "";
                try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { }

                #endregion


                dynamic collectionWrapper = new
                {
                    ID  = id,
                    Msg = Classes.Language.Sklad.Language.msg19
                };
                return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, ""));

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Esempio n. 29
0
        public async Task <IHttpActionResult> GetDirContractor1Types(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));

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

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

                #endregion


                #region Параметры

                Params _params = new Params();

                //paramList -список параметров
                var paramList = request.GetQueryNameValuePairs();
                //Параметры
                _params.limit     = 999999;                                                                                           // sysSetting.PageSizeDir; //Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "limit", true) == 0).Value); //Записей на страницу
                _params.page      = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "page", true) == 0).Value); //Номер страницы
                _params.Skip      = _params.limit * (_params.page - 1);
                _params.type      = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "type", true) == 0).Value;
                _params.parSearch = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "parSearch", true) == 0).Value; if (_params.parSearch != null)
                {
                    _params.parSearch = _params.parSearch.ToLower();                                                                                                                                      //Поиск
                }
                #endregion


                if (_params.type == "Grid")
                {
                    #region Основной запрос *** *** ***

                    var query =
                        (
                            from dirContractor1Types in db.DirContractor1Types
                            select new
                    {
                        DirContractor1TypeID = dirContractor1Types.DirContractor1TypeID,
                        DirContractor1TypeName = dirContractor1Types.DirContractor1TypeName,
                    }
                        );

                    #endregion


                    #region Условия (параметры) *** *** ***


                    #region OrderBy и Лимит

                    //query = query.OrderBy(x => x.DirContractor1TypeName); //.Skip(_params.Skip).Take(_params.limit);

                    #endregion


                    #endregion


                    #region Отправка JSON

                    //К-во Номенклатуры
                    int dirCount = await Task.Run(() => db.DirContractor1Types.Count());

                    //А вдруг к-во меньше Лимита, тогда показать не общее к-во, а реальное!
                    //int dirCount2 = query.Count();
                    //if (dirCount2 < _params.limit) dirCount = _params.limit * (_params.page - 1) + dirCount2;

                    dynamic collectionWrapper = new
                    {
                        sucess             = true,
                        total              = dirCount,
                        DirContractor1Type = query
                    };
                    return(await Task.Run(() => Ok(collectionWrapper)));

                    #endregion
                }
                else //Tree
                {
                    #region Отобразить только "Руты" *** *** ***

                    var query =
                        (
                            from x in db.DirContractor1Types
                            select new
                    {
                        id = x.DirContractor1TypeID,
                        text = x.DirContractor1TypeName,
                        leaf = true
                    }
                        );

                    #endregion


                    #region Отправка JSON

                    //return Ok(await Task.Run(() => query));

                    dynamic collectionWrapper = new
                    {
                        query
                    };
                    return(Ok(await Task.Run(() => collectionWrapper)));

                    #endregion
                }
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
        //Спецификация
        public string GenerateSQLSelectCollection(Models.Sklad.Sys.SysSetting sysSettings)
        {
            string
                Discount = "(1 - Docs.Discount / 100)",
                SQL      = "";


            SQL =
                "SELECT " +
                "[Docs].[DocDate] AS [DocDate], " +
                //НДС
                "[Docs].[DirVatValue] AS [DirVatValue], " +
                "[Docs].[Discount] AS [Discount], " +

                "[DirServiceNomens].[DirServiceNomenName] AS [DirServiceNomenName], " +
                "[DirServiceNomens].[DirServiceNomenName] AS [DirServiceNomenNameRemove], " +

                //"[DirServiceNomens].[DirServiceNomenArticle] AS [DirServiceNomenArticle], " +
                //"[DirServiceNomens].[DirServiceNomenMinimumBalance] AS [DirServiceNomenMinimumBalance], " +
                "[DirServiceNomens].[DirServiceNomenNameFull] AS [DirServiceNomenNameFull], " +
                "[DirServiceNomens].[DescriptionFull] AS [DescriptionFull], " +
                "[DirServiceNomenGroups].[DirServiceNomenName] AS [DirServiceNomenGroupName], " + //Группа (Sub)

                "[DocSecondHandRetailReturnTabs].[DocSecondHandRetailReturnTabID] AS [DocSecondHandRetailReturnTabID], " +
                "[DocSecondHandRetailReturnTabs].[DocSecondHandRetailReturnID] AS [DocSecondHandRetailReturnID], " +
                "[DocSecondHandRetailReturnTabs].[DirServiceNomenID] AS [DirServiceNomenID], " +
                "[DocSecondHandRetailReturnTabs].[Quantity] AS [Quantity], " +
                "[DocSecondHandRetailReturnTabs].[DirCurrencyID] AS [DirCurrencyID], " +
                "[DocSecondHandRetailReturnTabs].[DirCurrencyRate] AS [DirCu, " +
                "[DocSecondHandRetailReturnTabs].[Quantity] AS [Quantity_NumInWords], " +
                "[DocSecondHandRetailReturnTabs].[PriceVAT] AS [PriceVAT]rrencyRate], " +
                "[DocSecondHandRetailReturnTabs].[DirCurrencyMultiplicity] AS [DirCurrencyMultiplicity], " +
                "[DirCurrencies].[DirCurrencyName] || ' (' || [DocSecondHandRetailReturnTabs].[DirCurrencyRate] || ', ' || [DocSecondHandRetailReturnTabs].[DirCurrencyMultiplicity] || ')' AS [DirCurrencyName], " +
                //"[DocSecondHandRetailReturnTabs].[DirCharColourID] AS [DirCharColourID], " +
                "[DirCharColours].[DirCharColourName] AS [DirCharColourName], " +
                //"[DocSecondHandRetailReturnTabs].[DirCharMaterialID] AS [DirCharMaterialID], " +
                "[DirCharMaterials].[DirCharMaterialName] AS [DirCharMaterialName], " +
                //"[DocSecondHandRetailReturnTabs].[DirCharNameID] AS [DirCharNameID], " +
                "[DirCharNames].[DirCharNameName] AS [DirCharNameName], " +
                //"[DocSecondHandRetailReturnTabs].[DirCharSeasonID] AS [DirCharSeasonID], " +
                "[DirCharSeasons].[DirCharSeasonName] AS [DirCharSeasonName], " +
                //"[DocSecondHandRetailReturnTabs].[DirCharSexID] AS [DirCharSexID], " +
                "[DirCharSexes].[DirCharSexName] AS [DirCharSexName], " +
                //"[DocSecondHandRetailReturnTabs].[DirCharSizeID] AS [DirCharSizeID], " +
                "[DirCharSizes].[DirCharSizeName] AS [DirCharSizeName], " +
                //"[DocSecondHandRetailReturnTabs].[DirCharStyleID] AS [DirCharStyleID], " +
                "[DirCharStyles].[DirCharStyleName] AS [DirCharStyleName], " +
                //"[DocSecondHandRetailReturnTabs].[DirCharTextureID] AS [DirCharTextureID], " +
                "[DirCharTextures].[DirCharTextureName] AS [DirCharTextureName], " +
                "CASE WHEN ([DirCharColours].[DirCharColourName] IS NULL) THEN '' ELSE [DirCharColours].[DirCharColourName] END || ' ' || CASE WHEN ([DirCharMaterials].[DirCharMaterialName] IS NULL) THEN '' ELSE [DirCharMaterials].[DirCharMaterialName] END || ' ' || CASE WHEN ([DirCharNames].[DirCharNameName] IS NULL) THEN '' ELSE [DirCharNames].[DirCharNameName] END || ' ' || CASE WHEN ([DirCharSeasons].[DirCharSeasonName] IS NULL) THEN '' ELSE [DirCharSeasons].[DirCharSeasonName] END || ' ' || CASE WHEN ([DirCharSexes].[DirCharSexName] IS NULL) THEN '' ELSE [DirCharSexes].[DirCharSexName] END || ' ' || CASE WHEN ([DirCharSizes].[DirCharSizeName] IS NULL) THEN '' ELSE [DirCharSizes].[DirCharSizeName] END || ' ' || CASE WHEN ([DirCharStyles].[DirCharStyleName] IS NULL) THEN '' ELSE [DirCharStyles].[DirCharStyleName] END || ' ' || CASE WHEN ([DirCharTextures].[DirCharTextureName] IS NULL) THEN '' ELSE [DirCharTextures].[DirCharTextureName] END AS [DirChar], " +
                "[Rem2Parties].[SerialNumber] AS [SerialNumber], " +
                "[Rem2Parties].[Barcode] AS [Barcode], " +
                "[Rem2Parties].[Barcode] AS [BarcodeImage], " +

                "[DirContractorOrg].[DirContractorName] AS [DirContractorNameOrg], " +

                //Приходная цена
                "[DocSecondHandRetailReturnTabs].[PriceCurrency] AS [PriceCurrency], " +
                //"Цена без НДС" в валюте
                "ROUND([DocSecondHandRetailReturnTabs].[PriceVAT] / (1 + [Docs].[DirVatValue] / 100), " + sysSettings.FractionalPartInSum + ") AS [PurchPriceNoVAT], " +
                //"Цена без НДС" в текущей валюте
                "ROUND([DocSecondHandRetailReturnTabs].[PriceCurrency] / (1 + [Docs].[DirVatValue] / 100), " + sysSettings.FractionalPartInSum + ") AS [PurchPriceNoVATCurrency], " +
                //Цена С НДС в валюте (словами)
                "ROUND([DocSecondHandRetailReturnTabs].[PriceVat], " + sysSettings.FractionalPartInSum + ") AS [PriceVAT_InWords], " +
                //Цена С НДС в текущей валюте (словами)
                "ROUND([DocSecondHandRetailReturnTabs].[PriceCurrency], " + sysSettings.FractionalPartInSum + ") AS [PriceCurrency_InWords], " +
                //"Цена с НДС" в текущей валюте со Скидкой
                "ROUND([DocSecondHandRetailReturnTabs].[PriceCurrency] * " + Discount + ", " + sysSettings.FractionalPartInSum + ") 'PriceCurrencyDiscount', " +
                //"Сумма НДС" (НДС документа)
                "ROUND([DocSecondHandRetailReturnTabs].[Quantity] * ([DocSecondHandRetailReturnTabs].[PriceCurrency] / (1 + [Docs].[DirVatValue] / 100) * [Docs].[DirVatValue] / 100), " + sysSettings.FractionalPartInSum + ") AS [SumVatValue], " +
                //"Стоимость без НДС" в валюте
                "ROUND(([DocSecondHandRetailReturnTabs].[Quantity] * [DocSecondHandRetailReturnTabs].[PriceVAT]) / (1 + [Docs].[DirVatValue] / 100), " + sysSettings.FractionalPartInSum + ") AS [SUMPurchPriceNoVAT], " +
                //"Стоимость Прихода без НДС" в текущей валюте
                "ROUND(([DocSecondHandRetailReturnTabs].[Quantity] * [DocSecondHandRetailReturnTabs].[PriceCurrency]) / (1 + [Docs].[DirVatValue] / 100), " + sysSettings.FractionalPartInSum + ") AS [SUMPurchPriceNoVATCurrency], " +
                //Себестоимось прихода
                "ROUND([DocSecondHandRetailReturnTabs].[Quantity] * [DocSecondHandRetailReturnTabs].[PriceVat], " + sysSettings.FractionalPartInSum + ") AS [SUMPurchPriceVAT], " +
                "ROUND([DocSecondHandRetailReturnTabs].[Quantity] * [DocSecondHandRetailReturnTabs].[PriceCurrency], " + sysSettings.FractionalPartInSum + ") AS [SUMPurchPriceVATCurrency], " +
                //Стоимость с НДС в текущей валюте со Скидкой
                "ROUND([DocSecondHandRetailReturnTabs].[Quantity] * [DocSecondHandRetailReturnTabs].[PriceCurrency] * " + Discount + ", " + sysSettings.FractionalPartInSum + ") 'SUMPriceCurrencyDiscount', " +


                //Розница
                "ROUND((100 * ([Rem2Parties].[PriceRetailVAT] - [Rem2Parties].[PriceVAT])) / [Rem2Parties].[PriceVAT], " + sysSettings.FractionalPartInSum + ") AS [MarkupRetail], " +
                "[Rem2Parties].[PriceRetailVAT] AS [PriceRetailVAT], " +
                "[Rem2Parties].[PriceRetailCurrency] AS [PriceRetailCurrency], " +
                //Стоимость Розницы в валюте
                "ROUND([DocSecondHandRetailReturnTabs].[Quantity] * [Rem2Parties].[PriceRetailVAT], " + sysSettings.FractionalPartInSum + ") AS [SUMRetailPriceVAT], " +
                //Стоимость Розницы в текущей валюте
                "ROUND([DocSecondHandRetailReturnTabs].[Quantity] * [Rem2Parties].[PriceRetailCurrency], " + sysSettings.FractionalPartInSum + ") 'SUMRetailPriceCurrency', " +

                //Опт
                "ROUND((100 * ([Rem2Parties].[PriceWholesaleVAT] - [Rem2Parties].[PriceVAT])) / [Rem2Parties].[PriceVAT], " + sysSettings.FractionalPartInSum + ") AS [MarkupWholesale], " +
                "[Rem2Parties].[PriceWholesaleVAT] AS [PriceWholesaleVAT], " +
                "[Rem2Parties].[PriceWholesaleCurrency] AS [PriceWholesaleCurrency], " +
                //Стоимость Опта в валюте
                "ROUND([DocSecondHandRetailReturnTabs].[Quantity] * [Rem2Parties].[PriceWholesaleVat], " + sysSettings.FractionalPartInSum + ") AS [SUMWholesalePriceVAT], " +
                //Стоимость Опта в текущей валюте
                "ROUND([DocSecondHandRetailReturnTabs].[Quantity] * [Rem2Parties].[PriceWholesaleCurrency], " + sysSettings.FractionalPartInSum + ") AS [SUMWholesalePriceCurrency], " +

                //Интернет-Магазин
                "ROUND((100 * ([Rem2Parties].[PriceIMVAT] - [Rem2Parties].[PriceVAT])) / [Rem2Parties].[PriceVAT], " + sysSettings.FractionalPartInSum + ") AS [MarkupIM], " +
                "[Rem2Parties].[PriceIMVAT] AS [PriceIMVAT], " +
                "[Rem2Parties].[PriceIMCurrency] AS [PriceIMCurrency], " +

                //Прочерк
                "'-' AS FieldDash, " +
                //Пустое поле
                "' ' AS FieldEmpty " +

                "FROM [Docs], [DocSecondHandRetailReturns], [DocSecondHandRetailReturnTabs] " +

                //docSecondHandRetailReturnTabs.rem2PartyMinus.rem2Party.DirCharColourID
                "LEFT OUTER JOIN [Rem2PartyMinuses] ON [DocSecondHandRetailReturnTabs].[Rem2PartyMinusID] = [Rem2PartyMinuses].[Rem2PartyMinusID] " +
                "LEFT OUTER JOIN [Rem2Parties] ON [Rem2PartyMinuses].[Rem2PartyID] = [Rem2Parties].[Rem2PartyID] " +

                "LEFT OUTER JOIN [DirCharColours] ON [Rem2Parties].[DirCharColourID] = [DirCharColours].[DirCharColourID] " +
                "LEFT OUTER JOIN [DirCharMaterials] ON [Rem2Parties].[DirCharMaterialID] = [DirCharMaterials].[DirCharMaterialID] " +
                "LEFT OUTER JOIN [DirCharNames] ON [Rem2Parties].[DirCharNameID] = [DirCharNames].[DirCharNameID] " +
                "LEFT OUTER JOIN [DirCharSeasons] ON [Rem2Parties].[DirCharSeasonID] = [DirCharSeasons].[DirCharSeasonID] " +
                "LEFT OUTER JOIN [DirCharSexes] ON [Rem2Parties].[DirCharSexID] = [DirCharSexes].[DirCharSexID] " +
                "LEFT OUTER JOIN [DirCharSizes] ON [Rem2Parties].[DirCharSizeID] = [DirCharSizes].[DirCharSizeID] " +
                "LEFT OUTER JOIN [DirCharStyles] ON [Rem2Parties].[DirCharStyleID] = [DirCharStyles].[DirCharStyleID] " +
                "LEFT OUTER JOIN [DirCharTextures] ON [Rem2Parties].[DirCharTextureID] = [DirCharTextures].[DirCharTextureID] " +
                "INNER JOIN [DirServiceNomens] ON [Rem2Parties].[DirServiceNomenID] = [DirServiceNomens].[DirServiceNomenID] " +
                "LEFT OUTER JOIN [DirServiceNomens] AS [DirServiceNomenGroups] ON [DirServiceNomenGroups].[Sub] = [DirServiceNomens].[DirServiceNomenID] " +
                "INNER JOIN [DirCurrencies] ON [DocSecondHandRetailReturnTabs].[DirCurrencyID] = [DirCurrencies].[DirCurrencyID] " +
                "INNER JOIN [DirContractors] AS [DirContractorOrg] ON [Docs].[DirContractorIDOrg] = [DirContractorOrg].[DirContractorID] " +

                "WHERE ([Docs].[DocID]=[DocSecondHandRetailReturns].[DocID])and([DocSecondHandRetailReturns].[DocSecondHandRetailReturnID]=[DocSecondHandRetailReturnTabs].[DocSecondHandRetailReturnID])and(Docs.DocID=@DocID) " +

                "";


            return(SQL);
        }