Пример #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);
                }
            }
        }
Пример #2
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);
                }

                LoginSuccess login = userServices.LoginAsHealthProfessionalByCert().Result;
                if (login == null)
                {
                    throw new Exception("No se pudo realizar login");
                }

                ApiPharmacyPrescriptionsToDeliver prescriptionsToDeliver = pharmacyServices.GetPrescriptionsToDeliverAsync().Result;

                //Para validar el tipo de identificación
                List <IdentificationType> identificationTypes = catalogServices.GetIdentificationTypesAsync().Result;

                foreach (ApiPharmacyPrescription apiPharmacyPrescription in prescriptionsToDeliver.prescriptionsToDeliver)
                {
                    if (apiPharmacyPrescription.quote != null && apiPharmacyPrescription.externalPharmacyCode != null && apiPharmacyPrescription.quote.express &&
                        apiPharmacyPrescription.quote.addressInfo != null && apiPharmacyPrescription.quote.addressInfo.politicalRegion != null && apiPharmacyPrescription.quote.addressInfo != null && apiPharmacyPrescription.quote.billingInfo != null)
                    {
                        //Encabezado
                        Console.WriteLine(
                            "Código de farmacia: " + apiPharmacyPrescription.externalPharmacyCode + "\n" +
                            "Nombre del cliente: " + apiPharmacyPrescription.patient.firstName + " " + apiPharmacyPrescription.patient.lastName + "\n" +
                            //*Facturación
                            "Tipo de identificación: " + apiPharmacyPrescription.quote.billingInfo.identificationTypeCode + "\n" +
                            "Número de identificación: " + apiPharmacyPrescription.quote.billingInfo.identification + "\n" +
                            "Email_Facturación: " + apiPharmacyPrescription.quote.billingInfo.email + "\n" +
                            "Nombre para Facturación: " + apiPharmacyPrescription.quote.billingInfo.name + "\n" +
                            //**
                            "Fecha_Documento: " + apiPharmacyPrescription.quote.quoteDate + "\n" +
                            "Telefono: " + apiPharmacyPrescription.patient.phoneNumber + "\n" +
                            "Email: " + apiPharmacyPrescription.patient.email + "\n" +
                            "Num_Aprobacion_Pago: " + apiPharmacyPrescription.quote.paymentTransaction.authorizationCode + "\n" +
                            "Fecha de pago: " + apiPharmacyPrescription.quote.paymentTransaction.date.ToString() + "\n" +
                            "Pago_Total: " + apiPharmacyPrescription.quote.totalPrice + "\n" +
                            "Monto_Total: " + apiPharmacyPrescription.quote.totalPrice + "\n");


                        //Region politica
                        if (apiPharmacyPrescription.quote.addressInfo != null)
                        {
                            PoliticalRegion politicalRegion = apiPharmacyPrescription.quote.addressInfo.politicalRegion;
                            if (politicalRegion != null && politicalRegion.parent != null && politicalRegion.parent.parent != null)
                            {
                                //Para comprobar esta información, puede ver politicalRegion.description
                                //El tipo de dato se distingue por su nivel: Level 1: Provincia, Level 2:Cantón, Level 3: Distrito
                                Console.WriteLine(
                                    "Provincia_ID: " + politicalRegion.parent.parent.description + ": " + politicalRegion.parent.parent.number + "\n" +
                                    "Canton_ID: " + politicalRegion.parent.description + ": " + politicalRegion.parent.number + "\n" +
                                    "Distrito_ID: " + politicalRegion.description + ": " + politicalRegion.number);
                            }

                            //Señas dirección
                            Console.WriteLine(
                                "Detalle de la dirección: " + apiPharmacyPrescription.quote.addressInfo.addressDetail + "\n" +
                                "Lugar de entrega: " + apiPharmacyPrescription.quote.addressInfo.deliveryPlaceDetail);
                        }

                        //Detalle

                        Console.WriteLine(
                            "ID_Documento: " + apiPharmacyPrescription.id);
                        //Almecenar ID_Documento en sus sistemas, para que sea posible la dispensación en DrsBee

                        foreach (Dictionary <string, List <DrugPharmacyQuotePresentation> > keyValues in apiPharmacyPrescription.quote.quotePresentationsByDrugIdByVademecumId.Values)
                        {
                            foreach (List <DrugPharmacyQuotePresentation> drugPharmacyQuotePresentations in keyValues.Values)
                            {
                                foreach (DrugPharmacyQuotePresentation drugPharmacyQuotePresentation in drugPharmacyQuotePresentations)
                                {
                                    Console.WriteLine(
                                        "Codigo_Articulo: " + drugPharmacyQuotePresentation.pharmacyPresentationCode + "\n" +
                                        "Unidad: " + drugPharmacyQuotePresentation.loose + "\n" +
                                        "Cantidad: " + drugPharmacyQuotePresentation.quantity + "\n" +
                                        "Precio_Bruto_total_DrsBee: " + drugPharmacyQuotePresentation.grossPrice + "\n" +
                                        "Precio_Bruto_Unitario indicado por farmacia: " + drugPharmacyQuotePresentation.unitaryPrice + "\n" +
                                        "Descuento_Porcentaje: " + drugPharmacyQuotePresentation.discountPercentage + "\n" +
                                        "Fecha vencimiento del descuento: " + (drugPharmacyQuotePresentation.discountDueDate != null ? drugPharmacyQuotePresentation.discountDueDate.ToString() : "-") + "\n" +
                                        "Impuesto_Porcentaje: " + drugPharmacyQuotePresentation.taxPercentage + "\n" +
                                        "Total_Linea: " + drugPharmacyQuotePresentation.totalPrice + "\n");
                                }
                            }
                        }
                    }
                }

                Console.WriteLine("Actualmente hay: " + prescriptionsToDeliver.prescriptionsToDeliver.Count + " prescription a entregar");
                if (prescriptionsToDeliver.prescriptionsToDeliver.Count > 0)
                {
                    ApiPharmacyPrescription prescriptionToDispense = prescriptionsToDeliver.prescriptionsToDeliver[prescriptionsToDeliver.prescriptionsToDeliver.Count - 1];
                    Console.WriteLine("Dispensando primer prescripcion con id " + prescriptionToDispense.id + " pendiente de dispensar desde " + prescriptionToDispense.quote.lastModifiedDate);
                    pharmacyServices.DispenseQuotedPrescriptionAsync(prescriptionToDispense.id).Wait();
                    Console.WriteLine("Prescription dispensada");
                }

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Exception           realException = ex is AggregateException && ex.InnerException != null ? ex.InnerException : ex;
                WebServiceException wsex          = realException as WebServiceException;
                HttpException       httpEx        = realException as HttpException;
                // Error en drsbee backend con mensaje de usuario final incluido, Malas credenciales, malos parametros, prescripcion en estado incorrecto, etc.
                if (wsex != null)
                {
                    Console.WriteLine("El API de DrsBee retornó un error: " + wsex.Message + " de tipo " + wsex.Type);
                }
                // Error HTTP fuera drsbee, falla de conexion, timeout,etc.
                else if (httpEx != null)
                {
                    Console.WriteLine("Hubo un error de comunicación http con DrsBee, código: " + httpEx.HttpCode + "  invocando el URL: " + httpEx.Url);
                }
                else
                {
                    Console.WriteLine("Ocurrió un error desconocido: " + realException.Message);
                    Console.WriteLine(realException.StackTrace);
                }
            }
        }