public async Task <IActionResult> Create(Tournament tournament)
        {
            if (ModelState.IsValid)
            {
                TimeSpan FromTime = TimeSpan.Parse(tournament.FromTime);
                TimeSpan Totime   = TimeSpan.Parse(tournament.ToTime);

                // == 1 --> from > to , -1 --> from <to ,  0 --> from == to
                if (TimeSpan.Compare(FromTime, Totime) != 1)
                {
                    ViewBag.ShootingFields = new SelectList(_context.ShootingFields.ToList(), "Id", "ShootingName");
                    _context.Add(tournament);
                    await _context.SaveChangesAsync();

                    TempData["message"] = NotificationSystem.AddMessage("تم اضافة الدورة بنجاح ", NotificationType.Success.Value);
                }
                else
                {
                    TempData["message"] = NotificationSystem.AddMessage("وقت البدء يجب ان يكون اصغر من وقت الانتهاء ", NotificationType.Danger.Value);
                    return(View(tournament));
                }


                return(RedirectToAction(nameof(Index)));
            }
            return(View(tournament));
        }
        public async Task <IActionResult> Edit(int id, Tournament tournament)
        {
            if (id != tournament.Id)
            {
                return(Redirect("/Error/404"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(tournament);
                    ViewBag.ShootingFields = new SelectList(_context.ShootingFields.ToList(), "Id", "ShootingName", tournament.ShootingFieldId);
                    await _context.SaveChangesAsync();

                    TempData["message"] = NotificationSystem.AddMessage("تم تعديل الدورة بنجاح ", NotificationType.Success.Value);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TournamentExists(tournament.Id))
                    {
                        return(Redirect("/Error/404"));
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(tournament));
        }
Example #3
0
        public async Task <ActionResult> Index(DateTime ReportDate, int?id)
        {
            DailyReportVM drVM = new DailyReportVM();

            // current user Id Logged In
            var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            // tournament Id assigned to current user Id
            int?TournamentId = _context.UserTournaments.Where(u => u.UserId == userId).Select(t => t.TournamentId).FirstOrDefault();

            var user = await _userManager.FindByIdAsync(userId);

            // if  id not null and user  is  viewer we set tournament id to new id else still tournament id that assign to current user
            // this condition if  id != 0 and user role is viewer (general or 3a2id abou daher )  ==> request from general or 3a2id abou daher
            if (await _userManager.IsInRoleAsync(user, "Viewer") || await _userManager.IsInRoleAsync(user, "SuperAdmin"))
            {
                TournamentId = id != 0 ? id : TournamentId;
            }

            if (TournamentId == 0)
            {
                drVM.ReportDate     = ReportDate;
                TempData["message"] = NotificationSystem.AddMessage("لا يوجد دورة ", NotificationType.Danger.Value);
                return(View(drVM));
            }
            drVM.TournamentId = (int)TournamentId;

            //  select today daily incidents
            drVM.DailyIncidents = _context.DailyIncidents.Where(t => t.TournamentId == TournamentId &&
                                                                (ReportDate.Date >= t.StartDate.Value.Date && ReportDate.Date <= t.EndDate.Value.Date)).Include(o => o.Officer).Include(r => r.ReasonOfIncident).ToList();



            // select today daily Notes
            drVM.DailyNotes = _context.DailyNotes.Where(t => t.CreationDate == ReportDate).Include(o => o.Officer).ToList();

            // select current today report
            DailyReport dr = new DailyReport();

            dr = _context.DailyReports.Where(t => t.ReportDate.Date == ReportDate.Date && t.TournamentId == TournamentId).FirstOrDefault();

            int basenumber = _context.Officers.Where(t => t.TournamentId == TournamentId).Count();

            drVM.ReportDate     = ReportDate;
            drVM.BaseNumber     = dr != null ? dr.BaseNumber : basenumber;
            drVM.ReadyNumber    = dr != null ? dr.ReadyNumber : drVM.BaseNumber;
            drVM.NotReadyNumber = drVM.BaseNumber - drVM.ReadyNumber;
            if (dr == null)
            {
                TempData["message"] = NotificationSystem.AddMessage("لا يوجد تقرير يومي في هذا التاريخ ", NotificationType.Danger.Value);
                return(View(drVM));
            }

            return(View(drVM));
        }
        public ActionResult AddDailyIncidentsForTournament(DailyIncident dailyIncident)
        {
            if (ModelState.IsValid)
            {
                if (dailyIncident.EndDate >= dailyIncident.StartDate)
                {
                    // get list of dates between
                    List <DateTime> ListOfDatesBetween = GetDatesBetween((DateTime)dailyIncident.StartDate, (DateTime)dailyIncident.EndDate);


                    // get list of officer in this tournament
                    List <Officer> officersList = _context.Officers.Where(o => o.IsActive && o.TournamentId == dailyIncident.TournamentId).ToList();
                    //loop in officer to insert fo everyone a dailyincident
                    foreach (var officer in officersList)
                    {
                        DailyIncident di = new DailyIncident();
                        di.IsActive           = true;
                        di.CreationDate       = DateTime.Now.Date;
                        di.Explanation        = dailyIncident.Explanation;
                        di.StartDate          = dailyIncident.StartDate;
                        di.EndDate            = dailyIncident.EndDate;
                        di.TournamentId       = dailyIncident.TournamentId;
                        di.OfficerId          = officer.Id;
                        di.ReasonOfIncidentId = dailyIncident.ReasonOfIncidentId;
                        // -1 cz i select each day to create daily report for it
                        di.CountDaysOfIncident = dailyIncident.NotCountDayOfIncident ?0 :ListOfDatesBetween.Count - 1;
                        _context.DailyIncidents.Add(di);
                    }

                    //loop in each day and add to daily report
                    foreach (var day in ListOfDatesBetween)
                    {
                        DailyReport dr = new DailyReport();
                        dr.IsActive       = true;
                        dr.CreationDate   = DateTime.Now.Date;
                        dr.ReportDate     = day.Date;
                        dr.BaseNumber     = officersList.Count;
                        dr.ReadyNumber    = 0;
                        dr.NotReadyNumber = officersList.Count;
                        dr.TournamentId   = dailyIncident.TournamentId;
                        _context.DailyReports.Add(dr);
                    }
                }
                else
                {
                    TempData["message"] = NotificationSystem.AddMessage("يجب التأكد من التاريخ    ", NotificationType.Danger.Value);
                    return(View(dailyIncident));
                }
                _context.SaveChanges();
            }
            return(RedirectToAction("Index"));
        }
Example #5
0
        public ActionResult AssignUserToTournament(List <UserTournamentVM> ListUserTournament, int TournamentId)
        {
            var tournament = _context.Tournaments.Find(TournamentId);

            if (tournament == null)
            {
                return(View("NotFound"));
            }
            List <UserTournament> userTournaments = new List <UserTournament>();

            for (int i = 0; i < ListUserTournament.Count; i++)
            {
                // check if has users assign already to this tournament
                if (UserAssigned(ListUserTournament[i].UserId, TournamentId))
                {
                    // get this record
                    UserTournament userTournament = _context.UserTournaments.Where(o => o.UserId == ListUserTournament[i].UserId && o.TournamentId == TournamentId).SingleOrDefault();
                    // if not selected i remove this assignment
                    if (!ListUserTournament[i].IsSelected)
                    {
                        _context.UserTournaments.Remove(userTournament);
                    }
                }
                // if user has no assignment to tournament
                else
                {
                    // if selected i create object of UserTournament and insert it to UserTournaments table
                    if (ListUserTournament[i].IsSelected)
                    {
                        UserTournament userTournament = new UserTournament();

                        // this user is never assign to a tournament
                        if (!UserAssigned(ListUserTournament[i].UserId))
                        {
                            userTournament.UserId       = ListUserTournament[i].UserId;
                            userTournament.TournamentId = TournamentId;
                        }
                        else
                        {
                            TempData["message"] = NotificationSystem.AddMessage("لا يمكن تعيين دور لمستخدم لأكثر من دورة", NotificationType.Danger.Value);
                            return(RedirectToAction("AssignUserToTournament", new { id = TournamentId }));
                        }

                        _context.UserTournaments.Add(userTournament);
                    }
                }
            }
            _context.SaveChanges();
            return(RedirectToAction("Index", "Tournaments"));
        }
        public async Task <IActionResult> Login(LoginVM loginVM)
        {
            if (ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(loginVM.Email, loginVM.Password, loginVM.RememberMe, false);

                if (result.Succeeded)
                {
                    TempData["message"] = NotificationSystem.AddMessage("تم تسجيل الدخول  بنجاح ", NotificationType.Success.Value);

                    return(RedirectToAction("Index", "Tournaments"));
                }

                ModelState.AddModelError(string.Empty, "كلمة المرور او البريد الاكتروني غير صحيح");
            }
            return(View());
        }
        public ActionResult AddDailyIncidentsForTournament(int id)
        {
            Tournament tournament = _context.Tournaments.Find(id);

            DailyIncident di = new DailyIncident();

            ViewBag.DDLReason = new SelectList(_context.ReasonOfIncidents.ToList().OrderBy(n => n.Name), "Id", "Name");

            if (tournament == null)
            {
                TempData["message"] = NotificationSystem.AddMessage("لا يوجد دورة", NotificationType.Danger.Value);
                return(View(di));
            }
            ViewBag.TournamnetName = tournament.Name;
            di.TournamentId        = id;
            return(View(di));
        }
        public async Task <IActionResult> Create(TournamentVM tournamentVM)
        {
            if (ModelState.IsValid)
            {
                string image = "default_tournament_image.jpg";
                _fileManagementController = new FileManagementController(_appEnvironment);

                #region Image
                //if we uploaded an image
                if (tournamentVM.TournamentImage != null)
                {
                    //  #region File Upload Validation
                    bool fileUploadError = _fileManagementController.ValidateFileUploadExtensionAndSize(ModelState, tournamentVM.TournamentImage, FileType.Image, 2);
                    //return error if there is a file upload Error
                    if (fileUploadError)
                    {
                        TempData["message"] = NotificationSystem.AddMessage("لقد حصل خطأ في تحميل الملف", NotificationType.Danger.Value);
                        return(View(tournamentVM));
                    }
                    // upload and remove existing
                    image = _fileManagementController.UploadFile(tournamentVM.TournamentImage, "Media/Tournament");
                }
                #endregion

                // create tournament
                Tournament tournament = new Tournament()
                {
                    TournamentImage = image,
                    Name            = tournamentVM.Name,
                    Note            = tournamentVM.Note,
                    CreationDate    = DateTime.Now.Date,
                    IsActive        = true
                };

                _context.Add(tournament);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(tournamentVM));
        }
        public async Task <IActionResult> Edit(OfficerVM officerVM)
        {
            if (ModelState.IsValid)
            {
                string image = "defaultofficer.png";
                _fileManagementController = new FileManagementController(_appEnvironment);

                #region Image
                //if we uploaded an image
                if (officerVM.Profileimage != null)
                {
                    //  #region File Upload Validation
                    bool fileUploadError = _fileManagementController.ValidateFileUploadExtensionAndSize(ModelState, officerVM.Profileimage, FileType.Image, 2);
                    //return error if there is a file upload Error
                    if (fileUploadError)
                    {
                        TempData["message"] = NotificationSystem.AddMessage("لقد حصل خطأ في تحميل الملف", NotificationType.Danger.Value);
                        return(View(officerVM));
                    }
                    // upload and remove existing
                    image = _fileManagementController.UploadFile(officerVM.Profileimage, "Media/Officer_Profile");
                }
                else
                {
                    image = officerVM.ExistingImage;
                }
                #endregion

                // create officer
                Officer officer = new Officer()
                {
                    Id                    = officerVM.Id,
                    TournamentId          = officerVM.TournamentId,
                    Name                  = officerVM.Name,
                    MilitaryNumber        = officerVM.MilitaryNumber,
                    PhoneNumber           = officerVM.PhoneNumber,
                    Email                 = officerVM.Email,
                    BirthAddress          = officerVM.BirthAddress,
                    BirthDate             = officerVM.BirthDate,
                    Nationality           = officerVM.Nationality,
                    Address               = officerVM.Address,
                    BloodType             = officerVM.BloodType,
                    Height                = officerVM.Height,
                    PreviousJob           = officerVM.PreviousJob,
                    HealthProblem         = officerVM.HealthProblem,
                    RatingEnteringYear    = officerVM.RatingEnteringYear,
                    RatingEnteringNumber  = officerVM.RatingEnteringNumber,
                    Specialization        = officerVM.Specialization,
                    RatingGradutionYear   = officerVM.RatingGradutionYear,
                    RatingGradutionNumber = officerVM.RatingGradutionNumber,
                    Notes                 = officerVM.Notes,
                    ProfileImage          = image,
                    IsActive              = true,
                    CreationDate          = DateTime.Now
                };
                _context.Officers.Update(officer);



                // clear all EducationalAttainments for current officer
                ClearEducationalAttainments(officerVM.Id);
                // loop each row in educational list then insert to database
                foreach (EducationalAttainment item in officerVM.EducationalAttainments)
                {
                    EducationalAttainment educationalAttainment = new EducationalAttainment()
                    {
                        Certificate = item.Certificate,
                        Source      = item.Source,
                        Date        = item.Date,
                        Grade       = item.Grade,
                        OfficerId   = officer.Id
                    };
                    _context.EducationalAttainments.Update(educationalAttainment);
                }


                // clear all Language for current officer
                ClearLanguages(officerVM.Id);
                // loop each row in Language list then insert to database
                foreach (Language item in officerVM.Languages)
                {
                    Language language = new Language()
                    {
                        Name      = item.Name,
                        Listen    = item.Listen,
                        Speak     = item.Speak,
                        Read      = item.Read,
                        Write     = item.Write,
                        OfficerId = officer.Id
                    };
                    _context.Languages.Update(language);
                }

                // clear all Hobbies for current officer
                ClearHobbies(officerVM.Id);
                // loop each row in Hobby list then insert to database
                foreach (Hobby item in officerVM.Hobbies)
                {
                    Hobby hobby = new Hobby()
                    {
                        Name        = item.Name,
                        Explanation = item.Explanation,
                        Level       = item.Level,
                        OfficerId   = officer.Id
                    };
                    _context.Hobbies.Update(hobby);
                }

                await _context.SaveChangesAsync();

                TempData["message"] = NotificationSystem.AddMessage("تم تعديل ضابط بنجاح", NotificationType.Success.Value);
                return(RedirectToAction(nameof(Index)));
            }
            return(View(officerVM));
        }
        public async Task <IActionResult> Create(OfficerVM officerVM, int TournamnetId)
        {
            // if has an error  on post i keep latest tournament
            var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            // tournament Id assigned to current user Id
            int        TournamentId = _context.UserTournaments.Where(u => u.UserId == userId).Select(t => t.TournamentId).FirstOrDefault();
            Tournament tournament   = _context.Tournaments.Where(t => t.Id == TournamentId).First(); officerVM.TournamentId = tournament.Id;

            officerVM.TournamentId   = tournament.Id;
            officerVM.TournamentName = tournament.Name;

            if (ModelState.IsValid)
            {
                using (var transaction = _context.Database.BeginTransaction())
                {
                    try
                    {
                        string image = "defaultofficer.png";
                        _fileManagementController = new FileManagementController(_appEnvironment);

                        #region Image
                        //if we uploaded an image
                        if (officerVM.Profileimage != null)
                        {
                            //  #region File Upload Validation
                            bool fileUploadError = _fileManagementController.ValidateFileUploadExtensionAndSize(ModelState, officerVM.Profileimage, FileType.Image, 2);
                            //return error if there is a file upload Error
                            if (fileUploadError)
                            {
                                TempData["message"] = NotificationSystem.AddMessage("لقد حصل خطأ في تحميل الملف", NotificationType.Danger.Value);
                                return(View(officerVM));
                            }
                            // upload and remove existing
                            image = _fileManagementController.UploadFile(officerVM.Profileimage, "Media/Officer_Profile");
                        }
                        #endregion

                        // create officer
                        Officer officer = new Officer()
                        {
                            TournamentId          = TournamnetId,
                            Name                  = officerVM.Name,
                            MilitaryNumber        = officerVM.MilitaryNumber,
                            PhoneNumber           = officerVM.PhoneNumber,
                            Email                 = officerVM.Email,
                            BirthAddress          = officerVM.BirthAddress,
                            BirthDate             = officerVM.BirthDate,
                            Nationality           = officerVM.Nationality,
                            Address               = officerVM.Address,
                            BloodType             = officerVM.BloodType,
                            Height                = officerVM.Height,
                            PreviousJob           = officerVM.PreviousJob,
                            HealthProblem         = officerVM.HealthProblem,
                            RatingEnteringYear    = officerVM.RatingEnteringYear,
                            RatingEnteringNumber  = officerVM.RatingEnteringNumber,
                            Specialization        = officerVM.Specialization,
                            RatingGradutionYear   = officerVM.RatingGradutionYear,
                            RatingGradutionNumber = officerVM.RatingGradutionNumber,
                            Notes                 = officerVM.Notes,
                            ProfileImage          = image,
                            IsActive              = true,
                            CreationDate          = DateTime.Now
                        };
                        _context.Officers.Add(officer);
                        _context.SaveChanges();



                        // loop each row in educational list then insert to database
                        foreach (EducationalAttainment item in officerVM.EducationalAttainments)
                        {
                            if (!String.IsNullOrEmpty(item.Certificate))
                            {
                                EducationalAttainment educationalAttainment = new EducationalAttainment()
                                {
                                    Certificate = item.Certificate,
                                    Source      = item.Source,
                                    Date        = item.Date,
                                    Grade       = item.Grade,
                                    OfficerId   = officer.Id
                                };
                                _context.EducationalAttainments.Add(educationalAttainment);
                            }
                        }

                        // loop each row in Language list then insert to database
                        foreach (Language item in officerVM.Languages)
                        {
                            if (!String.IsNullOrEmpty(item.Name))
                            {
                                Language language = new Language()
                                {
                                    Name      = item.Name,
                                    Listen    = item.Listen,
                                    Speak     = item.Speak,
                                    Read      = item.Read,
                                    Write     = item.Write,
                                    OfficerId = officer.Id
                                };
                                _context.Languages.Add(language);
                            }
                        }

                        // loop each row in Hobby list then insert to database
                        foreach (Hobby item in officerVM.Hobbies)
                        {
                            if (!String.IsNullOrEmpty(item.Name))
                            {
                                Hobby hobby = new Hobby()
                                {
                                    Name        = item.Name,
                                    Explanation = item.Explanation,
                                    Level       = item.Level,
                                    OfficerId   = officer.Id
                                };
                                _context.Hobbies.Add(hobby);
                            }
                        }

                        await _context.SaveChangesAsync();

                        transaction.Commit();
                        TempData["message"] = NotificationSystem.AddMessage("تم اضافة ضابط بنجاح", NotificationType.Success.Value);
                        return(RedirectToAction(nameof(Index)));
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Console.WriteLine("Error occurred.");
                    }
                }
            }
            TempData["message"] = NotificationSystem.AddMessage("يجب التأكد من حقل الدورة قبل ادخال الضابط", NotificationType.Danger.Value);

            return(View(officerVM));
        }
        public async Task <IActionResult> Edit(int id, TournamentVM tournamentVM)
        {
            if (id != tournamentVM.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    List <Officer> officers = _context.Officers.Where(t => t.TournamentId == tournamentVM.Id).ToList();

                    if (!tournamentVM.IsActive)
                    {
                        foreach (var item in officers)
                        {
                            item.IsActive = false;
                            _context.Officers.Update(item);
                        }
                    }
                    else
                    {
                        foreach (var item in officers)
                        {
                            item.IsActive = true;
                            _context.Officers.Update(item);
                        }
                    }

                    string image = "default_tournament_image.jpg";
                    _fileManagementController = new FileManagementController(_appEnvironment);

                    #region Image
                    //if we uploaded an image
                    if (tournamentVM.TournamentImage != null)
                    {
                        //  #region File Upload Validation
                        bool fileUploadError = _fileManagementController.ValidateFileUploadExtensionAndSize(ModelState, tournamentVM.TournamentImage, FileType.Image, 2);
                        //return error if there is a file upload Error
                        if (fileUploadError)
                        {
                            TempData["message"] = NotificationSystem.AddMessage("لقد حصل خطأ في تحميل الملف", NotificationType.Danger.Value);
                            return(View(tournamentVM));
                        }
                        // upload and remove existing
                        image = _fileManagementController.UploadFile(tournamentVM.TournamentImage, "Media/Tournament");
                    }
                    else
                    {
                        image = tournamentVM.ExistingTournamentImage;
                    }
                    #endregion

                    Tournament tournament = _context.Tournaments.Find(tournamentVM.Id);
                    tournament.IsActive        = tournamentVM.IsActive;
                    tournament.Name            = tournamentVM.Name;
                    tournament.Note            = tournamentVM.Note;
                    tournament.TournamentImage = image;
                    _context.Update(tournament);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TournamentExists(tournamentVM.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                TempData["message"] = NotificationSystem.AddMessage("تم تعديل الدورة بنجاح", NotificationType.Success.Value);

                return(RedirectToAction(nameof(Index)));
            }
            return(View(tournamentVM));
        }
Example #12
0
        public ActionResult Create(DailyReportVM drVM, string SubmitButton)
        {
            // check why model state is false
            var errors = ModelState
                         .Where(x => x.Value.Errors.Count > 0)
                         .Select(x => new { x.Key, x.Value.Errors })
                         .ToArray();

            if (ModelState.IsValid)
            {
                drVM.ReportDate = drVM.ReportDate != null ? drVM.ReportDate : DateTime.Today.Date;
                switch (SubmitButton)
                {
                case "بحث":

                    return(RedirectToAction("Create", new { currentReportdate = drVM.ReportDate }));


                case "اضافة":

                    if (drVM.BaseNumber == 0)
                    {
                        TempData["message"] = NotificationSystem.AddMessage("لا يوجد ضباط ", NotificationType.Danger.Value);
                        return(View(drVM));
                    }
                    // daily report

                    /// check if report exist today cz Report Date only inserted one time
                    DailyReport dr_today = _context.DailyReports.Where(t => t.TournamentId == drVM.TournamentId &&
                                                                       (drVM.ReportDate.Date == t.ReportDate.Date)).FirstOrDefault();
                    if (dr_today == null)
                    {
                        DailyReport dr = new DailyReport()
                        {
                            TournamentId   = drVM.TournamentId,
                            IsActive       = true,
                            CreationDate   = DateTime.Today.Date,
                            ReportDate     = drVM.ReportDate,
                            BaseNumber     = drVM.BaseNumber,
                            ReadyNumber    = drVM.ReadyNumber,
                            NotReadyNumber = drVM.NotReadyNumber
                        };
                        _context.DailyReports.Add(dr);
                    }
                    else
                    {
                        dr_today.ReadyNumber    = drVM.ReadyNumber;
                        dr_today.NotReadyNumber = dr_today.NotReadyNumber;
                        _context.DailyReports.Update(dr_today);
                    }

                    // count of incidents already in database and today
                    int counttodayincidents = 0;
                    // loop in old record incidents
                    if (drVM.TodayDailyIncidents != null && drVM.TodayDailyIncidents.Count > 0)
                    {
                        counttodayincidents = drVM.TodayDailyIncidents.Count;
                        foreach (var item in drVM.TodayDailyIncidents)
                        {
                            // find existed daily incident
                            DailyIncident di = _context.DailyIncidents.Find(item.Id);

                            // if the daily incident of officer is finished , we need to update enddate to today
                            if (item.IsFinish)
                            {
                                if (di == null)
                                {
                                    TempData["message"] = NotificationSystem.AddMessage("حصل خطأ في احد وقوعات الضباط ", NotificationType.Danger.Value);
                                    return(View(drVM));
                                }
                                // count day between start date and report date ,  cz when i finish some incident  enddate updated to current report date
                                int countdaybetween = GetCountdaysBetween((DateTime?)item.StartDate, (DateTime?)drVM.ReportDate);

                                // this incident will finish in current date posted
                                di.EndDate             = drVM.ReportDate;
                                di.CountDaysOfIncident = countdaybetween;
                            }
                            di.Explanation = item.Explanation;
                            _context.DailyIncidents.Update(di);

                            //di.ReasonOfIncidentId = item.ReasonOfIncidentId;
                        }
                    }


                    // loop in Daily Notes
                    int CountDailyNotePosted = 0;
                    if (drVM.DailyNotes != null)
                    {
                        foreach (var item in drVM.DailyNotes)
                        {
                            if (item.OfficerId != null || !String.IsNullOrEmpty(item.Note))
                            {
                                DailyNote dn = new DailyNote()
                                {
                                    CreationDate = drVM.ReportDate,
                                    OfficerId    = item.OfficerId,
                                    Note         = item.Note,
                                    IsActive     = true,
                                    IsImportant  = item.IsImportant,
                                    IsPositive   = item.IsPositive,
                                    TournamentId = drVM.TournamentId
                                };
                                CountDailyNotePosted++;
                                _context.DailyNotes.Add(dn);
                            }
                        }
                    }

                    drVM.CountDailyNotePosted = CountDailyNotePosted;



                    // take the records needed from Basenumber record
                    if (drVM.NotReadyNumber - counttodayincidents > 0)
                    {
                        drVM.DailyIncidents = drVM.DailyIncidents.Take(drVM.NotReadyNumber - counttodayincidents).ToList();
                        // loop in new Inserted Record of Daily Incident
                        foreach (var item in drVM.DailyIncidents)
                        {
                            if (item.OfficerId != null)
                            {
                                if (item.EndDate >= item.StartDate)
                                {
                                    int           countdaybetween = GetCountdaysBetween((DateTime?)item.StartDate, (DateTime?)item.EndDate);
                                    DailyIncident di = new DailyIncident()
                                    {
                                        CreationDate        = DateTime.Today,
                                        ReasonOfIncidentId  = item.ReasonOfIncidentId,
                                        Explanation         = item.Explanation,
                                        StartDate           = item.StartDate.Value.Date,
                                        EndDate             = item.EndDate.Value.Date,
                                        IsActive            = true,
                                        OfficerId           = item.OfficerId,
                                        CountDaysOfIncident = countdaybetween,
                                        TournamentId        = drVM.TournamentId
                                    };
                                    _context.DailyIncidents.Add(di);
                                }
                                else
                                {
                                    // if an error exist , i need to call ddlreson cz each user has reson so id need ddlreason data
                                    drVM.DDLReason      = new SelectList(_context.ReasonOfIncidents.ToList().OrderBy(n => n.Name), "Id", "Name");
                                    TempData["message"] = NotificationSystem.AddMessage("يجب التأكد من التاريخ    ", NotificationType.Danger.Value);
                                    return(View(drVM));
                                }
                            }
                            else
                            {
                                // if an error exist , i need to call ddlreson cz each user has reson so id need ddlreason data
                                drVM.DDLReason      = new SelectList(_context.ReasonOfIncidents.ToList().OrderBy(n => n.Name), "Id", "Name");
                                TempData["message"] = NotificationSystem.AddMessage("يوجد وقوعات دون ضابط ", NotificationType.Danger.Value);
                                return(View(drVM));
                            }
                        }
                    }



                    _context.SaveChanges();
                    TempData["message"] = NotificationSystem.AddMessage("تم اضافة التقرير اليومي بنجاح", NotificationType.Success.Value);
                    return(RedirectToAction("Index", new { currentreportdate = drVM.ReportDate }));
                }
            }
            TempData["message"] = NotificationSystem.AddMessage("حصل خطأ ما", NotificationType.Danger.Value);
            return(View(drVM));
        }
Example #13
0
        public ActionResult Create(DateTime?currentReportdate)
        {
            DailyReportVM drVM = new DailyReportVM();

            drVM.ReportDate = currentReportdate != null ? (DateTime)currentReportdate : DateTime.Today.Date;
            if (ModelState.IsValid)
            {
                // current user Id Logged In
                var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
                // tournament Id assigned to current user Id
                int TournamentId = _context.UserTournaments.Where(u => u.UserId == userId).Select(t => t.TournamentId).FirstOrDefault();


                Tournament tournament = TournamentId != 0 ? _context.Tournaments.Where(t => t.Id == TournamentId).First():null;

                if (tournament == null)
                {
                    TempData["message"] = NotificationSystem.AddMessage("لا يوجد دورة ", NotificationType.Danger.Value);
                    return(View(drVM));
                }

                drVM.TournamentId   = TournamentId;
                drVM.TournamentName = tournament.Name;

                drVM.BaseNumber = _context.Officers.Where(t => t.TournamentId == tournament.Id).Count();
                if (drVM.BaseNumber == 0)
                {
                    drVM.ReportDate     = drVM.ReportDate;
                    TempData["message"] = NotificationSystem.AddMessage("لا يوجد ضباط ", NotificationType.Danger.Value);
                    return(View(drVM));
                }


                // get today daily incident by date
                drVM.TodayDailyIncidents = _context.DailyIncidents.Include(o => o.Officer).Include(r => r.ReasonOfIncident)
                                           .Where(t => t.TournamentId == drVM.TournamentId &&
                                                  (drVM.ReportDate >= t.StartDate.Value.Date && drVM.ReportDate <= t.EndDate.Value.Date)).ToList();
                foreach (var item in drVM.TodayDailyIncidents)
                {
                    item.OfficerName = item.Officer.Name;
                }
                //  get distinct daily incident group by officer Id
                int CountDistinctdailyIncidents = _context.DailyIncidents.Where(t => t.TournamentId == tournament.Id &&
                                                                                (drVM.ReportDate >= t.StartDate.Value.Date && drVM.ReportDate <= t.EndDate.Value.Date)).Select(o => o.OfficerId).Distinct().Count();

                drVM.ReadyNumber    = drVM.BaseNumber - CountDistinctdailyIncidents;
                drVM.NotReadyNumber = CountDistinctdailyIncidents;
                drVM.ReportDate     = drVM.ReportDate;

                // check if has a daily report in this date
                DailyReport dr_today = _context.DailyReports.Where(t => t.TournamentId == drVM.TournamentId &&
                                                                   (drVM.ReportDate.Date == t.ReportDate.Date)).FirstOrDefault();


                // get reasons from database
                drVM.DDLReason = new SelectList(_context.ReasonOfIncidents.ToList().OrderBy(n => n.Name), "Id", "Name");
                if (dr_today == null)
                {
                    TempData["message"] = NotificationSystem.AddMessage("لا يوجد تقرير يومي في هذا التاريخ ", NotificationType.Danger.Value);
                    return(View(drVM));
                }
            }
            return(View(drVM));
        }