public override void Execute()
        {
            foreach (var e in _evaluators)
            {
                if (e.Action == EvaluatorAction.Add)
                {
                    if (_employeeEvaluation.UserName != e.UserName)
                    {
                        var employee = RavenSession
                                       .Query <Employee, EmployeeByUserName_Search>()
                                       .Where(x => x.UserName == e.UserName)
                                       .FirstOrDefault();

                        if (employee != null)
                        {
                            var evId = _employeeEvaluation.Id ?? EmployeeEvaluation.GenerateEvaluationId(_employeeEvaluation.Period, _employeeEvaluation.UserName);
                            ExecuteCommand(new GenerateCalificationCommand(_employeeEvaluation.Period, _employeeEvaluation.UserName, e.UserName, _employeeEvaluation.TemplateId, CalificationType.Evaluator, evId));
                        }
                        else
                        {
                            throw new ApplicationException(string.Format("Error: Evaluador no valido: {0}.", e.UserName));
                        }
                    }
                }
                else
                {
                    var id           = EvaluationCalification.GenerateCalificationId(_employeeEvaluation.Period, _employeeEvaluation.UserName, e.UserName);
                    var calification = RavenSession.Load <EvaluationCalification>(id);
                    if (calification != null)
                    {
                        RavenSession.Delete(calification);
                    }
                }
            }
        }
        public IEnumerable <EmployeeEvaluation> GetAllRatingPerUser(int id)
        {
            List <EmployeeEvaluation> employeeEvaluations = new List <EmployeeEvaluation>();

            var       UserConnectionString = _dbContext.Database.GetDbConnection().ConnectionString;
            DataTable dt = SCObjects.LoadDataTable(string.Format("EXEC [dbo].[spGetEvaluationScorePerRater] @Rater = {0}", id.ToString()), UserConnectionString);

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    var item = new EmployeeEvaluation
                    {
                        Id             = int.Parse(dr["Id"].ToString()),
                        Name           = dr["EmployeeName"].ToString(),
                        TotalScore     = decimal.Parse(dr["TotalScore"].ToString()),
                        TotalWeight    = decimal.Parse(dr["TotalWeight"].ToString()),
                        ConvertedScore = decimal.Parse(dr["ConvertedScore"].ToString()),
                        WeightedScore  = decimal.Parse(dr["WeightedScore"].ToString()),
                        Percentage     = decimal.Parse(dr["Percentage"].ToString()),
                    };
                    employeeEvaluations.Add(item);
                }
            }
            return(employeeEvaluations);
        }
Пример #3
0
 public static void saveEmployeeEvaluation(DataTable dt, ref EmployeeEvaluation mo)
 {
     foreach (DataRow dr in dt.Rows)
     {
         saveEmployeeEvaluation(dr, ref mo);
     }
 }
        public override SharedLink ExecuteWithResult()
        {
            var evaluation = RavenSession.Load <EmployeeEvaluation>(EmployeeEvaluation.GenerateEvaluationId(_period, _userName));

            if (evaluation == null)
            {
                throw new ApplicationException($"Could not find evaluation for period {_period} and user name {_userName}");
            }
            if (evaluation.SharedLinks == null)
            {
                evaluation.SharedLinks = new SharedLinkList();
            }
            //regular expression for strings that starts with "Link#" and followed only by numbers
            var regExp         = new Regex(@"^Link#(\d+)$");
            var lastLinkNumber = evaluation.SharedLinks
                                 .Select(x => x.FriendlyName)
                                 .Select(x => regExp.Match(x))
                                 .Where(x => x.Success)
                                 .Select(x => int.Parse(x.Groups[1].Value))
                                 .OrderBy(x => x)
                                 .LastOrDefault();

            var newSharedLink = new SharedLink()
            {
                FriendlyName   = $"Link#{lastLinkNumber + 1}",
                ExpirationDate = DateTime.Now.AddDays(3).ToUniversalTime(),
                SharedCode     = GenerateSharedCode()
            };

            evaluation.SharedLinks.Add(newSharedLink);
            RavenSession.SaveChanges();
            return(newSharedLink);
        }
Пример #5
0
        public static EmployeeEvaluation loadFromDataRow(DataRow r)
        {
            DataRowLoader a  = new DataRowLoader();
            IModelObject  mo = new EmployeeEvaluation();

            a.DataSource = r;
            a.load(mo);
            return((EmployeeEvaluation)mo);
        }
Пример #6
0
        /// <summary>
        /// Reload the EmployeeEvaluation from the database
        /// </summary>
        /// <remarks>
        /// use this method when you want to relad the EmployeeEvaluation
        /// from the database, discarding any changes
        /// </remarks>
        public static void reload(ref EmployeeEvaluation mo)
        {
            if (mo == null)
            {
                throw new System.ArgumentNullException("null object past to reload function");
            }

            mo = (EmployeeEvaluation) new EmployeeEvaluationDBMapper().findByKey(mo.Id);
        }
Пример #7
0
        public override void Execute()
        {
            var evaluationId              = EmployeeEvaluation.GenerateEvaluationId(_period, _evaluatedEmployee);
            var evaluation                = RavenSession.Load <EmployeeEvaluation>(evaluationId);
            var califications             = RavenSession.Advanced.LoadStartingWith <EvaluationCalification>(evaluationId + "/").ToList();
            var isResponsibleEvalFinished = califications.Any(x => x.Owner == CalificationType.Responsible && x.Finished);
            var isCompanyEvalFinished     = califications.Any(x => x.Owner == CalificationType.Company && x.Finished);
            var isAutoEvalFinished        = califications.Any(x => x.Owner == CalificationType.Auto && x.Finished);
            var isEvaluatorEvalFinished   = califications.Any(x => x.Owner == CalificationType.Evaluator && x.Finished);
            var action = RevertEvaluationActionsHelper.TryParse(_action);

            if (!RevertEvaluationActionsHelper.FindPosibleRevertAction(
                    evaluation.Finished,
                    evaluation.ReadyForDevolution,
                    isCompanyEvalFinished,
                    isResponsibleEvalFinished,
                    isAutoEvalFinished,
                    isEvaluatorEvalFinished,
                    action))
            {
                throw new ApplicationException("Action not allowed");
            }
            var calificationsByType = califications.ToLookup(x => x.Owner);

            switch (action)
            {
            case RevertAction.ReopenForDevolution:
                evaluation.Finished = false;
                break;

            case RevertAction.CancelDevolution:
                evaluation.ReadyForDevolution = false;
                break;

            case RevertAction.ReopenEvalCompany:
                calificationsByType[CalificationType.Company].First().Finished = false;
                break;

            case RevertAction.ReopenEvalResponsible:
                calificationsByType[CalificationType.Responsible].First().Finished = false;
                RavenSession.Delete(calificationsByType[CalificationType.Company].First());
                break;

            case RevertAction.ReopenAutoEvaluation:
                calificationsByType[CalificationType.Auto].First().Finished = false;
                break;

            case RevertAction.ReopenEvalEvaluators:
                foreach (var calification in calificationsByType[CalificationType.Evaluator])
                {
                    calification.Finished = false;
                }
                break;
            }
        }
        public override void Execute()
        {
            var evaluation = RavenSession.Load <EmployeeEvaluation>(EmployeeEvaluation.GenerateEvaluationId(_period, _userName));

            if (evaluation == null)
            {
                throw new ApplicationException($"Could not find evaluation for period {_period} and user name {_userName}");
            }
            if (evaluation.SharedLinks == null || evaluation.SharedLinks.RemoveAll(x => x.SharedCode == _sharedLink.SharedCode) < 1)
            {
                throw new ApplicationException($"This evaluation does not contain a Shared link with code {_sharedLink.SharedCode}. Unable to delete");
            }
        }
Пример #9
0
        public static void saveEmployeeEvaluation(DataRow dr, ref EmployeeEvaluation mo)
        {
            if (mo == null)
            {
                mo = new EmployeeEvaluation();
            }

            foreach (DataColumn dc in dr.Table.Columns)
            {
                mo.setAttribute(dc.ColumnName, dr[dc.ColumnName]);
            }

            saveEmployeeEvaluation(mo);
        }
        public override void Execute()
        {
            var evaluation = RavenSession.Load <EmployeeEvaluation>(EmployeeEvaluation.GenerateEvaluationId(_period, _userName));

            if (evaluation == null)
            {
                throw new ApplicationException($"Could not find evaluation for period {_period} and user name {_userName}");
            }
            var updatedLink = evaluation.SharedLinks.Where(x => x.SharedCode == _sharedLink.SharedCode).FirstOrDefault();

            if (updatedLink == null)
            {
                throw new ApplicationException($"This evaluation does not contain a Shared link with code {_sharedLink.SharedCode}. Unable to update");
            }
            updatedLink.FriendlyName   = _sharedLink.FriendlyName;
            updatedLink.ExpirationDate = _sharedLink.ExpirationDate;
        }
Пример #11
0
        public override IDbCommand getUpdateDBCommand(IModelObject modelObj, string sql)
        {
            EmployeeEvaluation obj  = (EmployeeEvaluation)modelObj;
            IDbCommand         stmt = this.dbConn.getCommand(sql);

            stmt.Parameters.Add(this.dbConn.getParameter(EmployeeEvaluation.STR_FLD_EVALUATOR_ID, obj.PrEvaluatorId));
            stmt.Parameters.Add(this.dbConn.getParameter(EmployeeEvaluation.STR_FLD_EVALUATION_DATE, obj.PrEvaluationDate));
            stmt.Parameters.Add(this.dbConn.getParameter(EmployeeEvaluation.STR_FLD_EMPLOYEE_ID, obj.PrEmployeeId));

            if (obj.isNew)
            {
            }
            else
            {
                //only add primary key if we are updating and as the last parameter
                stmt.Parameters.Add(this.dbConn.getParameter(EmployeeEvaluation.STR_FLD_EMPLOYEE_EVALUATION_ID, obj.PrEmployeeEvaluationId));
            }

            return(stmt);
        }
Пример #12
0
        private bool CanUpdate(string loggedUser, EmployeeEvaluation evaluation, EvaluationCalification calification)
        {
            //Auto evaluator
            if (loggedUser == evaluation.UserName)
            {
                if (calification.Owner == CalificationType.Auto && calification.EvaluatorEmployee == loggedUser && !calification.Finished)
                {
                    return(true);
                }
            }

            //Responsible
            if (loggedUser == evaluation.ResponsibleId)
            {
                if (calification.Owner == CalificationType.Responsible && calification.EvaluatorEmployee == loggedUser && !calification.Finished)
                {
                    return(true);
                }

                // Auto calification can be edited (by the responsible) once finished (at the devolution)
                if (calification.Owner == CalificationType.Auto && evaluation.ReadyForDevolution)
                {
                    return(true);
                }

                // Company calification can be edited (by the responsible) once finished (at the devolution)
                if (calification.Owner == CalificationType.Company && calification.EvaluatorEmployee == COMPANY)
                {
                    return(true);
                }
            }

            //Evaluator
            if (calification.Owner == CalificationType.Evaluator && calification.EvaluatorEmployee == loggedUser && !calification.Finished)
            {
                return(true);
            }

            return(false);
        }
        public override void Execute()
        {
            foreach (var e in _employeesEvaluations)
            {
                EmployeeEvaluation employeeEvaluation = new EmployeeEvaluation();

                //Both Period and TemplateId will be fixed for this release
                employeeEvaluation.Period     = _period;
                employeeEvaluation.TemplateId = Template.Template2019Test;
                //---
                employeeEvaluation.UserName      = e.UserName;
                employeeEvaluation.ResponsibleId = e.ResponsibleId;
                employeeEvaluation.FullName      = e.FullName;
                //employeeEvaluation.Seniority will not be stored at this point
                //employeeEvaluation.CurrentPosition will not be stored at this point

                RavenSession.Store(employeeEvaluation);

                //After we create the evaluation, we create the calification document for the auto-evaluation and the responsible
                ExecuteCommand(new GenerateCalificationCommand(employeeEvaluation.Period, employeeEvaluation.UserName, employeeEvaluation.UserName, employeeEvaluation.TemplateId, CalificationType.Auto, employeeEvaluation.Id));
                ExecuteCommand(new GenerateCalificationCommand(employeeEvaluation.Period, employeeEvaluation.UserName, employeeEvaluation.ResponsibleId, employeeEvaluation.TemplateId, CalificationType.Responsible, employeeEvaluation.Id));
            }
        }
Пример #14
0
 public static CalificationsEvaluationDto Create(EmployeeEvaluation evaluation, List <string> evaluators, string currentPosition, string seniority, bool companyEvaluationDone, EvaluationState state)
 {
     return(new CalificationsEvaluationDto()
     {
         Id = evaluation.Id,
         UserName = evaluation.UserName,
         FullName = evaluation.FullName,
         CurrentPosition = currentPosition,
         Seniority = seniority,
         Project = evaluation.Project,
         ResponsibleId = evaluation.ResponsibleId,
         TemplateId = evaluation.TemplateId,
         Period = evaluation.Period,
         DevolutionInProgress = evaluation.ReadyForDevolution,
         Finished = evaluation.Finished,
         StrengthsComment = evaluation.StrengthsComment,
         ToImproveComment = evaluation.ToImproveComment,
         ActionPlanComment = evaluation.ActionPlanComment,
         Evaluators = evaluators,
         IsCompanyEvaluationDone = companyEvaluationDone,
         State = state
     });
 }
Пример #15
0
        public override void load(IModelObject mo)
        {
            const int DATAREADER_FLD_EMPLOYEE_EVALUATION_ID = 0;
            const int DATAREADER_FLD_EVALUATOR_ID           = 1;
            const int DATAREADER_FLD_EVALUATION_DATE        = 2;
            const int DATAREADER_FLD_EMPLOYEE_ID            = 3;

            EmployeeEvaluation obj = (EmployeeEvaluation)mo;

            obj.IsObjectLoading = true;

            if (!this.reader.IsDBNull(DATAREADER_FLD_EMPLOYEE_EVALUATION_ID))
            {
                obj.PrEmployeeEvaluationId = Convert.ToInt64(this.reader.GetInt32(DATAREADER_FLD_EMPLOYEE_EVALUATION_ID));
            }
            if (!this.reader.IsDBNull(DATAREADER_FLD_EVALUATOR_ID))
            {
                obj.PrEvaluatorId = Convert.ToInt64(this.reader.GetInt32(DATAREADER_FLD_EVALUATOR_ID));
            }
            if (!this.reader.IsDBNull(DATAREADER_FLD_EVALUATION_DATE))
            {
                obj.PrEvaluationDate = this.reader.GetDateTime(DATAREADER_FLD_EVALUATION_DATE);
            }
            if (!this.reader.IsDBNull(DATAREADER_FLD_EMPLOYEE_ID))
            {
                obj.PrEmployeeId = Convert.ToInt64(this.reader.GetInt32(DATAREADER_FLD_EMPLOYEE_ID));
            }


            obj.isNew = false;
            // since we've just loaded from database, we mark as "old"
            obj.isDirty         = false;
            obj.IsObjectLoading = false;
            obj.afterLoad();

            return;
        }
        public async Task <ApiResponse> Handle(RejectEmployeeAppraisalRequestCommand request, CancellationToken cancellationToken)
        {
            ApiResponse response = new ApiResponse();

            try
            {
                List <EmployeeAppraisalDetailsModel> lst = new List <EmployeeAppraisalDetailsModel>();
                var emplst = await _dbContext.EmployeeAppraisalDetails.FirstOrDefaultAsync(x => x.EmployeeAppraisalDetailsId == request.EmployeeAppraisalDetailsId && x.AppraisalStatus == false);

                emplst.AppraisalStatus = false;
                emplst.ModifiedById    = request.ModifiedById;
                emplst.ModifiedDate    = request.ModifiedDate;
                emplst.IsDeleted       = true;
                await _dbContext.SaveChangesAsync();

                EmployeeEvaluation evaluationModel = new EmployeeEvaluation();
                evaluationModel.CreatedById                = request.CreatedById;
                evaluationModel.CreatedDate                = request.CreatedDate;
                evaluationModel.EmployeeId                 = emplst.EmployeeId;
                evaluationModel.CurrentAppraisalDate       = emplst.CurrentAppraisalDate;
                evaluationModel.IsDeleted                  = true;
                evaluationModel.EvaluationStatus           = null;
                evaluationModel.EmployeeAppraisalDetailsId = emplst.EmployeeAppraisalDetailsId;
                await _dbContext.EmployeeEvaluation.AddAsync(evaluationModel);

                await _dbContext.SaveChangesAsync();

                response.StatusCode = StaticResource.successStatusCode;
                response.Message    = "Success";
            }
            catch (Exception ex)
            {
                response.StatusCode = StaticResource.failStatusCode;
                response.Message    = ex.Message;
            }
            return(response);
        }
 public static void saveEmployeeEvaluation(DataTable dt, ref EmployeeEvaluation mo)
 {
     foreach (DataRow dr in dt.Rows) {
         saveEmployeeEvaluation(dr, ref mo);
     }
 }
Пример #18
0
        public static void deleteEmployeeEvaluation(EmployeeEvaluation EmployeeEvaluationObj)
        {
            EmployeeEvaluationDBMapper dbm = new EmployeeEvaluationDBMapper();

            dbm.delete(EmployeeEvaluationObj);
        }
Пример #19
0
        public async Task <ApiResponse> Handle(AddEmployeeAppraisalMoreDetailsCommand request, CancellationToken cancellationToken)
        {
            ApiResponse response = new ApiResponse();

            try
            {
                var recordList = await _dbContext.EmployeeEvaluation.Where(x => x.EmployeeId == request.EmployeeId && x.CurrentAppraisalDate.Date == DateTime.Now.Date).ToListAsync();

                _dbContext.RemoveRange(recordList);

                List <EmployeeEvaluation>  lst        = new List <EmployeeEvaluation>();
                List <StrongandWeakPoints> StrongList = new List <StrongandWeakPoints>();
                List <StrongandWeakPoints> WeakList   = new List <StrongandWeakPoints>();
                foreach (var item in request.EmployeeEvaluationModelList)
                {
                    EmployeeEvaluation obj = new EmployeeEvaluation();
                    obj.FinalResultQues1     = request.FinalResultQues1;
                    obj.FinalResultQues2     = request.FinalResultQues2;
                    obj.FinalResultQues3     = request.FinalResultQues3;
                    obj.FinalResultQues4     = request.FinalResultQues4;
                    obj.FinalResultQues5     = request.FinalResultQues5;
                    obj.DirectSupervisor     = request.DirectSupervisor;
                    obj.CommentsByEmployee   = request.CommentsByEmployee;
                    obj.CreatedById          = request.CreatedById;
                    obj.CreatedDate          = request.CreatedDate;
                    obj.CurrentAppraisalDate = DateTime.Now;
                    obj.EmployeeId           = request.EmployeeId;
                    lst.Add(obj);
                }
                await _dbContext.EmployeeEvaluation.AddRangeAsync(lst);

                foreach (var item in request.StrongPoints)
                {
                    StrongandWeakPoints obj = new StrongandWeakPoints();
                    obj.CreatedById          = request.CreatedById;
                    obj.CreatedDate          = request.CreatedDate;
                    obj.CurrentAppraisalDate = DateTime.Now;
                    obj.EmployeeId           = request.EmployeeId;
                    obj.Point  = item;
                    obj.Status = 1;         // 1 for strong points
                    StrongList.Add(obj);
                }
                await _dbContext.StrongandWeakPoints.AddRangeAsync(StrongList);

                foreach (var item in request.WeakPoints)
                {
                    StrongandWeakPoints obj = new StrongandWeakPoints();
                    obj.CreatedById          = request.CreatedById;
                    obj.CreatedDate          = request.CreatedDate;
                    obj.CurrentAppraisalDate = DateTime.Now;
                    obj.EmployeeId           = request.EmployeeId;
                    obj.Point  = item;
                    obj.Status = 2;         // 2 for Weak points
                    WeakList.Add(obj);
                }
                await _dbContext.StrongandWeakPoints.AddRangeAsync(WeakList);

                await _dbContext.SaveChangesAsync();

                response.StatusCode = StaticResource.successStatusCode;
                response.Message    = "Success";
            }
            catch (Exception ex)
            {
                response.StatusCode = StaticResource.failStatusCode;
                response.Message    = ex.Message;
            }
            return(response);
        }
Пример #20
0
 public void saveEmployeeEvaluation(EmployeeEvaluation mo)
 {
     base.save(mo);
 }
Пример #21
0
        public void testVBNetCreateRecords()
        {
            ModelContext.Current.config.DoCascadeDeletes = true;
            ModelContext.beginTrans();
            ModelContext.Current.addGlobalModelValidator(typeof(Employee), typeof(CsharpEmployeeValidator));
            DateTime hireDate = new DateTime(DateTime.Now.Year + 10, 1, 1);

            try {
                EmployeeRank er = EmployeeRankFactory.Create();
                er.PrRank = "My New Rank";

                Employee employee = EmployeeFactory.Create();
                NUnit.Framework.Assert.IsTrue(employee is IAuditable, "Empoyee must implement IAuditable");

                employee.PrRank         = er;
                employee.PrEmployeeName = "test employee";
                employee.PrSalary       = 100m;
                employee.PrSSINumber    = "1030045";
                employee.PrTelephone    = "2234455";
                employee.PrHireDate     = hireDate;
                employee.PrIsActive     = true;

                Guid g = Guid.NewGuid();
                employee.PrSampleGuidField = g;
                employee.PrEmployeeProjectAdd(EmployeeProjectFactory.Create());
                EmployeeProject emplProj = employee.PrEmployeeProjectGetAt(0);
                emplProj.PrAssignDate            = new DateTime(DateTime.Now.Year + 10, 3, 1);
                emplProj.PrEndDate               = new DateTime(DateTime.Now.Year + 10, 6, 1);
                emplProj.PrEPProjectId           = 1;
                emplProj.PrProject               = ProjectFactory.Create();
                emplProj.PrProject.PrProjectName = "MyProject";

                NUnit.Framework.Assert.IsTrue(employee.isNew);
                NUnit.Framework.Assert.IsTrue(employee.isDirty);
                NUnit.Framework.Assert.IsTrue(employee.NeedsSave);

                // 3 ways to persist to database
                // method 1: use ModelContext.Current().save

                NUnit.Framework.Assert.IsTrue(employee.CreateDate == null, "Before save, created date is null");
                NUnit.Framework.Assert.IsTrue(employee.UpdateDate == null, "Before save, UpdateDate is not null");

                ModelContext.Current.saveModelObject(employee);

                NUnit.Framework.Assert.IsTrue(employee.PrSSINumber == "12345XX", "12345XX value in PrSSINumber is Proof that validator was called");
                NUnit.Framework.Assert.IsTrue(employee.CreateDate != null, "Before save, created date is not null");
                NUnit.Framework.Assert.IsTrue(employee.UpdateDate != null, "Before save, UpdateDate is not null");
                NUnit.Framework.Assert.IsTrue(employee.CreateUser != null, "Before save, CreateUser date is not null");
                NUnit.Framework.Assert.IsTrue(employee.UpdateUser != null, "Before save, UpdateUser is not null");
                NUnit.Framework.Assert.IsTrue(employee.UpdateDate.GetValueOrDefault().ToString("dd/MM/yyyy") == employee.CreateDate.GetValueOrDefault().ToString("dd/MM/yyyy"), "update date = create date after saving new");
                NUnit.Framework.Assert.IsTrue(employee.UpdateUser == employee.CreateUser, "update date = create date after saving new");

                long x = (long)employee.Id;
                NUnit.Framework.Assert.IsFalse(employee.isNew, "After save, model object isNew property must return false");
                NUnit.Framework.Assert.IsFalse(employee.isDirty, "After save to db, model object isDirty property must return false");

                employee = EmployeeDataUtils.findByKey(x);

                NUnit.Framework.Assert.IsNotNull(employee, "New employee not found");

                NUnit.Framework.Assert.IsFalse(employee.isNew, "After load from db, model object isNew property returns false");
                NUnit.Framework.Assert.IsFalse(employee.isDirty, "After load from db, model object isDirty property returns false");
                NUnit.Framework.Assert.AreEqual(employee.PrSampleGuidField, g);
                NUnit.Framework.Assert.AreEqual(employee.PrRank.PrRank, "My New Rank");
                NUnit.Framework.Assert.AreEqual(employee.PrSalary, 100m);
                NUnit.Framework.Assert.AreEqual(employee.PrEmployeeName, "test employee");
                NUnit.Framework.Assert.AreEqual(employee.PrSSINumber, "12345XX");
                NUnit.Framework.Assert.AreEqual(employee.PrHireDate, hireDate);
                NUnit.Framework.Assert.AreEqual(employee.PrEmployeeProjects.ToList().Count, 1);
                NUnit.Framework.Assert.AreEqual(employee.PrEmployeeProjectGetAt(0).PrProject.PrProjectName, "MyProject");

                //change some values on child and parent objects
                employee.PrEmployeeProjectGetAt(0).PrEndDate = new DateTime(DateTime.Now.Year + 10, 6, 1);
                employee.PrEmployeeProjectGetAt(0).PrProject.PrProjectName = "MyProject Updated"; // here we are updating parent record of child object of employee!
                NUnit.Framework.Assert.IsTrue(employee.NeedsSave, "After changing parent or child obejcts values, e.NeedsSave must be true");
                NUnit.Framework.Assert.IsFalse(employee.isDirty, "After changing parent or child obejcts values, e.isDirty must be false since we did not change anything on the Model Object");

                // method 2: call [ModelObject]DataUtils.save
                EmployeeDataUtils.saveEmployee(employee);

                var lst = EmployeeDataUtils.findList("hiredate between ? and ?", new DateTime(DateTime.Now.Year + 10, 1, 1), new DateTime(DateTime.Now.Year + 10, 12, 1));
                NUnit.Framework.Assert.AreEqual(1, lst.Count);
                employee = EmployeeDataUtils.findByKey(x);

                //NUnit.Framework.Assert.IsTrue(e.UpdateDate > e.CreateDate, "after update of record, update must be date > create date ");
                // note that above test cannot be sucess since save is happening too fast

                NUnit.Framework.Assert.AreEqual(employee.PrEmployeeProjectGetAt(0).PrEndDate, new DateTime(DateTime.Now.Year + 10, 6, 1));
                NUnit.Framework.Assert.AreEqual(employee.PrEmployeeProjectGetAt(0).PrProject.PrProjectName, "MyProject Updated", "Expected to have parent record of child updated!");

                employee.PrSSINumber              = "XXXXX";
                employee.PrEmployeeInfo           = EmployeeInfoFactory.Create();
                employee.PrEmployeeInfo.PrAddress = "2 nikoy thefanous street";
                employee.PrEmployeeInfo.PrSalary  = 3000;

                NUnit.Framework.Assert.IsTrue(employee.NeedsSave, "After changing value, e.NeedsSave must be true");
                NUnit.Framework.Assert.IsTrue(employee.isDirty, "After changing value e.isDirty must be true");

                // method 3: call [ModelObject]dbMapper.save
                new EmployeeDBMapper().save(employee);
                employee = EmployeeDataUtils.findByKey(x);
                NUnit.Framework.Assert.AreEqual(employee.PrSSINumber, "XXXXX");
                NUnit.Framework.Assert.AreEqual(employee.PrEmployeeProjectGetAt(0).PrEndDate, new DateTime(DateTime.Now.Year + 10, 6, 1));
                NUnit.Framework.Assert.AreEqual(employee.PrEmployeeProjectGetAt(0).PrProject.PrProjectName, "MyProject Updated", "Expected to have parent record of child updated!");

                employee.PrEmployeeProjectsClear();
                NUnit.Framework.Assert.AreEqual(employee.PrEmployeeProjects.ToList().Count, 0, "Expected to have no Projects linked after call to clear");
                EmployeeDataUtils.saveEmployee(employee);

                employee = EmployeeDataUtils.findByKey(x);
                NUnit.Framework.Assert.AreEqual(employee.PrEmployeeProjects.ToList().Count, 0, "Expected to have no Projects linked, after reloading from db");

                List <Employee> empls = EmployeeDataUtils.findList("EmployeeName={0} and Salary between {1} and {2} and HireDate={3}", "test employee", 0, 100, hireDate);
                NUnit.Framework.Assert.IsTrue(empls.Count > 0, "Employee Count not the expected!");

                EmployeeDataUtils.deleteEmployee(employee);
                employee = EmployeeDataUtils.findByKey(x);
                NUnit.Framework.Assert.IsNull(employee, "New employee must have been deleted!");

                // now let's test string primary key
                EmployeeType et = EmployeeTypeFactory.Create();
                et.PrEmployeeType     = "A Description";
                et.PrEmployeeTypeCode = "XX";

                EmployeeType et1 = EmployeeTypeFactory.Create();
                et1.PrEmployeeType     = "A Description 1";
                et1.PrEmployeeTypeCode = "XX1";

                EmployeeType et2 = EmployeeTypeFactory.Create();
                et2.PrEmployeeType     = "A Description 2";
                et2.PrEmployeeTypeCode = "XX2";

                EmployeeTypeDataUtils.saveEmployeeType(et, et1, et2);

                et2 = EmployeeTypeDataUtils.findByKey("XX2");
                NUnit.Framework.Assert.IsNotNull(et2, "New employeetype must have been created!");
                et1 = EmployeeTypeDataUtils.findByKey("XX1");
                NUnit.Framework.Assert.IsNotNull(et1, "New employeetype must have been created!");

                Project p = ProjectFactory.Create();
                p.PrIsActive      = true;
                p.PrProjectTypeId = ModelLibVBGenCode.EnumProjectType.EXTERNAL;
                p.PrProjectName   = "Test";
                ProjectDataUtils.saveProject(p);
                long pid = p.PrProjectId;
                p = ProjectDataUtils.findByKey(pid);
                NUnit.Framework.Assert.IsNotNull(p, "New project must have been saved to the db!");
                NUnit.Framework.Assert.AreEqual(p.PrProjectTypeId, ModelLibVBGenCode.EnumProjectType.EXTERNAL);

                p.PrProjectTypeId = null; // test null value to enumaration
                ProjectDataUtils.saveProject(p);
                p = ProjectDataUtils.findByKey(pid);
                NUnit.Framework.Assert.IsNotNull(p, "New project must have been saved to the db!");
                NUnit.Framework.Assert.IsNull(p.PrProjectTypeId, "project type id must be null after saved to the db, instead got value:" + p.PrProjectTypeId);

                List <Employee>    elst = EmployeeDataUtils.findList();
                EmployeeEvaluation ep   = EmployeeEvaluationFactory.Create();
                ep.PrEmployeeId     = elst[0].PrEmployeeId;
                ep.PrEvaluatorId    = elst[1].PrEmployeeId;
                ep.PrEvaluationDate = hireDate;
                EmployeeEvaluationDataUtils.saveEmployeeEvaluation(ep); // insert
                NUnit.Framework.Assert.IsTrue(ep.PrEmployeeEvaluationId > 0);
                long eid = ep.PrEmployeeEvaluationId;

                EmployeeEvaluation ep2 = EmployeeEvaluationDataUtils.findByKey(eid);
                NUnit.Framework.Assert.IsNotNull(ep2);
                NUnit.Framework.Assert.AreEqual(ep, ep2);
                ep2.PrEvaluationDate = new DateTime(hireDate.Year, hireDate.Month + 1, 1);
                EmployeeEvaluationDataUtils.saveEmployeeEvaluation(ep2);   // update

                EmployeeEvaluationDataUtils.deleteEmployeeEvaluation(ep2); //delete
                ep2 = EmployeeEvaluationDataUtils.findByKey(eid);
                NUnit.Framework.Assert.IsNull(ep2);

                Bank alphaBank = BankDataUtils.findOne("bankcode='09'");
                if (alphaBank == null)
                {
                    alphaBank            = BankFactory.Create();
                    alphaBank.PrBankCode = "09";
                    alphaBank.PrBankName = "ALPHA Bank";
                    BankDataUtils.saveBank(alphaBank);
                }

                Account pa = AccountDataUtils.findOne("Account='ALPHA'");
                if ((pa == null))
                {
                    pa                                     = AccountFactory.Create();
                    pa.PrAccount                           = "ALPHA";
                    pa.PrDescription                       = "ALPHA TEST";
                    pa.PrAccountTypeid                     = 1;
                    pa.PrBankaccnumber                     = "000000000004";
                    pa.PrBankAccountInfo                   = AccountBankInfoFactory.Create();
                    pa.PrBankAccountInfo.PrBankId          = alphaBank.PrBANKID;
                    pa.PrBankAccountInfo.PrCompanyName     = "UNIT TESTS LTD";
                    pa.PrBankAccountInfo.PrCompanyBankCode = "111";
                    AccountDataUtils.saveAccount(pa);
                }
            } finally {
                ModelContext.rollbackTrans();
            }
        }
        public override void Execute()
        {
            var evaluationId = EmployeeEvaluation.GenerateEvaluationId(_period, _evaluatedUserName);
            var evaluation   = RavenSession.Load <EmployeeEvaluation>(evaluationId);

            if (evaluation == null)
            {
                throw new ApplicationException(string.Format("Error: Evaluación inexistente: {0}.", evaluationId));
            }

            // Check that the new responsible exist
            var newResponsible = RavenSession
                                 .Query <Employee_Search.Projection, Employee_Search>()
                                 .Where(x => x.IsActive && x.UserName == _newResponsibleName).FirstOrDefault();


            if (newResponsible == null)
            {
                throw new ApplicationException(string.Format("Error: Empleado inexistente: {0}.", _newResponsibleName));
            }

            // Check that new responsible is not the evaluated employee
            if (evaluation.UserName == newResponsible.UserName)
            {
                throw new ApplicationException(string.Format("Error: {0} no puede ser responsable de su propia evaluación.", _newResponsibleName));
            }

            // If the new responsible is the same as the old one, cancel the operation.
            if (evaluation.ResponsibleId == newResponsible.UserName)
            {
                throw new ApplicationException(string.Format("Error: {0} es actualmente el responsable de esta evaluación.", newResponsible.UserName));
            }

            // The only moment when a user cant change an evaluation responsible,
            // is when the evaluation is complete and closed
            if (evaluation.Finished)
            {
                throw new ApplicationException(string.Format("Error: Esta evaluación ya está cerrada. No se puede modificar el responsable."));
            }

            // Load evaluation califications
            var evaluationCalifications = RavenSession.Advanced.LoadStartingWith <EvaluationCalification>(evaluationId + "/").ToList();

            var oldResponsibleCalification = evaluationCalifications.Where(x => x.Owner == CalificationType.Responsible).FirstOrDefault();

            // Change the old responsible califications to an "Evaluator" calification type
            oldResponsibleCalification.Owner = CalificationType.Evaluator;

            // If the new responsible is an evaluator, make its calification as "Responsible" type
            var newResponsibleCalification = evaluationCalifications
                                             .Where(x => x.Owner == CalificationType.Evaluator && x.EvaluatorEmployee == newResponsible.UserName)
                                             .FirstOrDefault();

            if (newResponsibleCalification != null)
            {
                newResponsibleCalification.Owner = CalificationType.Responsible;
            }
            // if not, create a new "Responsible" calification
            else
            {
                var newCalification = new EvaluationCalification
                {
                    Owner             = CalificationType.Responsible,
                    Period            = evaluation.Period,
                    EvaluationId      = evaluation.Id,
                    EvaluatedEmployee = evaluation.UserName,
                    EvaluatorEmployee = newResponsible.UserName,
                    TemplateId        = "Template/Default"
                };
                RavenSession.Store(newCalification);
            }

            // Update responsible in the evaluation
            evaluation.ResponsibleId = newResponsible.UserName;

            RavenSession.SaveChanges();
        }
        /// <summary>
        /// Reload the EmployeeEvaluation from the database
        /// </summary>
        /// <remarks>
        /// use this method when you want to relad the EmployeeEvaluation 
        /// from the database, discarding any changes
        /// </remarks>
        public static void reload(ref EmployeeEvaluation mo)
        {
            if (mo == null) {
                throw new System.ArgumentNullException("null object past to reload function");
            }

            mo = (EmployeeEvaluation)new EmployeeEvaluationDBMapper().findByKey(mo.Id);
        }
 public static EmployeeEvaluation loadFromDataRow(DataRow r)
 {
     DataRowLoader a = new DataRowLoader();
     IModelObject mo = new EmployeeEvaluation();
     a.DataSource = r;
     a.load(mo);
     return (EmployeeEvaluation)mo;
 }
        public override CalificationsDto ExecuteWithResult()
        {
            var evId             = EmployeeEvaluation.GenerateEvaluationId(_period, _evaluatedUser);
            var evaluation       = RavenSession.Load <EmployeeEvaluation>(evId);
            var evaluationHelper = new EmployeeEvaluationHelper(RavenSession, _loggedUser);

            if (evaluation == null)
            {
                throw new ApplicationException(string.Format("Error: Evaluación inexistente: {0}.", evId));
            }

            var isVisitor = (evaluation.SharedLinks == null ? false : evaluation.SharedLinks.Any(x => x.SharedCode == _sharedCode && x.ExpirationDate > DateTime.UtcNow)) || //has SharedCode
                            (string.Compare(evaluationHelper.GetLastPeriodForResponisble(_evaluatedUser), _period) > 0); //is newer Responsible

            Employee_Search.Projection employee = RavenSession
                                                  .Query <Employee_Search.Projection, Employee_Search>()
                                                  .Where(x => x.IsActive && x.UserName == evaluation.UserName).FirstOrDefault();

            var califications = RavenSession.Advanced.LoadStartingWith <EvaluationCalification>(evId + "/").ToList();

            var evaluators                = califications.Where(c => c.Owner == CalificationType.Evaluator).Select(c => c.EvaluatorEmployee).ToList();
            var autoEvaluationDone        = califications.Any(c => c.Owner == CalificationType.Auto && c.Finished);
            var responsibleEvaluationDone = califications.Any(c => c.Owner == CalificationType.Responsible && c.Finished);
            var companyEvaluationDone     = califications.Any(c => c.Owner == CalificationType.Company && c.Finished);
            var state = EvaluationStateHelper.GetEvaluationState(autoEvaluationDone, responsibleEvaluationDone, companyEvaluationDone, evaluation.ReadyForDevolution, evaluation.Finished);

            var evaluationDto = CalificationsEvaluationDto.Create(evaluation, evaluators, evaluation.CurrentPosition ?? employee.CurrentPosition, evaluation.Seniority ?? employee.Seniority, companyEvaluationDone, state);

            if (!CanViewEvaluation(evaluationDto, califications, isVisitor))
            {
                throw new ApplicationException(string.Format("Error: Usuario {0} no tiene permiso para ver la evaluación {1}", _loggedUser, evId));
            }

            // If evaluation is finished
            // - Show ALWAYS company & auto

            if (evaluation.Finished)
            {
                return(GetFinishedEvaluation(evaluationDto, califications));
            }

            // If loggedUser is the evaluated
            // - Show auto-eval if not RFD
            // - Show auto-eval & company if RFD

            if (_loggedUser == _evaluatedUser)
            {
                return(GetAutoEvaluation(evaluationDto, califications));
            }

            // If loggedUser is responsible
            // - Show all

            if (_loggedUser == evaluationDto.ResponsibleId)
            {
                return(GetFullEvaluation(evaluationDto, califications));
            }

            // If loggedUser is evaluator
            // - Show evluator eval

            return(GetEvaluatorEvaluation(evaluationDto, califications));
        }
        public static void saveEmployeeEvaluation(DataRow dr, ref EmployeeEvaluation mo)
        {
            if (mo == null) {
                mo = new EmployeeEvaluation();
            }

            foreach (DataColumn dc in dr.Table.Columns) {
                mo.setAttribute(dc.ColumnName, dr[dc.ColumnName]);
            }

            saveEmployeeEvaluation(mo);
        }
    [TestMethod()] public void TestLoadAndSaveEmployeeEvaluation()
    {
        ModelContext.beginTrans();
        try {
            CsModelMappers.EmployeeEvaluationDBMapper pdb = new CsModelMappers.EmployeeEvaluationDBMapper();

            long count = pdb.RecordCount();

            if (pdb.SelectFromObjectName != pdb.ManagedTableName)
            {
                long countFromSelectObject = pdb.dbConn.getLngValue("select count(*) from " + pdb.SelectFromObjectName);
                Assert.AreEqual(count, countFromSelectObject,
                                "Count of records in managedTableName {0} and SelectFromObjectName {1} should be equal, as there needs to be exactly 1 to 1 match between records in managed table and selectFromObject.",
                                pdb.ManagedTableName, pdb.SelectFromObjectName);
            }

            if (count == 0)
            {
                Assert.Inconclusive("No EmployeeEvaluation in database, table is empty");
            }
            else
            {
                /**
                 * using (DataContext ctx = DBUtils.Current().dbContext()) {
                 *
                 *      var query = ctx.ExecuteQuery<EmployeeEvaluation>(@"SELECT * FROM " + pdb.SelectFromObjectName ).Skip(1).Take(1);
                 *      var lst = query.ToList();
                 *
                 *      Assert.AreEqual(lst.Count, 1, "Expected to receive 1 record, got: " + lst.Count);
                 *
                 * }
                 * todo: fix boolean fields by generating properties of original fields
                 **/
                object pid = ModelContext.CurrentDBUtils.getObjectValue("select top 1 " + pdb.pkFieldName + " from " + pdb.ManagedTableName);

                EmployeeEvaluation p  = pdb.findByKey(pid);
                EmployeeEvaluation p2 = (EmployeeEvaluation)p.copy();

                //Test equality and hash codes
                Assert.AreEqual(p.GetHashCode(), p2.GetHashCode());
                Assert.AreEqual(p, p2);

                p.isDirty = true;                  // force save
                pdb.save(p);

                // now reload object from database
                p = null;
                p = pdb.findByKey(pid);

                //test fields to be equal before and after save
                Assert.IsTrue(p.PrEmployeeEvaluationId == p2.PrEmployeeEvaluationId, "Expected Field EmployeeEvaluationId to be equal");
                Assert.IsTrue(p.PrEvaluatorId.GetValueOrDefault() == p2.PrEvaluatorId.GetValueOrDefault(), "Expected Field EvaluatorId to be equal");
                Assert.IsTrue(p.PrEvaluationDate.GetValueOrDefault() == p2.PrEvaluationDate.GetValueOrDefault(), "Expected Field EvaluationDate to be equal");
                //skip long field:evaluation_result
                Assert.IsTrue(p.PrEmployeeId.GetValueOrDefault() == p2.PrEmployeeId.GetValueOrDefault(), "Expected Field EmployeeId to be equal");

                p.isDirty = true;                 //to force save
                ModelContext.Current.saveModelObject(p);

                p = ModelContext.Current.loadModelObject <EmployeeEvaluation>(p.Id);
                p.loadObjectHierarchy();

                string json = JsonConvert.SerializeObject(p, Formatting.Indented,
                                                          new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
                System.IO.FileInfo jf = new System.IO.FileInfo(".\\EmployeeEvaluation.json");
                System.IO.File.WriteAllText(jf.FullName, json);

                if (pdb.isPrimaryKeyAutogenerated)
                {
                    p.isNew   = true;
                    p.isDirty = true;

                    try {
                        pdb.save(p);
                    } catch (System.Exception e) {
                        Assert.IsTrue(e.Message.ToUpper().Contains("UNIQUE INDEX") || e.Message.Contains("Violation of UNIQUE KEY constraint"),
                                      "Insert statement produced error other than violation of unique key:" + e.Message);
                    }
                }
            }
        } finally {
            ModelContext.rollbackTrans(); // 'Nothing should be saved to the database!
        }
    }
 public static void deleteEmployeeEvaluation(EmployeeEvaluation EmployeeEvaluationObj)
 {
     EmployeeEvaluationDBMapper dbm = new EmployeeEvaluationDBMapper();
     dbm.delete(EmployeeEvaluationObj);
 }
 public void saveEmployeeEvaluation(EmployeeEvaluation mo)
 {
     base.save(mo);
 }