public static void FillOperationDetails(PayPalExpressCheckoutOperation operation, Practice practice, AccountContract contractInfo, Billing billing)
        {
            operation.DefaultCurrencyCode = CurrencyCode.Brazilian_Real;
            operation.PaymentRequests = new PayPalList<PayPalPaymentRequest>
            {
                new PayPalPaymentRequest
                {
                    BillingAgreementDescription = "O Cerebello é um software de gerênciamento de consultórios e clínicas médicas.",
                    //BillingType = BillingCode.RecurringPayments,
                    Description = "Cerebello - Plano profissional",
                    InvoiceNum = string.Format("{3}{2}:{0}.{1}", billing.IdentitySetName, billing.IdentitySetNumber, practice.Id, DebugConfig.PayPal.InvoiceIdPrefix),
                    Items = new PayPalList<PayPalPaymentRequestItem>
                    {
                        new PayPalPaymentRequestItem
                        {
                            Amount = contractInfo.BillingAmount,
                            Name = "Cerebello SaaS",
                            Description = "Software de gerenciamento de consultório médico.",
                            Category = ItemCategory.Digital,
                        },
                    },
                },
            };

            if (contractInfo.BillingDiscountAmount > 0)
            {
                operation.PaymentRequests[0].Items.Add(new PayPalPaymentRequestItem
                    {
                        Amount = -contractInfo.BillingDiscountAmount,
                        Name = "Desconto",
                        Category = ItemCategory.Digital,
                    });
            }
        }
        /// <summary>
        /// Converts the specified date and time at the location of the current practice to UTC.
        /// </summary>
        /// <param name="practice"> </param>
        /// <param name="practiceDateTime"></param>
        /// <returns></returns>
        public static DateTime ConvertToUtcDateTime(Practice practice, DateTime practiceDateTime)
        {
            if (practice == null) throw new ArgumentNullException("practice");

            var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(practice.WindowsTimeZoneId);
            return DateTimeHelper.ConvertToUtcDateTime(practiceDateTime, timeZoneInfo);
        }
        /// <summary>
        /// Converts the specified UTC date and time for the location of the current practice.
        /// </summary>
        /// <param name="practice"> </param>
        /// <param name="utcDateTime"></param>
        /// <returns></returns>
        public static DateTime ConvertToLocalDateTime(Practice practice, DateTime utcDateTime)
        {
            if (practice == null) throw new ArgumentNullException("practice");

            var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(practice.WindowsTimeZoneId);
            var result = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, timeZoneInfo);
            return result;
        }
        public static List<DoctorViewModel> GetDoctorViewModelsFromPractice(CerebelloEntitiesAccessFilterWrapper db, Practice practice, DateTime localNow)
        {
            var usersThatAreDoctors = db.Users
                .Where(u => u.PracticeId == practice.Id)
                .Where(u => u.Doctor != null);

            var dataCollection = usersThatAreDoctors
                .Select(u => new
                {
                    ViewModel = new DoctorViewModel()
                    {
                        Id = u.Id,
                        Name = u.Person.FullName,
                        UrlIdentifier = u.Doctor.UrlIdentifier,
                        CRM = u.Doctor.CRM,
                        MedicalSpecialty = u.Doctor.MedicalSpecialtyName,
                    },
                    u.Doctor.MedicalEntityCode,
                    u.Doctor.MedicalEntityJurisdiction,
                    u.Doctor,
                    u.Person.EmailGravatarHash,
                })
                .ToList();

            // Getting more doctor's informations:
            // Todo: this is going to become a problem in the future, because this info has no cache.
            // - next free time slot of each doctor;
            // - gravatar image.
            foreach (var eachItem in dataCollection)
            {
                if (!string.IsNullOrEmpty(eachItem.EmailGravatarHash))
                    eachItem.ViewModel.ImageUrl = GravatarHelper.GetGravatarUrl(eachItem.EmailGravatarHash, GravatarHelper.Size.s16);

                eachItem.ViewModel.MedicalEntity = string.Format(
                    string.IsNullOrEmpty(eachItem.MedicalEntityJurisdiction) ? "{0}" : "{0}-{1}",
                    eachItem.MedicalEntityCode,
                    eachItem.MedicalEntityJurisdiction);

                // It is only possible to determine the next available time if the schedule of the doctor is already configured.
                if (eachItem.Doctor.CFG_Schedule != null)
                {
                    var nextSlotInLocalTime = ScheduleController.FindNextFreeTimeInPracticeLocalTime(db, eachItem.Doctor, localNow);
                    eachItem.ViewModel.NextAvailableTime = nextSlotInLocalTime.Item1;
                }
            }

            var doctors = dataCollection.Select(item => item.ViewModel).ToList();
            return doctors;
        }
 public static void FillPersonViewModel(Practice practice, Person person, PersonViewModel viewModel)
 {
     viewModel.BirthPlace = person.BirthPlace;
     viewModel.FullName = person.FullName;
     viewModel.Gender = person.Gender;
     viewModel.MaritalStatus = person.MaritalStatus;
     viewModel.Ethnicity = person.Ethnicity;
     viewModel.Schooling = person.Schooling;
     viewModel.FatherName = person.FatherName;
     viewModel.FatherProfession = person.FatherProfession;
     viewModel.MotherName = person.MotherName;
     viewModel.MotherProfession = person.MotherProfession;
     viewModel.DateOfBirth = ConvertToLocalDateTime(practice, person.DateOfBirth);
     viewModel.Profissao = person.Profession;
     viewModel.Cpf = person.CPF;
     viewModel.Rg = person.RG;
     viewModel.Email = person.Email;
     viewModel.PhoneCell = person.PhoneCell;
     viewModel.PhoneLand = person.PhoneLand;
 }
 /// <summary>
 /// Create a new Practice object.
 /// </summary>
 /// <param name="id">Initial value of the Id property.</param>
 /// <param name="name">Initial value of the Name property.</param>
 /// <param name="urlIdentifier">Initial value of the UrlIdentifier property.</param>
 /// <param name="createdOn">Initial value of the CreatedOn property.</param>
 /// <param name="windowsTimeZoneId">Initial value of the WindowsTimeZoneId property.</param>
 /// <param name="accountDisabled">Initial value of the AccountDisabled property.</param>
 /// <param name="accountCancelRequest">Initial value of the AccountCancelRequest property.</param>
 public static Practice CreatePractice(global::System.Int32 id, global::System.String name, global::System.String urlIdentifier, global::System.DateTime createdOn, global::System.String windowsTimeZoneId, global::System.Boolean accountDisabled, global::System.Boolean accountCancelRequest)
 {
     Practice practice = new Practice();
     practice.Id = id;
     practice.Name = name;
     practice.UrlIdentifier = urlIdentifier;
     practice.CreatedOn = createdOn;
     practice.WindowsTimeZoneId = windowsTimeZoneId;
     practice.AccountDisabled = accountDisabled;
     practice.AccountCancelRequest = accountCancelRequest;
     return practice;
 }
 /// <summary>
 /// Deprecated Method for adding a new object to the Practices EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToPractices(Practice practice)
 {
     base.AddObject("Practices", practice);
 }
        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;
        }
        internal void InitDbPractice(RequestContext requestContext)
        {
            if (this.DbPractice == null && this.DbUser != null)
            {
                if (!requestContext.HttpContext.Request.IsAuthenticated)
                    return;

                var authenticatedPrincipal = requestContext.HttpContext.User as AuthenticatedPrincipal;

                if (authenticatedPrincipal == null)
                    throw new Exception(
                        "HttpContext.User should be a AuthenticatedPrincipal when the user is authenticated");

                var practiceName = this.RouteData.Values["practice"] as string;

                var practice = this.db.Users
                    .Where(u => u.Id == this.DbUser.Id && u.Practice.UrlIdentifier == practiceName)
                    .Select(u => u.Practice)
                    .SingleOrDefault();

                this.DbPractice = practice;
            }
        }
        public User SetCurrentUserById(int userId)
        {
            this.user = this.innerDb.Users.Include("Practice").SingleOrDefault(u => u.Id == userId);

            if (this.user != null)
                this.practice = this.user.Practice;

            this.AccountDisabled = this.practice == null || this.practice.AccountDisabled;

            return this.user;
        }
        public static List<SessionViewModel> GetSessionViewModels(Practice practice, Patient patient, DateTimeInterval? filterUtcInterval)
        {
            var eventDates = new List<DateTime>();

            var utcDateFilterStart = filterUtcInterval.HasValue ? filterUtcInterval.Value.Start : (DateTime?)null;
            var utcDateFilterEnd = filterUtcInterval.HasValue ? filterUtcInterval.Value.End : (DateTime?)null;

            // anamneses
            var anamneses = filterUtcInterval.HasValue
                ? patient.Anamneses.Where(x => x.MedicalRecordDate >= utcDateFilterStart && x.MedicalRecordDate < utcDateFilterEnd)
                : patient.Anamneses;
            var anamnesesByDate =
                (from avm in
                     (from r in anamneses
                      select new SessionEvent
                                 {
                                     LocalDate = ConvertToLocalDateTime(practice, r.MedicalRecordDate),
                                     Id = r.Id
                                 })
                 group avm by avm.LocalDate.Date
                     into g
                     select g).ToDictionary(g => g.Key, g => g.ToList());

            eventDates.AddRange(anamnesesByDate.Keys);

            // physical examinations
            var physicalExaminations = filterUtcInterval.HasValue
                ? patient.PhysicalExaminations.Where(x => x.MedicalRecordDate >= utcDateFilterStart && x.MedicalRecordDate < utcDateFilterEnd)
                : patient.PhysicalExaminations;
            var physicalExaminationsByDate =
                (from pe in
                     (from r in physicalExaminations
                      select new SessionEvent
                      {
                          LocalDate = ConvertToLocalDateTime(practice, r.MedicalRecordDate),
                          Id = r.Id
                      })
                 group pe by pe.LocalDate.Date
                     into g
                     select g).ToDictionary(g => g.Key, g => g.ToList());

            eventDates.AddRange(physicalExaminationsByDate.Keys);

            // diagnostic hipotheses
            var diagnosticHypotheses = filterUtcInterval.HasValue
                ? patient.DiagnosticHypotheses.Where(x => x.MedicalRecordDate >= utcDateFilterStart && x.MedicalRecordDate < utcDateFilterEnd)
                : patient.DiagnosticHypotheses;
            var diagnosticHypothesesByDate =
                (from pe in
                     (from r in diagnosticHypotheses
                      select new SessionEvent
                      {
                          LocalDate = ConvertToLocalDateTime(practice, r.MedicalRecordDate),
                          Id = r.Id
                      })
                 group pe by pe.LocalDate.Date
                     into g
                     select g).ToDictionary(g => g.Key, g => g.ToList());

            eventDates.AddRange(diagnosticHypothesesByDate.Keys);

            // receipts
            var receipts = filterUtcInterval.HasValue
                ? patient.Receipts.Where(x => x.IssuanceDate >= utcDateFilterStart && x.IssuanceDate < utcDateFilterEnd)
                : patient.Receipts;
            var receiptsByDate =
                (from rvm in
                     (from r in receipts
                      select new SessionEvent
                                 {
                                     LocalDate = ConvertToLocalDateTime(practice, r.IssuanceDate),
                                     Id = r.Id
                                 })
                 group rvm by rvm.LocalDate.Date
                     into g
                     select g).ToDictionary(g => g.Key, g => g.ToList());

            eventDates.AddRange(receiptsByDate.Keys);

            // certificates
            var certificates = filterUtcInterval.HasValue
                ? patient.MedicalCertificates.Where(x => x.IssuanceDate >= utcDateFilterStart && x.IssuanceDate < utcDateFilterEnd)
                : patient.MedicalCertificates;
            var certificatesByDate =
                (from cvm in
                     (from c in certificates
                      select new SessionEvent
                                 {
                                     LocalDate = ConvertToLocalDateTime(practice, c.IssuanceDate),
                                     Id = c.Id
                                 })
                 group cvm by cvm.LocalDate.Date
                     into g
                     select g).ToDictionary(g => g.Key, g => g.ToList());

            eventDates.AddRange(certificatesByDate.Keys);

            // exam requests
            var examRequests = filterUtcInterval.HasValue
                ? patient.ExaminationRequests.Where(x => x.RequestDate >= utcDateFilterStart && x.RequestDate < utcDateFilterEnd)
                : patient.ExaminationRequests;
            var examRequestsByDate =
                (from ervm in
                     (from c in examRequests
                      select new SessionEvent
                                 {
                                     LocalDate = ConvertToLocalDateTime(practice, c.RequestDate),
                                     Id = c.Id
                                 })
                 group ervm by ervm.LocalDate.Date
                     into g
                     select g).ToDictionary(g => g.Key, g => g.ToList());

            eventDates.AddRange(examRequestsByDate.Keys);

            // exam results
            var examResults = filterUtcInterval.HasValue
                ? patient.ExaminationResults.Where(x => x.ReceiveDate >= utcDateFilterStart && x.ReceiveDate < utcDateFilterEnd)
                : patient.ExaminationResults;
            var examResultsByDate =
                (from ervm in
                     (from c in examResults
                      select new SessionEvent
                                 {
                                     LocalDate = ConvertToLocalDateTime(practice, c.ReceiveDate),
                                     Id = c.Id
                                 })
                 group ervm by ervm.LocalDate.Date
                     into g
                     select g).ToDictionary(g => g.Key, g => g.ToList());

            eventDates.AddRange(examResultsByDate.Keys);

            // diagnosis
            var diagnosis = filterUtcInterval.HasValue
                ? patient.Diagnoses.Where(x => x.MedicalRecordDate >= utcDateFilterStart && x.MedicalRecordDate < utcDateFilterEnd)
                : patient.Diagnoses;
            var diagnosisByDate =
                (from dvm in
                     (from d in diagnosis
                      select new SessionEvent
                                 {
                                     LocalDate = ConvertToLocalDateTime(practice, d.MedicalRecordDate),
                                     Id = d.Id
                                 })
                 group dvm by dvm.LocalDate.Date
                     into g
                     select g).ToDictionary(g => g.Key, g => g.ToList());

            eventDates.AddRange(diagnosisByDate.Keys);

            // patientFiles
            var patientFiles = filterUtcInterval.HasValue
                ? patient.PatientFileGroups.Where(x => x.ReceiveDate >= utcDateFilterStart && x.ReceiveDate < utcDateFilterEnd)
                : patient.PatientFileGroups;
            var patientFilesByDate =
                (from dvm in
                     (from d in patientFiles
                      select new SessionEvent
                      {
                          LocalDate = ConvertToLocalDateTime(practice, d.ReceiveDate),
                          Id = d.Id
                      })
                 group dvm by dvm.LocalDate.Date
                     into g
                     select g).ToDictionary(g => g.Key, g => g.ToList());

            eventDates.AddRange(patientFilesByDate.Keys);

            // discover what dates have events
            eventDates = eventDates.Distinct().OrderBy(dt => dt).ToList();

            // creating sessions
            var sessions = eventDates.Select(
                eventDate => new SessionViewModel
                                 {
                                     PatientId = patient.Id,
                                     Date = eventDate,
                                     AnamneseIds =
                                         anamnesesByDate.ContainsKey(eventDate)
                                             ? anamnesesByDate[eventDate].Select(a => a.Id).ToList()
                                             : new List<int>(),
                                     PhysicalExaminationIds =
                                        physicalExaminationsByDate.ContainsKey(eventDate)
                                            ? physicalExaminationsByDate[eventDate].Select(a => a.Id).ToList()
                                    : new List<int>(),
                                     DiagnosticHipothesesId =
                                     diagnosticHypothesesByDate.ContainsKey(eventDate)
                                     ? diagnosticHypothesesByDate[eventDate].Select(a => a.Id).ToList()
                                     : new List<int>(),
                                     ReceiptIds =
                                         receiptsByDate.ContainsKey(eventDate)
                                             ? receiptsByDate[eventDate].Select(v => v.Id).ToList()
                                             : new List<int>(),
                                     MedicalCertificateIds =
                                         certificatesByDate.ContainsKey(eventDate)
                                             ? certificatesByDate[eventDate].Select(c => c.Id).ToList()
                                             : new List<int>(),
                                     ExaminationRequestIds =
                                         examRequestsByDate.ContainsKey(eventDate)
                                             ? examRequestsByDate[eventDate].Select(v => v.Id).ToList()
                                             : new List<int>(),
                                     ExaminationResultIds =
                                         examResultsByDate.ContainsKey(eventDate)
                                             ? examResultsByDate[eventDate].Select(v => v.Id).ToList()
                                             : new List<int>(),
                                     DiagnosisIds =
                                         diagnosisByDate.ContainsKey(eventDate)
                                             ? diagnosisByDate[eventDate].Select(v => v.Id).ToList()
                                             : new List<int>(),
                                     PatientFiles =
                                         patientFilesByDate.ContainsKey(eventDate)
                                             ? patientFilesByDate[eventDate].Select(v => v.Id).ToList()
                                             : new List<int>()
                                 }).ToList();

            return sessions;
        }
Beispiel #12
0
 public User UserOwner(Practice practice)
 {
     return practice.Owner;
 }
Beispiel #13
0
 public Secretary NewSecretaryTtMilena(Practice practice)
 {
     return Firestarter.CreateSecretary_Milena(this.db, practice);
 }
Beispiel #14
0
 public Secretary NewSecretary(Practice practice, string username, string password, string name)
 {
     var user = Firestarter.CreateUser(this.db, practice, username, password, name);
     user.Secretary = new Secretary { PracticeId = user.PracticeId };
     return user.Secretary;
 }
Beispiel #15
0
 public void DelPractice(Practice practice)
 {
     if (practice != null) this.db.DeleteObject(practice);
     this.db.SaveChanges();
 }
Beispiel #16
0
        internal static void FillUserViewModel(User user, Practice practice, UserViewModel viewModel)
        {
            viewModel.Id = user.Id;
            viewModel.UserName = user.UserName;

            viewModel.FullName = user.Person.FullName;
            viewModel.ImageUrl = GravatarHelper.GetGravatarUrl(user.Person.EmailGravatarHash, GravatarHelper.Size.s16);
            viewModel.Gender = user.Person.Gender;
            viewModel.DateOfBirth = ConvertToLocalDateTime(practice, user.Person.DateOfBirth);
            viewModel.MaritalStatus = user.Person.MaritalStatus;
            viewModel.BirthPlace = user.Person.BirthPlace;
            viewModel.Cpf = user.Person.CPF;
            viewModel.Profissao = user.Person.Profession;
            viewModel.Email = user.Person.Email;

            viewModel.IsAdministrador = user.AdministratorId != null;
            viewModel.IsDoctor = user.DoctorId != null;
            viewModel.IsSecretary = user.SecretaryId != null;
            viewModel.IsOwner = user.IsOwner;
        }