예제 #1
0
        // Returns a List of all absences of all employees
        public static List<Absence> GetAbsences(DateTime initialDate, DateTime finalDate)
        {
            // Create an empty list of absences:
            List<Absence> absences = new List<Absence>();

            if (!InitializeCompany())
                return absences;

            // Get Data from Absence of the employee with ID=employeeId
            StdBELista list = PriEngine.Engine.Consulta(
                "SELECT CadastroFaltas.Funcionario AS CadastroFaltasFuncionario, CadastroFaltas.Data AS CadastroFaltasData, Funcionarios.Nome AS FuncionariosNome " +
                "FROM CadastroFaltas " +
                "INNER JOIN Funcionarios ON CadastroFaltas.Funcionario = Funcionarios.Codigo " +
                "WHERE CadastroFaltas.Data >= '" + initialDate.ToString("yyyyMMdd") + "' AND CadastroFaltas.Data <= '" + finalDate.ToString("yyyyMMdd") + "' " +
                "ORDER BY CadastroFaltas.Data"
                );

            while (!list.NoFim())
            {
                Absence absence = new Absence();
                absence.EmployeeId = list.Valor("CadastroFaltasFuncionario");
                absence.EmployeeName = list.Valor("FuncionariosNome");
                absence.Date = list.Valor("CadastroFaltasData");

                // Add absence to the list:
                absences.Add(absence);

                // Next item:
                list.Seguinte();
            }

            return absences;
        }
예제 #2
0
        public static void Add(Absence absence)
        {
            if (absence == null)
                throw new ArgumentNullException("absence");

            // compute next id
            absence.Id = Absences.Any() ? Absences.Max(a => a.Id) + 1 : 1;

            Absences.Add(absence);
        }
 public AbsenceResult(Absence absence)
 {
     Reason = absence.Reason;
     ReasonSlug = absence.ReasonSlug;
     AbsenceType = absence.AbsenceType.ToString();
     HasCertificate = absence.HasCertificate;
     From = absence.RealDate;
     To = absence.To ?? absence.RealDate;
     Attachment = absence.Attachment;
     Note = absence.Note;
 }
예제 #4
0
        private void EditIllness()
        {
            Absence absence = FocusedEntity;

            if (absence != null && absence.AbsenceTypeID == AbsenceType.Illness)
            {
                AbsenceForm form = new AbsenceForm(absence);
                form.AbsenceManager  = _absencemanager;
                form.CountryReadOnly = true;
                if (CheckUsedAbsence(FocusedEntity))
                {
                    form.EntityUsed = true;
                }
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (_bindingAbsences.GetItemByID(form.Absence.ID) != null)
                    {
                        _bindingAbsences.SetEntity(form.Absence);
                    }
                }
            }
        }
예제 #5
0
        public ActionResult Delete(long id, AbsenceViewModel avm)
        {
            try
            {
                activeUser = userBll.GetUserById((long)HttpContext.Session.GetInt32("userId"));
                string  userCode = userBll.GetUserById(absenceBll.GetAbsenceById(id).UserId).Login;
                Absence absence  = absenceBll.GetAbsenceById(id);
                if (activeUser.Administrator > 0 || activeUser.UserId == absence.UserId)
                {
                    absenceBll.DeleteAbsence(id);
                }

                ViewData["sessionData"] = new int?[] { HttpContext.Session.GetInt32("admin"), HttpContext.Session.GetInt32("language") };
                return(RedirectToAction(nameof(Index), new AbsenceViewModel {
                    UserCode = userCode
                }));
            }
            catch
            {
                return(View());
            }
        }
예제 #6
0
        public ActionResult ModifierAbsence(AbsenceViewModel absenceVM)
        {
            ViewBag.Message = "Modification d'une absence.";
            if (!ModelState.IsValid)
            {
                return(View("ModifierAbsence", absenceVM));
            }

            Absence absence;

            absence = new Absence {
                Motif = absenceVM.Motif, DateAbsence = absenceVM.DateAbsence, EleveId = absenceVM.EleveId, AbsenceId = absenceVM.AbsenceId
            };
            BusinessManager.Instance.ModifierAbsence(absence);

            Eleve          e = BusinessManager.Instance.GetEleveById(absenceVM.EleveId);
            EleveViewModel eleveViewModel = new EleveViewModel {
                Nom = e.Nom, Prenom = e.Prenom, DateNaissance = e.DateNaissance
            };

            return(RedirectToAction("DetailEleve", "Eleve", new { usePartial = false, eleveID = absenceVM.EleveId }));
        }
예제 #7
0
        private void btnRemoveAbsence_Click(object sender, EventArgs e)
        {
            this.Uow = new UnitOfWork();

            Absence absence = (Absence)this.gridvAbsent.GetRow(this.gridvAbsent.FocusedRowHandle);

            if (absence == null)
            {
                return;
            }

            absence = new XPQuery <Absence>(this.Uow).FirstOrDefault(q => q.Id == absence.Id);

            if (XtraMessageBox.Show(this.LookAndFeel, "Bent u zeker dat u deze afwezigheid wilt verwijderen?", "Verwijderen?",
                                    MessageBoxButtons.YesNoCancel,
                                    MessageBoxIcon.Question, MessageBoxDefaultButton.Button3) == DialogResult.Yes)
            {
                absence.Delete();
                this.Uow.CommitChanges();
                FindAllAbsences();
            }
        }
예제 #8
0
        private bool CheckUsedAbsence(Absence absence)
        {
            if (absence == null)
            {
                throw new ArgumentNullException();
            }

            if (_idsUsedAbsence == null || _idsUsedAbsence.Length == 0)
            {
                return(false);
            }

            foreach (long id in _idsUsedAbsence)
            {
                if (absence.ID == id)
                {
                    return(true);
                }
            }

            return(false);
        }
예제 #9
0
        public ActionResult Delete(int?absenceId)
        {
            if (absenceId == null)
            {
                return(Index());
            }
            Absence          a     = DB.Absences.Where(x => x.AbsenceId == absenceId).FirstOrDefault();
            Employee         Nurse = a.AbsenceNurse;
            List <WorkOrder> WO    = DB.WorkOrders.Where(x => x.Nurse.EmployeeId == Nurse.EmployeeId).ToList();

            for (int i = 0; i < WO.Count; i++)
            {
                int       tmp = WO.ElementAt(i).WorkOrderId;
                WorkOrder w   = DB.WorkOrders.FirstOrDefault(x => x.WorkOrderId == tmp);
                for (int j = 0; j < w.Visits.Count; j++)
                {
                    Visit vi = DB.Visits.Find(w.Visits.ElementAt(j).VisitId);
                    if (vi.DateConfirmed >= DateTime.Now && !vi.Done && vi.DateConfirmed >= a.DateStart && vi.DateConfirmed <= a.DateEnd)
                    {
                        var forceLoad = vi.NurseReplacement; //Aleluja
                        vi.NurseReplacement = null;          // Now EF knows something has changed
                        DB.SaveChanges();
                    }
                }
            }
            DB.Absences.Remove(a);
            DB.SaveChanges();


            //ervm.AllNurses = DB.Employees.Where(x => x.Title == Employee.JobTitle.HealthNurse).ToList();
            EndReplacementViewModel ervm = new EndReplacementViewModel();

            ervm.AllNurses   = DB.Employees.Where(x => x.JobTitle.Title == JobTitle.HealthNurse && x.User.Active == true).ToList();
            ervm.Absences    = new List <Absence>();
            ervm.CanDelete   = new List <bool>();
            ervm.ViewMessage = "Konec nadomeščanja uspešna";
            ervm.NurseId     = Nurse.FullNameWithCode;
            return(EndReplacement(ervm));
        }
예제 #10
0
        private void NewIllness()
        {
            if (Country == null)
            {
                return;
            }

            Absence absence = ClientEnvironment.AbsenceService.CreateEntity();

            absence.CountryID     = Country.ID;
            absence.AbsenceTypeID = AbsenceType.Illness;
            AbsenceForm form = new AbsenceForm(absence);

            form.AbsenceManager  = _absencemanager;
            form.CountryReadOnly = true;
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (_bindingAbsences.GetItemByID(absence.ID) == null)
                {
                    _bindingAbsences.Add(absence);
                }
            }
        }
예제 #11
0
        private void NewAbsence()
        {
            Absence absence = ClientEnvironment.AbsenceService.CreateEntity();

            if (Country != null)
            {
                absence.CountryID = Country.ID;
            }
            //new Domain.Absence();
            absence.AbsenceTypeID = AbsenceType.Absence;
            AbsenceForm form = new AbsenceForm(absence);

            form.AbsenceManager  = _absencemanager;
            form.CountryReadOnly = Country != null;

            if (form.ShowDialog() == DialogResult.OK)
            {
                if (_bindingAbsences.GetItemByID(form.Absence.ID) == null)
                {
                    _bindingAbsences.Add(form.Absence);
                }
            }
        }
예제 #12
0
        private void ProcessFixedTimeAbsence(Absence absence)
        {
            if (absence.Value > 0)
            {
                int count = (int)(absence.Value * 60);

                if (gridView.SelectedRowsCount == 1)
                {
                    EmployeeDayView dayView = GetEmployeeDayView();
                    TimeColumnInfo  info    = GetColumnInfo(gridView.FocusedColumn);

                    if (dayView != null && info != null)
                    {
                        dayView.SetAbsence(absence, info.FromTime, info.FromTime + count);
                        if (dayView.Modified)
                        {
                            Context.Modified = true;
                        }
                        UpdateEmployeePlanningDays();
                    }
                }
            }
        }
예제 #13
0
        private void FillCboDrivers()
        {
            var absences = new Absence(new UnitOfWork()).GetAll(this._planningId, this.dteJobDate.DateTime.Date);
            var jobs     = new Job(new UnitOfWork()).GetAll(this._planningId, this.dteJobDate.DateTime.Date);
            List <AssignedDriver> assignedDrivers = new AssignedDriver(new UnitOfWork()).GetAll(this._planningId);

            if (this._job.Driver != null)
            {
                this.cboDriver.Items.Add(this._job.Driver);
                this.cboDriver.SelectedIndex = 0;
            }

            foreach (Absence absence in absences)
            {
                var result = assignedDrivers.Where(x => x.DriverName.Equals(absence.DriverName));

                if (result.ToList()[0] != null)
                {
                    assignedDrivers.Remove(result.ToList()[0]);
                }
            }

            foreach (Job job in jobs)
            {
                var result = assignedDrivers.Where(x => x.DriverName == job.Driver);
                assignedDrivers.Remove(result.ToList()[0]);
            }

            foreach (AssignedDriver assignedDriver in assignedDrivers)
            {
                this.cboDriver.Items.Add(assignedDriver.DriverName);
                if (assignedDriver.DriverName == this._job.Driver)
                {
                    this.cboDriver.SelectedIndex = this.cboDriver.Items.Count - 1;
                }
            }
        }
예제 #14
0
        public ViewResult CourseStudentsDays(int courseId, TimeSpan span)
        {
            if (courseId == 0)
            {
                courseId = 1;
            }

            Course         course      = courseRepo.Courses.FirstOrDefault(c => c.CourseId == courseId);
            List <Student> studentList = studentRepo.GetAllStudentsFromCourses(course);
            List <string>  students    = new List <string>();
            List <string>  dates       = GetDateSpan(span);

            Dictionary <string, Dictionary <string, string> > dic = new Dictionary <string, Dictionary <string, string> >();

            foreach (Student student in studentList)
            {
                Dictionary <string, string> dico = new Dictionary <string, string>();

                foreach (string date in dates)
                {
                    Absence a = absenceRepo.AbsenceForDateCourseStudent(course, DateTime.Parse(date), student);
                    dico.Add(date, a != null ? a.Status : "");
                }

                string s = ShortenName(student.Name);
                students.Add(s);
                dic.Add(s, dico);
            }

            return(View("CourseStudentsDays", new StudentsDaysViewModel {
                Dates = dates,
                StudentList = students,
                StudentStatuses = dic,
                Course = course,
                Education = new Education()
            }));
        }
예제 #15
0
        public List <Absence> GetForSchoolYear(int schoolYearID)
        {
            List <Absence> returnMe = new List <Absence>();

            if (!string.IsNullOrEmpty(this.SQLConnectionString))
            {
                using (SqlConnection connection = new SqlConnection(SQLConnectionString))
                {
                    using (SqlCommand sqlCommand = new SqlCommand())
                    {
                        sqlCommand.Connection  = connection;
                        sqlCommand.CommandType = CommandType.Text;
                        sqlCommand.CommandText = "SELECT * FROM Attendance WHERE iSchoolYearID=@SYID;";
                        sqlCommand.Parameters.AddWithValue("SYID", schoolYearID);
                        sqlCommand.Connection.Open();
                        SqlDataReader dataReader = sqlCommand.ExecuteReader();
                        if (dataReader.HasRows)
                        {
                            while (dataReader.Read())
                            {
                                Absence parsedObject = dataReaderToObject(dataReader);
                                if (parsedObject != null)
                                {
                                    returnMe.Add(parsedObject);
                                }
                            }
                        }
                        sqlCommand.Connection.Close();
                    }
                }
            }
            else
            {
                throw new InvalidConnectionStringException("Connection string is empty");
            }
            return(returnMe);
        }
예제 #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;

            Absence _absenceService = new Absence();

            if (AbsenceId != null && AbsenceId != "")
            {
                _absence = _absenceService.GetAbsenceByID(AbsenceId);
            }
            if (_absence != null && (_absence.Type == 1000 || _absence.Type == 1002))
            {
                TextBox txtBox = FindControl("txtName") as TextBox;
                txtBox.Text = _absence.PayeeName;

                txtBox      = FindControl("txtAddress1") as TextBox;
                txtBox.Text = _absence.PayeeAddress1;

                txtBox      = FindControl("txtAddress2") as TextBox;
                txtBox.Text = _absence.PayeeAddress2;

                txtBox      = FindControl("txtAddress3") as TextBox;
                txtBox.Text = _absence.PayeeAddress3;

                txtBox      = FindControl("txtCity") as TextBox;
                txtBox.Text = _absence.PayeeCity;

                txtBox      = FindControl("txtState") as TextBox;
                txtBox.Text = _absence.PayeeState;

                txtBox      = FindControl("txtCountry") as TextBox;
                txtBox.Text = _absence.PayeeCountry;

                txtBox      = FindControl("txtZip") as TextBox;
                txtBox.Text = _absence.PayeeZipCode;
            }
        }
        async void saveBtn_Clicked(System.Object sender, System.EventArgs e)
        {
            String sdate = date.Date.ToString();

            if (classePicker.SelectedIndex >= 0 && lessonPicker.SelectedIndex >= 0)
            {
                String sclasse        = classePicker.Items[classePicker.SelectedIndex];
                String slesson        = lessonPicker.Items[lessonPicker.SelectedIndex];
                Classe selectedClasse = (from cl in classeList where cl.name == sclasse select cl).FirstOrDefault();
                Lesson selectedLesson = (from alesson in lessonList where alesson.name == slesson select alesson).FirstOrDefault();

                Seance seance = new Seance(sdate, selectedLesson.id, selectedClasse.id);

                await _connection.InsertAsync(seance);

                List <Seance> seanceList = await _connection.Table <Seance>().ToListAsync();

                List <Student> students = await _connection.Table <Student>().Where(st => st.classeId == seance.classeId).ToListAsync();

                Absence abs;
                int     nb = 0;
                foreach (Student st in students)
                {
                    abs           = new Absence();
                    abs.isAbsent  = false;
                    abs.lessonId  = seance.lessonId;
                    abs.seanceId  = seance.id;
                    abs.studentId = st.id;
                    nb           += await _connection.InsertAsync(abs);
                }
                await Navigation.PopAsync();
            }
            else
            {
                await DisplayAlert("Alert", "Informations non completes !", "OK");
            }
        }
예제 #18
0
        private void ProcessCountAliquotAbsence(Absence absence)
        {
            if (absence.IsFixed)
            {
                if (gridView.SelectedRowsCount == 1)
                {
                    EmployeeDayView dayView = GetEmployeeDayView();

                    TimeColumnInfo info = GetColumnInfo(gridView.FocusedColumn);

                    if (dayView != null && info != null)
                    {
                        int count = DateTimeHelper.RoundToQuoter((short)((dayView.ContractHoursPerWeek / Context.StoreDays.AvgDayInWeek)));

                        dayView.SetAbsence(absence, info.FromTime, info.FromTime + count);
                        if (dayView.Modified)
                        {
                            Context.Modified = true;
                        }
                        UpdateEmployeePlanningDays();
                    }
                }
            }
        }
예제 #19
0
        /// <summary>
        /// Loads a student object with data suitable for the INAC report
        /// </summary>
        /// <param name="connection">A database connection</param>
        /// <param name="school"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public static List <Student> loadStudentData(SqlConnection connection, School school, DateTime startDate, DateTime endDate)
        {
            List <Student> loadedStudentList = new List <Student>();
            List <Student> allLoadedStudents = Student.loadReserveStudentsFromThisSchool(connection, school);

            // Filter students to only those in a track that falls between the given dates
            foreach (Student student in allLoadedStudents)
            {
                student.track = Track.loadThisTrack(connection, student.getTrackID());
                if ((student.track.endDate > startDate) && (student.track.startDate < endDate))
                {
                    loadedStudentList.Add(student);
                }
            }

            // Load required data for students
            foreach (Student student in loadedStudentList)
            {
                // Load contacts for students
                student.contacts = Contact.loadContactsForStudent(connection, student);

                // Load absenses for students
                student.absences = Absence.loadAbsencesForThisStudentAndTimePeriod(connection, student, startDate, endDate);

                // Load any terms that fall within the specified dates
                student.track.terms = Term.loadTermsBetweenTheseDates(connection, student.track, startDate, endDate);

                // Load enrolled courses into the terms
                foreach (Term term in student.track.terms)
                {
                    term.Courses = SchoolClass.loadStudentEnrolledClassesForThisTerm(connection, student, term);
                }
            }

            return(loadedStudentList);
        }
예제 #20
0
        public void TestEditAbsence()
        {
            //Ajout classe
            Manager.Instance.AddClasse(new Classe {
                Niveau = "DUT", NomEtablissement = "uca"
            });
            Classe classe = Manager.Instance.GetAllClasses().LastOrDefault();

            Assert.AreEqual("DUT", classe.Niveau);
            Assert.AreEqual("uca", classe.NomEtablissement);

            Manager.Instance.AddEleve(new Eleve {
                Nom = "Kolac", Prenom = "Jean", DateNaissance = DateTime.Now.Date, ClassId = classe.ClassId
            });
            Eleve eleve = Manager.Instance.GetAllEleves("").LastOrDefault();

            Assert.AreEqual("Kolac", eleve.Nom);
            Assert.AreEqual("Jean", eleve.Prenom);

            Manager.Instance.AddAbsence(new Absence {
                Motif = "Otite", DateAbsence = DateTime.Now.Date, EleveId = eleve.EleveId
            });
            Absence absence = Manager.Instance.GetAllAbsences().LastOrDefault();

            Assert.AreEqual("Otite", absence.Motif);
            Assert.AreEqual(DateTime.Now.Date, absence.DateAbsence);

            //Modification absence
            absence.Motif       = "Gastro";
            absence.DateAbsence = new DateTime(2020, 11, 21);
            Manager.Instance.EditAbsence(absence);
            Absence expectedAbsence = Manager.Instance.GetAbsenceById(absence.AbsenceId);

            Assert.AreEqual(expectedAbsence.Motif, absence.Motif);
            Assert.AreEqual(expectedAbsence.DateAbsence, absence.DateAbsence);
        }
예제 #21
0
        public void Can_Delete_Absence()
        {
            // Arrange (Организация)
            Mock <IAbsenceRepository> mock = new Mock <IAbsenceRepository>();

            mock.Setup(_ => _.Absences).Returns(new List <Absence>
            {
                new Absence {
                    Id = 1, DateAbsence = DateTime.Now, StudentId = 1, SubjectId = 1, TeacherId = 1, TypeClassId = 1
                },
                new Absence {
                    Id = 2, DateAbsence = DateTime.Now, StudentId = 2, SubjectId = 2, TeacherId = 2, TypeClassId = 2
                },
                new Absence {
                    Id = 3, DateAbsence = DateTime.Now, StudentId = 3, SubjectId = 3, TeacherId = 3, TypeClassId = 3
                },
                new Absence {
                    Id = 4, DateAbsence = DateTime.Now, StudentId = 4, SubjectId = 4, TeacherId = 4, TypeClassId = 4
                },
                new Absence {
                    Id = 5, DateAbsence = DateTime.Now, StudentId = 5, SubjectId = 5, TeacherId = 5, TypeClassId = 5
                }
            });

            Absence absence = new Absence();

            absence.Id = 1;

            // Act (Действие)
            AbsenceController controller = new AbsenceController(mock.Object);

            Absence result = controller.Delete(absence).ViewData.Model as Absence;

            // Assert (Утверждение)
            Assert.AreEqual(absence.Id, result.Id);
        }
예제 #22
0
        private void gridvAbsent_DoubleClick(object sender, EventArgs e)
        {
            if (((ComboBoxItem)this.cboDispatcher.SelectedItem).Value.UsrID != Context.User.UsrID)
            {
                return;
            }

            //TODO: check if mouse is on row
            Absence absence = (Absence)this.gridvAbsent.GetRow(this.gridvAbsent.FocusedRowHandle);

            if (absence == null)
            {
                return;
            }

            AbsentDetail editAbsence = new AbsentDetail(this._planning, absence);

            editAbsence.ShowDialog();

            if (editAbsence.DialogResult == DialogResult.OK)
            {
                FindAllAbsences();
            }
        }
예제 #23
0
        public async Task CreateAsync(CreateAbsenceBindingModel absenceModel, string teacherName)
        {
            EdumanUser Student = this.context.Users.FirstOrDefault(u =>
                                                                   u.FirstName == absenceModel.StudentFirstName && u.LastName == absenceModel.StudentLastName && u.IsConfirmed);

            EdumanUser Teacher =
                this.context.Users.FirstOrDefault(u => u.UserName == teacherName);

            if (Student == null || !(await userManager.IsInRoleAsync(Student, "Student")))
            {
                throw new Exception("The User is either non-existent or is not a student");
            }

            Absence absence = new Absence
            {
                DateAbsent = absenceModel.DateAbsent,
                StudentId  = Student.Id,
                Subject    = absenceModel.Subject,
                TeacherId  = Teacher.Id
            };

            this.context.Absences.Add(absence);
            this.context.SaveChanges();
        }
예제 #24
0
        void UpdateButtonEnable()
        {
            if (!isUserWriteRight)
            {
                return;
            }
            bi_Delete.Enabled      = (FocusedEntity != null && !CheckUsedAbsence(FocusedEntity));
            bi_editabsence.Enabled = FocusedEntity != null;
            if (FocusedEntity != null)
            {
                Absence     absence = FocusedEntity;
                AbsenceType ate     = absence.AbsenceTypeID;
                switch (ate)
                {
                case AbsenceType.Holiday:
                    bi_editabsence.Caption = GetLocalized("editholiday");
                    bi_Delete.Caption      = GetLocalized("deleteholiday");
                    break;

                case AbsenceType.Absence:
                    bi_editabsence.Caption = GetLocalized("editabsence");
                    bi_Delete.Caption      = GetLocalized("deleteabsence");
                    break;

                case AbsenceType.Illness:
                    bi_editabsence.Caption = GetLocalized("editillness");
                    bi_Delete.Caption      = GetLocalized("deleteillness");
                    break;
                }
            }
            else
            {
                bi_editabsence.Caption = GetLocalized("editabsence");
                bi_Delete.Caption      = GetLocalized("delete");
            }
        }
예제 #25
0
        public bool ResetRange()
        {
            bool modified = false;

            if (Bizy)
            {
                modified = true;
            }
            if (IsWorkigntime)
            {
                modified = true;
            }
            if (this.Absence != null)
            {
                modified = true;
            }

            this.Absence = null;

            RangeColor    = EMPTY_COLOR;
            IsWorkigntime = false;

            return(modified);
        }
예제 #26
0
        public Boolean deleteAbsence(Absence absence)
        {
            Boolean success;

            OleDbCommand cmd = DBConnection.getInstance.getDbCommand();

            cmd.CommandText = "DELETE FROM ABSENCE WHERE ID_ABSENCE=?";
            cmd.Parameters.Add("ID_ABSENCE", OleDbType.Integer).Value = absence.idAbsence;

            try
            {
                cmd.ExecuteNonQuery();
                success = true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Erro ao excluir!" + e);
                success = false;
            }

            DBConnection.getInstance.closeConnection();

            return(success);
        }
예제 #27
0
        private async Task SeedAbsences(ApplicationDbContext dbContext)
        {
            if (dbContext.Absences.Any())
            {
                return;
            }

            var firstDbSubject = await dbContext.Subjects.FirstOrDefaultAsync(s => s.StudentSubjects.Any());

            if (firstDbSubject != null)
            {
                var absence = new Absence()
                {
                    Teacher        = firstDbSubject.Teacher,
                    Period         = AbsencePeriod.FirstTerm,
                    Type           = AbsenceType.OneThird,
                    StudentSubject = firstDbSubject.StudentSubjects.FirstOrDefault()
                };

                await dbContext.Absences.AddAsync(absence);

                await dbContext.SaveChangesAsync();
            }
        }
예제 #28
0
 public Absence AddAbsence(Absence absence)
 {
     this.session.SaveOrUpdate(absence);
     this.session.Flush();
     return(absence);
 }
        public async Task <Absence> ResendAbsence(int integrationUnitId, Absence absence)
        {
            await SignIn(integrationUnitId);

            foreach (var absenceEntry  in absence.AbsenceEntries)
            {
                var workTypeId = await _entityMapService.GetWorkTypeId(absenceEntry.LocalAbsenceCode, integrationUnitId);

                var isWorkItem = workTypeId != null;

                if (isWorkItem)
                {
                    var workRelationId = await _entityMapService.GetWorkRelationId(absence.EmployeeId, integrationUnitId);

                    absenceEntry.ExternalEntityId    = workRelationId.ToString();
                    absenceEntry.ExternalAbsenceCode = workTypeId.ToString();

                    var workItem = new WorkItem
                    {
                        // From AbsenceDay
                        StartTime  = absenceEntry.StartTime,
                        EndTime    = absenceEntry.EndTime,
                        WorkTypeId = workTypeId.Value,

                        // From Absence
                        UnitId         = absence.UnitId,
                        WorkRelationId = workRelationId.Value,
                        Description    = absence.Description,
                        LunchInMinutes = absence.LunchInMinutes
                    };
                    if (string.IsNullOrWhiteSpace(absenceEntry.ExternalId))
                    {
                        var externalId = await _unimicroClient.PostWorkItem(workItem);

                        absenceEntry.ExternalId = externalId.ToString();
                    }
                    else
                    {
                        workItem.Id = int.Parse(absenceEntry.ExternalId);
                        await _unimicroClient.PutWorkItem(workItem);
                    }
                }
                else
                {
                    var employementLeaveId = await _entityMapService.GetEmploymentLeaveId(absenceEntry.LocalAbsenceCode, absence.UnitId);

                    var isEmploymentLeave = employementLeaveId != null;

                    if (isEmploymentLeave)
                    {
                        var employmentId = await _entityMapService.GetEmploymentId(absence.EmployeeId, integrationUnitId);

                        absenceEntry.ExternalEntityId    = employmentId.ToString();
                        absenceEntry.ExternalAbsenceCode = employementLeaveId.ToString();

                        var employmentLeave = new EmploymentLeave()
                        {
                            EmploymentID = employmentId.Value,
                            LeaveType    = Enum.Parse <LeaveType>(employementLeaveId.Value.ToString()),
                            FromDate     = absenceEntry.StartTime.Date,
                            ToDate       = absenceEntry.StartTime.Date,
                            LeavePercent = 100
                        };

                        if (string.IsNullOrWhiteSpace(absenceEntry.ExternalId))
                        {
                            var externalId = await _unimicroClient.PostEmploymentLeave(employmentLeave);

                            absenceEntry.ExternalId = externalId.ToString();
                        }
                        else
                        {
                            employmentLeave.Id = int.Parse(absenceEntry.ExternalId);
                            await _unimicroClient.PutEmploymentLeave(employmentLeave);
                        }
                    }
                    else
                    {
                        throw new ArgumentException($"Mapping is not found for absencecode={absenceEntry.LocalAbsenceCode}. This error should have been taken care of in pre-validation");
                    }
                }
            }
            return(absence);
        }
예제 #30
0
 /// <summary>
 /// Remove an absence for an employee
 /// </summary>
 /// <param name="absence">Absence (object)</param>
 /// <param name="_employee">Employee (object)</param>
 public void RemoveAbsenceFromEmployee(Absence absence, Employee _employee)
 {
     AccessDataBase.RemoveAbsenceFromEmployee(absence, _employee);
 }
 public async Task Update(Absence absence)
 {
     _context.Update(absence);
     await _context.SaveChangesAsync();;
 }
 public async Task CreateAbs(Absence absence)
 {
     _context.Add(absence);
     await _context.SaveChangesAsync();
 }
예제 #33
0
 /// <summary>
 /// Creates a success response.
 /// </summary>
 /// <param name="address">Saved shipping.</param>
 /// <returns>Response.</returns>
 public SaveAbsenceResponse(Absence absence) : this(true, string.Empty, absence)
 {
     Absence = Absence;
 }
예제 #34
0
 private void OnAddAbscenceButtonClick(string s)
 {
     try
     {
         if(AbsenceType == null || InputAbsenceStart > InputAbsenceEnd)
             throw new ArgumentNullException();
         var newAbsence = new Absence
         {
             StartDate = InputAbsenceStart,
             EndDate = InputAbsenceEnd,
             AbsenceType_id = AbsenceType.id
         };
         var userId = Employee.Id;
         ServiceSalaire.addAbsence(userId, newAbsence);
         Employee = ServiceSalaire.GetUserById(userId);
     }
     catch (ArgumentNullException)
     {
         MessageBox.Show("Les paramètres sont invalides, recommencer", "Erreur de paramètres",
             MessageBoxButton.OK, MessageBoxImage.Error);
     }
     catch (FormatException)
     {
         MessageBox.Show("Merci d'indiquer un nombre pour le montant.", "Erreur de montant", MessageBoxButton.OK,
             MessageBoxImage.Error);
     }
 }
        public ActionResult Create(AbsenceIndexViewModel viewModel)
        {
            //TODO: Refreshing the whole list of Courses, only the selected 1 is posting back, maybe refactor later?
            viewModel.CourseTitles = db.Courses.Select(c => c.Title).ToList();

            if (ModelState.IsValid)
            {
                var absence = new Absence();

                absence.StudentLastName = viewModel.StudentLastName;
                absence.StudentFirstName = viewModel.StudentFirstName;
                absence.AbsenceDate = viewModel.AbsenceDate;

                //Old Code

                //.Replace(" ", "")  and .ToLower() are used to try and get both strings to a similar format
                //this helps when trying to compare 2 strings, and input/comparison variations are likely

                //var student = db.Students.Where(s => s.FirstName.Replace(" ", "").ToLower() == viewModel.StudentFirstName.Replace(" ", "").ToLower() &&
                //                                     s.LastName.Replace(" ", "").ToLower() == viewModel.StudentLastName.Replace(" ", "").ToLower()).FirstOrDefault();

                //var course = db.Courses.Where(c => c.Title.Replace(" ", "").ToLower() == viewModel.CourseTitle.Replace(" ", "").ToLower()).FirstOrDefault();

                //New Code
                var student = db.Students.Where(s => s.FirstName.Replace(" ", "").ToLower() == viewModel.StudentFirstName.Replace(" ", "").ToLower() &&
                                                     s.LastName.Replace(" ", "").ToLower() == viewModel.StudentLastName.Replace(" ", "").ToLower()).FirstOrDefault();

                var course = db.Courses.Where(c => c.Title == viewModel.CourseTitle).FirstOrDefault();

                //Get the student and course record for entered data
                //TODO: Update Later.
                if (student == null)
                {
                    return View("Create", viewModel);
                    //Old Code
                   // return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Student was not found.");
                }

                if (course == null)
                {
                    return View("Create", viewModel);

                    //Old Code
                    //return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Course was not found.");
                }

                //Make sure that student is enrolled in that specific course
                var enrollment = db.Enrollments.Where(e => e.StudentId == student.Id && e.CourseId == course.Id).FirstOrDefault();

                if (enrollment == null)
                {
                    return View("Create", viewModel);

                    //Old Code
                    //return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Student is not enrolled in that course.");
                }

                absence.CourseId = course.Id;
                absence.StudentId = student.Id;
                absence.CourseTitle = course.Title; //Use the db instance of the title (in case the user entered in a mangled string :))

                db.Absences.Add(absence);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

               return View("Create", viewModel);
        }