Ejemplo n.º 1
0
        public InPatient GetInPatient(Guid inPatientID)
        {
            InPatient result   = null;
            int       tryTimes = 0;

            do
            {
                tryTimes++;
                try
                {
                    //.Include("InPatientDrugRecords.DrugFees")
                    result = this.context.InPatients.Where(i => i.InPatientID == inPatientID).FirstOrDefault();
                    //getData = false;
                }
                catch (System.Data.Entity.Core.EntityCommandExecutionException)
                {
                    //getData = false;
                }
                catch (System.Data.Entity.Core.EntityException)
                {
                }
                catch (Exception)
                {
                    //getData = false;

                    //throw;
                }
            } while (tryTimes < 51);


            return(result);
        }
Ejemplo n.º 2
0
        public void UpdateInPatient(InPatient patient)
        {
            var selected = hos.InPatients.FirstOrDefault((e) => e.InPatientID == patient.InPatientID);

            if (selected == null)
            {
                throw new Exception("Patient not found to update");
            }
            hos.SaveChanges();
        }
Ejemplo n.º 3
0
        public SqlException Create(InPatient ip)
        {
            //insert
            string insert = "INSERT INTO InPatient (PatientNumber, WardNumber, InWardOrWaitingList, DateExpectedToLeave, DatePlacedOnWaitingList, ExpectedDurationOfStay, ActualDateLeft)" +
                            " VALUES(@PatientNumber, @WardNumber, @InWardOrWaitingList, @DateExpectedToLeave, @DatePlacedOnWaitingList, @ExpectedDurationOfStay, @ActualDateLeft)";

            //create sql command, insert query, preparing quries, create parameterized quieries,

            // 1. declare command object with parameter + insert query
            SqlCommand cmd = InitializeDatabase.CreateSqlCommand(insert);


            // 2. define parameters used in command object
            List <SqlParameter> prm = new List <SqlParameter>()
            {
                new SqlParameter("@PatientNumber", SqlDbType.Int)
                {
                    Value = ip.PatientNumber
                },
                new SqlParameter("@WardNumber", SqlDbType.Int)
                {
                    Value = ip.WardNumber
                },
                new SqlParameter("@DatePlacedOnWaitingList", SqlDbType.DateTime)
                {
                    Value = ip.DatePlacedOnWaitingList
                },
                new SqlParameter("@ExpectedDurationOfStay", SqlDbType.Int)
                {
                    Value = ip.ExpectedDurationOfStay
                },
                new SqlParameter("@ActualDateLeft", SqlDbType.DateTime)
                {
                    Value = ip.ActualDateLeft
                },
                new SqlParameter("@InWardOrWaitingList", SqlDbType.NVarChar)
                {
                    Value = ip.InWardOrWaitingList
                },
                new SqlParameter("@DateExpectedToLeave", SqlDbType.DateTime)
                {
                    Value = ip.DateExpectedToLeave
                },
            };

            // 3. add new parameter to command object
            cmd.Parameters.AddRange(prm.ToArray());

            //run
            SqlException res = InitializeDatabase.RunSqlCommand(cmd);

            return(res);
        }
Ejemplo n.º 4
0
        public SqlException Update(InPatient ip, int patientID)
        {
            string update = "UPDATE InPatient " +
                            "SET PatientNumber = @PatientNumber, WardNumber = @WardNumber, DatePlacedOnWaitingList = @DatePlacedOnWaitingList," +
                            "ExpectedDurationOfStay = @ExpectedDurationOfStay, ActualDateLeft = @ActualDateLeft, InWardOrWaitingList = @InWardOrWaitingList" +
                            "WHERE PatientNumber = @PatientID;";

            // 1. declare command object with parameter + insert query
            SqlCommand cmd = InitializeDatabase.CreateSqlCommand(update);


            // 2. define parameters used in command object
            List <SqlParameter> prm = new List <SqlParameter>()
            {
                new SqlParameter("@PatientNumber", SqlDbType.Int)
                {
                    Value = ip.PatientNumber
                },
                new SqlParameter("@WardNumber", SqlDbType.Int)
                {
                    Value = ip.WardNumber
                },
                new SqlParameter("@DatePlacedOnWaitingList", SqlDbType.DateTime)
                {
                    Value = ip.DatePlacedOnWaitingList
                },
                new SqlParameter("@ExpectedDurationOfStay", SqlDbType.Int)
                {
                    Value = ip.ExpectedDurationOfStay
                },
                new SqlParameter("@ActualDateLeft", SqlDbType.DateTime)
                {
                    Value = ip.ActualDateLeft
                },
                new SqlParameter("@PatientID", SqlDbType.Int)
                {
                    Value = patientID
                },
                new SqlParameter("@InWardOrWaitingList", SqlDbType.DateTime)
                {
                    Value = ip.InWardOrWaitingList
                }
            };

            // 3. add new parameter to command object
            cmd.Parameters.AddRange(prm.ToArray());

            //run
            SqlException res = InitializeDatabase.RunSqlCommand(cmd);

            return(res);
        }
Ejemplo n.º 5
0
        static void CreateInPatient()
        {
            InPatient inPatient = new InPatient();

            inPatient.ActualDateLeft          = new DateTime(2001, 10, 10);
            inPatient.DatePlacedOnWaitingList = new DateTime(2000, 09, 09);
            inPatient.ExpectedDurationOfStay  = 10;
            inPatient.InWardOrWaitingList     = "Ward";
            inPatient.DateExpectedToLeave     = new DateTime(2001, 10, 10);

            inPatient.PatientNumber = 4;
            inPatient.WardNumber    = 4;
            InPatientsController ipc   = new InPatientsController();
            SqlException         ipcer = ipc.Create(inPatient);
        }
Ejemplo n.º 6
0
 public ActionResult InPatient(InPatient c)
 {
     try
     {
         if (dl.InsertInPatient_Sp(c) > 0)
         {
             TempData["MSG"] = "Patient Added Successfully";
         }
     }
     catch (Exception ex)
     {
         TempData["MSG"] = "Something went wrong.";
         return(Redirect("/InPatient/InPatient"));
     }
     TempData["MSG"] = "Patient Added Successfully.";
     return(Redirect("/InPatient/InPatient"));
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Does the mapping from the FHIR input to the flat output that is stored into the SQL database
        /// </summary>
        /// <param name="inPatient">InPatient object built from the FHIR JSON</param>
        /// <param name="encounter">Encoutner object built from the FHIR JSON</param>
        /// <param name="observations">List of Observation objects built from the FHIR JSON</param>
        /// <param name="conditions">List of Conditions objects built from the FHIR JSON</param>
        /// <returns>patient</returns>
        public static Patient PopulatePatientData(InPatient inPatient, Encounter encounter, List <Observation> observations, List <Condition> conditions)
        {
            Patient patient = new Patient();

            // data from the patient input
            patient.FirstName  = inPatient.Name[0].Given[0];
            patient.MiddleName = inPatient.Name[0].Given[1];
            patient.LastName   = inPatient.Name[0].Family;
            patient.Gender     = inPatient.Gender;

            // data from the encounter input
            patient.Eid   = encounter.Id;
            patient.Vdate = encounter.Period.Start;
            // special handling because the data may be missing in the input FHIR JSON
            patient.Rcount = encounter.RCount == null ? "1" : encounter.RCount;
            patient.Facid  = encounter.ServiceProvider.Display;

            // data from the observations input
            patient.Hematocrit                = GetObservationValue(observations, "hematocrit");
            patient.Neutrophils               = GetObservationValue(observations, "neutrophils");
            patient.Sodium                    = GetObservationValue(observations, "sodium");
            patient.Glucose                   = GetObservationValue(observations, "glucose");
            patient.Bloodureanitro            = GetObservationValue(observations, "bloodureanitro");
            patient.Creatinine                = GetObservationValue(observations, "creatinine");
            patient.Bmi                       = GetObservationValue(observations, "bmi");
            patient.Pulse                     = (int)GetObservationValue(observations, "pulse");
            patient.Respiration               = GetObservationValue(observations, "respiration");
            patient.Secondarydiagnosisnonicd9 = (int)GetObservationValue(observations, "secondarydiagnosisnonicd9");

            // data from the conditions input
            patient.Dialysisrenalendstage = GetConditionValue(conditions, "dialysisrenalendstage");
            patient.Asthma                     = GetConditionValue(conditions, "asthma");
            patient.Irondef                    = GetConditionValue(conditions, "irondef");
            patient.Pneum                      = GetConditionValue(conditions, "pneum");
            patient.Substancedependence        = GetConditionValue(conditions, "substancedependence");
            patient.Psychologicaldisordermajor = GetConditionValue(conditions, "phsycholgicaldisordermajor");
            patient.Depress                    = GetConditionValue(conditions, "depress");
            patient.Psychother                 = GetConditionValue(conditions, "psychother");
            patient.Fibrosisandother           = GetConditionValue(conditions, "fibriosisandother");
            patient.Malnutrition               = GetConditionValue(conditions, "malnutrition");
            patient.Hemo = GetConditionValue(conditions, "hemo");

            return(patient);
        }
Ejemplo n.º 8
0
 public void UpdateInPatient(InPatient patient)
 {
     pat.UpdateInPatient(patient);
 }
Ejemplo n.º 9
0
 public void AddInPatient(InPatient patient)
 {
     pat.AddInPatient(patient);
 }
Ejemplo n.º 10
0
        protected override void Seed(PhMS2dot1Domain.Models.PhMS2dot1DomainContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
            var guid1  = Guid.Parse("a1ac51b3-8497-49be-920e-ea070b1f8067");
            var guid2  = Guid.Parse("bbf2c365-0efb-4ce6-a12d-c405910193ac");
            var guid3  = Guid.Parse("75eaccac-3a03-456d-a447-8f90c575d9ae");
            var guid4  = Guid.Parse("c9b4add3-32d6-4b5d-a2cc-6f929266b596");
            var guid5  = Guid.Parse("421a5dde-d9cf-4844-9bc0-ef3114331802");
            var guid6  = Guid.Parse("f17beda9-530b-4167-a138-3e10b9a0e0de");
            var guid7  = Guid.Parse("88090c83-6e1c-4380-a1b2-383d7d56cfd5");
            var guid8  = Guid.Parse("32276913-86b5-4723-b190-7a66b32b0df4");
            var guid9  = Guid.Parse("49f39f62-f491-4b68-9d88-8270cfd8f8bf");
            var guid10 = Guid.Parse("3abf4cb7-3aa2-4d9e-a982-f1c947b431ea");

            #region Patient
            var patient1 = new Patient
            {
                PatientID = guid1
            };
            var patient2 = new Patient
            {
                PatientID = guid2
            };
            var patient3 = new Patient
            {
                PatientID = guid3
            };
            context.Patients.AddOrUpdate(i => i.PatientID,
                                         patient1,
                                         patient2,
                                         patient3);
            context.SaveChanges();
            #endregion
            #region InPatient

            var inPatient1 = new InPatient
            {
                InPatientID    = guid1,
                PatientID      = patient1.PatientID,
                InDate         = DateTime.Parse("2016-7-1 10:00:00"),
                OutDate        = DateTime.Parse("2016-7-3 23:59:59"),
                Origin_DEPT_ID = 132,
                Origin_IN_DEPT = 132,
                Times          = 2,
            };
            var inPatient2 = new InPatient
            {
                InPatientID    = guid2,
                PatientID      = patient2.PatientID,
                InDate         = DateTime.Parse("2016-7-2 10:00:00"),
                OutDate        = DateTime.Parse("2016-7-3 23:59:59"),
                Origin_DEPT_ID = 132,
                Origin_IN_DEPT = 132,
                Times          = 2,
            };
            var inPatient3 = new InPatient
            {
                InPatientID    = guid3,
                PatientID      = patient3.PatientID,
                InDate         = DateTime.Parse("2016-7-2 10:00:00"),
                OutDate        = DateTime.Parse("2016-7-4 23:59:59"),
                Origin_DEPT_ID = 132,
                Origin_IN_DEPT = 132,
                Times          = 2,
            };
            context.InPatients.AddOrUpdate(i => i.InPatientID,
                                           inPatient1,
                                           inPatient2,
                                           inPatient3);
            context.SaveChanges();
            #endregion

            #region DrugRecord

            var drugRecord1 = new InPatientDrugRecord
            {
                InPatientDrugRecordID = guid1,
                InPatientID           = inPatient1.InPatientID,
                IsEssential           = true,
                Origin_KSSDJID        = 0,
                Origin_CJID           = 1,
                Origin_EXEC_DEPT      = 132,
                Origin_ORDER_DOC      = 15,
                ProductName           = "测试药品1",
                Origin_ORDER_USAGE    = "口服"
            };
            var drugRecord2 = new InPatientDrugRecord
            {
                InPatientDrugRecordID = guid2,
                InPatientID           = inPatient1.InPatientID,
                IsEssential           = true,
                Origin_KSSDJID        = 0,
                Origin_CJID           = 2,
                Origin_EXEC_DEPT      = 132,
                Origin_ORDER_DOC      = 15,
                ProductName           = "测试药品2",
                Origin_ORDER_USAGE    = "口服"
            };

            var drugRecord3 = new InPatientDrugRecord
            {
                InPatientDrugRecordID = guid3,
                InPatientID           = inPatient2.InPatientID,
                IsEssential           = true,
                Origin_KSSDJID        = 3,
                Origin_CJID           = 132,
                Origin_EXEC_DEPT      = 132,
                Origin_ORDER_DOC      = 15,
                ProductName           = "测试药品3",
                Origin_ORDER_USAGE    = "口服"
            };
            var drugRecord4 = new InPatientDrugRecord
            {
                InPatientDrugRecordID = guid4,
                InPatientID           = inPatient2.InPatientID,
                IsEssential           = true,
                Origin_KSSDJID        = 1,
                Origin_CJID           = 133,
                Origin_EXEC_DEPT      = 132,
                Origin_ORDER_DOC      = 15,
                ProductName           = "测试药品4",
                Origin_ORDER_USAGE    = "口服"
            };

            context.InPatientDrugRecords.AddOrUpdate(i => i.InPatientDrugRecordID,
                                                     drugRecord1,
                                                     drugRecord2,
                                                     drugRecord3,
                                                     drugRecord4);
            context.SaveChanges();
            #endregion

            #region DrugFee
            var drugFee1 = new DrugFee
            {
                DrugFeeID             = guid5,
                InPatientDrugRecordID = drugRecord1.InPatientDrugRecordID,
                ChargeTime            = DateTime.Parse("2016-7-2 10:00:00"),
                ActualPrice           = 15,
                Origin_Unit           = "包",
                Quantity  = 3,
                UnitPrice = 5.00M
            };
            var drugFee2 = new DrugFee
            {
                DrugFeeID             = guid6,
                InPatientDrugRecordID = drugRecord1.InPatientDrugRecordID,
                ChargeTime            = DateTime.Parse("2016-7-2 16:00:00"),
                ActualPrice           = 15,
                Origin_Unit           = "包",
                Quantity  = 3,
                UnitPrice = 5.00M
            };
            var drugFee3 = new DrugFee
            {
                DrugFeeID             = guid7,
                InPatientDrugRecordID = drugRecord2.InPatientDrugRecordID,
                ChargeTime            = DateTime.Parse("2016-7-2 16:00:00"),
                ActualPrice           = 15,
                Origin_Unit           = "包",
                Quantity  = 3,
                UnitPrice = 5.00M
            };
            var drugFee4 = new DrugFee
            {
                DrugFeeID             = guid8,
                InPatientDrugRecordID = drugRecord2.InPatientDrugRecordID,
                ChargeTime            = DateTime.Parse("2016-7-2 16:00:00"),
                ActualPrice           = 15,
                Origin_Unit           = "包",
                Quantity  = 3,
                UnitPrice = 5.00M
            };
            var drugFee5 = new DrugFee
            {
                DrugFeeID             = guid9,
                InPatientDrugRecordID = drugRecord3.InPatientDrugRecordID,
                ChargeTime            = DateTime.Parse("2016-7-2 16:00:00"),
                ActualPrice           = 15,
                Origin_Unit           = "包",
                Quantity  = 3,
                UnitPrice = 5.00M
            };
            var drugFee6 = new DrugFee
            {
                DrugFeeID             = guid10,
                InPatientDrugRecordID = drugRecord3.InPatientDrugRecordID,
                ChargeTime            = DateTime.Parse("2016-7-2 16:00:00"),
                ActualPrice           = 15,
                Origin_Unit           = "包",
                Quantity  = 3,
                UnitPrice = 5.00M
            };
            var drugFee7 = new DrugFee
            {
                DrugFeeID             = guid1,
                InPatientDrugRecordID = drugRecord4.InPatientDrugRecordID,
                ChargeTime            = DateTime.Parse("2016-7-2 16:00:00"),
                ActualPrice           = 15,
                Origin_Unit           = "包",
                Quantity  = 3,
                UnitPrice = 5.00M
            };
            var drugFee8 = new DrugFee
            {
                DrugFeeID             = guid2,
                InPatientDrugRecordID = drugRecord4.InPatientDrugRecordID,
                ChargeTime            = DateTime.Parse("2016-7-2 16:00:00"),
                ActualPrice           = 15,
                Origin_Unit           = "包",
                Quantity  = 3,
                UnitPrice = 5.00M
            };

            //测试找到OutDate在DrugFee之前,即在出院后仍有数据产生

            var drugFee9 = new DrugFee
            {
                DrugFeeID             = guid3,
                InPatientDrugRecordID = drugRecord4.InPatientDrugRecordID,
                ChargeTime            = DateTime.Parse("2016-7-2 16:00:00"),
                ActualPrice           = -15,
                Origin_Unit           = "包",
                Quantity  = -3,
                UnitPrice = 5.00M
            };
            var drugFee10 = new DrugFee
            {
                DrugFeeID             = guid4,
                InPatientDrugRecordID = drugRecord4.InPatientDrugRecordID,
                ChargeTime            = DateTime.Parse("2016-7-2 16:00:00"),
                ActualPrice           = -15,
                Origin_Unit           = "包",
                Quantity  = -3,
                UnitPrice = 5.00M
            };
            context.DrugFees.AddOrUpdate(i => i.DrugFeeID,
                                         drugFee1,
                                         drugFee2,
                                         drugFee3,
                                         drugFee4,
                                         drugFee5,
                                         drugFee6,
                                         drugFee7,
                                         drugFee8,
                                         drugFee9,
                                         drugFee10
                                         );
            context.SaveChanges();
            #endregion
        }
Ejemplo n.º 11
0
 public void AddInPatient(InPatient patient)
 {
     hos.InPatients.Add(patient);
     hos.SaveChanges();
 }
Ejemplo n.º 12
0
        public static async Task <object> Run([HttpTrigger("post")] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"{nameof(PatientAdmissionFunc)} triggered on {DateTime.UtcNow}");

            using (var patientTelemetry =
                       new PatientTelemetry(Environment.GetEnvironmentVariable(CommonConstants.InstumentationKey,
                                                                               EnvironmentVariableTarget.Process),
                                            nameof(PatientAdmissionFunc)))
            {
                try
                {
                    var userIdentity  = req.GetRequestContext().Principal.Identity as ClaimsIdentity;
                    var authorization = new ADAuthorization(userIdentity);

                    patientTelemetry.Caller(authorization.GetCallerName());

                    if (false == await authorization.Authorize(CommonConstants.CareLineManagerRole))
                    {
                        patientTelemetry.Unauthorized();
                        return(req.CreateResponse(HttpStatusCode.Unauthorized, new
                        {
                            result = $"Unauthorized {HttpStatusCode.Unauthorized}"
                        }));
                    }

                    // Get request data
                    dynamic data = await req.Content.ReadAsAsync <object>();

                    if (data == null)
                    {
                        return(req.CreateResponse(HttpStatusCode.BadRequest, new
                        {
                            result = "bad request"
                        }));
                    }

                    // convert the input to the corresponding objects
                    InPatient          inPatient    = data.patient.ToObject <InPatient>();
                    Encounter          encounter    = data.encounter.ToObject <Encounter>();
                    List <Observation> observations = data.observations.ToObject <List <Observation> >();
                    List <Condition>   conditions   = data.conditions.ToObject <List <Condition> >();

                    //get resource from key vault
                    var appResources = await Settings.GetAppResources();

                    new SqlEncryptionHelper();

                    //get patient data from FHIR data
                    var patient = FHIRMapping.PopulatePatientData(inPatient, encounter, observations, conditions);

                    try
                    {
                        var predictLengthOfStayService =
                            new PredictLengthOfStayService(appResources.PredictLengthOfStayServiceEndpoint,
                                                           appResources.PredictLengthOfStayServiceApiKey);

                        patientTelemetry.DependencyStarted();
                        patient.PredictedLengthOfStay = await predictLengthOfStayService.PredictLengthOfStay(patient);

                        patientTelemetry.DependencyCompleted(nameof(PredictLengthOfStayService),
                                                             "PredictLengthOfStay", true);
                    }
                    catch (PredictLengthOfStayServiceException ex)
                    {
                        patientTelemetry.DependencyCompleted(nameof(PredictLengthOfStayService),
                                                             "PredictLengthOfStay", false);
                        patientTelemetry.Error(ex);
                    }

                    var hospital = new Hospital(appResources.PatientDbConnectionString);
                    var id       = await hospital.AdmitPatient(patient);

                    if (id == -1)
                    {
                        return(req.CreateResponse(HttpStatusCode.OK, new
                        {
                            result = "invalid encounter id"
                        }));
                    }

                    var existingPatient = await hospital.GetPatient(id);

                    patientTelemetry.Success();
                    return(req.CreateResponse(HttpStatusCode.OK, new
                    {
                        encounterId = existingPatient.Eid,
                        name = $"{existingPatient.FirstName} {existingPatient.MiddleName} {existingPatient.LastName}",
                        gender = existingPatient.Gender,
                        admittedOn = existingPatient.Vdate
                    }));
                }
                catch (AuthorizationException ex)
                {
                    patientTelemetry.Error(ex);

                    return(req.CreateResponse(HttpStatusCode.ExpectationFailed, new
                    {
                        error = ex.Message
                    }));
                }
                catch (Exception ex)
                {
                    patientTelemetry.Error(ex);

                    return(req.CreateResponse(HttpStatusCode.InternalServerError, new
                    {
                        result = "failed"
                    }));
                }
            }
        }
        private AntibioticPerson GetAntibioticPerson(DateTime startTime, DateTime endTime, InPatient inPatient)
        {
            var result = new AntibioticPerson();
            PhMS2dot1DomainContext context = new PhMS2dot1DomainContext();

            var inPatientDrugRecords = new List <InPatientDrugRecord>();
            var drugRecords          = context.InPatientDrugRecords.Where(a => a.InPatientID == inPatient.InPatientID).ToList();

            foreach (var drugRecord in drugRecords)
            {
                var drugFees = context.DrugFees.Where(a => a.InPatientDrugRecordID == drugRecord.InPatientDrugRecordID && a.ChargeTime >= startTime && a.ChargeTime < endTime).ToList();
                drugRecord.DrugFees = drugFees;
                inPatientDrugRecords.Add(drugRecord);
            }
            context.Dispose();

            inPatient.InPatientDrugRecords = inPatientDrugRecords;
            //计算出当前inPatient中AntibioticPerson
            result = inPatient.AntibioticDepartmentPerson(startTime, endTime);
            return(result);
        }
Ejemplo n.º 14
0
        public static async Task <object> Run([HttpTrigger("put")] HttpRequestMessage req, TraceWriter log)
        {
            log.Info($"{nameof(PatientDischargeFunc)} triggered on {DateTime.UtcNow}");

            using (var patientTelemetry =
                       new PatientTelemetry(
                           Environment.GetEnvironmentVariable(CommonConstants.InstumentationKey, EnvironmentVariableTarget.Process),
                           nameof(PatientDischargeFunc)))
            {
                try
                {
                    //authorize user
                    var userIdentity  = req.GetRequestContext().Principal.Identity as ClaimsIdentity;
                    var authorization = new ADAuthorization(userIdentity);

                    patientTelemetry.Caller(authorization.GetCallerName());

                    if (false == await authorization.Authorize(CommonConstants.CareLineManagerRole))
                    {
                        patientTelemetry.Unauthorized();
                        return(req.CreateResponse(HttpStatusCode.Unauthorized, new
                        {
                            result = $"Unauthorized {HttpStatusCode.Unauthorized}"
                        }));
                    }

                    // Get request data
                    dynamic data = await req.Content.ReadAsAsync <object>();

                    if (data == null)
                    {
                        return(req.CreateResponse(HttpStatusCode.BadRequest, new
                        {
                            result = "bad request"
                        }));
                    }

                    // convert the input to the corresponding objects
                    InPatient inPatient  = data.patient.ToObject <InPatient>();
                    Encounter encounter  = data.encounter.ToObject <Encounter>();
                    int       patientEid = encounter.Id;

                    //get resources from key vault
                    var appResources = await Settings.GetAppResources();

                    new SqlEncryptionHelper();

                    patientTelemetry.DischargingPatient();

                    var hospital = new Hospital(appResources.PatientDbConnectionString);
                    var id       = await hospital.DischargePatient(patientEid, encounter.Period.End);

                    if (id == -1)
                    {
                        return(req.CreateResponse(HttpStatusCode.OK, new
                        {
                            error = "invalid encounter id"
                        }));
                    }

                    var existingPatient = await hospital.GetPatient(id);

                    patientTelemetry.PatientDischarged();

                    patientTelemetry.Success();
                    return(req.CreateResponse(HttpStatusCode.OK, new
                    {
                        encounterId = existingPatient.Eid,
                        name = $"{existingPatient.FirstName} {existingPatient.MiddleName} {existingPatient.LastName}",
                        dischargedOn = existingPatient.Discharged,
                        daysStayed = existingPatient.Lengthofstay
                    }));
                }
                catch (AuthorizationException ex)
                {
                    patientTelemetry.Error(ex);

                    return(req.CreateResponse(HttpStatusCode.ExpectationFailed, new
                    {
                        ex.Message
                    }));
                }
                catch (Exception ex)
                {
                    patientTelemetry.Error(ex);
                    return(req.CreateResponse(HttpStatusCode.InternalServerError, new
                    {
                        result = "failed"
                    }));
                }
            }
        }