public void Create_1_HappyPath()
        {
            ExamsController controller;
            Patient patient;
            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                patient = Firestarter.CreateFakePatients(doctor, this.db).First();
                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>();
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Creating a new examination request.
            ActionResult actionResult;

            {
                var medicalProc = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.03.04.36-1");
                var viewModel = new ExaminationRequestViewModel
                {
                    PatientId = patient.Id,
                    Notes = "Any text",
                    MedicalProcedureId = medicalProc.Id,
                    MedicalProcedureName = "Hemograma com contagem de plaquetas ou frações (eritrograma, leucograma, plaquetas)",
                };

                actionResult = controller.Create(new[] { viewModel });
            }

            // Verifying the ActionResult.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");

            // Verifying the controller model-state.
            Assert.IsTrue(controller.ModelState.IsValid, "ModelState is not valid.");

            // Verifying the database.
            Assert.IsTrue(this.db.ExaminationRequests.Any(x => x.PatientId == patient.Id), "Database record was not saved.");

            // Verifying the database.
            using (var db2 = DbTestBase.CreateNewCerebelloEntities())
            {
                var obj = db2.ExaminationRequests.FirstOrDefault(x => x.PatientId == patient.Id);
                Assert.IsNotNull(obj, "Database record was not saved.");
                Assert.AreEqual("Any text", obj.Text);
                Assert.AreEqual("4.03.04.36-1", obj.MedicalProcedureCode);
                Assert.AreEqual("Hemograma com contagem de plaquetas ou frações (eritrograma, leucograma, plaquetas)", obj.MedicalProcedureName);
            }
        }
        public ActionResult Edit(int? id, int? patientId, int? y, int? m, int? d)
        {
            ExaminationRequestViewModel viewModel = null;

            // Todo: security issue... must check current user practice againt the practice of the edited objects.

            if (id != null)
            {
                var modelObj = this.db.ExaminationRequests.FirstOrDefault(r => r.Id == id);

                // todo: if modelObj is null, we must tell the user that this object does not exist.

                viewModel = GetViewModel(modelObj, this.GetToLocalDateTimeConverter());
            }
            else
                viewModel = new ExaminationRequestViewModel()
                {
                    Id = null,
                    PatientId = patientId,
                    RequestDate = DateTimeHelper.CreateDate(y, m, d) ?? this.GetPracticeLocalNow(),
                };

            return this.View("Edit", viewModel);
        }
 public ActionResult Create(ExaminationRequestViewModel[] examRequests)
 {
     return this.Edit(examRequests);
 }
        public ActionResult Edit(ExaminationRequestViewModel[] examRequests)
        {
            var formModel = examRequests.Single();

            ExaminationRequest dbObject;

            if (formModel.Id == null)
            {
                Debug.Assert(formModel.PatientId != null, "formModel.PatientId != null");
                dbObject = new ExaminationRequest
                {
                    CreatedOn = this.GetUtcNow(),
                    PatientId = formModel.PatientId.Value,
                    PracticeId = this.DbUser.PracticeId,
                };

                this.db.ExaminationRequests.AddObject(dbObject);
            }
            else
            {
                dbObject = this.db.ExaminationRequests.FirstOrDefault(r => r.Id == formModel.Id);

                // If modelObj is null, we must tell the user that this object does not exist.
                if (dbObject == null)
                    return View("NotFound", formModel);

                // Security issue... must check current user practice against the practice of the edited objects.
                if (this.DbUser.Practice.Id != dbObject.Patient.Doctor.Users.FirstOrDefault().PracticeId)
                    return View("NotFound", formModel);
            }

            if (this.ModelState.IsValid)
            {
                dbObject.Patient.IsBackedUp = false;
                dbObject.Text = formModel.Notes;
                dbObject.MedicalProcedureCode = formModel.MedicalProcedureId.HasValue
                    ? this.db.SYS_MedicalProcedure.Where(mp => mp.Id == formModel.MedicalProcedureId).Select(mp => mp.Code).FirstOrDefault()
                    : formModel.MedicalProcedureCode;

                dbObject.MedicalProcedureName = formModel.MedicalProcedureName;
                dbObject.RequestDate = this.ConvertToUtcDateTime(formModel.RequestDate.Value);

                this.db.SaveChanges();

                return this.View("Details", GetViewModel(dbObject, this.GetToLocalDateTimeConverter()));
            }

            return this.View("Edit", formModel);
        }
        public void Create_WithoutMedicalProcedure()
        {
            ExamsController controller;
            Patient patient;
            bool isDbChangesSaved = false;
            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                patient = Firestarter.CreateFakePatients(doctor, this.db).First();
                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>(
                        setupNewDb: db => db.SavingChanges += (s, e) => { isDbChangesSaved = true; });
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Creating a new examination request without the text.
            // This is not allowed and must generate a model state validation message.
            ActionResult actionResult;
            ExaminationRequestViewModel viewModel;

            {
                viewModel = new ExaminationRequestViewModel
                {
                    PatientId = patient.Id,
                };

                Mvc3TestHelper.SetModelStateErrors(controller, viewModel);

                actionResult = controller.Create(new[] { viewModel });
            }

            // Verifying the ActionResult, and the DB.
            // - The result must be a ViewResult, with the name "Edit".
            // - The controller ModelState must have one validation message.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            var viewResult = (ViewResult)actionResult;
            Assert.AreEqual("edit", viewResult.ViewName, ignoreCase: true);
            Assert.IsFalse(controller.ModelState.IsValid, "ModelState should not be valid.");
            Assert.AreEqual(
                1,
                controller.ModelState.GetPropertyErrors(() => viewModel.MedicalProcedureName).Count(),
                "ModelState should contain one validation message.");

            // Verifying the database: cannot save the changes.
            Assert.IsFalse(isDbChangesSaved, "Database changes were saved, but they should not.");
        }
        public void Edit_4_EditExamThatDoesNotExist()
        {
            ExamsController controller;
            ExaminationRequestViewModel viewModel;
            var isDbChangesSaved = false;
            var localNow = new DateTime(2012, 08, 16);
            try
            {
                var drandre = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var patient = Firestarter.CreateFakePatients(drandre, this.db).First();

                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>(
                        setupNewDb: db => db.SavingChanges += (s, e) => { isDbChangesSaved = true; });
                Debug.Assert(drandre != null, "drandre must not be null");
                var utcNow = PracticeController.ConvertToUtcDateTime(drandre.Users.First().Practice, localNow);
                controller.UtcNowGetter = () => utcNow;

                // saving the object that will be edited
                var medicalProc0 = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.03.04.36-1");
                var examRequest = new ExaminationRequest
                                      {
                                          CreatedOn = utcNow,
                                          PatientId = patient.Id,
                                          Text = "Old text",
                                          MedicalProcedureCode = medicalProc0.Code,
                                          MedicalProcedureName = medicalProc0.Name,
                                          PracticeId = drandre.PracticeId,
                                      };
                this.db.ExaminationRequests.AddObject(examRequest);
                this.db.SaveChanges();

                // Define André as the logged user.
                mr.SetCurrentUser_Andre_CorrectPassword();

                // Creating view-model and setting up controller ModelState based on the view-model.
                var medicalProc1 = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.01.03.23-4");
                viewModel = new ExaminationRequestViewModel
                {
                    Id = 19837,
                    PatientId = patient.Id,
                    Notes = "New text",
                    MedicalProcedureCode = medicalProc1.Code,
                    MedicalProcedureName = medicalProc1.Name,
                };

                Mvc3TestHelper.SetModelStateErrors(controller, viewModel);
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Editing an examination request that does not belong to the current user's practice.
            // This is not allowed and must throw an exception.
            // note: this is not a validation error, this is a malicious attack...
            ActionResult actionResult = controller.Edit(new[] { viewModel });

            // Verifying the ActionResult, and the DB.
            // - The result must be a ViewResult, with the name "Edit".
            // - The controller ModelState must have one validation message.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            var viewResult = (ViewResult)actionResult;
            Assert.AreEqual("NotFound", viewResult.ViewName);

            // Verifying the database: cannot save the changes.
            Assert.IsFalse(isDbChangesSaved, "Database changes were saved, but they should not.");
        }
        public void Edit_2_WithoutMedicalProcedure()
        {
            ExamsController controller;
            Patient patient;
            ExaminationRequest examRequest;
            var isDbChangesSaved = false;
            var localNow = new DateTime(2012, 08, 16);
            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                patient = Firestarter.CreateFakePatients(doctor, this.db).First();
                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>(
                        setupNewDb: db => db.SavingChanges += (s, e) => { isDbChangesSaved = true; });
                Debug.Assert(doctor != null, "doctor must not be null");
                var utcNow = PracticeController.ConvertToUtcDateTime(doctor.Users.First().Practice, localNow);
                controller.UtcNowGetter = () => utcNow;

                // saving the object that will be edited
                examRequest = new ExaminationRequest
                {
                    CreatedOn = utcNow,
                    PatientId = patient.Id,
                    Text = "Old text",
                    PracticeId = doctor.PracticeId,
                    MedicalProcedureName = "Hemoglobina (eletroforese ou HPLC)",
                    MedicalProcedureCode = "4.03.04.35-3",
                };
                this.db.ExaminationRequests.AddObject(examRequest);
                this.db.SaveChanges();
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Creating a new examination request without the text.
            // This is not allowed and must generate a model state validation message.
            ActionResult actionResult;
            ExaminationRequestViewModel viewModel;

            {
                viewModel = new ExaminationRequestViewModel
                {
                    Id = examRequest.Id,
                    PatientId = patient.Id,
                };

                Mvc3TestHelper.SetModelStateErrors(controller, viewModel);

                actionResult = controller.Edit(new[] { viewModel });
            }

            // Verifying the ActionResult, and the DB.
            // - The result must be a ViewResult, with the name "Edit".
            // - The controller ModelState must have one validation message.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));
            var viewResult = (ViewResult)actionResult;
            Assert.AreEqual("edit", viewResult.ViewName, true);
            Assert.IsFalse(controller.ModelState.IsValid, "ModelState should not be valid.");
            Assert.AreEqual(
                1,
                controller.ModelState.GetPropertyErrors(() => viewModel.MedicalProcedureName).Count(),
                "ModelState should contain one validation message.");

            // Verifying the database: cannot save the changes.
            Assert.IsFalse(isDbChangesSaved, "Database changes were saved, but they should not.");
        }
        public void Edit_1_HappyPath()
        {
            ExamsController controller;
            Patient patient;
            ExaminationRequest examRequest;
            DateTime utcNow;
            var localNow = new DateTime(2012, 08, 16);
            try
            {
                var doctor = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                patient = Firestarter.CreateFakePatients(doctor, this.db).First();

                var mr = new MockRepository(true);
                controller = mr.CreateController<ExamsController>();
                Debug.Assert(doctor != null, "doctor must not be null");
                utcNow = PracticeController.ConvertToUtcDateTime(doctor.Users.First().Practice, localNow);
                controller.UtcNowGetter = () => utcNow;

                // saving the object that will be edited
                var medicalProc = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.03.04.36-1");
                examRequest = new ExaminationRequest
                {
                    CreatedOn = utcNow,
                    PatientId = patient.Id,
                    Text = "Old text",
                    MedicalProcedureCode = medicalProc.Code,
                    MedicalProcedureName = medicalProc.Name,
                    PracticeId = doctor.PracticeId,
                };
                this.db.ExaminationRequests.AddObject(examRequest);
                this.db.SaveChanges();
            }
            catch (Exception ex)
            {
                InconclusiveInit(ex);
                return;
            }

            // Creating a new examination request.
            ActionResult actionResult;

            {
                var medicalProc = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.01.03.23-4");
                var viewModel = new ExaminationRequestViewModel
                {
                    Id = examRequest.Id,
                    PatientId = patient.Id,
                    Notes = "Any text",
                    MedicalProcedureId = medicalProc.Id, // editing value: old = "4.03.04.36-1"; new = "4.01.03.23-4"
                    MedicalProcedureName = "Eletrencefalograma em vigília, e sono espontâneo ou induzido",
                };

                Mvc3TestHelper.SetModelStateErrors(controller, viewModel);

                actionResult = controller.Edit(new[] { viewModel });
            }

            // Verifying the ActionResult.
            Assert.IsNotNull(actionResult, "The result of the controller method is null.");

            // Verifying the controller model-state.
            Assert.IsTrue(controller.ModelState.IsValid, "ModelState is not valid.");

            // Verifying the database.
            using (var db2 = DbTestBase.CreateNewCerebelloEntities())
            {
                var obj = db2.ExaminationRequests.FirstOrDefault(x => x.PatientId == patient.Id);
                Assert.IsNotNull(obj, "Database record was not saved.");
                Assert.AreEqual("Any text", obj.Text);
                Assert.AreEqual(utcNow, obj.CreatedOn);
                Assert.AreEqual("4.01.03.23-4", obj.MedicalProcedureCode);
                Assert.AreEqual("Eletrencefalograma em vigília, e sono espontâneo ou induzido", obj.MedicalProcedureName);
            }
        }