Beispiel #1
0
        public static void Main(string[] args)
        {
            try
            {
                // Inicializamos el token para los servicios de API
                using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(API_KEY_RESOURCE))
                {
                    DrsBeeAuth.InitApi(API_KEY_ACCOUNT, resourceStream);
                }
                //Revisa la conexión al ambiente y obtiene info basica
                Console.WriteLine("-------- Conectando a ambiente ------");
                var environment = infoServices.getBackendEnvironmentAsync().Result;
                Console.WriteLine("-> " + environment.applicationEnvironment);
                Console.WriteLine("-> Vademecum:" + environment.defaultVademecumDescription + "(ID" + environment.defaultVademecumId + ")");

                //Obtenemos los catalogos necesarios
                List <TimeUnit> timeUnits = catalogWebService.getTimeUnitsAsync().Result;
                List <PrescriptionAbbreviature> prescriptionAbbreviatures = catalogWebService.getPrescriptionAbbreviaturesAsync().Result;
                List <DoseUnit>            doseUnits            = catalogWebService.getDoseUnitsAsync().Result;
                List <AdministrationRoute> administrationRoutes = catalogWebService.getAdministrationRoutesAsync().Result;

                string newPhysicianIdentification = string.Format("{0}{1}{2}{3}{4}{5}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
                //Se intenta hacer login para probar si medico existe
                Console.WriteLine("-------- Se intenta hacer login como si medico existiera ------");
                LoginSuccess login = apiWebServices.loginAsHealthProfessional(newPhysicianIdentification, TEST_PHYSICIAN_IDENTIFICATION_TYPE_CODE).Result;
                if (login == null)
                {
                    Console.WriteLine("-> Medico no existe, se procede a hacer login con medico nuevo");
                    login = apiWebServices.loginAsNewPhysician(identification: newPhysicianIdentification,
                                                               identificationTypeCode: TEST_PHYSICIAN_IDENTIFICATION_TYPE_CODE,
                                                               email: newPhysicianIdentification + "@test.com",
                                                               firstName: "Test Physician",
                                                               lastName: newPhysicianIdentification,
                                                               physicianCode: newPhysicianIdentification).Result;
                }
                if (login == null)
                {
                    throw new Exception("No se pudo realizar login");
                }

                Console.WriteLine("-> " + login.userType);

                //Una vez obteniendo el tipo de usuario logeado, se procede a obtener sus datos
                Console.WriteLine("-------- Login con médico de prueba ------");
                var physician = userWebService.getPhysicianLoginAsync().Result;
                Console.WriteLine("-> Cedula " + physician.identification);
                Console.WriteLine("-> Nombre " + physician.firstName + "-" + physician.lastName);

                // Obtenemos las farmacias disponibles
                Console.WriteLine("-------- Obteniendo farmacias medicamentos ------");
                List <Pharmacy> pharmacies = pharmacyWebService.getPharmaciesAsync().Result;
                Console.WriteLine("-> Farmacias registradas" + pharmacies.Count);


                //Obtenemos cuantas prescripciones tiene restantes
                var prescriptions = userWebService.getHealthProfessionalRemainingPrescriptionsAsync().Result;
                Console.WriteLine("-> Prescripciones restantes " + prescriptions.count);


                //Se busca un paciente por nombre
                Console.WriteLine("-------- Buscando pacientes por nombre ------");
                var pacientes = patientWebService.searchPatientsAsync(criteria: "juan", includeUnregistered: true, limit: 50).Result;
                Console.WriteLine("-> Pacientes encontrados por nombre " + pacientes.Count);

                Console.WriteLine("-------- Buscando paciente sin cédula, pero registrado en sistema externo ------");
                string patientIdInOurSystem = string.Format("{0}{1}{2}{3}{4}{5}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
                PatientSearchResult existingPatientWithOurId = apiWebServices.searchPatientByExternalId(patientIdInOurSystem).Result;
                if (existingPatientWithOurId == null)
                {
                    Console.WriteLine("-------- Paciente no se encontró paciente con nuestro ID, procedemos a crearlo con nuestro ID ------");
                    CreatedEncounter encounterJustToRegister = encounterWebService.beginEncounterNewPatientWithExternalIdAsync(
                        externalId: patientIdInOurSystem,
                        firstName: "paciente", lastName: "prueba api externo",
                        phoneNumber: "88888888",
                        birthdateDay: 1, birthdateMonth: 1, birthdateYear: 1999
                        , reason: "cita de prueba").Result;
                    CompleteEncounter encounterFinish = new CompleteEncounter();
                    encounterFinish.encounter = encounterJustToRegister;
                    encounterWebService.finishEncounterAsync(encounterFinish).Wait();

                    Console.WriteLine("-------- Repetimos la busqueda, ahora deberia aparecer el paciente con el ID externo ------");
                    existingPatientWithOurId = apiWebServices.searchPatientByExternalId(patientIdInOurSystem).Result;
                }


                PatientSearchResult pacienteRegistrado = existingPatientWithOurId;

                CreatedEncounter encounter;
                // Procedemos a crear una cita, ya sea con un paciente registrado o con uno nuevo para registrar
                if (pacienteRegistrado != null)
                {
                    Console.WriteLine("-------- Iniciando cita con paciente ya registrado ------");
                    encounter = encounterWebService.beginEncounterPatientAsync(pacienteRegistrado.id, "cita de prueba").Result;
                }
                else
                {
                    Console.WriteLine("-------- Iniciando cita con paciente nuevo ------");
                    encounter = encounterWebService.beginEncounterNewPatientAsync(
                        identification: PATIENT_IDENTIFICATION, identificationTypeCode: CEDULA_PANAMA_TYPE,
                        firstName: "paciente", lastName: "prueba",
                        phoneNumber: "88888888",
                        birthdateDay: 1, birthdateMonth: 1, birthdateYear: 1999
                        , reason: "cita de prueba").Result;
                }


                Console.WriteLine("-------- Buscando medicamentos ------");
                var drugSearchResult = drugWebService.findDrugsByFilterAsync("Aceta").Result;
                Console.WriteLine("-> Encontrados por marca " + drugSearchResult.drugsByName.Count);
                Console.WriteLine("-> Encontrados por principio activo " + drugSearchResult.drugsByActiveIngredient.Count);

                Drug drugToAdd = drugSearchResult.drugsByName[0];

                // Muchos medicamentos traen su dosificación usual, si la trae vamos a usarla
                var suggestedDosage = drugSearchResult.dosageSuggestionByDrugId.ContainsKey(drugToAdd.id) ?
                                      drugSearchResult.dosageSuggestionByDrugId[drugToAdd.id] : null;

                PrescriptionDrug prescriptionDrug = new PrescriptionDrug();
                prescriptionDrug.drugId = drugToAdd.id;

                prescriptionDrug.dose = suggestedDosage != null && suggestedDosage.dose != null ? suggestedDosage.dose.Value : 1;
                prescriptionDrug.administrationRouteId = drugToAdd.administrationRouteById.Keys.First(); // Como ejemplo , utilizamos la primera via de administracion
                prescriptionDrug.duration             = suggestedDosage != null && suggestedDosage.duration != null ? suggestedDosage.duration.Value : 1;
                prescriptionDrug.durationTimeUnitCode = suggestedDosage != null && !string.IsNullOrEmpty(suggestedDosage.durationTimeUnitCode) ? suggestedDosage.durationTimeUnitCode : timeUnits[0].code;

                // Para la frecuencia del consumo utilizamos codigo predefinidos que establecen el horario, por ejemplo QUID , que significa
                prescriptionDrug.prescriptionAbbreviatureCode = suggestedDosage != null && !string.IsNullOrEmpty(suggestedDosage.prescriptionAbbreviatureCode) ? suggestedDosage.prescriptionAbbreviatureCode : prescriptionAbbreviatures[0].code;

                //En caso de que el medico no quiera usar un horario predefinido, puede especificarlo manualmente
                //prescriptionDrug.hours = new List<DayTime>()
                //{
                //    new DayTime(10,0),
                //    new DayTime(18,0)
                //};

                prescriptionDrug.notes       = "Prueba desde DEMO API";
                prescriptionDrug.vademecumId = environment.defaultVademecumId;

                PrescriptionDrug manualPrescriptionDrug = new PrescriptionDrug();
                manualPrescriptionDrug.drugDescription       = "Manual drug";
                manualPrescriptionDrug.doseUnitCode          = doseUnits[0].code;
                manualPrescriptionDrug.administrationRouteId = administrationRoutes[0].code;
                manualPrescriptionDrug.dose = 1;
                manualPrescriptionDrug.prescriptionAbbreviatureCode = prescriptionAbbreviatures[0].code;
                manualPrescriptionDrug.duration             = 1;
                manualPrescriptionDrug.durationTimeUnitCode = timeUnits[0].code;

                List <PrescriptionDrug> drugsToAdd = new List <PrescriptionDrug>();
                drugsToAdd.Add(prescriptionDrug);
                drugsToAdd.Add(manualPrescriptionDrug);


                Console.WriteLine("-------- Agregamos enfermedades que queremos registrar en el expediente del paciente pero que habian sido detectadas en consultas pasadas -----");


                List <Disease> results = diseaseWebService.searchDiseaseByNameAsync(DISEASE_CATALOG_VERSION, "dolor").Result; //-> Opcional permite ayudarle al medico a buscar enfermedades en el catalogo oficial

                List <HealthProblem> healthProblems = new List <HealthProblem>();
                healthProblems.Add(new HealthProblem()
                {
                    description    = "Existing health problem with code from catalog",
                    statusCode     = DISEASE_ACTIVE,
                    icdCode        = results[0].ICDCode,
                    icdVersion     = results[0].ICDVersion,
                    diagnosticDate = DateTime.Now.AddYears(-1) //Detected one year prior
                });

                healthProblems.Add(new HealthProblem()
                {
                    description    = "Existing health problem with code from other catalogs",
                    statusCode     = DISEASE_ACTIVE,
                    icdCode        = "000111",
                    icdVersion     = "icd-test",
                    diagnosticDate = DateTime.Now.AddMonths(-2) //Detected two months prior
                });
                healthProblems.Add(new HealthProblem()
                {
                    description    = "Existing health problem but inactive with description only",
                    statusCode     = DISEASE_INACTIVE,
                    diagnosticDate = DateTime.Now.AddYears(-2) //Detected two years prior
                });


                //Agregamos enfermedades
                Console.WriteLine("-------- Agregamos diagnosticos encontrados en este encuentro -----");

                List <EncounterDiagnostic> encounterDiagnostics = new List <EncounterDiagnostic>();
                encounterDiagnostics.Add(new EncounterDiagnostic()
                {
                    description = "Diagnostic description with code from catalog",
                    icdCode     = results[1].ICDCode,
                    icdVersion  = results[1].ICDVersion
                });

                encounterDiagnostics.Add(new EncounterDiagnostic()
                {
                    description = "Diagnostic description with code from other catalogs",
                    icdCode     = "000111",
                    icdVersion  = "icd-test"
                });

                encounterDiagnostics.Add(new EncounterDiagnostic()
                {
                    description = "Diagnostic description only"
                });



                Console.WriteLine("-------- Revisamos la prescripción y obtenemos una vista previa del documento de prescripción ------");
                // Hacemos una revisión de la prescripción, esto es útil para obtener una imagen del documento de la prescripción y así poder confirmar.
                // Una cita puede tener o no una prescripción, al hacer esto estamos especificando que sí tiene una prescripción.
                var encounterReview = encounterWebService.reviewEncounter(new PrescriptionDocumentRequest()
                {
                    encounterId = encounter.id,
                    drugs       = drugsToAdd
                }).Result;

                Console.WriteLine("-> URL " + encounterReview.url);

                Console.WriteLine("-------- Finalizamos la cita y enviamos la prescripción ------");
                CompleteEncounter encounterContainer = new CompleteEncounter();
                encounterContainer.encounter             = encounter;
                encounterContainer.encounter.diagnostics = encounterDiagnostics;
                encounterContainer.ehr = new EHR();
                encounterContainer.ehr.healthProblems = healthProblems;
                //Registramos la ubicación geográfica del médico, ya sea obtenida por el disposivo o especificada por medio de que se seleccione un consultorio al iniciar la cita.
                // esto es importante para mantener una trazabilidad de las prescripciones por ubicación y ademas para que las farmacias cercanas puedan ver
                // esta prescripción para poder cotizar.
                encounterContainer.locationLatitude  = LATITUDE;
                encounterContainer.locationLongitude = LONGITUDE;

                var finishedEncounter = encounterWebService.finishEncounterAsync(encounterContainer).Result;

                Console.WriteLine("-> ID de prescripción nueva " + finishedEncounter.prescriptionId);
                Console.WriteLine("-> Código para retirar la prescripción en farmacias " + finishedEncounter.prescriptionPublicCode);
            }
            catch (Exception ex)
            {
                WebServiceException         wsex = ex.InnerException != null ? ex.InnerException as WebServiceException : null;
                HttpServiceRequestException hex  = ex.InnerException != null ? ex.InnerException as HttpServiceRequestException : null;
                if (wsex != null)
                {
                    Console.WriteLine("El API de DrsBee retornó un error: " + wsex.Message + " de tipo " + wsex.Type + "  invocando el URL: " + wsex.RequestUrl);
                }
                else if (hex != null)
                {
                    Console.WriteLine("Hubo un error de comunicación http con DrsBee, código: " + hex.HttpCode + "  invocando el URL: " + hex.RequestUrl);
                }
                else
                {
                    Console.WriteLine("Ocurrió un error desconocido ");
                    Console.WriteLine(ex.StackTrace);
                }
            }
        }
Beispiel #2
0
        public async Task <IActionResult> AddVisit(AddVisitViewModel visitViewModel)
        {
            if (visitViewModel.Reservation.DoctorId == 0 ||
                visitViewModel.Reservation.PatientId == 0)
            {
                return(StatusCode(404));
            }

            var reserve = await _db.Reservations
                          .FirstOrDefaultAsync(a =>
                                               a.DoctorId.Equals(visitViewModel.Reservation.DoctorId) &&
                                               a.PatientId.Equals(visitViewModel.Reservation.PatientId) &&
                                               a.ReserveDate.Equals(visitViewModel.Reservation.ReserveDate));

            if (reserve == null)
            {
                return(StatusCode(404));
            }

            string[] drugs  = null;
            string[] number = null;
            if (!string.IsNullOrEmpty(visitViewModel.DrugList))
            {
                string[] temp = null;
                try
                {
                    temp = visitViewModel.DrugList.Split('،');
                }
                catch (Exception)
                {
                    return(StatusCode(403));
                }

                drugs  = temp.Where((x, i) => i % 2 == 0).ToArray();
                number = temp.Where((x, i) => i % 2 != 0).ToArray();

                if (drugs.Any(a => a.Equals("")) || number.Any(a => a.Equals("")))
                {
                    return(StatusCode(403));
                }

                if (drugs.Length != number.Length)
                {
                    return(StatusCode(403));
                }
            }

            DateTime reserveDateTimeAgain = DateTime.MinValue;

            if (!(string.IsNullOrEmpty(visitViewModel.ReserveDateAgain) || string.IsNullOrEmpty(visitViewModel.ReserveTimeAgain)))
            {
                if (!TimeSpan.TryParse(visitViewModel.ReserveTimeAgain, out var time))
                {
                    return(StatusCode(402));
                }

                var dates = visitViewModel.ReserveDateAgain.Split('/');
                reserveDateTimeAgain = new DateTime(Int32.Parse(dates[0]), int.Parse(dates[1]), int.Parse(dates[2]), new PersianCalendar());
                reserveDateTimeAgain = reserveDateTimeAgain.Date + time;

                if (reserveDateTimeAgain.Date <= DateTime.Today.Date)
                {
                    return(StatusCode(406));
                }

                var dayOfWeek = reserveDateTimeAgain.DayOfWeek switch
                {
                    DayOfWeek.Sunday => "یکشنبه",
                    DayOfWeek.Monday => "دوشنبه",
                    DayOfWeek.Tuesday => "سه شنبه",
                    DayOfWeek.Wednesday => "چهارشنبه",
                    DayOfWeek.Thursday => "پنج شنبه",
                    DayOfWeek.Saturday => "شنبه",
                    _ => null
                };

                if (string.IsNullOrEmpty(dayOfWeek))
                {
                    return(StatusCode(401));
                }

                var day = await _db.WeekDays.FirstOrDefaultAsync(a =>
                                                                 a.DoctorId.Equals(visitViewModel.Reservation.DoctorId) &&
                                                                 a.DayName.Equals(dayOfWeek));

                switch (time.Hours)
                {
                case 8 when !day.EightTen.Equals("خالی"):
                    return(StatusCode(400));

                case 10 when !day.TenTwelve.Equals("خالی"):
                    return(StatusCode(400));

                case 12 when !day.TwelveFourteen.Equals("خالی"):
                    return(StatusCode(400));

                case 14 when !day.FourteenSixteen.Equals("خالی"):
                    return(StatusCode(400));
                }


                var isAvailableReserve = await _db.Reservations
                                         .AnyAsync(a =>
                                                   a.DoctorId.Equals(visitViewModel.Reservation.DoctorId) &&
                                                   a.ReserveDate.Equals(reserveDateTimeAgain));

                var isPatientBusy = await _db.Reservations
                                    .AnyAsync(a =>
                                              a.PatientId.Equals(reserve.PatientId) &&
                                              a.ReserveDate.Equals(reserveDateTimeAgain) &&
                                              a.ReserveStatus.Contains("در انتظار ویزیت"));

                if (isPatientBusy)
                {
                    return(StatusCode(409));
                }

                if (isAvailableReserve)
                {
                    return(StatusCode(405));
                }
            }

            InsuranceProvider insurance = null;

            if (!string.IsNullOrEmpty(visitViewModel.InsuranceProviderName))
            {
                if (drugs == null)
                {
                    return(StatusCode(409));
                }
                insurance = await _db.InsuranceProviders
                            .FirstOrDefaultAsync(a =>
                                                 a.InsuranceName.Equals(visitViewModel.InsuranceProviderName));
            }

            if (!reserveDateTimeAgain.Equals(DateTime.MinValue))
            {
                var reserveAgain = new Reservation()
                {
                    Doctor        = await _db.Doctors.FindAsync(visitViewModel.Reservation.DoctorId),
                    Patient       = await _db.Patients.FindAsync(visitViewModel.Reservation.PatientId),
                    ReserveDate   = reserveDateTimeAgain,
                    ReserveStatus = "در انتظار ویزیت"
                };

                await _db.Reservations.AddAsync(reserveAgain);

                await _db.SaveChangesAsync();
            }

            reserve.ReserveStatus = "ویزیت شده";

            var newVisit = new Visit()
            {
                CauseOfPatientReferral = visitViewModel.Visit.CauseOfPatientReferral,
                DoctorAssessment       = visitViewModel.Visit.DoctorAssessment,
                DoctorNote             = visitViewModel.Visit.DoctorNote,
                Reservation            = reserve,
                InsuranceProvider      = insurance
            };
            await _db.Visits.AddAsync(newVisit);

            await _db.SaveChangesAsync();

            _db.Reservations.Update(reserve);
            await _db.SaveChangesAsync();

            if (drugs != null)
            {
                var newPrescription = new Prescription()
                {
                    PaymentMethod = "نقدی",
                    Status        = "پرداخت نشده",
                    Visit         = newVisit
                };
                await _db.Prescriptions.AddAsync(newPrescription);

                await _db.SaveChangesAsync();

                int i = 0;
                foreach (var drug in drugs)
                {
                    var drugDb = await _db.Drugs.FirstOrDefaultAsync(a => a.Name.Equals(drug));

                    if (drugDb != null)
                    {
                        var newPresDrug = new PrescriptionDrug()
                        {
                            Drug         = drugDb,
                            Prescription = newPrescription,
                            Count        = int.Parse(number[i]),
                            IsBought     = false
                        };
                        i++;
                        await _db.PrescriptionDrugs.AddAsync(newPresDrug);

                        await _db.SaveChangesAsync();
                    }
                    else
                    {
                        var unknownCategory = await _db.DrugCategories
                                              .FirstOrDefaultAsync(a =>
                                                                   a.Name.Equals("نامشخص"));

                        if (unknownCategory == null)
                        {
                            var newUnknownCategory = new DrugCategory()
                            {
                                Name = "نامشخص"
                            };
                            await _db.DrugCategories.AddAsync(newUnknownCategory);

                            await _db.SaveChangesAsync();

                            unknownCategory = newUnknownCategory;
                        }

                        var newDrug = new Drug()
                        {
                            Name         = drug,
                            Count        = 0,
                            DrugCategory = unknownCategory,
                            Cost         = 9999,
                            Instruction  = "نامشخص",
                            Status       = false
                        };
                        await _db.Drugs.AddAsync(newDrug);

                        await _db.SaveChangesAsync();

                        var newPresDrug = new PrescriptionDrug()
                        {
                            Drug         = newDrug,
                            Prescription = newPrescription,
                            Count        = int.Parse(number[i]),
                            IsBought     = false
                        };
                        i++;
                        await _db.PrescriptionDrugs.AddAsync(newPresDrug);

                        await _db.SaveChangesAsync();
                    }
                }
            }

            return(StatusCode(200));
        }