Exemplo n.º 1
0
        public async Task <IHttpActionResult> DeleteSysJourDisp(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, "RightSysJourDisps"));

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

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

            #endregion

            #region Удаление

            try
            {
                SysJourDisp sysJourDisp = await db.SysJourDisps.FindAsync(id);

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

                // === Удаляем === === === === ===
                db.SysJourDisps.Remove(sysJourDisp);
                await db.SaveChangesAsync();

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

            #endregion
        }
Exemplo n.º 2
0
        // GET: Develop
        public async Task <ActionResult> Index(HttpRequestMessage request, FormCollection formCollection)
        {
            //return View();
            try
            {
                #region Логин

                HttpCookie CookieIPOL = Request.Cookies["CookieIPOL"];

                Classes.Account.Login       login = new Classes.Account.Login();
                Classes.Account.Login.Field field = await Task.Run(() => login.Return(CookieIPOL, true)); //HttpCookie CookieIPOL = Request.Cookies["CookieIPOL"];

                if (!field.Access)
                {
                    return(Redirect("~/account/login/"));
                }

                #endregion

                #region Доступ в Разработчик

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

                if (iRight != 1)
                {
                    return(Redirect("~/develop/noaccess/"));
                }

                #endregion

                #region Тема, Язык, Интерфейс

                //Тема
                ViewData["CookieT"] = CookieIPOL["CookieT"]; if (ViewData["CookieT"] == null)
                {
                    ViewData["CookieT"] = 1;
                }
                //Язык
                ViewData["CookieL"] = CookieIPOL["CookieL"]; if (ViewData["CookieL"] == null)
                {
                    ViewData["CookieL"] = 1;
                }
                //Интерфейс
                ViewData["CookieI"] = CookieIPOL["CookieI"]; if (ViewData["CookieI"] == null)
                {
                    ViewData["CookieI"] = 1;
                }

                #endregion


                return(View());
            }
            catch (Exception ex)
            {
                Classes.Function.Exceptions.ExceptionEntry exceptionEntry = new Classes.Function.Exceptions.ExceptionEntry();
                return(Redirect("~/account/login/?Err=" + exceptionEntry.Return(ex)));
            }
        }
Exemplo n.º 3
0
        private async Task <bool> RecordInLog(
            int ListObjectID,
            int DocXID,
            string Msg,
            Classes.Account.Login.Field field,
            DbConnectionSklad dbX
            )
        {
            if (ListObjectID == 40)
            {
                Models.Sklad.Log.LogService log = new Models.Sklad.Log.LogService(); Controllers.Sklad.Log.LogServicesController logController = new Log.LogServicesController();

                //Пишем в Лог о смене статуса и мастера, если такое было
                log.DocServicePurchID   = DocXID;
                log.DirServiceLogTypeID = 4;
                log.DirEmployeeID       = field.DirEmployeeID;
                log.Msg = Msg;

                await logController.mPutPostLogServices(dbX, log, EntityState.Added);
            }
            else
            {
                Models.Sklad.Log.LogMovement logService = new Models.Sklad.Log.LogMovement(); Controllers.Sklad.Log.LogMovementsController logController = new Log.LogMovementsController();

                //Пишем в Лог о смене статуса и мастера, если такое было
                logService.DocMovementID        = DocXID;
                logService.DirMovementLogTypeID = 2;
                logService.DirEmployeeID        = field.DirEmployeeID;
                logService.Msg = Msg;

                await logController.mPutPostLogMovements(dbX, logService, EntityState.Added);
            }

            return(true);
        }
Exemplo 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);
        }
Exemplo n.º 5
0
        private async Task <string> mAllReport(DbConnectionSklad db, Classes.Account.Login.Field field)
        {
            string ret = "";


            return(ret);
        }
Exemplo n.º 6
0
        //Получаем DomainName из базы MS SQL
        private async Task <string> SelectDomainName(Classes.Account.Login.Field field)
        {
            string DomainName = "";

            using (Models.DbConnectionLogin dbLogin = new Models.DbConnectionLogin("ConnStrMSSQL"))
            {
                var query = await dbLogin.DirCustomers.Where(x => x.DirCustomersID == field.DirCustomersID && x.Active == true).ToListAsync();

                if (query.Count() > 0)
                {
                    DomainName = query[0].DomainName;
                }
                else
                {
                    DomainName = "Не найден клиент или не активный!";
                }
            }

            return(DomainName);
        }
        internal async Task <DocServicePurch2Tab> mPutPostDocServicePurch2Tab(
            DbConnectionSklad db,
            Models.Sklad.Doc.DocServicePurch docServicePurch,
            DocServicePurch2Tab docServicePurch2Tab,

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

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

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

            #endregion


            #region Save

            docServicePurch2Tab.TabDate = DateTime.Now;

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

            #endregion

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


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

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


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

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

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

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

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

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

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

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

            #endregion

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

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

            #endregion


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


            #region Проверка

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

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

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

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

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

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

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

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

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

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

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

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

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

            #endregion


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

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

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

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

            #endregion


            #endregion


            #endregion


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

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

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

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

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

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

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

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

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

            #endregion

            #region Удаление

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

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

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

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

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

                    try
                    {
                        #region Лог

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

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

                        #endregion

                        #region Save

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

                        #endregion


                        #region Партии

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

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

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

                        #endregion


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

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


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

            #endregion
        }
Exemplo n.º 9
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))));
            }
        }
Exemplo n.º 10
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
        }
Exemplo 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))));
            }
        }
Exemplo n.º 12
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))));
            }
        }
        // GET: api/DocSales
        public async Task <IHttpActionResult> GetDocSales(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, "RightDocServicePurchesReport"));

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

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

                #endregion


                #region Параметры

                //paramList -список параметров
                var paramList = request.GetQueryNameValuePairs();


                pID = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "pID", true) == 0).Value;

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

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

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

                TypeRepair = false;
                bool bTypeRepair = Boolean.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "TypeRepair", true) == 0).Value, out TypeRepair); //TypeRepair

                DirContractorIDOrg = 0;
                bool bDirContractorIDOrg = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorIDOrg", true) == 0).Value, out DirContractorIDOrg); //DirContractorIDOrg
                DirContractorNameOrg = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirContractorNameOrg", true) == 0).Value;                                           //Request.Params["DirContractorNameOrg"];

                DirWarehouseID = 0;
                bool bDirWarehouseID = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseID", true) == 0).Value, out DirWarehouseID); //DirWarehouseID
                DirWarehouseName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseName", true) == 0).Value;                                       //Request.Params["DirWarehouseName"];

                DirServiceStatusID = 0;
                bool bDirServiceStatusID = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceStatusID", true) == 0).Value, out DirServiceStatusID); //DirServiceStatusID
                DirServiceStatusName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceStatusName", true) == 0).Value;                                           //Request.Params["DirServiceStatusName"];

                DirEmployeeID = 0;
                bool bDirEmployeeID = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirEmployeeID", true) == 0).Value, out DirEmployeeID); //DirEmployeeID
                DirEmployeeName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirEmployeeName", true) == 0).Value;                                      //Request.Params["DirEmployeeName"];

                DirEmployeeIDMaster = 0;
                bool bDirEmployeeIDMaster = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirEmployeeIDMaster", true) == 0).Value, out DirEmployeeIDMaster); //DirEmployeeIDMaster
                DirEmployeeNameMaster = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirEmployeeNameMaster", true) == 0).Value;                                            //Request.Params["DirEmployeeNameMaster"];

                DirServiceContractorID = 0;
                bool bDirServiceContractorID = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceContractorID", true) == 0).Value, out DirServiceContractorID); //DirServiceContractorID
                DirServiceContractorName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirServiceContractorName", true) == 0).Value;                                               // Request.Params["DirServiceContractorName"];

                ReportType = 0;
                bool bReportType = Int32.TryParse(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "ReportType", true) == 0).Value, out ReportType); //ReportType
                ReportTypeName = paramList.FirstOrDefault(kv => string.Compare(kv.Key, "ReportTypeName", true) == 0).Value;                               // Request.Params["ReportTypeName"];

                #endregion



                #region queryTemp

                var queryTemp =
                    (
                        #region from

                        from docServicePurches in db.DocServicePurches


                        join dirServiceNomens11 in db.DirServiceNomens on docServicePurches.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 docServicePurch1Tabs1 in db.DocServicePurch1Tabs on docServicePurches.DocServicePurchID equals docServicePurch1Tabs1.DocServicePurchID into docServicePurch1Tabs2
                         * from docServicePurch1Tabs in docServicePurch1Tabs2.DefaultIfEmpty()
                         * //where docServicePurch1Tabs.PriceCurrency > 0
                         */

                        /*
                         * join docServicePurch2Tabs1 in db.DocServicePurch2Tabs on docServicePurches.DocServicePurchID equals docServicePurch2Tabs1.DocServicePurchID into docServicePurch2Tabs2
                         * from docServicePurch2Tabs in docServicePurch2Tabs2.DefaultIfEmpty()
                         * //where docServicePurch2Tabs.PriceCurrency > 0
                         */

                        #endregion

                        where docServicePurches.doc.DirContractorIDOrg == DirContractorIDOrg //&& docServicePurches.doc.DocDate >= DateS && docServicePurches.doc.DocDate <= DatePo

                        #region group

                        /*
                         * group new { docServicePurch1Tabs, docServicePurch2Tabs }
                         * //group new { docServicePurches }
                         * by new
                         * {
                         *  DocID = docServicePurches.DocID,
                         *  DocDate = docServicePurches.doc.DocDate,
                         *  Base = docServicePurches.doc.Base,
                         *  Held = docServicePurches.doc.Held,
                         *  Discount = docServicePurches.doc.Discount,
                         *  Del = docServicePurches.doc.Del,
                         *  Description = docServicePurches.doc.Description,
                         *  IsImport = docServicePurches.doc.IsImport,
                         *  DirVatValue = docServicePurches.doc.DirVatValue,
                         *  //DirPaymentTypeID = docServicePurches.doc.DirPaymentTypeID,
                         *
                         *  //Принял
                         *  DirEmployeeID = docServicePurches.doc.DirEmployeeID,
                         *  DirEmployeeName = docServicePurches.doc.dirEmployee.DirEmployeeName,
                         *  //Мастер
                         *  DirEmployeeIDMaster = docServicePurches.DirEmployeeIDMaster,
                         *  DirEmployeeNameMaster = docServicePurches.dirEmployee.DirEmployeeName,
                         *
                         *  DirServiceNomenID = docServicePurches.DirServiceNomenID,
                         *  //DirServiceNomenName = docServicePurches.dirServiceNomen.DirServiceNomenName,
                         *  DirServiceNomenName =
                         *      dirServiceNomensSubGroup.DirServiceNomenName == null ? docServicePurches.dirServiceNomen.DirServiceNomenName :
                         *      dirServiceNomensGroup.DirServiceNomenName == null ? dirServiceNomensSubGroup.DirServiceNomenName + " / " + docServicePurches.dirServiceNomen.DirServiceNomenName :
                         *      dirServiceNomensGroup.DirServiceNomenName + " / " + dirServiceNomensSubGroup.DirServiceNomenName + " / " + docServicePurches.dirServiceNomen.DirServiceNomenName,
                         *
                         *  DocServicePurchID = docServicePurches.DocServicePurchID,
                         *  DirContractorName = docServicePurches.doc.dirContractor.DirContractorName,
                         *  DirContractorIDOrg = docServicePurches.doc.dirContractorOrg.DirContractorID,
                         *  DirContractorNameOrg = docServicePurches.doc.dirContractorOrg.DirContractorName,
                         *  DirWarehouseID = docServicePurches.dirWarehouse.DirWarehouseID,
                         *  DirWarehouseName = docServicePurches.dirWarehouse.DirWarehouseName,
                         *
                         *  DirServiceStatusID = docServicePurches.DirServiceStatusID,
                         *  DirServiceStatusID_789 = docServicePurches.DirServiceStatusID_789,
                         *  SerialNumber = docServicePurches.SerialNumber,
                         *  TypeRepair = docServicePurches.TypeRepair,
                         *  ComponentDevice = docServicePurches.ComponentDevice,
                         *
                         *  ComponentBattery = docServicePurches.ComponentBattery,
                         *  ComponentBatterySerial = docServicePurches.ComponentBatterySerial,
                         *  ComponentBackCover = docServicePurches.ComponentBackCover,
                         *  ComponentPasTextNo = docServicePurches.ComponentPasTextNo,
                         *  ComponentPasText = docServicePurches.ComponentPasText,
                         *  ComponentOtherText = docServicePurches.ComponentOtherText,
                         *  ProblemClientWords = docServicePurches.ProblemClientWords,
                         *  Note = docServicePurches.Note,
                         *  DirServiceContractorName = docServicePurches.DirServiceContractorName,
                         *  DirServiceContractorRegular = docServicePurches.DirServiceContractorRegular,
                         *  DirServiceContractorID = docServicePurches.DirServiceContractorID,
                         *  DirServiceContractorAddress = docServicePurches.DirServiceContractorAddress,
                         *  DirServiceContractorPhone = docServicePurches.DirServiceContractorPhone,
                         *  DirServiceContractorEmail = docServicePurches.DirServiceContractorEmail,
                         *
                         *  PriceVAT = docServicePurches.PriceVAT,
                         *  //PriceCurrency = docServicePurches.PriceCurrency,
                         *
                         *  DirCurrencyID = docServicePurches.DirCurrencyID,
                         *  DirCurrencyRate = docServicePurches.DirCurrencyRate,
                         *  DirCurrencyMultiplicity = docServicePurches.DirCurrencyMultiplicity,
                         *  DirCurrencyName = docServicePurches.dirCurrency.DirCurrencyName + " (" + docServicePurches.DirCurrencyRate + ", " + docServicePurches.DirCurrencyMultiplicity + ")",
                         *
                         *  DateDone = docServicePurches.DateDone,
                         *  UrgentRepairs = docServicePurches.UrgentRepairs,
                         *  Prepayment = docServicePurches.Prepayment,
                         *  PrepaymentSum = docServicePurches.PrepaymentSum == null ? 0 : docServicePurches.PrepaymentSum,
                         *
                         *  IssuanceDate = docServicePurches.IssuanceDate,
                         *  DateStatusChange = docServicePurches.DateStatusChange,
                         *
                         *  //Оплата
                         *  Payment = docServicePurches.doc.Payment,
                         *
                         *  //Сумма Выполненный работ + Запчастей
                         *  Sums = docServicePurches.Sums,
                         *  Sums1 = docServicePurches.Sums1,
                         *  Sums2 = docServicePurches.Sums2,
                         * }
                         * into g
                         */

                        #endregion

                        #region select docServicePurches

                        select new
                {
                    DocID = docServicePurches.DocID,
                    DocDate = docServicePurches.doc.DocDate.ToString(), DocDate1 = docServicePurches.doc.DocDate,
                    Base = docServicePurches.doc.Base,
                    Held = docServicePurches.doc.Held,
                    Del = docServicePurches.doc.Del,
                    Description = docServicePurches.doc.Description,
                    IsImport = docServicePurches.doc.IsImport,
                    DirVatValue = docServicePurches.doc.DirVatValue,
                    //DirPaymentTypeID = docServicePurches.DirPaymentTypeID,
                    //DirPaymentTypeName = docServicePurches.DirPaymentTypeName,

                    //Принял
                    DirEmployeeID = docServicePurches.doc.DirEmployeeID,
                    DirEmployeeName = docServicePurches.doc.dirEmployee.DirEmployeeName,
                    //Мастер
                    DirEmployeeIDMaster = docServicePurches.DirEmployeeIDMaster,
                    DirEmployeeNameMaster = docServicePurches.dirEmployee.DirEmployeeName,

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

                    DocServicePurchID = docServicePurches.DocServicePurchID,
                    DirContractorName = docServicePurches.doc.dirContractor.DirContractorName,
                    DirContractorIDOrg = docServicePurches.doc.dirContractorOrg.DirContractorID,
                    DirContractorNameOrg = docServicePurches.doc.dirContractorOrg.DirContractorName,
                    DirWarehouseID = docServicePurches.DirWarehouseID,
                    DirWarehouseName = docServicePurches.dirWarehouse.DirWarehouseName,

                    DirServiceStatusID = docServicePurches.DirServiceStatusID,
                    DirServiceStatusID_789 = docServicePurches.DirServiceStatusID_789,
                    SerialNumber = docServicePurches.SerialNumber,
                    TypeRepair = docServicePurches.TypeRepair,
                    ComponentDevice = docServicePurches.ComponentDevice,

                    ComponentBattery = docServicePurches.ComponentBattery,
                    ComponentBatterySerial = docServicePurches.ComponentBatterySerial,
                    ComponentBackCover = docServicePurches.ComponentBackCover,
                    ComponentPasTextNo = docServicePurches.ComponentPasTextNo,
                    ComponentPasText = docServicePurches.ComponentPasText,
                    ComponentOtherText = docServicePurches.ComponentOtherText,
                    ProblemClientWords = docServicePurches.ProblemClientWords,
                    Note = docServicePurches.Note,
                    DirServiceContractorName = docServicePurches.DirServiceContractorName,
                    DirServiceContractorRegular = docServicePurches.DirServiceContractorRegular,
                    DirServiceContractorID = docServicePurches.DirServiceContractorID,
                    DirServiceContractorAddress = docServicePurches.DirServiceContractorAddress,
                    DirServiceContractorPhone = docServicePurches.DirServiceContractorPhone,
                    DirServiceContractorEmail = docServicePurches.DirServiceContractorEmail,

                    PriceVAT = docServicePurches.PriceVAT,
                    //PriceCurrency = docServicePurches.PriceCurrency,

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

                    DateDone = docServicePurches.DateDone.ToString(), DateDone1 = docServicePurches.DateDone,
                    UrgentRepairs = docServicePurches.UrgentRepairs,
                    Prepayment = docServicePurches.Prepayment,
                    PrepaymentSum = docServicePurches.PrepaymentSum == null ? 0 : docServicePurches.PrepaymentSum,

                    IssuanceDate = docServicePurches.IssuanceDate.ToString(), IssuanceDate1 = docServicePurches.IssuanceDate,
                    DateStatusChange = docServicePurches.DateStatusChange.ToString(), DateStatusChange1 = docServicePurches.DateStatusChange,

                    //Оплата
                    Payment = docServicePurches.doc.Payment,


                    /*
                     * //1. Подсчет табличной части Работы "SumDocServicePurch1Tabs"
                     * SumDocServicePurch1Tabs = g.Sum(x => x.docServicePurch1Tabs.PriceCurrency) == null ? 0 : Math.Round(g.Sum(x => x.docServicePurch1Tabs.PriceCurrency), sysSetting.FractionalPartInSum),
                     *
                     * //2. Подсчет табличной части Работы "SumDocServicePurch2Tabs"
                     * SumDocServicePurch2Tabs = g.Sum(x => x.docServicePurch2Tabs.PriceCurrency) == null ? 0 : Math.Round(g.Sum(x => x.docServicePurch2Tabs.PriceCurrency), sysSetting.FractionalPartInSum),
                     *
                     *
                     * //3. Сумма 1+2 "SumTotal"
                     * SumTotal =
                     * Math.Round(
                     * (g.Sum(x => x.docServicePurch1Tabs.PriceCurrency) == null ? 0 : g.Sum(x => x.docServicePurch1Tabs.PriceCurrency)) +
                     * (g.Sum(x => x.docServicePurch2Tabs.PriceCurrency) == null ? 0 : g.Sum(x => x.docServicePurch2Tabs.PriceCurrency))
                     * , sysSetting.FractionalPartInSum),
                     *
                     * //4. Константа "PrepaymentSum"
                     * //...
                     *
                     * //5. 3 - 4 "SumTotal2"
                     * SumTotal2 = g.Key.Sums,
                     */

                    DiscountX = docServicePurches.DiscountX,
                    SumDocServicePurch1Tabs = docServicePurches.Sums1,

                    DiscountY = docServicePurches.DiscountY,
                    SumDocServicePurch2Tabs = docServicePurches.Sums2,

                    SumTotal =
                        (docServicePurches.Sums1 - docServicePurches.DiscountX)
                        +
                        (docServicePurches.Sums2 - docServicePurches.DiscountY),

                    SumTotal2 = docServicePurches.Sums - docServicePurches.DiscountX - docServicePurches.DiscountY,
                }

                        #endregion

                    );

                if (DirWarehouseID > 0)
                {
                    queryTemp = queryTemp.Where(z => z.DirWarehouseID == DirWarehouseID);
                }
                if (DirServiceStatusID > 0)
                {
                    queryTemp = queryTemp.Where(z => z.DirServiceStatusID == DirServiceStatusID);
                }
                if (DirEmployeeID > 0)
                {
                    queryTemp = queryTemp.Where(z => z.DirEmployeeID == DirEmployeeID);
                }
                if (DirEmployeeIDMaster > 0)
                {
                    queryTemp = queryTemp.Where(z => z.DirEmployeeIDMaster == DirEmployeeIDMaster);
                }
                if (DirServiceContractorID > 0)
                {
                    queryTemp = queryTemp.Where(z => z.DirServiceContractorID == DirServiceContractorID);
                }
                if (ReportType > 0)
                {
                    switch (ReportType)
                    {
                    //1. Выданные (все)
                    case 1:
                    {
                        queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 9 && (z.DateStatusChange1 >= DateS && z.DateStatusChange1 <= DatePo));
                    }
                    break;

                    //2. Выданные (готовые)
                    case 2:
                    {
                        queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 9 && z.DirServiceStatusID_789 == 7 && (z.DateStatusChange1 >= DateS && z.DateStatusChange1 <= DatePo));
                    }
                    break;

                    //3. Не отремонтированные все (Выданные (отказные))
                    case 3:
                    {
                        queryTemp = queryTemp.Where(z => z.DirServiceStatusID_789 == 8 && (z.IssuanceDate1 >= DateS && z.IssuanceDate1 <= DatePo));         //queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 9 && z.DirServiceStatusID_789 == 8 && (z.DocDate >= DateS && z.DocDate <= DatePo));
                    }
                    break;

                    //4. Сделанные
                    case 4:
                    {
                        queryTemp = queryTemp.Where(z => z.DirServiceStatusID_789 == 7 && (z.IssuanceDate1 >= DateS && z.IssuanceDate1 <= DatePo));         //queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 7 && (z.DocDate >= DateS && z.DocDate <= DatePo));
                    }
                    break;

                    //5. Принятые
                    case 5:
                    {
                        queryTemp = queryTemp.Where(z => (z.DocDate1 >= DateS && z.DocDate1 <= DatePo));         //queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 1 && (z.DocDate >= DateS && z.DocDate <= DatePo));
                    }
                    break;

                    default:
                    {
                        queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 9 && (z.DateStatusChange1 >= DateS && z.DateStatusChange1 <= DatePo));
                    }
                    break;
                    }
                }
                else
                {
                    queryTemp = queryTemp.Where(z => z.DirServiceStatusID == 9 && (z.DateStatusChange1 >= DateS && z.DateStatusChange1 <= DatePo));
                }

                #endregion


                #region Отправка JSON

                int dirCount = queryTemp.Count();

                dynamic collectionWrapper1 = new
                {
                    sucess = true,
                    total  = dirCount,
                    DocServicePurchesReport = queryTemp
                };
                return(await Task.Run(() => Ok(collectionWrapper1)));

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Exemplo n.º 14
0
        public async Task <IHttpActionResult> PostDocBankSum(DocBankSum docBankSum)
        {
            #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, "RightDocBankSums"));

            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);
            }
            //Подстановки - некоторые поля надо заполнить, если они не заполены
            //docBankSum.Substitute();
            docBankSum.DirEmployeeID = field.DirEmployeeID;

            #endregion


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

            try
            {
                docBankSum = await Task.Run(() => mPutPostDocBankSum(db, docBankSum, EntityState.Added));


                #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       = docBankSum.DocBankSumID;
                sysJourDisp.Description        = "";
                try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { }

                #endregion


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

            #endregion
        }
Exemplo n.º 15
0
        // GET: api/RemPartyMinuses
        public async Task <IHttpActionResult> GetRemPartyMinuses(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, "RightRemPartyMinuses"));
                 * 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.RemPartyID  = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "RemPartyID", true) == 0).Value);
                _params.DirNomenID  = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirNomenID", true) == 0).Value);
                _params.DocSaleID   = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocSaleID", true) == 0).Value);
                _params.DocRetailID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocRetailID", 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.DirWarehouseID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DirWarehouseID", 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"));
                }

                #endregion



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

                var query =
                    (
                        from remPartyMinuses in db.RemPartyMinuses

                        /*
                         * where
                         *  remPartyMinuses.Remnant > 0 &&
                         *  remPartyMinuses.DirContractorIDOrg == _params.DirContractorIDOrg &&
                         *  remPartyMinuses.DirNomenID == _params.DirNomenID &&
                         *  remPartyMinuses.DirWarehouseID == _params.DirWarehouseID
                         */
                        select new
                {
                    RemPartyMinusID = remPartyMinuses.RemPartyMinusID,
                    DocID = remPartyMinuses.DocID,
                    RemPartyID = remPartyMinuses.RemPartyID,
                    DirNomenID = remPartyMinuses.DirNomenID,
                    DirNomenName = remPartyMinuses.dirNomen.DirNomenName,
                    DocDate = remPartyMinuses.doc.DocDate,
                    DirContractorNameOrg = remPartyMinuses.doc.dirContractorOrg.DirContractorName,
                    DirContractorName = remPartyMinuses.doc.dirContractor.DirContractorName,

                    DirCurrencyID = remPartyMinuses.DirCurrencyID,
                    DirCurrencyName = remPartyMinuses.dirCurrency.DirCurrencyName,
                    DirCurrencyRate = remPartyMinuses.DirCurrencyRate,
                    DirCurrencyMultiplicity = remPartyMinuses.DirCurrencyMultiplicity,

                    DirVatValue = remPartyMinuses.DirVatValue,
                    DirWarehouseID = remPartyMinuses.dirWarehouse.DirWarehouseID, DirWarehouseName = remPartyMinuses.dirWarehouse.DirWarehouseName,
                    ListDocNameRu = remPartyMinuses.doc.listObject.ListObjectNameRu,
                    PriceVAT = remPartyMinuses.PriceVAT,
                    PriceCurrency = remPartyMinuses.PriceCurrency,
                    Quantity = remPartyMinuses.Quantity,
                    Reserve = remPartyMinuses.Reserve
                }
                    );

                #endregion


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


                #region Кликнули на товар - паказать список партий

                if (_params.RemPartyID > 0)
                {
                    query = query.Where(x => x.RemPartyID == _params.RemPartyID);
                }
                else if (_params.DirNomenID > 0)
                {
                    query = query.Where(x => x.DirNomenID == _params.DirNomenID);
                }
                else if (_params.DocSaleID > 0)
                {
                    //query = query.Where(x => x.DocSaleID == _params.DocSaleID);
                    //Алгоритм:
                    //1. Получаем DocID по DocSaleID
                    //2. query = query.Where(x => x.DocID == iDocID);

                    //1. Получаем DocID по DocSaleID
                    var queryDocSale = await db.DocSales.FindAsync(_params.DocSaleID);

                    int iDocID = Convert.ToInt32(queryDocSale.DocID);

                    //2. query = query.Where(x => x.DocID == iDocID);
                    query = query.Where(x => x.DocID == iDocID);
                }
                else if (_params.DocRetailID > 0)
                {
                    //query = query.Where(x => x.DocRetailID == _params.DocRetailID);
                    //Алгоритм:
                    //1. Получаем DocID по DocRetailID
                    //2. query = query.Where(x => x.DocID == iDocID);

                    //1. Получаем DocID по DocRetailID
                    var queryDocRetail = await db.DocRetails.FindAsync(_params.DocRetailID);

                    int iDocID = Convert.ToInt32(queryDocRetail.DocID);

                    //2. query = query.Where(x => x.DocID == iDocID);
                    query = query.Where(x => x.DocID == iDocID);
                }

                #endregion


                #region Поиск партии по Серийному номеру или по Штрих-коду

                if (!String.IsNullOrEmpty(_params.parSearch))
                {
                }

                #endregion

                //По дате
                if (_params.DateS != null)
                {
                    query = query.Where(x => x.DocDate >= _params.DateS && x.DocDate <= _params.DatePo);
                }
                //По складу
                if (_params.DirWarehouseID > 0)
                {
                    query = query.Where(x => x.DirWarehouseID == _params.DirWarehouseID);
                }

                #endregion


                #region Отправка JSON

                //А вдруг к-во меньше Лимита, тогда показать не общее к-во, а реальное!
                int dirCount = query.Count();

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

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Exemplo n.º 16
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
        }
Exemplo n.º 17
0
        internal async Task <DirWarehouse> mPutPostDirWarehouse(
            DbConnectionSklad db,
            DirWarehouse dirWarehouse,
            EntityState entityState,          //EntityState.Added, Modified

            Classes.Account.Login.Field field //Дополнительные данные о сотруднике
            )
        {
            if (dirWarehouse.SmenaClose && (dirWarehouse.SmenaCloseTime == null || dirWarehouse.SmenaCloseTime.Length != 5))
            {
                throw new System.InvalidOperationException("Не верное времмя закрытия смены ККМ!");
            }


            db.Entry(dirWarehouse).State = entityState;
            await Task.Run(() => db.SaveChangesAsync());


            #region Sub (Локации)

            //Если создаём новый склад, то создаём новые под-склады
            if (entityState == EntityState.Added)
            {
                //1.1. Списание
                Models.Sklad.Dir.DirWarehouse dirWarehouse1 = new DirWarehouse();
                dirWarehouse1.Sub                 = dirWarehouse.DirWarehouseID;
                dirWarehouse1.DirBankID           = dirWarehouse.DirBankID;
                dirWarehouse1.DirCashOfficeID     = dirWarehouse.DirCashOfficeID;
                dirWarehouse1.DirWarehouseAddress = dirWarehouse.DirWarehouseAddress;
                dirWarehouse1.Phone               = dirWarehouse.Phone;
                dirWarehouse1.DirWarehouseName    = dirWarehouse.DirWarehouseName + SubWar1;
                dirWarehouse1.DirWarehouseLoc     = 1;

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


                //1.2. Возвраты
                Models.Sklad.Dir.DirWarehouse dirWarehouse2 = new DirWarehouse();
                dirWarehouse2.Sub                 = dirWarehouse.DirWarehouseID;
                dirWarehouse2.DirBankID           = dirWarehouse.DirBankID;
                dirWarehouse2.DirCashOfficeID     = dirWarehouse.DirCashOfficeID;
                dirWarehouse2.DirWarehouseAddress = dirWarehouse.DirWarehouseAddress;
                dirWarehouse2.Phone               = dirWarehouse.Phone;
                dirWarehouse2.DirWarehouseName    = dirWarehouse.DirWarehouseName + SubWar2;
                dirWarehouse2.DirWarehouseLoc     = 2;

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


                //1.3. Заказы для ремонтов
                Models.Sklad.Dir.DirWarehouse dirWarehouse3 = new DirWarehouse();
                dirWarehouse3.Sub                 = dirWarehouse.DirWarehouseID;
                dirWarehouse3.DirBankID           = dirWarehouse.DirBankID;
                dirWarehouse3.DirCashOfficeID     = dirWarehouse.DirCashOfficeID;
                dirWarehouse3.DirWarehouseAddress = dirWarehouse.DirWarehouseAddress;
                dirWarehouse3.Phone               = dirWarehouse.Phone;
                dirWarehouse3.DirWarehouseName    = dirWarehouse.DirWarehouseName + SubWar3;
                dirWarehouse3.DirWarehouseLoc     = 3;

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


                //1.4. Предзаказы
                Models.Sklad.Dir.DirWarehouse dirWarehouse4 = new DirWarehouse();
                dirWarehouse4.Sub                 = dirWarehouse.DirWarehouseID;
                dirWarehouse4.DirBankID           = dirWarehouse.DirBankID;
                dirWarehouse4.DirCashOfficeID     = dirWarehouse.DirCashOfficeID;
                dirWarehouse4.DirWarehouseAddress = dirWarehouse.DirWarehouseAddress;
                dirWarehouse4.Phone               = dirWarehouse.Phone;
                dirWarehouse4.DirWarehouseName    = dirWarehouse.DirWarehouseName + SubWar4;
                dirWarehouse4.DirWarehouseLoc     = 4;

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


                //1.5. БУ.Разбор
                Models.Sklad.Dir.DirWarehouse dirWarehouse5 = new DirWarehouse();
                dirWarehouse5.Sub                 = dirWarehouse.DirWarehouseID;
                dirWarehouse5.DirBankID           = dirWarehouse.DirBankID;
                dirWarehouse5.DirCashOfficeID     = dirWarehouse.DirCashOfficeID;
                dirWarehouse5.DirWarehouseAddress = dirWarehouse.DirWarehouseAddress;
                dirWarehouse5.Phone               = dirWarehouse.Phone;
                dirWarehouse5.DirWarehouseName    = dirWarehouse.DirWarehouseName + SubWar5;
                dirWarehouse5.DirWarehouseLoc     = 5;

                db.Entry(dirWarehouse5).State = EntityState.Added;
                await Task.Run(() => db.SaveChangesAsync());
            }
            else
            {
                //1.1. Списание
                var query1 = await db.DirWarehouses.Where(x => x.Sub == dirWarehouse.DirWarehouseID && x.DirWarehouseLoc == 1).ToListAsync();

                if (query1.Count() > 0)
                {
                    Models.Sklad.Dir.DirWarehouse dirWarehouse1 = query1[0];
                    dirWarehouse1.DirBankID           = dirWarehouse.DirBankID;
                    dirWarehouse1.DirCashOfficeID     = dirWarehouse.DirCashOfficeID;
                    dirWarehouse1.DirWarehouseAddress = dirWarehouse.DirWarehouseAddress;
                    dirWarehouse1.Phone            = dirWarehouse.Phone;
                    dirWarehouse1.DirWarehouseName = dirWarehouse.DirWarehouseName + SubWar1;
                    dirWarehouse1.DirWarehouseLoc  = 1;

                    db.Entry(dirWarehouse1).State = EntityState.Modified;
                    await Task.Run(() => db.SaveChangesAsync());
                }


                //1.2. Возвраты
                var query2 = await db.DirWarehouses.Where(x => x.Sub == dirWarehouse.DirWarehouseID && x.DirWarehouseLoc == 2).ToListAsync();

                if (query2.Count() > 0)
                {
                    Models.Sklad.Dir.DirWarehouse dirWarehouse1 = query2[0];
                    dirWarehouse1.DirBankID           = dirWarehouse.DirBankID;
                    dirWarehouse1.DirCashOfficeID     = dirWarehouse.DirCashOfficeID;
                    dirWarehouse1.DirWarehouseAddress = dirWarehouse.DirWarehouseAddress;
                    dirWarehouse1.Phone            = dirWarehouse.Phone;
                    dirWarehouse1.DirWarehouseName = dirWarehouse.DirWarehouseName + SubWar2;
                    dirWarehouse1.DirWarehouseLoc  = 2;

                    db.Entry(dirWarehouse1).State = EntityState.Modified;
                    await Task.Run(() => db.SaveChangesAsync());
                }


                //1.3. Заказы для ремонтов
                var query3 = await db.DirWarehouses.Where(x => x.Sub == dirWarehouse.DirWarehouseID && x.DirWarehouseLoc == 3).ToListAsync();

                if (query3.Count() > 0)
                {
                    Models.Sklad.Dir.DirWarehouse dirWarehouse1 = query3[0];
                    dirWarehouse1.DirBankID           = dirWarehouse.DirBankID;
                    dirWarehouse1.DirCashOfficeID     = dirWarehouse.DirCashOfficeID;
                    dirWarehouse1.DirWarehouseAddress = dirWarehouse.DirWarehouseAddress;
                    dirWarehouse1.Phone            = dirWarehouse.Phone;
                    dirWarehouse1.DirWarehouseName = dirWarehouse.DirWarehouseName + SubWar3;
                    dirWarehouse1.DirWarehouseLoc  = 3;

                    db.Entry(dirWarehouse1).State = EntityState.Modified;
                    await Task.Run(() => db.SaveChangesAsync());
                }


                //1.4. Предзаказы
                var query4 = await db.DirWarehouses.Where(x => x.Sub == dirWarehouse.DirWarehouseID && x.DirWarehouseLoc == 4).ToListAsync();

                if (query4.Count() > 0)
                {
                    Models.Sklad.Dir.DirWarehouse dirWarehouse1 = query4[0];
                    dirWarehouse1.DirBankID           = dirWarehouse.DirBankID;
                    dirWarehouse1.DirCashOfficeID     = dirWarehouse.DirCashOfficeID;
                    dirWarehouse1.DirWarehouseAddress = dirWarehouse.DirWarehouseAddress;
                    dirWarehouse1.Phone            = dirWarehouse.Phone;
                    dirWarehouse1.DirWarehouseName = dirWarehouse.DirWarehouseName + SubWar4;
                    dirWarehouse1.DirWarehouseLoc  = 4;

                    db.Entry(dirWarehouse1).State = EntityState.Modified;
                    await Task.Run(() => db.SaveChangesAsync());
                }


                //1.5. БУ.Разбор
                var query5 = await db.DirWarehouses.Where(x => x.Sub == dirWarehouse.DirWarehouseID && x.DirWarehouseLoc == 5).ToListAsync();

                if (query5.Count() > 0)
                {
                    Models.Sklad.Dir.DirWarehouse dirWarehouse1 = query5[0];
                    dirWarehouse1.DirBankID           = dirWarehouse.DirBankID;
                    dirWarehouse1.DirCashOfficeID     = dirWarehouse.DirCashOfficeID;
                    dirWarehouse1.DirWarehouseAddress = dirWarehouse.DirWarehouseAddress;
                    dirWarehouse1.Phone            = dirWarehouse.Phone;
                    dirWarehouse1.DirWarehouseName = dirWarehouse.DirWarehouseName + SubWar5;
                    dirWarehouse1.DirWarehouseLoc  = 5;

                    db.Entry(dirWarehouse1).State = EntityState.Modified;
                    await Task.Run(() => db.SaveChangesAsync());
                }
            }


            #endregion


            return(dirWarehouse);
        }
Exemplo n.º 18
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))));
            }
        }
        // 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))));
            }
        }
Exemplo n.º 20
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))));
            }
        }
Exemplo n.º 21
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))));
            }
        }
Exemplo n.º 22
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))));
            }
        }
Exemplo n.º 23
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
        }
Exemplo n.º 24
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);
        }
Exemplo n.º 25
0
        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))));
            }
        }
Exemplo n.º 26
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
        }
Exemplo n.º 27
0
        // 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))));
            }
        }
Exemplo n.º 28
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))));
            }
        }
Exemplo 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))));
            }
        }
Exemplo n.º 30
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
        }