/// <summary>
        /// Generates notifications for new Medical Appointments
        /// </summary>
        private static void GenerateNotificationsForNewMedicalAppointments(
            [NotNull] CerebelloEntities db, DateTime referenceTime, [NotNull] ICollection <Tuple <Notification, object> > notificationsToBeDispatched)
        {
            if (db == null)
            {
                throw new ArgumentNullException("db");
            }
            if (notificationsToBeDispatched == null)
            {
                throw new ArgumentNullException("notificationsToBeDispatched");
            }

            // check for appointments that have to be notified
            var timeOffset             = referenceTime.AddMinutes(10);
            var unnotifiedAppointments =
                db.Appointments.Where(
                    a => !a.Notified && a.Type == (int)TypeAppointment.MedicalAppointment && a.Start >= referenceTime && a.Start < timeOffset).ToList();

            foreach (var appointment in unnotifiedAppointments)
            {
                Debug.Assert(appointment.PatientId != null, "appointment.PatientId != null");

                var medicalAppointmentData = new MedicalAppointmentNotificationData
                {
                    PatientId     = appointment.PatientId.Value,
                    PatientName   = appointment.Patient.Person.FullName,
                    DoctorName    = appointment.Patient.Doctor.Users.First().Person.FullName,
                    DoctorId      = appointment.Patient.DoctorId,
                    AppointmentId = appointment.Id,
                    Time          = DateTimeHelper.GetFormattedTime(
                        PracticeController.ConvertToLocalDateTime(appointment.Practice, appointment.Start)),
                    PracticeIdentifier = appointment.Practice.UrlIdentifier,
                    DoctorIdentifier   = appointment.Doctor.UrlIdentifier
                };

                var medicalAppointmentDataString = new JavaScriptSerializer().Serialize(medicalAppointmentData);

                // for each secretary, I need to create a new notification
                foreach (var user in appointment.Practice.Users.Where(user => user.Secretary != null))
                {
                    var newNotification = new Notification()
                    {
                        CreatedOn  = referenceTime,
                        IsClosed   = false,
                        UserToId   = user.Id,
                        Type       = NotificationConstants.MEDICAL_APPOINTMENT_NOTIFICATION_TYPE,
                        PracticeId = appointment.PracticeId,
                        Data       = medicalAppointmentDataString
                    };

                    user.Notifications.Add(newNotification);
                    notificationsToBeDispatched.Add(new Tuple <Notification, object>(newNotification, medicalAppointmentData));
                }

                appointment.Notified = true;
            }
            db.SaveChanges();
        }
        /// <summary>
        /// Generates notifications for new Medical Appointments
        /// </summary>
        private static void GenerateNotificationsForNewGenericAppointments(
            [NotNull] CerebelloEntities db, DateTime referenceTime, [NotNull] ICollection <Tuple <Notification, object> > notificationsToBeDispatched)
        {
            if (db == null)
            {
                throw new ArgumentNullException("db");
            }
            if (notificationsToBeDispatched == null)
            {
                throw new ArgumentNullException("notificationsToBeDispatched");
            }

            // check for appointments that have to be notified
            var timeOffset             = referenceTime.AddMinutes(30);
            var unnotifiedAppointments =
                db.Appointments.Where(
                    a => !a.Notified && a.Type == (int)TypeAppointment.GenericAppointment && a.Start >= referenceTime && a.Start < timeOffset).ToList();

            foreach (var appointment in unnotifiedAppointments)
            {
                Debug.Assert(appointment.PatientId != null, "appointment.PatientId != null");

                var genericAppointmentData = new GenericAppointmentNotificationData()
                {
                    Text = appointment.Description,
                    Time = DateTimeHelper.GetFormattedTime(
                        PracticeController.ConvertToLocalDateTime(appointment.Practice, appointment.Start))
                };

                var genericAppointmentDataString = new JavaScriptSerializer().Serialize(genericAppointmentData);

                // notify the doctor
                var newNotification = new Notification()
                {
                    CreatedOn  = referenceTime,
                    IsClosed   = false,
                    UserToId   = appointment.DoctorId,
                    Type       = NotificationConstants.GENERIC_APPOINTMENT_NOTIFICATION_TYPE,
                    PracticeId = appointment.PracticeId,
                    Data       = genericAppointmentDataString
                };

                appointment.Doctor.Users.First().Notifications.Add(newNotification);
                notificationsToBeDispatched.Add(new Tuple <Notification, object>(newNotification, genericAppointmentData));

                appointment.Notified = true;
            }
            db.SaveChanges();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Creates and saves the given number of fake patients
        /// </summary>
        public static List<Patient> CreateFakePatients(Doctor doctor, CerebelloEntities db, int count)
        {
            var maleFirstNames = new[]
                {
                    "André",
                    "Anderson",
                    "Alan",
                    "Artur",
                    "Bruno",
                    "Carlos",
                    "Daniel",
                    "Danilo",
                    "Ernani",
                    "Fabiano",
                    "Fábio",
                    "Guilherme",
                    "Hélcio",
                    "Jorge",
                    "Leonardo",
                    "Marcelo",
                    "Miguel", // po cara! eu tb! // blz! haha
                    "Nelson",
                    "Osvaldo",
                    "Patrício",
                    "Roberto",
                    "Ronan",
                    "Thiago"
                };

            var femaleFirstNames = new[]
                {
                    "Alice",
                    "Aline",
                    "Bianca",
                    "Bruna",
                    "Carla",
                    "Daniela",
                    "Elaine",
                    "Fabíola",
                    "Fabiana",
                    "Giovana",
                    "Íngridi",
                    "Jaqueline",
                    "Larissa",
                    "Marcela",
                    "Natália",
                    "Paula",
                    "Quelen",
                    "Renata",
                    "Silvana",
                    "Tatiana",
                    "Valquíria",
                    "Zilá"
                };

            var middleNames = new[]
                {
                    "Albuquerque",
                    "Almeida",
                    "Bastos",
                    "Queiróz",
                    "Teixeira",
                    "Silva",
                    "Rodrigues",
                    "Santos",
                    "Pena",
                    "Bicudo",
                    "Gonçalves",
                    "Machado",
                    "Vianna",
                    "Souza",
                    "Moreira",
                    "Vieira",
                    "Correia",
                    "Reis",
                    "Delgado"
                };

            var professions = new[]
                {
                    "Pedreiro(a)",
                    "Arquiteto(a)",
                    "Programador(a)",
                    "Economista",
                    "Engenheiro(a)",
                    "Padeiro(a)",
                    "Eletricista",
                    "Vendedor(a)",
                    "Consultor(a)",
                    "Biólogo(a)",
                    "Carpinteiro(a)",
                    "Advogado(a)"
                };

            using (var rc = RandomContext.Create())
            {
                var random = rc.Random;
                var result = new List<Patient>();

                for (var i = 0; i < count; i++)
                {
                    // gender (random upper bound is exclusive)
                    var gender = random.Next(0, 2);

                    // first name
                    var possibleFirstNames = gender == 0 ? maleFirstNames : femaleFirstNames;
                    var firstName = possibleFirstNames[random.Next(possibleFirstNames.Length)];

                    // middle names
                    var chosenMiddleNames = new string[random.Next(2, 4)];
                    for (var j = 0; j < chosenMiddleNames.Length; j++)
                        chosenMiddleNames[j] = middleNames[random.Next(middleNames.Length)];

                    var birthDate = new DateTime(
                        random.Next(1950, 2000),
                        random.Next(1, 13),
                        random.Next(1, 29),
                        00,
                        00,
                        000,
                        DateTimeKind.Utc);

                    var patient = new Patient
                        {
                            Person = new Person
                                {
                                    FullName = firstName + " " + string.Join(" ", chosenMiddleNames),
                                    Gender = (short)gender,
                                    DateOfBirth = birthDate,
                                    MaritalStatus = (short?)random.Next(0, 4),
                                    BirthPlace = "Brasileiro(a)",
                                    CPF = "87324128910",
                                    Profession = professions[random.Next(professions.Length)],
                                    CreatedOn = Firestarter.UtcNow,
                                    PracticeId = doctor.PracticeId,
                                },

                            Doctor = doctor,
                            PracticeId = doctor.PracticeId,
                        };

                    // it's important do remove diacritics because StmpClient crashes on non-ascii characters
                    patient.Person.Email =  StringHelper.RemoveDiacritics((firstName + string.Join("", chosenMiddleNames)).ToLower() + "@fakemail.com");
                    Debug.Assert(!patient.Person.Addresses.Any());
                    patient.Person.Addresses.Add(
                        new Address
                            {
                                CEP = random.Next(36000000, 37000000).ToString(CultureInfo.InvariantCulture),
                                StateProvince = "MG",
                                City = "Juiz de Fora",
                                Neighborhood = "Centro",
                                Street =
                                    "Rua " + middleNames[random.Next(middleNames.Length)] + " " +
                                    middleNames[random.Next(middleNames.Length)],
                                Complement = "",
                                PracticeId = doctor.PracticeId,
                            });

                    result.Add(patient);
                    db.Patients.AddObject(patient);
                }

                db.SaveChanges();
                return result;
            }
        }
Exemplo n.º 4
0
        private static void SaveLeafletsToDb(CerebelloEntities db, List<MedicineRaw> medicines, Action<int, int> progress = null)
        {
            db.ExecuteStoreCommand("delete from SYS_MedicineActiveIngredient");
            db.ExecuteStoreCommand("delete from SYS_ActiveIngredient");
            db.ExecuteStoreCommand("delete from SYS_Medicine");
            db.ExecuteStoreCommand("delete from SYS_Laboratory");

            int count, max;
            {
                // INGREDIENTS
                Console.WriteLine("SYS_ActiveIngredient");
                List<string> activeIngredientNames =
                    (from m in medicines
                     from ai in m.ActiveIngredient.Split('+')
                     select
                         StringHelper.CapitalizeFirstLetters(
                             Regex.Replace(ai.Trim(), @"\s+", " "),
                             new[] { "a", "o", "ao", "e", "de", "da", "do", "as", "as", "os", "das", "dos", "des" }))
                        .Distinct()
                        .ToList();

                count = 0;
                max = activeIngredientNames.Count;
                foreach (string activeIngredientName in activeIngredientNames)
                {
                    if (progress != null) progress(count, max);

                    if (!string.IsNullOrEmpty(activeIngredientName) && activeIngredientName != "-")
                        db.SYS_ActiveIngredient.AddObject(new SYS_ActiveIngredient { Name = activeIngredientName });

                    if (count % 100 == 0)
                        db.SaveChanges();

                    count++;
                }
                if (progress != null) progress(count, max);

                // LABORATORIES
                Console.WriteLine("SYS_Laboratory");
                List<string> laboratoryNames = (from m in medicines.ToList() select m.Laboratory).Distinct().ToList();

                count = 0;
                max = laboratoryNames.Count;
                foreach (string laboratoryName in laboratoryNames)
                {
                    if (progress != null) progress(count, max);

                    if (!string.IsNullOrEmpty(laboratoryName) && laboratoryName != "-")
                        db.SYS_Laboratory.AddObject(new SYS_Laboratory { Name = laboratoryName });

                    if (count % 100 == 0)
                        db.SaveChanges();

                    count++;
                }
                if (progress != null) progress(count, max);
            }

            db.SaveChanges();

            // MEDICINES
            Console.WriteLine("SYS_Medicine");
            var medicinesList = (from m in medicines group m by new { m.Name, m.Concentration })
                .Where(mg => mg.Key.Name != "-")
                .ToList();

            count = 0;
            max = medicinesList.Count;
            foreach (var medicinesGrouped in medicinesList)
            {
                if (progress != null) progress(count, max);

                string medicineName = medicinesGrouped.Key.Name;

                var medicine = new SYS_Medicine
                    {
                        Name = medicineName + " (" + medicinesGrouped.Key.Concentration + ")"
                    };

                // associating active ingredients with medicine
                List<string> activeIngredientNames =
                    (from ai in medicinesGrouped.ElementAt(0).ActiveIngredient.Split('+')
                     select
                         StringHelper.CapitalizeFirstLetters(
                             Regex.Replace(ai.Trim(), @"\s+", " "),
                             new[] { "a", "o", "ao", "e", "de", "da", "do", "as", "as", "os", "das", "dos", "des" }))
                        .ToList();
                activeIngredientNames = activeIngredientNames
                    .Where(ain => !string.IsNullOrEmpty(ain) && ain != "-")
                    .ToList();
                foreach (string ain in activeIngredientNames)
                {
                    SYS_ActiveIngredient activeIngredient = db.SYS_ActiveIngredient.First(ai => ai.Name == ain);
                    medicine.ActiveIngredients.Add(activeIngredient);
                }

                // associating the medicine with the laboratory
                if (!string.IsNullOrEmpty(medicinesGrouped.ElementAt(0).Laboratory))
                {
                    string laboratoryName = medicinesGrouped.ElementAt(0).Laboratory;
                    medicine.Laboratory = db.SYS_Laboratory.First(l => l.Name == laboratoryName);
                }

                foreach (var leaflet in medicinesGrouped.Select(mg => new { Description = mg.LeafletType, Url = mg.LeafletUrl }))
                    medicine.Leaflets.Add(new SYS_Leaflet { Description = leaflet.Description, Url = leaflet.Url });

                db.SYS_Medicine.AddObject(medicine);

                db.SaveChanges();

                count++;
            }
            if (progress != null) progress(count, max);

            db.SaveChanges();
        }
Exemplo n.º 5
0
        public static void BackupEverything([NotNull] CerebelloEntities db, List <string> errors = null)
        {
            if (db == null)
            {
                throw new ArgumentNullException("db");
            }
            if (errors == null)
            {
                errors = new List <string>();
            }

            using (db)
            {
                var dbWrapper        = new CerebelloEntitiesAccessFilterWrapper(db);
                var patientsToBackup = db.Patients.Where(p => p.Doctor.Users.Any(u => u.Person.GoogleUserAccoutInfoes.Any()) && !p.IsBackedUp).GroupBy(p => p.DoctorId);
                foreach (var patientGroup in patientsToBackup.ToList())
                {
                    try
                    {
                        var doctor = db.Doctors.First(d => d.Id == patientGroup.Key);
                        dbWrapper.SetCurrentUserById(doctor.Users.First().Id);
                        var doctorGoogleAccountInfo = doctor.Users.First().Person.GoogleUserAccoutInfoes.FirstOrDefault();
                        if (doctorGoogleAccountInfo != null)
                        {
                            // in this case the doctor for these patients have a Google Account associated
                            var requestAccessResult = GoogleApiHelper.RequestAccessToken(doctorGoogleAccountInfo.RefreshToken);
                            var authenticator       = GoogleApiHelper.GetAuthenticator(
                                doctorGoogleAccountInfo.RefreshToken, requestAccessResult.access_token);
                            var driveService = new DriveService(authenticator);

                            // create Cerebello folder if it does not exist
                            var  practiceGoogleDriveInfo = doctor.Practice.GoogleDrivePracticeInfoes.FirstOrDefault();
                            File cerebelloFolder         = null;
                            if (practiceGoogleDriveInfo != null)
                            {
                                try
                                {
                                    cerebelloFolder = GoogleApiHelper.GetFile(driveService, practiceGoogleDriveInfo.CerebelloFolderId);
                                    if (cerebelloFolder.Labels.Trashed.HasValue && cerebelloFolder.Labels.Trashed.Value)
                                    {
                                        cerebelloFolder = null;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    var errorMessage = "Error downloading file from Google Drive. Exception message: " + ex.Message;
                                    // the f*****g user deleted the f*****g folder OR something went wrong downloading the file
                                    Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage);
                                    errors.Add(errorMessage);
                                }
                            }
                            if (cerebelloFolder == null)
                            {
                                cerebelloFolder = GoogleApiHelper.CreateFolder(driveService, "Cerebello", "Pasta do Cerebello");
                                if (practiceGoogleDriveInfo != null)
                                {
                                    practiceGoogleDriveInfo.CerebelloFolderId = cerebelloFolder.Id;
                                }
                                else
                                {
                                    practiceGoogleDriveInfo = new GoogleDrivePracticeInfo()
                                    {
                                        CerebelloFolderId = cerebelloFolder.Id,
                                        PracticeId        = doctor.PracticeId
                                    };
                                    doctor.Practice.GoogleDrivePracticeInfoes.Add(practiceGoogleDriveInfo);
                                }
                                db.SaveChanges();
                            }

                            foreach (var patient in patientGroup)
                            {
                                try
                                {
                                    var patientBackup   = GeneratePatientBackup(dbWrapper, patient);
                                    var fileName        = string.Format("{0} (id:{1})", patient.Person.FullName, patient.Id) + ".zip";
                                    var fileDescription = string.Format(
                                        "Arquivo de backup do(a) paciente {0} (id:{1})", patient.Person.FullName, patient.Id);

                                    // check if the file exists already
                                    var  patientGoogleDriveFile = patient.GoogleDrivePatientInfoes.FirstOrDefault();
                                    File googleDrivePatientFile = null;
                                    if (patientGoogleDriveFile != null)
                                    {
                                        try
                                        {
                                            // get reference to existing file to make sure it exists
                                            var existingFile = GoogleApiHelper.GetFile(
                                                driveService, patientGoogleDriveFile.PatientBackupFileId);
                                            if (!existingFile.Labels.Trashed.HasValue || !existingFile.Labels.Trashed.Value)
                                            {
                                                googleDrivePatientFile = GoogleApiHelper.UpdateFile(
                                                    driveService,
                                                    patientGoogleDriveFile.PatientBackupFileId,
                                                    fileName,
                                                    fileDescription,
                                                    MimeTypesHelper.GetContentType(".zip"),
                                                    patientBackup);
                                                if (googleDrivePatientFile.Labels.Trashed.HasValue && googleDrivePatientFile.Labels.Trashed.Value)
                                                {
                                                    googleDrivePatientFile = null;
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            var errorMessage = "Error updating file from Google Drive. Exception message: " + ex.Message;
                                            // the f*****g user deleted the f*****g folder OR something went wrong downloading the file
                                            Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage);
                                            errors.Add(errorMessage);
                                        }
                                    }

                                    if (googleDrivePatientFile == null)
                                    {
                                        googleDrivePatientFile = GoogleApiHelper.CreateFile(
                                            driveService,
                                            fileName,
                                            fileDescription,
                                            MimeTypesHelper.GetContentType(".zip"),
                                            patientBackup,
                                            new List <ParentReference>()
                                        {
                                            new ParentReference()
                                            {
                                                Id = cerebelloFolder.Id
                                            }
                                        });

                                        if (patientGoogleDriveFile != null)
                                        {
                                            patientGoogleDriveFile.PatientBackupFileId = googleDrivePatientFile.Id;
                                        }
                                        else
                                        {
                                            patient.GoogleDrivePatientInfoes.Add(
                                                new GoogleDrivePatientInfo()
                                            {
                                                PatientBackupFileId = googleDrivePatientFile.Id,
                                                PracticeId          = doctor.PracticeId
                                            });
                                        }
                                    }
                                    patient.IsBackedUp = true;
                                    db.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    var errorMessage = "Error synchronizing files for a specific doctor. Exception message" + ex.Message;
                                    // the f*****g user deleted the f*****g folder OR something went wrong downloading the file
                                    Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage);
                                    errors.Add(errorMessage);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var errorMessage = "Error synchronizing files. Exception message" + ex.Message;
                        // the f*****g user deleted the f*****g folder OR something went wrong downloading the file
                        Trace.TraceError("BackupHelper.BackupEverything(db, errors): " + errorMessage);
                        errors.Add(errorMessage);
                    }
                }
            }
        }
Exemplo n.º 6
0
        public string StartFullBackup()
        {
            var errors = new List<string>();
            using (var db = new CerebelloEntities())
            {
                foreach (var patient in db.Patients)
                    patient.IsBackedUp = false;
                db.SaveChanges();

                BackupHelper.BackupEverything(db, errors);
            }

            return "Errors : " + string.Join(",", errors);
        }