public async Task <IHttpActionResult> PutDirEmployeeHistory(int id, DirEmployeeHistory dirEmployeeHistory)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != dirEmployeeHistory.DirEmployeeHistoryID)
            {
                return(BadRequest());
            }

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

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

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public async Task <IHttpActionResult> GetDirEmployeeHistory(int id)
        {
            DirEmployeeHistory dirEmployeeHistory = await db.DirEmployeeHistories.FindAsync(id);

            if (dirEmployeeHistory == null)
            {
                return(NotFound());
            }

            return(Ok(dirEmployeeHistory));
        }
        public async Task <IHttpActionResult> PostDirEmployeeHistory(DirEmployeeHistory dirEmployeeHistory)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.DirEmployeeHistories.Add(dirEmployeeHistory);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = dirEmployeeHistory.DirEmployeeHistoryID }, dirEmployeeHistory));
        }
        public async Task <IHttpActionResult> DeleteDirEmployeeHistory(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
            {
                DirEmployeeHistory dirEmployeeHistory = await db.DirEmployeeHistories.FindAsync(id);

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


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

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

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


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

                dynamic collectionWrapper = new
                {
                    ID  = dirEmployeeHistory.DirEmployeeHistoryID,
                    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.º 5
0
        //Сохранение
        private void mPutPostDirEmployee(
            DirEmployee dirEmployee,
            EntityState entityState, //EntityState.Added, Modified
            Models.Sklad.Dir.DirEmployeeWarehouses[] dirEmployeeWarehousesCollection,

            Classes.Account.Login.Field field //Для "ExistPay"
            )
        {
            using (System.Data.Entity.DbContextTransaction ts = db.Database.BeginTransaction())
            {
                #region 1. DirEmployee

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

                #endregion

                #region 2. dirEmployeeWarehouses *** *** *** *** *** *** *** *** *** ***


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


                //3.3. Проверяем, что бы склады не повторялись:
                for (int i = 0; i < dirEmployeeWarehousesCollection.Length; i++)
                {
                    for (int j = i + 1; j < dirEmployeeWarehousesCollection.Length; j++)
                    {
                        //Суммы равны
                        if (dirEmployeeWarehousesCollection[i].DirWarehouseID == dirEmployeeWarehousesCollection[j].DirWarehouseID)
                        {
                            ts.Rollback(); db.Database.Connection.Close();
                            throw new System.InvalidOperationException(Classes.Language.Sklad.Language.msg121);
                        }
                    }
                }


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

                #endregion

                #region 2. DirEmployeeHistory

                //Получаем историю
                DirEmployeeHistory dirEmployeeHistory = new DirEmployeeHistory();
                dirEmployeeHistory.DirEmployeeID    = Convert.ToInt32(dirEmployee.DirEmployeeID);
                dirEmployeeHistory.HistoryDate      = DateTime.Now;
                dirEmployeeHistory.DirCurrencyID    = dirEmployee.DirCurrencyID;
                dirEmployeeHistory.Salary           = dirEmployee.Salary;
                dirEmployeeHistory.SalaryDayMonthly = dirEmployee.SalaryDayMonthly;
                dirEmployeeHistory.DirBonusID       = dirEmployee.DirBonusID;


                //Алгоритм:
                // - Если не найдена, то создаём сразу запись, с датой = "1800-01-01", т.к. это первая запис в истории


                //1. Ищим дату самую блискую снизу вверх (Максимум) к дате "dirEmployeeHistory.DirEmployeeHistoryDate"
                //   Возмоно 2-а варианта: "есть дата" и "нет даты"
                var queryMax =
                    db.DirEmployeeHistories.
                    Where(x => x.DirEmployeeID == dirEmployee.DirEmployeeID).
                    GroupBy(g => new { g.HistoryDate, g.DirEmployeeHistoryID, g.DirCurrencyID, g.Salary, g.DirBonusID, g.SalaryDayMonthly }).
                    Where(grp => grp.Max(m => m.HistoryDate) <= dirEmployeeHistory.HistoryDate).
                    Select(x => x.Key).OrderByDescending(o => o.HistoryDate).FirstOrDefault();

                //var queryMax = queryMax1.ToList();

                //if (queryMax.Count() == 0)
                if (queryMax == null)
                {
                    //2. Нет данных: "INSERT", создаем новую запись в Истории
                    dirEmployeeHistory.HistoryDate     = Convert.ToDateTime("1800-01-01");
                    db.Entry(dirEmployeeHistory).State = EntityState.Added;
                }
                else
                {
                    //3.1. Если реквизиты совпадают, то ничего не делаем
                    //     - Если нет, то:
                    //       - Даты совпадают - UPDATE
                    //       - Даты не совпадают - INSERT

                    //Если не совпадают реквизиты
                    if (
                        queryMax.DirCurrencyID != dirEmployeeHistory.DirCurrencyID ||
                        queryMax.Salary != dirEmployeeHistory.Salary ||
                        queryMax.DirBonusID != dirEmployeeHistory.DirBonusID ||
                        queryMax.SalaryDayMonthly != dirEmployeeHistory.SalaryDayMonthly
                        )
                    {
                        if (Convert.ToDateTime(queryMax.HistoryDate).ToString("yyyy-MM-dd") == Convert.ToDateTime(dirEmployeeHistory.HistoryDate).ToString("yyyy-MM-dd"))
                        {
                            //"HistoryID" который надо обновить, т.к. обновляет по PK
                            dirEmployeeHistory.DirEmployeeHistoryID = queryMax.DirEmployeeHistoryID;

                            //  - Даты совпадают - UPDATE
                            db.Entry(dirEmployeeHistory).State = EntityState.Modified;
                        }
                        else
                        {
                            //  - Даты не совпадают - INSERT
                            db.Entry(dirEmployeeHistory).State = EntityState.Added;

                            //3.2. Если следуящая запись (вверх, до этого нижнюю смотрели) равна (Rate, Multy) вставляемой, то удалить её!
                            var queryMin =
                                db.DirEmployeeHistories.
                                Where(x => x.DirEmployeeID == dirEmployee.DirEmployeeID).
                                GroupBy(g => new { g.HistoryDate, g.DirEmployeeHistoryID, g.DirCurrencyID, g.Salary, g.DirBonusID, g.SalaryDayMonthly }).
                                Where(grp => grp.Min(m => m.HistoryDate) >= dirEmployeeHistory.HistoryDate).
                                Select(x => x.Key).
                                ToList();
                            if (
                                queryMin.Count() > 0 &&
                                queryMin[0].DirCurrencyID == dirEmployeeHistory.DirCurrencyID &&
                                queryMin[0].Salary == dirEmployeeHistory.Salary &&
                                queryMin[0].DirBonusID == dirEmployeeHistory.DirBonusID &&
                                queryMin[0].SalaryDayMonthly == dirEmployeeHistory.SalaryDayMonthly
                                )
                            {
                                DirEmployeeHistory dirEmployeeHistoryMin = db.DirEmployeeHistories.Find(queryMin[0].DirEmployeeHistoryID);
                                db.Entry(dirEmployeeHistoryMin).State = EntityState.Deleted;
                            }
                        }
                    }
                }

                db.SaveChanges();

                #endregion


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

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

                #endregion
            }
        }