示例#1
0
        public void Buy_WhenModelMinPurchaseAmountIsGreaterThanMaxPurchaseAmount_ReturnViewResultBuyPracticePage()
        {
            var emailSender = new Mock <ISendEmail>().Object;
            var tempData    = new Mock <ITempDataDictionary>().Object;
            var reCaptcha   = MockReCaptchaService.Create(true);
            var sut         = new PracticeController(Enumerable.Empty <IGenerateEmail>(), emailSender, reCaptcha);

            sut.TempData = tempData;

            var fixture = new Fixture();
            var model   = fixture
                          .Build <BuyPracticeModel>()
                          .Without(m => m.ContactPhoneNumber)
                          .Create();

            model.MinPurchaseAmount = 100;
            model.MaxPurchaseAmount = 99;

            var result = sut.Buy(model);

            Assert.IsType <Task <IActionResult> >(result);
            var viewResult = result.Result as ViewResult;

            Assert.Equal("Buy", viewResult?.ViewName);
        }
示例#2
0
        public void CanCreatePracticeController()
        {
            var emailSender = new Mock <ISendEmail>().Object;
            var reCaptcha   = new Mock <IRecaptchaService>().Object;

            // ReSharper disable once UnusedVariable
            var sut = new PracticeController(Enumerable.Empty <IGenerateEmail>(), emailSender, reCaptcha);
        }
示例#3
0
 public frmUser(User currentUser, Form frm)
 {
     InitializeComponent();
     user                = currentUser;
     _userController     = new UserController();
     _practiceController = new PracticeController();
     frmLogin            = (frmLogin)frm;
 }
示例#4
0
 public frmPractice(User Currentuser)
 {
     InitializeComponent();
     user = Currentuser;
     _WordPoolController       = new WordPoolController();
     _wordPoolDetailController = new WordPoolDetailController();
     _practiceController       = new PracticeController();
 }
示例#5
0
        public frmUserPractice(User currentUser, WordPool CurrentWordPool, Practice currentPractice)
        {
            InitializeComponent();
            this.ControlBox           = false;
            _wordPoolDetailController = new WordPoolDetailController();
            _practiceDetailController = new PracticeDetailController();
            _practiceController       = new PracticeController();

            user           = currentUser;
            practice       = currentPractice;
            wordPool       = CurrentWordPool;
            alreadyIndexed = new List <int>();
        }
示例#6
0
        public void Buy_WhenDoingHttpGet_ReturnsView()
        {
            var emailSender = new Mock <ISendEmail>().Object;
            var reCaptcha   = new Mock <IRecaptchaService>().Object;
            var sut         = new PracticeController(Enumerable.Empty <IGenerateEmail>(), emailSender, reCaptcha);

            var result = sut.Buy();

            // Assert
            var viewResult = Assert.IsType <ViewResult>(result);

            Assert.Equal(nameof(PracticeController.Buy), viewResult.ViewName);
        }
示例#7
0
        public void Buy_WhenModelIsValid_ReturnsRedirectToActionResultThankyouPage()
        {
            var emailSender = new Mock <ISendEmail>().Object;
            var reCaptcha   = MockReCaptchaService.Create(true);
            var sut         = new PracticeController(Enumerable.Empty <IGenerateEmail>(), emailSender, reCaptcha);

            var result = sut.Buy(new BuyPracticeModel());

            Assert.IsType <Task <IActionResult> >(result);
            var redirectToActionResult = result.Result as RedirectToActionResult;

            Assert.Equal("ThankYou", redirectToActionResult?.ControllerName);
            Assert.Equal("Index", redirectToActionResult?.ActionName);
        }
示例#8
0
        public void Buy_WhenReCaptchaFails_ReturnViewResultBuyPracticePage()
        {
            var emailSender = new Mock <ISendEmail>().Object;
            var tempData    = new Mock <ITempDataDictionary>().Object;
            var reCaptcha   = MockReCaptchaService.Create(false);
            var sut         = new PracticeController(Enumerable.Empty <IGenerateEmail>(), emailSender, reCaptcha);

            sut.TempData = tempData;

            var result = sut.Buy(new BuyPracticeModel());

            Assert.IsType <Task <IActionResult> >(result);
            var viewResult = result.Result as ViewResult;

            Assert.Equal("Buy", viewResult?.ViewName);
        }
示例#9
0
        public void Buy_WhenDoingHttpGet_ContainsCorrectCollectionsAmountOptions()
        {
            var emailSender = new Mock <ISendEmail>().Object;
            var reCaptcha   = new Mock <IRecaptchaService>().Object;
            var sut         = new PracticeController(Enumerable.Empty <IGenerateEmail>(), emailSender, reCaptcha);

            var result = sut.Buy();

            // Assert
            var viewResult                     = Assert.IsType <ViewResult>(result);
            var actualCollectionsList          = viewResult.ViewData["CollectionsAmount"] as SelectList;
            var actualCollectionsAmountOptions = actualCollectionsList.Items as IEnumerable <SelectListItem>;

            var expectedCollectionsAmountOptions = new[] { null, "$0 - $500,000", "$500,000 - $1,000,000", "$1,500,000 - $2,000,000", "$2,000,000 +" };

            Assert.Equal(expectedCollectionsAmountOptions, actualCollectionsAmountOptions.Select(x => x.Value));
        }
示例#10
0
        public void Sell_WhenModelIsInvalid_ReturnViewResultSellPracticePage()
        {
            var emailSender = new Mock <ISendEmail>().Object;
            var tempData    = new Mock <ITempDataDictionary>().Object;
            var reCaptcha   = MockReCaptchaService.Create(true);
            var sut         = new PracticeController(Enumerable.Empty <IGenerateEmail>(), emailSender, reCaptcha);

            sut.ModelState.AddModelError("ModelInvalid", "Test Invalid Model Error");
            sut.TempData = tempData;

            var result = sut.Sell(new SellPracticeModel());

            Assert.IsType <Task <IActionResult> >(result);
            var viewResult = result.Result as ViewResult;

            Assert.Equal("Sell", viewResult?.ViewName);
        }
示例#11
0
        public void Index_WhenDoingHttpPostForValidActionNotOnIndexController_RedirectsToTheExpectedControllerAndView(string action, string expectedControllerName, string expectedViewName)
        {
            var model = new PracticeOptionsModel
            {
                SelectedPracticeOption = action
            };

            var emailSender = new Mock <ISendEmail>().Object;
            var reCaptcha   = new Mock <IRecaptchaService>().Object;
            var sut         = new PracticeController(Enumerable.Empty <IGenerateEmail>(), emailSender, reCaptcha);

            var result = sut.Index(model);

            // Assert
            var redirectToActionResult = Assert.IsType <RedirectToActionResult>(result);

            Assert.Equal(expectedControllerName, redirectToActionResult.ControllerName);
            Assert.Equal(expectedViewName, redirectToActionResult.ActionName);
        }
示例#12
0
        public void Buy_WhenModelMinPurchaseAmountIsLessThanMaxPurchaseAmount_ModelStateIsValid()
        {
            var emailSender = new Mock <ISendEmail>().Object;
            var reCaptcha   = MockReCaptchaService.Create(true);
            var sut         = new PracticeController(Enumerable.Empty <IGenerateEmail>(), emailSender, reCaptcha);

            var fixture = new Fixture();
            var model   = fixture
                          .Build <BuyPracticeModel>()
                          .Without(m => m.ContactPhoneNumber)
                          .With(m => m.MinPurchaseAmount, 99)
                          .With(m => m.MaxPurchaseAmount, 100)
                          .Create();

            Assert.True(sut.ModelState.IsValid);

            var unused = sut.Buy(model);

            Assert.True(sut.ModelState.IsValid);
        }
示例#13
0
        public void Buy_WhenModelMinPurchaseAmountIsLessThanMaxPurchaseAmount_ReturnsRedirectToActionResultThankyouPage()
        {
            var emailSender = new Mock <ISendEmail>().Object;
            var reCaptcha   = MockReCaptchaService.Create(true);
            var sut         = new PracticeController(Enumerable.Empty <IGenerateEmail>(), emailSender, reCaptcha);

            var fixture = new Fixture();
            var model   = fixture
                          .Build <BuyPracticeModel>()
                          .Without(m => m.ContactPhoneNumber)
                          .With(m => m.MinPurchaseAmount, 99)
                          .With(m => m.MaxPurchaseAmount, 100)
                          .Create();

            var result = sut.Buy(model);

            Assert.IsType <Task <IActionResult> >(result);
            var redirectToActionResult = result.Result as RedirectToActionResult;

            Assert.Equal("ThankYou", redirectToActionResult?.ControllerName);
            Assert.Equal("Index", redirectToActionResult?.ActionName);
        }
        private static IEnumerable <DateTimeInterval> GetAccountContractBillingCycles(AccountContract accountContract)
        {
            var start = PracticeController.ConvertToLocalDateTime(accountContract.Practice, accountContract.StartDate);

            if (start == null)
            {
                return(Enumerable.Empty <DateTimeInterval>());
            }

            var startValue  = start.Value;
            var periodType  = accountContract.BillingPeriodType;
            var periodSize  = accountContract.BillingPeriodSize ?? 1;
            var periodCount = accountContract.BillingPeriodCount ?? 7305; // = 365.25 * 20

            var mainIntervals = DateTimeHelper.IntervalRange(
                startValue,
                periodCount,
                d =>
            {
                if (periodType == "M")
                {
                    return(d.AddMonths(periodSize, startValue.Day));
                }
                if (periodType == "d")
                {
                    return(d.AddDays(periodSize));
                }
                if (periodType == "y")
                {
                    return(d.AddYears(periodSize));
                }
                throw new Exception("Unknown period type.");
            });

            return(mainIntervals);
        }
        public void Delete_1_HappyPath()
        {
            ExamsController    controller;
            Patient            patient;
            ExaminationRequest examRequest;
            var isDbChangesSaved = false;
            var localNow         = new DateTime(2012, 08, 16);

            try
            {
                using (var db2 = DbTestBase.CreateNewCerebelloEntities())
                {
                    var drandre = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(db2);
                    patient = Firestarter.CreateFakePatients(drandre, db2).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 medicalProc1 = this.db.SYS_MedicalProcedure.Single(x => x.Code == "4.01.03.55-2");

                    examRequest = new ExaminationRequest
                    {
                        PracticeId           = patient.PracticeId,
                        CreatedOn            = utcNow,
                        PatientId            = patient.Id,
                        Text                 = "Old text",
                        MedicalProcedureCode = medicalProc1.Code,
                        MedicalProcedureName = medicalProc1.Name
                    };

                    db2.ExaminationRequests.AddObject(examRequest);
                    db2.SaveChanges();

                    // Define André as the logged user, he cannot edit Marta's patients.
                    mr.SetCurrentUser_Andre_CorrectPassword();
                }
            }
            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.Delete(examRequest.Id);

            // 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: cannot save the changes.
            Assert.IsTrue(isDbChangesSaved, "Database changes were not saved, but they should.");

            // Verifying the database.
            using (var db2 = DbTestBase.CreateNewCerebelloEntities())
            {
                var obj = db2.ExaminationRequests.FirstOrDefault(x => x.PatientId == patient.Id);
                Assert.IsNull(obj, "Database record was not deleted.");
            }
        }
        public ActionResult GenerateInvoice(GenerateInvoiceViewModel viewModel)
        {
            if (viewModel.Step == null)
            {
                if (string.IsNullOrEmpty(viewModel.PracticeIdentifier))
                {
                    this.ModelState.Clear();
                    viewModel.Step = 0;
                    return(this.View());
                }

                viewModel.Step =
                    string.IsNullOrEmpty(viewModel.InvoiceName)
                    ? 1
                    : 2;
            }

            var step = viewModel.Step ?? 0;

            using (var db = this.CreateNewCerebelloEntities())
            {
                // Getting the practice indicated in the view-model.
                Practice practice = null;
                if (!string.IsNullOrWhiteSpace(viewModel.PracticeIdentifier))
                {
                    practice = db.Practices
                               .SingleOrDefault(p => p.UrlIdentifier == viewModel.PracticeIdentifier);
                }

                if (practice == null ||
                    practice.ActiveAccountContractId == null ||
                    practice.AccountContract.IsTrial ||
                    this.ModelState.HasPropertyErrors(() => viewModel.PracticeIdentifier))
                {
                    if (practice == null)
                    {
                        this.ModelState.AddModelError(() => viewModel.PracticeIdentifier, "Consultório inexistente.");
                    }

                    if (practice != null && practice.ActiveAccountContractId == null)
                    {
                        this.ModelState.AddModelError(() => viewModel.PracticeIdentifier, "Consultório não possui uma conta ativa.");
                    }

                    if (practice != null && practice.AccountContract.IsTrial)
                    {
                        this.ModelState.AddModelError(() => viewModel.PracticeIdentifier, "Consultório possui conta trial.");
                    }

                    return(this.View(viewModel));
                }

                var utcNow = this.GetUtcNow();
                viewModel.Invoices = GetAccountInvoices(practice, utcNow);

                if (step == 0)
                {
                    if (this.Request.HttpMethod == "POST")
                    {
                        return(this.RedirectToAction("GenerateInvoice", new { viewModel.PracticeIdentifier }));
                    }

                    // going to the next step
                    this.ModelState.Clear();
                    viewModel.Step = 1;
                    return(this.View(viewModel));
                }

                var localNow = PracticeController.ConvertToLocalDateTime(practice, utcNow);

                if (step == 1)
                {
                    this.ModelState.Clear();
                    viewModel.Step = 1;
                    return(this.View(viewModel));
                }

                var selectedInvoiceInfo = viewModel.Invoices.SingleOrDefault(bi => bi.NameId == viewModel.InvoiceName);

                if (selectedInvoiceInfo == null)
                {
                    this.ModelState.AddModelError(() => viewModel.InvoiceName, "Nome de invoice não encontrado.");
                    viewModel.Step = 1;
                    return(this.View(viewModel));
                }

                Billing billing = null;
                var     idSet   = string.Format(
                    "CEREB.{1}{2}.{0}",
                    localNow.Year,
                    practice.AccountContract.BillingPeriodSize,
                    practice.AccountContract.BillingPeriodType);

                var invoiceStartUtc = PracticeController.ConvertToUtcDateTime(practice, selectedInvoiceInfo.Start);
                billing = db.Billings.SingleOrDefault(b => b.PracticeId == practice.Id &&
                                                      b.MainAccountContractId == practice.ActiveAccountContractId &&
                                                      b.ReferenceDate == invoiceStartUtc);

                if (billing == null)
                {
                    billing = new Billing
                    {
                        PracticeId            = practice.Id,
                        AfterDueMonthlyTax    = 1.00m, // 1%
                        AfterDueTax           = 2.00m, // 2%
                        IssuanceDate          = utcNow,
                        MainAmount            = selectedInvoiceInfo.TotalAmount,
                        MainDiscount          = selectedInvoiceInfo.TotalDiscount,
                        DueDate               = PracticeController.ConvertToUtcDateTime(practice, selectedInvoiceInfo.DueDate),
                        IdentitySetName       = idSet,
                        IdentitySetNumber     = db.Billings.Count(b => b.PracticeId == practice.Id && b.IdentitySetName == idSet) + 1,
                        ReferenceDate         = PracticeController.ConvertToUtcDateTime(practice, selectedInvoiceInfo.Start),
                        ReferenceDateEnd      = PracticeController.ConvertToUtcDateTime(practice, selectedInvoiceInfo.End),
                        MainAccountContractId = practice.ActiveAccountContractId.Value,
                    };

                    db.Billings.AddObject(billing);
                }

                if (practice.AccountContract.BillingPaymentMethod == "PayPal Invoice")
                {
                    this.ViewBag.IsPayPalInvoice = true;
                }

                if (this.ModelState.IsValid)
                {
                    db.SaveChanges();

                    // adding PayPal invoice info
                    viewModel.PayPalInvoice = new GenerateInvoiceViewModel.PayPalInvoiceInfo
                    {
                        UserEmail    = practice.Owner.Person.Email,
                        IssuanceDate = localNow.ToString("dd-MM-yyyy"),
                        Currency     = "BRL - Reais",
                        Number       = string.Format("{0}.{1}", billing.IdentitySetName, billing.IdentitySetNumber),
                        DuaDate      = selectedInvoiceInfo.DueDate.ToString("dd-MM-yyyy"),
                        Terms        = "Vencimento na data especificada",
                        Items        = new List <GenerateInvoiceViewModel.PayPalInvoiceItem>(),
                    };

                    var strStartToEnd = selectedInvoiceInfo.End != null
                        ? string.Format(
                        "{0} até {1}",
                        selectedInvoiceInfo.Start.ToString("yyyy'-'MM'-'dd"),
                        selectedInvoiceInfo.End.Value.ToString("yyyy'-'MM'-'dd"))
                        : string.Format(
                        "{0}",
                        selectedInvoiceInfo.Start.ToString("yyyy'-'MM'-'dd"));

                    viewModel.PayPalInvoice.Items.Add(
                        new GenerateInvoiceViewModel.PayPalInvoiceItem
                    {
                        NameId      = "Assinatura Cerebello",
                        Date        = "",
                        Quantity    = 1,
                        UnitPrice   = selectedInvoiceInfo.TotalAmount.ToString("0.00", CultureInfo.InvariantCulture).Replace('.', ','),
                        Description = string.Format("Assinatura do plano profissional do Cerebello ({0})", strStartToEnd),
                    });

                    var periodType     = practice.AccountContract.BillingPeriodType;
                    var periodSize     = practice.AccountContract.BillingPeriodSize;
                    var discountReason =
                        periodType == "M" && periodSize == 1 ? "mensal" :
                        periodType == "M" && periodSize == 3 ? "trimestral" :
                        periodType == "M" && periodSize == 6 ? "semestral" :
                        periodType == "M" && periodSize == 12 || periodType == "Y" && periodSize == 1 ? "anual" :
                        "";

                    if (selectedInvoiceInfo.TotalDiscount > 0)
                    {
                        viewModel.PayPalInvoice.Items.Add(
                            new GenerateInvoiceViewModel.PayPalInvoiceItem
                        {
                            NameId      = "Desconto da Assinatura Cerebello",
                            Date        = "",
                            Quantity    = 1,
                            UnitPrice   = selectedInvoiceInfo.TotalDiscount.ToString("'-'0.00", CultureInfo.InvariantCulture).Replace('.', ','),
                            Description = string.Format("Desconto na Assinatura (condições especiais para pagamento {0})", discountReason)
                        });
                    }

                    viewModel.Step = 2;
                    return(this.View(viewModel));
                }
            }

            return(this.View(viewModel));
        }
        private static List <InvoiceInfo> GetAccountInvoices(Practice practice, DateTime utcNow)
        {
            // getting info about the services that are being used, that is all active AccountContracts
            var activeAccountContracts = new[] { practice.AccountContract }
            .Concat(
                practice.AccountContracts
                .Where(ac => ac.EndDate == null || ac.EndDate >= utcNow)
                .Where(ac => ac.Id != practice.AccountContract.Id))
            .ToList();

            // The main account contract dictates the billing periods of subcontracts.
            // We must see what products (active account contracts) don't have
            // billing items in any period.
            var mainIntervals = GetAccountContractBillingCycles(practice.AccountContract)
                                .TakeWhile(it => it.Start < utcNow)
                                .ToList();

            var dateSetBillingCycles = new ContinuousSet <DateTime>(mainIntervals.Count * 2);

            foreach (var dateTimeInterval in mainIntervals)
            {
                dateSetBillingCycles.AddInterval(dateTimeInterval.Start, true, dateTimeInterval.End, false);
            }
            dateSetBillingCycles.Flatten(mergeRedundantTrues: false);

            var billingsDic = new Dictionary <DateTime, InvoiceInfo>();

            foreach (var activeAccountContract in activeAccountContracts)
            {
                var accountStart = PracticeController.ConvertToLocalDateTime(practice, activeAccountContract.StartDate);
                var accountEnd   = PracticeController.ConvertToLocalDateTime(practice, activeAccountContract.EndDate);

                var currentContractInterval = new ContinuousSet <DateTime>();
                if (accountStart.HasValue)
                {
                    currentContractInterval.AddPoint(accountStart.Value, false, true, true);
                }
                if (accountEnd.HasValue)
                {
                    currentContractInterval.AddPoint(accountEnd.Value, true, false, false);
                }

                // Getting intervals that already have invoices.
                var dateSetBillings = new ContinuousSet <DateTime>();
                foreach (var eachBilling in activeAccountContract.Billings)
                {
                    if (eachBilling.ReferenceDate == null)
                    {
                        continue;
                    }

                    var billingRefStart = PracticeController.ConvertToLocalDateTime(practice, (DateTime)eachBilling.ReferenceDate);
                    var billingRefEnd   = PracticeController.ConvertToLocalDateTime(practice, eachBilling.ReferenceDateEnd);

                    if (billingRefEnd.HasValue)
                    {
                        dateSetBillings.AddInterval(billingRefStart, true, billingRefEnd.Value, false);
                    }
                    else
                    {
                        dateSetBillings.AddPoint(billingRefStart, false, true, true);
                    }

                    InvoiceInfo billingInfo;
                    if (!billingsDic.TryGetValue(billingRefStart, out billingInfo))
                    {
                        billingsDic[billingRefStart] = billingInfo = new InvoiceInfo
                        {
                            IsSaved = true,
                            Start   = billingRefStart,
                            End     = billingRefEnd,
                            DueDate = PracticeController.ConvertToLocalDateTime(practice, eachBilling.DueDate),
                        }
                    }
                    ;

                    billingInfo.Items.Add(
                        new InvoiceInfo.Item
                    {
                        Amount         = activeAccountContract.BillingAmount ?? 0,
                        DiscountAmount = activeAccountContract.BillingDiscountAmount ?? 0,
                        ContractType   = (ContractTypes)activeAccountContract.ContractTypeId,
                    });
                }

                dateSetBillings.Flatten();

                // Merging date sets, to see where there are holes without any invoice.
                var dateSetResult = !dateSetBillings & dateSetBillingCycles & currentContractInterval;

                // Getting the intervals that represents missing invoices.
                foreach (var eachMissingInterval in dateSetResult.PositiveIntervals)
                {
                    Debug.Assert(practice.AccountContract.BillingDueDay != null, "practice.AccountContract.BillingDueDay != null");
                    var dueDay  = practice.AccountContract.BillingDueDay.Value;
                    var dueDate = DateTimeHelper.FindDayOfMonthOrNearest(eachMissingInterval.Start, dueDay);
                    if (dueDate >= eachMissingInterval.Start.AddDays(10))
                    {
                        dueDate = dueDate.AddMonths(1, dueDay);
                    }

                    InvoiceInfo billingInfo;
                    if (!billingsDic.TryGetValue(eachMissingInterval.Start, out billingInfo))
                    {
                        billingsDic[eachMissingInterval.Start] = billingInfo = new InvoiceInfo
                        {
                            Start   = eachMissingInterval.Start,
                            End     = eachMissingInterval.End,
                            DueDate = dueDate,
                        }
                    }
                    ;

                    billingInfo.Items.Add(
                        new InvoiceInfo.Item
                    {
                        Amount         = activeAccountContract.BillingAmount ?? 0,
                        DiscountAmount = activeAccountContract.BillingDiscountAmount ?? 0,
                        ContractType   = (ContractTypes)activeAccountContract.ContractTypeId,
                    });
                }
            }

            var result = billingsDic.Values.OrderBy(bi => bi.Start).ToList();

            return(result);
        }
示例#18
0
        private static PatientViewModel GetViewModel(PracticeController controller, [NotNull] Patient patient, bool includeSessions, bool includeFutureAppointments, bool includeAddressData = true)
        {
            if (patient == null)
            {
                throw new ArgumentNullException("patient");
            }

            // Person, address, and patient basic properties.
            var viewModel = new PatientViewModel();

            FillPersonViewModel(controller.DbPractice, patient.Person, viewModel);

            viewModel.Id           = patient.Id;
            viewModel.Code         = patient.Code.HasValue ? patient.Code.Value.ToString("D6") : "000000";
            viewModel.PatientId    = patient.Id;
            viewModel.PersonId     = patient.Person.Id;
            viewModel.Observations = patient.Person.Observations;

            if (includeAddressData)
            {
                var address = patient.Person.Addresses.SingleOrDefault();
                viewModel.Address = address != null?GetAddressViewModel(address) : new AddressViewModel();
            }

            // Other (more complex) properties.

            if (includeFutureAppointments)
            {
                // gets a textual date. The input date must be LOCAL
                Func <DateTime, string> getRelativeDate = s =>
                {
                    var result = s.ToShortDateString();
                    result += ", " + DateTimeHelper.GetFormattedTime(s);
                    result += ", " +
                              DateTimeHelper.ConvertToRelative(s, controller.GetPracticeLocalNow(),
                                                               DateTimeHelper.RelativeDateOptions.IncludeSuffixes |
                                                               DateTimeHelper.RelativeDateOptions.IncludePrefixes |
                                                               DateTimeHelper.RelativeDateOptions.ReplaceToday |
                                                               DateTimeHelper.RelativeDateOptions.ReplaceYesterdayAndTomorrow);

                    return(result);
                };

                // get appointments scheduled for the future
                var utcNow = controller.GetUtcNow();

                var appointments = patient.Appointments
                                   .Where(
                    a => a.DoctorId == patient.DoctorId &&
                    a.Start > utcNow)
                                   .ToList();

                viewModel.FutureAppointments = (from a in appointments
                                                select new AppointmentViewModel
                {
                    PatientId = a.PatientId,
                    PatientName = a.PatientId != default(int) ? a.Patient.Person.FullName : null,
                    LocalDateTime = ConvertToLocalDateTime(controller.DbPractice, a.Start),
                    LocalDateTimeSpelled = getRelativeDate(ConvertToLocalDateTime(controller.DbPractice, a.Start))
                }).ToList();
            }

            if (includeSessions)
            {
                var sessions = GetSessionViewModels(controller.DbPractice, patient, null);

                viewModel.Sessions = sessions;
            }

            return(viewModel);
        }
        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 Delete_3_ExamFromAnotherPractice()
        {
            ExamsController    controller;
            ExaminationRequest examRequest;
            var isDbChangesSaved = false;
            var localNow         = new DateTime(2012, 08, 16);

            try
            {
                var drandre         = Firestarter.Create_CrmMg_Psiquiatria_DrHouse_Andre(this.db);
                var dramarta        = Firestarter.Create_CrmMg_Psiquiatria_DraMarta_Marta(this.db);
                var patientDraMarta = Firestarter.CreateFakePatients(dramarta, 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");
                examRequest = new ExaminationRequest
                {
                    CreatedOn            = utcNow,
                    PatientId            = patientDraMarta.Id,
                    Text                 = "Old text",
                    MedicalProcedureCode = medicalProc0.Code,
                    MedicalProcedureName = medicalProc0.Name,
                    PracticeId           = dramarta.PracticeId,
                };
                this.db.ExaminationRequests.AddObject(examRequest);
                this.db.SaveChanges();

                // Define André as the logged user, he cannot edit Marta's patients.
                mr.SetCurrentUser_Andre_CorrectPassword();
            }
            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...
            var jsonResult = controller.Delete(examRequest.Id);

            // Verifying the ActionResult.
            Assert.IsNotNull(jsonResult, "The result of the controller method is null.");
            var jsonDelete = (JsonDeleteMessage)jsonResult.Data;

            Assert.IsFalse(jsonDelete.success, "Deletion should not succed.");
            Assert.IsNotNull(jsonDelete.text, "Deletion should fail with a message.");

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

            // 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);
            }
        }