Exemplo n.º 1
0
        public async Task <IHttpActionResult> PutDirBonus2Tab(int id, DirBonus2Tab dirBonus2Tab)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != dirBonus2Tab.DirBonus2TabID)
            {
                return(BadRequest());
            }

            db.Entry(dirBonus2Tab).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DirBonus2TabExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 2
0
        public async Task <IHttpActionResult> PutListObjectFieldName(int id, ListObjectFieldName listObjectFieldName)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != listObjectFieldName.ListObjectFieldNameID)
            {
                return(BadRequest());
            }

            db.Entry(listObjectFieldName).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ListObjectFieldNameExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 3
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.º 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
Arquivo: Docs.cs Projeto: mobile-v/CRM
        internal async Task <Models.Sklad.Doc.Doc> Save()
        {
            //Проверка Удалён ли документ, если удалён, то не сохранять
            if (await Deleted())
            {
                throw new System.InvalidOperationException(Classes.Language.Sklad.Language.msg85);
            }

            //Проверка Инвентаризирован ли документ, если Инвентаризирован, то не сохранять
            //if (Convert.ToBoolean(doc.Held) && await Inv()) { throw new System.InvalidOperationException(Classes.Language.Sklad.Language.msg85_1); }
            //if (Convert.ToBoolean(doc.Held)) { await Inv(); }
            await Inv();


            //Дата проведения
            if (!Convert.ToBoolean(doc.Held))
            {
                doc.DocDateHeld = doc.DocDate;
            }
            else
            {
                doc.DocDateHeld = DateTime.Now;
            }

            if (entityState == EntityState.Added)
            {
                doc.DocDateCreate = DateTime.Now;
            }

            //Дата оплаты (проверить, если нет оплаты, то ставить дату Документа)
            if (doc.Payment == 0)
            {
                doc.DocDatePayment = doc.DocDate;
            }
            else
            {
                if (doc.DocDatePayment == null)
                {
                    Models.Sklad.Doc.Doc docX = await dbRead.Docs.FindAsync(doc.DocID);

                    doc.DocDatePayment = docX.DocDatePayment;
                }
            }



            //Сохраянем
            if (doc.DirPaymentTypeID == null)
            {
                doc.DirPaymentTypeID = 1;
            }
            db.Entry(doc).State = entityState;
            await db.SaveChangesAsync();

            return(doc);
        }
Exemplo n.º 6
0
        //Используется в новых платежах по документу
        internal async Task <DocBankSum> mPutPostDocBankSum_2(
            DbConnectionSklad db,
            DocBankSum docBankSum,
            EntityState entityState         //EntityState.Added, Modified
            )
        {
            //Удалить платеж, но перед этим проверить был ли Z-отчет
            if (docBankSum.DocBankSumID > 0)
            {
                //Получем по "DocBankSumID" предыдущие значения платежа
                Models.Sklad.Doc.DocBankSum docBankSum_OLD = await Task.Run(() => db.DocBankSums.FindAsync(docBankSum.DocBankSumID));

                //Удаляем платеж
                db.Entry(docBankSum_OLD).State = EntityState.Deleted;
                await Task.Run(() => db.SaveChangesAsync());
            }


            //По кассе получаем
            Models.Sklad.Dir.DirBank dirBank = db.DirBanks.Find(docBankSum.DirBankID);

            //Проверка
            //1. В зависимости от "DirBankSumTypeID" сумма с "+" или с "-"
            Models.Sklad.Dir.DirBankSumType dirBankSumType = db.DirBankSumTypes.Find(docBankSum.DirBankSumTypeID);
            docBankSum.DocBankSumSum = dirBankSumType.Sign * docBankSum.DocBankSumSum;
            //2. Если изъятие из кассы и сумма в кассе меньше чем надо ихъять
            if (dirBankSumType.Sign < 0 && dirBank.DirBankSum < Math.Abs(docBankSum.DocBankSumSum))
            {
                throw new System.InvalidOperationException(
                          Classes.Language.Sklad.Language.msg27_4 + dirBank.DirBankSum +
                          Classes.Language.Sklad.Language.msg27_5 + Math.Abs(docBankSum.DocBankSumSum) +
                          Classes.Language.Sklad.Language.msg27_6
                          );
            }

            //4. Сохранение
            db.Entry(docBankSum).State = entityState;
            await Task.Run(() => db.SaveChangesAsync());

            //5. Ретурн
            return(docBankSum);
        }
Exemplo n.º 7
0
        internal async Task <DirNomenCategory> mPutPostDirNomenCategories(
            DbConnectionSklad db,
            DirNomenCategory dirNomenCategory,
            EntityState entityState //EntityState.Added, Modified
            )
        {
            db.Entry(dirNomenCategory).State = entityState;
            await db.SaveChangesAsync();

            return(dirNomenCategory);
        }
Exemplo n.º 8
0
        internal async Task <string> ReturnGenID(DbConnectionSklad db)
        //internal string ReturnGenID(DbConnectionSklad db)
        {
            Models.Sklad.Sys.SysGen sysGen = new Models.Sklad.Sys.SysGen();
            sysGen.SysGenID        = null;
            sysGen.SysGenTemp      = true;
            db.Entry(sysGen).State = EntityState.Added;
            await db.SaveChangesAsync();

            //db.SaveChangesAsync();

            string SysGenID = sysGen.SysGenID.ToString();

            return(SysGenID);
        }
Exemplo n.º 9
0
        //Сохранение
        internal async Task <DocBankSum> mPutPostDocBankSum(
            DbConnectionSklad db,
            DocBankSum docBankSum,
            EntityState entityState         //EntityState.Added, Modified
            )
        {
            //1. Дата операции
            DateTime DocBankSumDate = DateTime.Now;

            docBankSum.DocBankSumDate = DocBankSumDate;
            docBankSum.DateOnly       = Convert.ToDateTime(DocBankSumDate.ToString("yyyy-MM-dd"));
            //2. Валюта
            //2.1. По кассе получаем
            Models.Sklad.Dir.DirBank dirBank = db.DirBanks.Find(docBankSum.DirBankID);
            //2.2. Получаем Курсы
            Models.Sklad.Dir.DirCurrency dirCurrency = db.DirCurrencies.Find(dirBank.DirCurrencyID);
            docBankSum.DirCurrencyID           = dirCurrency.DirCurrencyID;
            docBankSum.DirCurrencyRate         = dirCurrency.DirCurrencyRate;
            docBankSum.DirCurrencyMultiplicity = dirCurrency.DirCurrencyMultiplicity;

            //3. Проверка
            //3.1. В зависимости от "DirBankSumTypeID" сумма с "+" или с "-"
            Models.Sklad.Dir.DirBankSumType dirBankSumType = db.DirBankSumTypes.Find(docBankSum.DirBankSumTypeID);
            docBankSum.DocBankSumSum = dirBankSumType.Sign * docBankSum.DocBankSumSum;
            //3.2. Если изъятие из кассы и сумма в кассе меньше чем надо ихъять
            if (dirBankSumType.Sign < 0 && dirBank.DirBankSum < Math.Abs(docBankSum.DocBankSumSum))
            {
                throw new System.InvalidOperationException(
                          Classes.Language.Sklad.Language.msg27_4 + dirBank.DirBankSum +
                          Classes.Language.Sklad.Language.msg27_5 + Math.Abs(docBankSum.DocBankSumSum) +
                          Classes.Language.Sklad.Language.msg27_6
                          );
            }

            //4. Сохранение
            db.Entry(docBankSum).State = entityState;
            await Task.Run(() => db.SaveChangesAsync());

            //5. Ретурн
            return(docBankSum);
        }
Exemplo n.º 10
0
        internal async Task <Models.Sklad.Rem.RemPartyMinus[]> Save111(
            DbConnectionSklad _db,
            Models.Sklad.Rem.RemPartyMinus[] remPartyMinusCollection
            )
        {
            db = _db;

            //Delete(_db, remPartyMinusCollection[0].DocID);

            //Сохраняем "party" и
            //Меняем полученный ID-шник
            for (int i = 0; i < remPartyMinusCollection.Count(); i++)
            {
                //party
                db.Entry(remPartyMinusCollection[i]).State = EntityState.Added;
                //await db.SaveChangesAsync();
            }
            await db.SaveChangesAsync();

            return(remPartyMinusCollection);
        }
Exemplo n.º 11
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.º 12
0
        public async Task <IHttpActionResult> PostDocServicePurch1Tab(DocServicePurch1Tab docServicePurch1Tab, HttpRequestMessage request)
        {
            try
            {
                #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

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

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

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

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

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

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


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

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

                #endregion

                #region Параметры

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

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

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

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

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

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

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

                #endregion


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


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

                    try
                    {
                        #region Save docServicePurch

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


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

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

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

                        #endregion

                        #endregion


                        #region Save docServicePurch1Tab


                        #region Лог

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

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

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

                        #endregion

                        docServicePurch1Tab.DirServiceStatusID = iDirServiceStatusID;

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

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

                        #endregion


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

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



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

                #endregion
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Exemplo n.º 13
0
        public async Task <IHttpActionResult> PostDirCharTexture(DirCharTexture dirCharTexture)
        {
            #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, "RightDirCharTextures"));

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

            #endregion


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

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


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

                #endregion


                dynamic collectionWrapper = new
                {
                    ID = dirCharTexture.DirCharTextureID
                };
                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.º 14
0
        public async Task <IHttpActionResult> PutSysSetting(int id, SysSetting sysSetting)
        {
            #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

            //Получаем Куку
            System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies["CookieIPOL"];
            int iLanguage = Convert.ToInt32(authCookie["CookieL"]) - 1;

            // Проверяем Логин и Пароль
            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, "RightSysSettings"));

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

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

            #endregion

            #region Проверки

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

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

            #endregion


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

            try
            {
                db.Entry(sysSetting).State = EntityState.Modified;
                await db.SaveChangesAsync();


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

                sysJourDisp.DirDispOperationID = 7; //Изменение настроек
                sysJourDisp.DirEmployeeID      = field.DirEmployeeID;
                sysJourDisp.ListObjectID       = ListObjectID;
                sysJourDisp.TableFieldID       = 1;
                sysJourDisp.Description        = "";
                try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { }

                #endregion


                dynamic collectionWrapper = new
                {
                    ID = sysSetting.SysSettingsID
                };
                return(Ok(returnServer.Return(true, collectionWrapper)));
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }

            #endregion
        }
Exemplo n.º 15
0
        public async Task <IHttpActionResult> DeleteDocServicePurch1Tab(int id, HttpRequestMessage request)
        {
            #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

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

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

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

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

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

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

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

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

            #endregion

            #region Параметры

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

            #endregion


            #region Удаление

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

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

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

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

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


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

                    try
                    {
                        #region Лог

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

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

                        #endregion

                        #region Save

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

                        #endregion

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

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


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

            #endregion
        }
Exemplo n.º 16
0
        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.º 17
0
        internal async Task <DocSalary> mPutPostDocSalary(
            DbConnectionSklad db,
            DbConnectionSklad dbRead,
            string UO_Action,
            //DbConnectionSklad dbRead,
            //Models.Sklad.Sys.SysSetting sysSetting,
            DocSalary docSalary,
            //bool InsertUpdate, //true - Insert, false - Update
            EntityState entityState, //EntityState.Added, Modified
            Models.Sklad.Doc.DocSalaryTab[] docSalaryTabCollection,

            Classes.Account.Login.Field field //Дополнительные данные о сотруднике
            )
        {
            if (UO_Action == "save" || UO_Action == "save_close" || UO_Action == "held")
            {
                #region 1. Doc

                //Модель
                Models.Sklad.Doc.Doc doc = new Models.Sklad.Doc.Doc();
                //Присваиваем значения
                doc.ListObjectID  = ListObjectID;
                doc.IsImport      = false;
                doc.NumberInt     = docSalary.NumberInt;
                doc.NumberReal    = docSalary.DocSalaryID;
                doc.DirEmployeeID = field.DirEmployeeID;
                //doc.DirPaymentTypeID = docSalary.DirPaymentTypeID;
                doc.Payment            = 0; //docSalary.Payment;
                doc.DirContractorID    = docSalary.DirContractorIDOrg;
                doc.DirContractorIDOrg = docSalary.DirContractorIDOrg;
                doc.Discount           = docSalary.Discount;
                doc.DirVatValue        = 0;
                doc.Base        = docSalary.Base;
                doc.Description = docSalary.Description;
                doc.DocDate     = docSalary.DocDate;
                //doc.DocDisc = docSalary.DocDisc;
                if (UO_Action == "held")
                {
                    doc.Held = true;
                }
                else
                {
                    doc.Held = false;
                }
                doc.DocID     = docSalary.DocID;
                doc.DocIDBase = docSalary.DocIDBase;

                //Класс
                Docs.Docs docs = new Docs.Docs(db, dbRead, doc, entityState);
                //doc = await docs.Save();
                await Task.Run(() => docs.Save());

                //Нужно вернуть "docSalary" со всем полями!
                docSalary.DocID = doc.DocID;

                #endregion

                #region 2. DocSalary

                docSalary.DocID = doc.DocID;

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

                #region 2.1. UpdateNumberInt, если INSERT

                if (entityState == EntityState.Added && (docSalary.doc.NumberInt == null || docSalary.doc.NumberInt.Length == 0))
                {
                    doc.NumberInt  = docSalary.DocSalaryID.ToString();
                    doc.NumberReal = docSalary.DocSalaryID;
                    docs           = new Docs.Docs(db, dbRead, doc, EntityState.Modified);
                    await Task.Run(() => docs.Save());
                }
                else if (entityState == EntityState.Added)
                {
                    doc.NumberReal = docSalary.DocSalaryID;
                    docs           = new Docs.Docs(db, dbRead, doc, EntityState.Modified);
                    await Task.Run(() => docs.Save());
                }

                #endregion


                #endregion

                #region 3. DocSalaryTab

                //2.1. Удаляем записи в БД, если UPDATE
                if (entityState == EntityState.Modified)
                {
                    SQLiteParameter parDocSalaryID = new SQLiteParameter("@DocSalaryID", System.Data.DbType.Int32)
                    {
                        Value = docSalary.DocSalaryID
                    };
                    db.Database.ExecuteSqlCommand("DELETE FROM DocSalaryTabs WHERE DocSalaryID=@DocSalaryID;", parDocSalaryID);
                }

                //2.2. Проставляем ID-шник "DocSalaryID" для всех позиций спецификации
                for (int i = 0; i < docSalaryTabCollection.Count(); i++)
                {
                    docSalaryTabCollection[i].DocSalaryTabID  = null;
                    docSalaryTabCollection[i].DocSalaryID     = Convert.ToInt32(docSalary.DocSalaryID);
                    db.Entry(docSalaryTabCollection[i]).State = EntityState.Added;
                }
                await db.SaveChangesAsync();

                #endregion
            }

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

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

            #endregion


            return(docSalary);
        }
Exemplo n.º 18
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.º 19
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.º 20
0
        public async Task <IHttpActionResult> DeleteDocPurchTab(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, "RightDocPurches"));

                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();
                //docPurchTab.DocPurchID = Convert.ToInt32(paramList.FirstOrDefault(kv => string.Compare(kv.Key, "DocPurchID", true) == 0).Value);

                #endregion

                #region Проверки

                if (!ModelState.IsValid)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg91)));                     //return BadRequest(ModelState);
                }
                //Если документ "docPurchTab.DocPurchID" проведён, то выдать Эксепшн
                Models.Sklad.Doc.DocPurchTab docPurchTab = await db.DocPurchTabs.FindAsync(id);

                //Models.Sklad.Doc.Doc doc = await db.Docs.FindAsync(docPurch.DocID);
                if (Convert.ToBoolean(docPurchTab.docPurch.doc.Held))
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg57_3)));
                }

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

                #endregion


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

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

                    try
                    {
                        //db.DocPurchTabs.Remove(docPurchTab);
                        //await db.SaveChangesAsync();

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

                        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 = 5; //Удаление записи
                sysJourDisp.DirEmployeeID      = field.DirEmployeeID;
                sysJourDisp.ListObjectID       = ListObjectID;
                sysJourDisp.TableFieldID       = docPurchTab.DocPurchID;
                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> DeleteDocSalary(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));
                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, "RightDocSalaries"));

                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
                {
                    //Документ проведён!<BR>Перед удалением, нужно отменить проводку!
                    var queryHeld = await Task.Run(() =>
                                                   (
                                                       from x in dbRead.DocSalaries
                                                       where x.DocSalaryID == id
                                                       select x
                                                   ).ToListAsync());

                    if (queryHeld.Count() > 0)
                    {
                        if (Convert.ToBoolean(queryHeld[0].doc.Held))
                        {
                            return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg18))); //return BadRequest();
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
                }

                #endregion


                #region Удаление

                //Алгоритм.
                //Удаляем по порядку:
                //1. RemParties
                //2. DocSalaryTabs
                //3. DocSalaries
                //4. Docs


                //Сотрудник
                Models.Sklad.Doc.DocSalary docSalary = await db.DocSalaries.FindAsync(id);

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


                using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction())
                {
                    try
                    {
                        #region 1. Ищим DocID *** *** *** *** ***

                        //1.1. Ищим DocID
                        int iDocID     = 0;
                        var queryDocs1 = await
                                         (
                            from x in db.DocSalaries
                            where x.DocSalaryID == id
                            select x
                                         ).ToListAsync();
                        if (queryDocs1.Count() > 0)
                        {
                            iDocID = Convert.ToInt32(queryDocs1[0].DocID);
                        }
                        else
                        {
                            return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg99)));
                        }

                        #endregion


                        #region 2. DocSalaryTabs *** *** *** *** ***

                        var queryDocSalaryTabs = await
                                                 (
                            from x in db.DocSalaryTabs
                            where x.DocSalaryID == id
                            select x
                                                 ).ToListAsync();
                        for (int i = 0; i < queryDocSalaryTabs.Count(); i++)
                        {
                            Models.Sklad.Doc.DocSalaryTab docSalaryTab = await db.DocSalaryTabs.FindAsync(queryDocSalaryTabs[i].DocSalaryTabID);

                            db.DocSalaryTabs.Remove(docSalaryTab);
                            await db.SaveChangesAsync();
                        }

                        #endregion


                        #region 3. DocSalaries *** *** *** *** ***

                        var queryDocSalaries = await
                                               (
                            from x in db.DocSalaries
                            where x.DocSalaryID == id
                            select x
                                               ).ToListAsync();
                        for (int i = 0; i < queryDocSalaries.Count(); i++)
                        {
                            Models.Sklad.Doc.DocSalary docSalary1 = await db.DocSalaries.FindAsync(queryDocSalaries[i].DocSalaryID);

                            db.DocSalaries.Remove(docSalary1);
                            await db.SaveChangesAsync();
                        }

                        #endregion


                        #region 4. Doc *** *** *** *** ***

                        var queryDocs2 = await
                                         (
                            from x in db.Docs
                            where x.DocID == iDocID
                            select x
                                         ).ToListAsync();
                        for (int i = 0; i < queryDocs2.Count(); i++)
                        {
                            Models.Sklad.Doc.Doc doc = await db.Docs.FindAsync(queryDocs2[i].DocID);

                            db.Docs.Remove(doc);
                            await db.SaveChangesAsync();
                        }

                        #endregion


                        ts.Commit();


                        #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


                        dynamic collectionWrapper = new
                        {
                            ID  = id,
                            Msg = Classes.Language.Sklad.Language.msg19
                        };
                        return(Ok(returnServer.Return(true, collectionWrapper))); //return Ok(returnServer.Return(true, ""));
                    }
                    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))));
                    } //catch
                }     //DbContextTransaction

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

            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
            {
                //История Сотрудника
                var query = await
                            (
                    from x in db.DirEmployeeHistories
                    where x.DirEmployeeID == id
                    select x
                            ).ToListAsync();


                //Сотрудник
                Models.Sklad.Dir.DirEmployee dirEmployee = await db.DirEmployees.FindAsync(id);

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

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


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

                    #endregion


                    using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction())
                    {
                        //1. Сотрудника
                        try
                        {
                            //1. Историю Сотрудника
                            for (int i = 0; i < query.Count(); i++)
                            {
                                Models.Sklad.Dir.DirEmployeeHistory dirEmployeeHistory = await db.DirEmployeeHistories.FindAsync(query[i].DirEmployeeHistoryID);

                                db.DirEmployeeHistories.Remove(dirEmployeeHistory);
                                await db.SaveChangesAsync();
                            }

                            db.DirEmployees.Remove(dirEmployee);
                            await db.SaveChangesAsync();

                            ts.Commit();

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

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

                                dynamic collectionWrapper = new
                                {
                                    ID  = dirEmployee.DirEmployeeID,
                                    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))));
                            }
                        } //catch
                    }     //DbContextTransaction
                }
                else
                {
                    // === Снимаем пометку на удаление === === === === ===

                    dirEmployee.Del = false;

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

                    dynamic collectionWrapper = new
                    {
                        ID  = dirEmployee.DirEmployeeID,
                        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.º 23
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.º 24
0
        public async Task <IHttpActionResult> PutSms(int id, DirSmsTemplate dirSmsTemplate, HttpRequestMessage request)
        {
            try
            {
                #region Проверяем Логин и Пароль + Изменяем строку соединения + Права + Разные Функции

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

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

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

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

                //Права

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

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

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

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

                #endregion

                #region Параметры

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

                #endregion


                #region Проверки

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


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

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

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

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

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

                    Phone = dirEmployee.Phone;
                }

                #endregion


                #region OLD

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

                #endregion


                int DocID = 0;

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


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

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

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

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

                #endregion


                dynamic collectionWrapper = new
                {
                    Msg = res
                };
                return(Ok(returnServer.Return(true, collectionWrapper)));
            }
            catch (Exception ex)
            {
                return(Ok(returnServer.Return(false, exceptionEntry.Return(ex))));
            }
        }
Exemplo n.º 25
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.º 26
0
        public async Task <IHttpActionResult> PutDirWebShopUO(int id, DirWebShopUO dirWebShopUO)
        {
            #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, "RightDirWebShopUOs"));

            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);
            }
            if (id != dirWebShopUO.DirWebShopUOID)
            {
                return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.msg8)));                                   //return BadRequest();
            }
            //Подстановки - некоторые поля надо заполнить, если они не заполены
            //dirWebShopUO.Substitute();

            if (!dirWebShopUO.Nomen_Remains == null)
            {
                dirWebShopUO.Nomen_Remains = false;
            }
            if (!dirWebShopUO.Orders_Reserve == null)
            {
                dirWebShopUO.Orders_Reserve = false;
            }

            #endregion


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

            try
            {
                db.Entry(dirWebShopUO).State = EntityState.Modified;
                await Task.Run(() => db.SaveChangesAsync());


                //Сохраняем Доменное имя в МС Скул
                using (DbConnectionLogin con = new DbConnectionLogin("ConnStrMSSQL"))
                {
                    Models.Login.Dir.DirCustomer dirCustomer = await con.DirCustomers.FindAsync(field.DirCustomersID);

                    dirCustomer.DomainName       = dirWebShopUO.DomainName;
                    con.Entry(dirCustomer).State = EntityState.Modified;
                    con.SaveChanges();
                }


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

                Models.Sklad.Sys.SysJourDisp sysJourDisp = new Models.Sklad.Sys.SysJourDisp();
                sysJourDisp.DirDispOperationID = 4; //Изменение записи
                sysJourDisp.DirEmployeeID      = field.DirEmployeeID;
                sysJourDisp.ListObjectID       = ListObjectID;
                sysJourDisp.TableFieldID       = dirWebShopUO.DirWebShopUOID;
                sysJourDisp.Description        = "";
                try { sysJourDispsController.mPutPostSysJourDisps(db, sysJourDisp, EntityState.Added); } catch (Exception ex) { }

                #endregion


                dynamic collectionWrapper = new
                {
                    ID = dirWebShopUO.DirWebShopUOID
                };
                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.º 27
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.º 28
0
        //Алгоритм:
        //1. INSERT в "DocSecondHandReturns"
        //2. UPDATE Status в "DocSecondHandPurches"

        internal async Task <DocSecondHandReturn> mPutPostDocSecondHandReturn(
            DbConnectionSklad db,
            DbConnectionSklad dbRead,
            string UO_Action,
            //DbConnectionSklad dbRead,
            //Models.Sklad.Sys.SysSetting sysSetting,
            DocSecondHandReturn docSecondHandReturn,
            //bool InsertUpdate, //true - Insert, false - Update
            EntityState entityState,          //EntityState.Added, Modified
                                              //Models.Sklad.Doc.DocSecondHandReturnTab[] docSecondHandReturnTabCollection,

            Classes.Account.Login.Field field //Дополнительные данные о сотруднике
            )
        {
            #region Проверка статуса аппарата, только если:
            //DirSecondHandStatusID == 9
            //DirSecondHandStatusID_789 == 7

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

            if (docSecondHandPurch.DirSecondHandStatusID != 10 || docSecondHandPurch.DirSecondHandStatusID_789 != 7)
            {
                throw new System.InvalidOperationException("Аппарат не готов к продаже или уже возвращён!");
            }

            #endregion

            #region Меняем статус аппарата

            docSecondHandPurch.DirSecondHandStatusID = 9;
            docSecondHandPurch.DirReturnTypeID       = docSecondHandReturn.DirReturnTypeID;
            docSecondHandPurch.DirDescriptionID      = docSecondHandReturn.DirDescriptionID;

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

            #endregion


            #region 1. Doc

            //Модель
            Models.Sklad.Doc.Doc doc = new Models.Sklad.Doc.Doc();
            //Присваиваем значения
            doc.ListObjectID     = ListObjectID;
            doc.IsImport         = false;
            doc.NumberInt        = docSecondHandReturn.NumberInt;
            doc.NumberReal       = docSecondHandReturn.DocSecondHandReturnID;
            doc.DirEmployeeID    = field.DirEmployeeID;
            doc.DirPaymentTypeID = docSecondHandReturn.DirPaymentTypeID;
            doc.Payment          = docSecondHandReturn.Payment;
            if (docSecondHandReturn.DirContractorID != null)
            {
                doc.DirContractorID = Convert.ToInt32(docSecondHandReturn.DirContractorID);
            }
            else
            {
                doc.DirContractorID = docSecondHandReturn.DirContractorIDOrg;
            }
            doc.DirContractorIDOrg = docSecondHandReturn.DirContractorIDOrg;
            doc.Discount           = docSecondHandReturn.Discount;
            doc.DirVatValue        = docSecondHandReturn.DirVatValue;
            doc.Base        = docSecondHandReturn.Base;
            doc.Description = docSecondHandReturn.Description;
            doc.DocDate     = DateTime.Now; //docSecondHandReturn.DocDate;
                                            //doc.DocDisc = docSecondHandReturn.DocDisc;
            if (UO_Action == "held")
            {
                doc.Held = true;
            }
            else
            {
                doc.Held = false;
            }
            doc.DocID           = docSecondHandReturn.DocID;
            doc.DocIDBase       = docSecondHandReturn.DocIDBase;
            doc.KKMSCheckNumber = docSecondHandReturn.KKMSCheckNumber;
            doc.KKMSIdCommand   = docSecondHandReturn.KKMSIdCommand;
            doc.KKMSEMail       = docSecondHandReturn.KKMSEMail;
            doc.KKMSPhone       = docSecondHandReturn.KKMSPhone;

            //Класс
            Docs.Docs docs = new Docs.Docs(db, dbRead, doc, entityState);
            //doc = await docs.Save();
            await Task.Run(() => docs.Save());

            //Нужно вернуть "docSecondHandReturn" со всем полями!
            docSecondHandReturn.DocID = doc.DocID;

            #endregion

            #region 2. DocSecondHandReturn

            docSecondHandReturn.DocID = doc.DocID;

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

            #region 2.1. UpdateNumberInt, если INSERT

            if (entityState == EntityState.Added && (docSecondHandReturn.doc.NumberInt == null || docSecondHandReturn.doc.NumberInt.Length == 0))
            {
                doc.NumberInt  = docSecondHandReturn.DocSecondHandReturnID.ToString();
                doc.NumberReal = docSecondHandReturn.DocSecondHandReturnID;
                docs           = new Docs.Docs(db, dbRead, doc, EntityState.Modified);
                await Task.Run(() => docs.Save());
            }
            else if (entityState == EntityState.Added)
            {
                doc.NumberReal = docSecondHandReturn.DocSecondHandReturnID;
                docs           = new Docs.Docs(db, dbRead, doc, EntityState.Modified);
                await Task.Run(() => docs.Save());
            }

            #endregion


            #endregion


            #region Касса или Банк


            #region 1. Получаем валюту из склада

            int    DirCurrencyID = 0, DirCurrencyMultiplicity = 0; //, DirCashOfficeID = 0, DirBankID = 0;;
            double DirCurrencyRate = 0;

            var query = await Task.Run(() =>
                                       (
                                           from x in db.DirWarehouses
                                           where x.DirWarehouseID == docSecondHandReturn.DirWarehouseID
                                           select new
            {
                //DirCashOfficeID= x.dirCashOffice.DirCashOfficeID,
                DirCurrencyID_Bank = x.dirBank.DirCurrencyID,
                DirCurrencyRate_Bank = x.dirBank.dirCurrency.DirCurrencyRate,
                DirCurrencyMultiplicity_Bank = x.dirBank.dirCurrency.DirCurrencyMultiplicity,

                //DirBankID = x.dirBank.DirBankID,
                DirCurrencyID_Cash = x.dirCashOffice.DirCurrencyID,
                DirCurrencyRate_Cash = x.dirCashOffice.dirCurrency.DirCurrencyRate,
                DirCurrencyMultiplicity_Cash = x.dirCashOffice.dirCurrency.DirCurrencyMultiplicity,
            }
                                       ).ToListAsync());

            if (query.Count() > 0)
            {
                if (doc.DirPaymentTypeID == 1)
                {
                    //DirCashOfficeID = Convert.ToInt32(query[0].DirCashOfficeID);
                    DirCurrencyID           = query[0].DirCurrencyID_Cash;
                    DirCurrencyRate         = query[0].DirCurrencyRate_Cash;
                    DirCurrencyMultiplicity = query[0].DirCurrencyMultiplicity_Cash;
                }
                else if (doc.DirPaymentTypeID == 2)
                {
                    //DirBankID = Convert.ToInt32(query[0].DirBankID);
                    DirCurrencyID           = query[0].DirCurrencyID_Bank;
                    DirCurrencyRate         = query[0].DirCurrencyRate_Bank;
                    DirCurrencyMultiplicity = query[0].DirCurrencyMultiplicity_Bank;
                }
                else
                {
                    throw new System.InvalidOperationException("Не выбран метод оплаты: Касса или Банк!");
                }
            }

            #endregion


            #region 2. Заполняем Модель

            Models.Sklad.Pay.Pay pay = new Models.Sklad.Pay.Pay();
            //pay.DirCashOfficeID = Convert.ToInt32(DirCashOfficeID);
            //pay.DirBankID = Convert.ToInt32(DirBankID);
            //Валюта
            pay.DirCurrencyID           = DirCurrencyID;
            pay.DirCurrencyRate         = DirCurrencyRate;
            pay.DirCurrencyMultiplicity = DirCurrencyMultiplicity;

            pay.DirEmployeeID    = field.DirEmployeeID;
            pay.DirPaymentTypeID = doc.DirPaymentTypeID;
            //pay.DirXName = ""; //no
            //pay.DirXSumTypeID = 0; //no
            pay.DocCashBankID = null;
            pay.DocID         = doc.DocID;
            pay.DocXID        = docSecondHandReturn.DocSecondHandReturnID;
            pay.DocXSumDate   = doc.DocDate;
            pay.DocXSumSum    = docSecondHandReturn.PriceCurrency - doc.Discount; // - получили при сохранении Спецификации (выше) docSecondHandReturn.PriceVAT

            //DocSecondHandPurchID - найти!!!
            pay.Base = "Возврат документа №" + docSecondHandPurch.DocSecondHandPurchID; //pay.Base = "Оплата за коды товаров: " + NomenName; // - получили при сохранении Спецификации (выше)

            //pay.Description = "";
            pay.KKMSCheckNumber = docSecondHandReturn.KKMSCheckNumber;
            pay.KKMSIdCommand   = docSecondHandReturn.KKMSIdCommand;
            pay.KKMSEMail       = docSecondHandReturn.KKMSEMail;
            pay.KKMSPhone       = docSecondHandReturn.KKMSPhone;

            pay.Discount = doc.Discount;

            #endregion


            #region 3. Сохраняем

            PartionnyAccount.Controllers.Sklad.Pay.PayController payController = new Pay.PayController();
            doc = await Task.Run(() => payController.mPutPostPay(db, pay, EntityState.Modified, field)); //sysSetting

            #endregion


            #endregion


            #region 4. Log

            logService.DocSecondHandPurchID   = docSecondHandPurch.DocSecondHandPurchID;
            logService.DirSecondHandLogTypeID = 14;
            logService.DirEmployeeID          = field.DirEmployeeID;
            logService.DirSecondHandStatusID  = docSecondHandPurch.DirSecondHandStatusID;
            logService.DirWarehouseIDFrom     = docSecondHandPurch.DirWarehouseID;
            logService.DirWarehouseIDTo       = docSecondHandPurch.DirWarehouseID;
            //logService.Msg = "Аппарат принят на точку №" + docSecondHandPurch.DirWarehouseID;

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

            #endregion


            return(docSecondHandReturn);
        }
Exemplo n.º 29
0
        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);
        }
Exemplo n.º 30
0
        public async Task <IHttpActionResult> DeleteDirCurrencyHistory(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, "RightDirCurrencies"));

            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
            {
                DirCurrencyHistory dirCurrencyHistory = await db.DirCurrencyHistories.FindAsync(id);

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


                //Если Мы удаляем единственную или самую первую запись, то выдать исключение!

                //1. Единственную
                if (await db.DirCurrencyHistories.Where(x => x.DirCurrencyID == dirCurrencyHistory.DirCurrencyID).CountAsync() == 1)
                {
                    return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.Mess01)));
                }

                //2. Самую первую запись
                DateTime dt = Convert.ToDateTime("1800-01-01 00:00:00");
                var      queryDirCurrencyHistoryID = db.DirCurrencyHistories.Where(x => x.DirCurrencyID == dirCurrencyHistory.DirCurrencyID).Select(x => x.DirCurrencyHistoryID); // && x.DirCurrencyHistoryDate <= dt
                if (queryDirCurrencyHistoryID.Count() > 0)
                {
                    if (queryDirCurrencyHistoryID.Min() == dirCurrencyHistory.DirCurrencyHistoryID)
                    {
                        return(Ok(returnServer.Return(false, Classes.Language.Sklad.Language.Mess04)));
                    }
                }


                db.DirCurrencyHistories.Remove(dirCurrencyHistory);
                await db.SaveChangesAsync();

                dynamic collectionWrapper = new
                {
                    ID  = dirCurrencyHistory.DirCurrencyHistoryID,
                    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
        }