public async Task <IHttpActionResult> PuttSourceOrganization(int id, tSourceOrganization SourceOrganization)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != SourceOrganization.ID)
            {
                return(BadRequest());
            }

            db.Entry(SourceOrganization).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!tSourceOrganizationExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public async Task <IHttpActionResult> GettSourceOrganization(int id)
        {
            tSourceOrganization tSourceOrganization = await db.tSourceOrganizations.FindAsync(id);

            if (tSourceOrganization == null)
            {
                return(NotFound());
            }

            return(Ok(tSourceOrganization));
        }
        public async Task <IHttpActionResult> PosttSourceOrganization(tSourceOrganization SourceOrganization)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.tSourceOrganizations.Add(SourceOrganization);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = SourceOrganization.ID }, SourceOrganization));
        }
        public async Task <IHttpActionResult> DeletetSourceOrganization(int id)
        {
            tSourceOrganization tSourceOrganization = await db.tSourceOrganizations.FindAsync(id);

            if (tSourceOrganization == null)
            {
                return(NotFound());
            }

            db.tSourceOrganizations.Remove(tSourceOrganization);
            await db.SaveChangesAsync();

            return(Ok(tSourceOrganization));
        }
        public IHttpActionResult Post(Sources value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.access_token == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        if (value.organization == null)
                        {
                            sourceServiceObj.TypeID = 2; //Wellness
                        }
                        else
                        {
                            sourceServiceObj.TypeID = 1; //Medical
                        }

                        sourceServiceObj.SourceID = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    //get user source service status
                    tUserSourceServiceStatus statusObj = null;
                    string strStatus = "";
                    if (value.syncStatus != null) //for wellness
                    {
                        strStatus = value.syncStatus.status;
                    }
                    else if (value.historySync != null) //for medical
                    {
                        strStatus = value.historySync.status;
                    }

                    statusObj = db.tUserSourceServiceStatuses.SingleOrDefault(x => x.Status == strStatus);

                    if (statusObj == null)
                    {
                        statusObj        = new tUserSourceServiceStatus();
                        statusObj.Status = strStatus;

                        db.tUserSourceServiceStatuses.Add(statusObj);
                    }

                    //Get credentials
                    tUserSourceService userSourceServiceObj = null;

                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.AccessToken == value.access_token &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = value.connectedSince;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now.AddDays(-30d);
                            userSourceServiceObj.LatestDateTime      = DateTime.Now;
                            userSourceServiceObj.StatusID            = statusObj.ID;
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                    }

                    foreach (string device in value.devices)
                    {
                        tSourceServiceDevice sourceServiceDevices = db.tSourceServiceDevices.SingleOrDefault(
                            x => x.Name == device);
                        if (sourceServiceDevices == null)
                        {
                            sourceServiceDevices      = new tSourceServiceDevice();
                            sourceServiceDevices.Name = device;

                            db.tSourceServiceDevices.Add(sourceServiceDevices);
                        }

                        tXrefUserSourceServiceDevice userdevices = db.tXrefUserSourceServiceDevices.SingleOrDefault(
                            x => x.UserSourceServiceID == userSourceServiceObj.ID &&
                            x.SourceServiceDeviceID == sourceServiceDevices.ID);
                        if (userdevices == null)
                        {
                            userdevices = new tXrefUserSourceServiceDevice();
                            userdevices.UserSourceServiceID   = userSourceServiceObj.ID;
                            userdevices.SourceServiceDeviceID = sourceServiceDevices.ID;

                            userdevices.tSourceServiceDevice = sourceServiceDevices;
                            userdevices.tUserSourceService   = userSourceServiceObj;

                            db.tXrefUserSourceServiceDevices.Add(userdevices);
                        }
                    }

                    tSourceOrganization userSourceOrganization = null;
                    if (value.organization != null)
                    {
                        //Get source org
                        userSourceOrganization = db.tSourceOrganizations
                                                 .Include("tOrganization")
                                                 .SingleOrDefault(x => x.SourceObjectID == value.organization.id);

                        if (userSourceOrganization == null)
                        {
                            //create org
                            tOrganization userOrganization = new tOrganization();
                            userOrganization.Name = value.organization.name;

                            //create new source org entry
                            userSourceOrganization = new tSourceOrganization();
                            userSourceOrganization.SourceObjectID  = value.organization.id;
                            userSourceOrganization.tOrganization   = userOrganization;
                            userSourceOrganization.OrganizationID  = userOrganization.ID;
                            userSourceOrganization.SourceServiceID = sourceServiceObj.ID;

                            db.tSourceOrganizations.Add(userSourceOrganization);
                        }
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userSourceServiceObj));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Beispiel #6
0
        public IHttpActionResult Post(Instructions value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.access_token == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 1; //Medical
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.AccessToken == value.access_token &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tSourceOrganization userSourceOrganization = null;
                    //Get source org via sourceserviceid [hack]
                    userSourceOrganization =
                        db.tSourceOrganizations.SingleOrDefault(x => x.SourceServiceID == sourceServiceObj.ID);

                    tUserInstruction userInstruction = null;
                    userInstruction = db.tUserInstructions
                                      .SingleOrDefault(x => x.SourceObjectID == value.Id);

                    if (userInstruction == null)
                    {
                        //insert
                        userInstruction = new tUserInstruction();
                        userInstruction.SourceObjectID = value.Id;
                        userInstruction.UserID         = credentialObj.UserID;
                        if (userSourceOrganization != null)
                        {
                            userInstruction.tSourceOrganization  = userSourceOrganization;
                            userInstruction.SourceOrganizationID = userSourceOrganization.ID;
                        }
                        userInstruction.tUserSourceService  = userSourceServiceObj;
                        userInstruction.UserSourceServiceID = userSourceServiceObj.ID;

                        userInstruction.Name = value.name;
                        userInstruction.Text = value.text;

                        userInstruction.StartDateTime  = value.dateTime;
                        userInstruction.SystemStatusID = 1;

                        db.tUserInstructions.Add(userInstruction);
                    }
                    else
                    {
                        //update
                        if (userSourceOrganization != null)
                        {
                            userInstruction.tSourceOrganization  = userSourceOrganization;
                            userInstruction.SourceOrganizationID = userSourceOrganization.ID;
                        }
                        userInstruction.tUserSourceService  = userSourceServiceObj;
                        userInstruction.UserSourceServiceID = userSourceServiceObj.ID;

                        userInstruction.Name = value.name;
                        userInstruction.Text = value.text;

                        userInstruction.StartDateTime       = value.dateTime;
                        userInstruction.LastUpdatedDateTime = DateTime.Now;
                    }

                    //codes
                    if (value.codes != null)
                    {
                        foreach (Codes code in value.codes)
                        {
                            if (code.code != null && code.codeSystem != null)
                            {
                                tCode instructionCode = null;
                                instructionCode = db.tCodes
                                                  .SingleOrDefault(x => x.Code == code.code && x.CodeSystem == code.codeSystem);
                                if (instructionCode == null)
                                {
                                    instructionCode                = new tCode();
                                    instructionCode.Code           = code.code;
                                    instructionCode.CodeSystem     = code.codeSystem;
                                    instructionCode.CodeSystemName = code.codeSystemName;
                                    instructionCode.Name           = code.name;

                                    db.tCodes.Add(instructionCode);
                                    db.SaveChanges();
                                }

                                tXrefUserInstructionsCode userXrefInsCodes = null;
                                userXrefInsCodes = db.tXrefUserInstructionsCodes
                                                   .SingleOrDefault(x => x.CodeID == instructionCode.ID &&
                                                                    x.UserInstructionID == userInstruction.ID);

                                if (userXrefInsCodes == null)
                                {
                                    userXrefInsCodes = new tXrefUserInstructionsCode();
                                    userXrefInsCodes.tUserInstruction  = userInstruction;
                                    userXrefInsCodes.tCode             = instructionCode;
                                    userXrefInsCodes.CodeID            = instructionCode.ID;
                                    userXrefInsCodes.UserInstructionID = userInstruction.ID;

                                    userInstruction.tXrefUserInstructionsCodes.Add(userXrefInsCodes);
                                }
                            }
                        }
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userInstruction));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
        public IHttpActionResult Post(TestResults value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.access_token == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 1; //Medical
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.AccessToken == value.access_token &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tSourceOrganization userSourceOrganization = null;
                    if (value.organization != null)
                    {
                        //Get source org
                        userSourceOrganization =
                            db.tSourceOrganizations.SingleOrDefault(x => x.SourceObjectID == value.organization.id);
                        if (userSourceOrganization == null)
                        {
                            //create org
                            tOrganization userOrganization = new tOrganization();
                            userOrganization.Name = value.organization.name;

                            //create new source org entry
                            userSourceOrganization = new tSourceOrganization();
                            userSourceOrganization.SourceObjectID  = value.organization.id;
                            userSourceOrganization.tOrganization   = userOrganization;
                            userSourceOrganization.OrganizationID  = userOrganization.ID;
                            userSourceOrganization.SourceServiceID = sourceServiceObj.ID;

                            db.tSourceOrganizations.Add(userSourceOrganization);
                        }
                    }

                    tProvider userOrderingProvider = new tProvider();
                    if (value.orderedBy != null)
                    {
                        userOrderingProvider.Name = value.orderedBy;
                        if (userSourceOrganization != null)
                        {
                            userOrderingProvider.tOrganization  = userSourceOrganization.tOrganization;
                            userOrderingProvider.OrganizationID = userSourceOrganization.OrganizationID;
                        }

                        db.tProviders.Add(userOrderingProvider);
                    }

                    tTestResultStatus testResultStatus = null;
                    if (value.status != null)
                    {
                        testResultStatus =
                            db.tTestResultStatuses.SingleOrDefault(x => x.Status == value.status);
                        if (testResultStatus == null)
                        {
                            testResultStatus        = new tTestResultStatus();
                            testResultStatus.Status = value.status;

                            db.tTestResultStatuses.Add(testResultStatus);
                        }
                    }

                    tUserTestResult userTestResult = null;
                    userTestResult = db.tUserTestResults
                                     .SingleOrDefault(x => x.SourceObjectID == value.Id);

                    if (userTestResult == null)
                    {
                        //insert
                        userTestResult = new tUserTestResult();
                        userTestResult.SourceObjectID = value.Id;
                        userTestResult.UserID         = credentialObj.UserID;
                        if (userSourceOrganization != null)
                        {
                            userTestResult.tSourceOrganization  = userSourceOrganization;
                            userTestResult.SourceOrganizationID = userSourceOrganization.ID;
                        }
                        userTestResult.tUserSourceService  = userSourceServiceObj;
                        userTestResult.UserSourceServiceID = userSourceServiceObj.ID;
                        userTestResult.Name = value.name;
                        if (value.orderedBy != null)
                        {
                            userTestResult.tProvider          = userOrderingProvider;
                            userTestResult.OrderingProviderID = userOrderingProvider.ID;
                        }
                        if (testResultStatus != null)
                        {
                            userTestResult.tTestResultStatus = testResultStatus;
                            userTestResult.StatusID          = testResultStatus.ID;
                        }
                        userTestResult.Comments       = value.comments;
                        userTestResult.Narrative      = value.narrative;
                        userTestResult.Impression     = value.impression;
                        userTestResult.Transcriptions = value.transcriptions;
                        userTestResult.ResultDateTime = value.resultDateTime;
                        userTestResult.SystemStatusID = 1;


                        db.tUserTestResults.Add(userTestResult);
                    }
                    else
                    {
                        //update
                        if (userSourceOrganization != null)
                        {
                            userTestResult.tSourceOrganization  = userSourceOrganization;
                            userTestResult.SourceOrganizationID = userSourceOrganization.ID;
                        }
                        userTestResult.tUserSourceService  = userSourceServiceObj;
                        userTestResult.UserSourceServiceID = userSourceServiceObj.ID;
                        userTestResult.Name = value.name;
                        if (value.orderedBy != null)
                        {
                            userTestResult.tProvider          = userOrderingProvider;
                            userTestResult.OrderingProviderID = userOrderingProvider.ID;
                        }
                        if (testResultStatus != null)
                        {
                            userTestResult.tTestResultStatus = testResultStatus;
                            userTestResult.StatusID          = testResultStatus.ID;
                        }
                        userTestResult.Comments            = value.comments;
                        userTestResult.Narrative           = value.narrative;
                        userTestResult.Impression          = value.impression;
                        userTestResult.Transcriptions      = value.transcriptions;
                        userTestResult.ResultDateTime      = value.resultDateTime;
                        userTestResult.LastUpdatedDateTime = DateTime.Now;

                        userTestResult.tTestResultStatus = testResultStatus;
                    }

                    if (value.codes != null)
                    {
                        foreach (Codes code in value.codes)
                        {
                            if (code.code != null && code.codeSystem != null)
                            {
                                tCode testResultCode = null;
                                testResultCode =
                                    db.tCodes.SingleOrDefault(
                                        x => x.Code == code.code && x.CodeSystem == code.codeSystem);
                                if (testResultCode == null)
                                {
                                    testResultCode                = new tCode();
                                    testResultCode.Code           = code.code;
                                    testResultCode.CodeSystem     = code.codeSystem;
                                    testResultCode.CodeSystemName = code.codeSystemName;
                                    testResultCode.Name           = code.name;

                                    db.tCodes.Add(testResultCode);
                                    db.SaveChanges();
                                }

                                tXrefUserTestResultsCode userXrefTestCodes = null;
                                userXrefTestCodes =
                                    db.tXrefUserTestResultsCodes.SingleOrDefault(
                                        x => x.CodeID == testResultCode.ID && x.UserTestResultID == userTestResult.ID);
                                if (userXrefTestCodes == null)
                                {
                                    userXrefTestCodes = new tXrefUserTestResultsCode();
                                    userXrefTestCodes.tUserTestResult  = userTestResult;
                                    userXrefTestCodes.tCode            = testResultCode;
                                    userXrefTestCodes.CodeID           = testResultCode.ID;
                                    userXrefTestCodes.UserTestResultID = userTestResult.ID;

                                    db.tXrefUserTestResultsCodes.Add(userXrefTestCodes);
                                }
                            }
                        }
                    }
                    db.SaveChanges();

                    //components & component codes
                    if (value.components != null)
                    {
                        foreach (Components component in value.components)
                        {
                            tUserTestResultComponent userTestResultComponent = null;
                            userTestResultComponent =
                                db.tUserTestResultComponents.SingleOrDefault(x => x.TestResultID == userTestResult.ID &&
                                                                             x.Name == component.name);
                            if (userTestResultComponent == null)
                            {
                                userTestResultComponent = new tUserTestResultComponent();
                                userTestResultComponent.tUserTestResult = userTestResult;
                                userTestResultComponent.TestResultID    = userTestResult.ID;
                                userTestResultComponent.SystemStatusID  = 1;
                            }

                            userTestResultComponent.Name = component.name;
                            if (component.value == null)
                            {
                                userTestResultComponent.Value = "No Data";
                            }
                            else
                            {
                                if (component.unit == null && component.value.Split(' ').Length == 2)
                                {
                                    StringParser sParse = FindUOM(component.value);
                                    if (sParse.matchCount == 1)
                                    {
                                        userTestResultComponent.Value = sParse.newValue;
                                        userTestResultComponent.UOMID = sParse.uomID;
                                        component.unit = sParse.newUnit;
                                    }
                                    else
                                    {
                                        userTestResultComponent.Value = component.value;
                                    }
                                }
                                else
                                {
                                    userTestResultComponent.Value = component.value;
                                }
                            }
                            userTestResultComponent.LowValue  = component.low;
                            userTestResultComponent.HighValue = component.high;
                            userTestResultComponent.RefRange  = component.refRange;
                            userTestResultComponent.Comments  = component.componentComments;

                            //UOM
                            if (component.unit != null)
                            {
                                tUnitsOfMeasure uom = null;
                                uom = db.tUnitsOfMeasures.SingleOrDefault(x => x.UnitOfMeasure == component.unit);
                                if (uom == null)
                                {
                                    uom = new tUnitsOfMeasure();
                                    uom.UnitOfMeasure = component.unit;

                                    db.tUnitsOfMeasures.Add(uom);
                                    db.SaveChanges();
                                }

                                userTestResultComponent.tUnitsOfMeasure = uom;
                                userTestResultComponent.UOMID           = uom.ID;
                            }
                            if (userTestResultComponent.ObjectID == null)
                            {
                                db.tUserTestResultComponents.Add(userTestResultComponent);
                            }

                            //component codes
                            foreach (Codes code in component.codes)
                            {
                                if (code.code != null && code.codeSystem != null)
                                {
                                    tCode componentCode = null;
                                    componentCode =
                                        db.tCodes.SingleOrDefault(
                                            x => x.Code == code.code && x.CodeSystem == code.codeSystem);
                                    if (componentCode == null)
                                    {
                                        componentCode                = new tCode();
                                        componentCode.Code           = code.code;
                                        componentCode.CodeSystem     = code.codeSystem;
                                        componentCode.CodeSystemName = code.codeSystemName;
                                        componentCode.Name           = code.name;

                                        db.tCodes.Add(componentCode);
                                        db.SaveChanges();
                                    }

                                    tXrefUserTestResultComponentsCode userXrefComponentCodes = null;
                                    userXrefComponentCodes =
                                        db.tXrefUserTestResultComponentsCodes.SingleOrDefault(
                                            x =>
                                            x.CodeID == componentCode.ID &&
                                            x.UserTestResultComponentID == userTestResultComponent.ID);
                                    if (userXrefComponentCodes == null)
                                    {
                                        userXrefComponentCodes = new tXrefUserTestResultComponentsCode();
                                        userXrefComponentCodes.tUserTestResultComponent = userTestResultComponent;
                                        userXrefComponentCodes.tCode  = componentCode;
                                        userXrefComponentCodes.CodeID = componentCode.ID;
                                        userXrefComponentCodes.UserTestResultComponentID = userTestResultComponent.ID;

                                        db.tXrefUserTestResultComponentsCodes.Add(userXrefComponentCodes);
                                    }
                                }
                            }
                        }
                    }

                    //Recipients
                    if (value.recipients != null)
                    {
                        foreach (Recipients recip in value.recipients)
                        {
                            tProvider userProviderRecipients = null;
                            userProviderRecipients =
                                db.tProviders.SingleOrDefault(x => x.SourceProviderID == recip.objectID);
                            if (userProviderRecipients == null)
                            {
                                userProviderRecipients = new tProvider();
                                userProviderRecipients.SourceProviderID = recip.objectID;
                                userProviderRecipients.Name             = recip.name;
                                if (userSourceOrganization != null)
                                {
                                    userProviderRecipients.OrganizationID = userSourceOrganization.OrganizationID;
                                }

                                db.tProviders.Add(userProviderRecipients);
                            }

                            tXrefUserTestResultRecipientsProvider userXrefProviderRecip =
                                new tXrefUserTestResultRecipientsProvider();
                            userXrefProviderRecip.tProvider        = userProviderRecipients;
                            userXrefProviderRecip.tUserTestResult  = userTestResult;
                            userXrefProviderRecip.IsPCP            = recip.isPCP;
                            userXrefProviderRecip.ProviderID       = userProviderRecipients.ID;
                            userXrefProviderRecip.UserTestResultID = userTestResult.ID;

                            db.tXrefUserTestResultRecipientsProviders.Add(userXrefProviderRecip);
                        }
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userTestResult));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
        private tUserAllergy UpdateAllergy(tUserAllergy userAllergy,
                                           Allergies newValues,
                                           Reaction userReaction,
                                           tCredential credentialObj,
                                           tSourceOrganization userSourceOrganization)
        {
            userAllergy.LastUpdateDateTime = DateTime.Now;

            //allergen name
            tAllergen allergenObj = db.tAllergens
                                    .Include("tAllergen1")
                                    .SingleOrDefault(x => x.Name == newValues.name);

            if (allergenObj == null)
            {
                allergenObj      = new tAllergen();
                allergenObj.Name = newValues.name;
                db.tAllergens.Add(allergenObj);
                db.SaveChanges();
            }

            int tmpAllergyID = 0;

            if (allergenObj.ParentID != null)
            {
                tmpAllergyID = allergenObj.tAllergen1.ID;
            }
            else
            {
                tmpAllergyID = allergenObj.ID;
            }

            //allergen changed?
            if (userAllergy.AllergenID != tmpAllergyID)
            {
                //invalidate current and add new
                userAllergy.SystemStatusID = 4;
                return(CreateAllergy(new tUserAllergy(), newValues, userReaction, credentialObj, userAllergy.tUserSourceService, userAllergy.tSourceOrganization));
            }
            else//same allergen
            {
                //status
                if (newValues.status != null)
                {
                    tAllergyStatus allergyStatusObj = db.tAllergyStatuses
                                                      .Include("tAllergyStatus1")
                                                      .SingleOrDefault(x => x.Status == newValues.status);
                    if (allergyStatusObj == null)
                    {
                        allergyStatusObj        = new tAllergyStatus();
                        allergyStatusObj.Status = newValues.status;
                        db.tAllergyStatuses.Add(allergyStatusObj);

                        userAllergy.tAllergyStatus = allergyStatusObj;
                        userAllergy.StatusID       = allergyStatusObj.ID;
                    }
                    else //check to see if reaction has a mapped parent
                    {
                        if (allergyStatusObj.ParentID != null)
                        {
                            userAllergy.tAllergyStatus = allergyStatusObj.tAllergyStatus1;
                            userAllergy.StatusID       = allergyStatusObj.tAllergyStatus1.ID;
                        }
                        else
                        {
                            userAllergy.tAllergyStatus = allergyStatusObj;
                            userAllergy.StatusID       = allergyStatusObj.ID;
                        }
                    }
                }

                //severity
                if (newValues.severity != null)
                {
                    tAllergySeverity allergySeverity = db.tAllergySeverities
                                                       .Include("tAllergySeverity1")
                                                       .SingleOrDefault(x => x.Severity == newValues.severity);
                    if (allergySeverity == null)
                    {
                        allergySeverity          = new tAllergySeverity();
                        allergySeverity.Severity = newValues.severity;
                        db.tAllergySeverities.Add(allergySeverity);

                        userAllergy.tAllergySeverity = allergySeverity;
                        userAllergy.SeverityID       = allergySeverity.ID;
                    }
                    else //check to see if reaction has a mapped parent
                    {
                        if (allergySeverity.ParentID != null)
                        {
                            userAllergy.tAllergySeverity = allergySeverity.tAllergySeverity1;
                            userAllergy.SeverityID       = allergySeverity.tAllergySeverity1.ID;
                        }
                        else
                        {
                            userAllergy.tAllergySeverity = allergySeverity;
                            userAllergy.SeverityID       = allergySeverity.ID;
                        }
                    }
                }

                //Dates
                if (newValues.dateRange.start != null && newValues.dateRange.start != DateTime.MinValue)
                {
                    userAllergy.StartDateTime = newValues.dateRange.start;
                }
                if (newValues.dateRange.end != null && newValues.dateRange.end != DateTime.MinValue)
                {
                    userAllergy.EndDateTime = newValues.dateRange.end;
                }

                //Allergy codes
                if (newValues.codes != null)
                {
                    foreach (Codes code in newValues.codes)
                    {
                        if (code.code != null && code.codeSystem != null)
                        {
                            tCode AllergyCode = null;
                            AllergyCode = db.tCodes
                                          .SingleOrDefault(x => x.Code == code.code && x.CodeSystem == code.codeSystem);

                            if (AllergyCode == null)
                            {
                                AllergyCode                = new tCode();
                                AllergyCode.Code           = code.code;
                                AllergyCode.CodeSystem     = code.codeSystem;
                                AllergyCode.CodeSystemName = code.codeSystemName;
                                AllergyCode.Name           = code.name;

                                db.tCodes.Add(AllergyCode);
                                db.SaveChanges();
                            }

                            tXrefUserAllergiesCode userXrefAllergensCodes = null;
                            userXrefAllergensCodes = db.tXrefUserAllergiesCodes
                                                     .SingleOrDefault(x => x.CodeID == AllergyCode.ID &&
                                                                      x.UserAllergiesID == userAllergy.ID);

                            if (userXrefAllergensCodes == null)
                            {
                                userXrefAllergensCodes = new tXrefUserAllergiesCode();
                                userXrefAllergensCodes.tUserAllergy    = userAllergy;
                                userXrefAllergensCodes.tCode           = AllergyCode;
                                userXrefAllergensCodes.CodeID          = AllergyCode.ID;
                                userXrefAllergensCodes.UserAllergiesID = userAllergy.ID;

                                db.tXrefUserAllergiesCodes.Add(userXrefAllergensCodes);
                            }
                        }
                    }
                }
            }

            //reactions
            if (userReaction != null)
            {
                tReaction reactionObj = null;

                if (userReaction.reactionType.name != null)
                {
                    reactionObj = db.tReactions
                                  .Include("tReaction1")
                                  .SingleOrDefault(x => x.Name == userReaction.reactionType.name);
                    if (reactionObj == null)
                    {
                        reactionObj                = new tReaction();
                        reactionObj.Name           = userReaction.reactionType.name;
                        reactionObj.ReactionTypeID = 1; //unspecified
                        db.tReactions.Add(reactionObj);

                        userAllergy.tReaction  = reactionObj;
                        userAllergy.ReactionID = reactionObj.ID;
                    }
                    else //check to see if reaction has a mapped parent
                    {
                        if (reactionObj.ParentID != null)
                        {
                            userAllergy.tReaction  = reactionObj.tReaction1;
                            userAllergy.ReactionID = reactionObj.tReaction1.ID;
                        }
                        else
                        {
                            userAllergy.tReaction  = reactionObj;
                            userAllergy.ReactionID = reactionObj.ID;
                        }
                    }
                }

                //Reaction codes
                if (userReaction.reactionType.codes != null)
                {
                    foreach (Codes code in userReaction.reactionType.codes)
                    {
                        if (code.code != null && code.codeSystem != null)
                        {
                            tCode ReactionCode = null;
                            ReactionCode = db.tCodes
                                           .SingleOrDefault(x => x.Code == code.code && x.CodeSystem == code.codeSystem);

                            if (ReactionCode == null)
                            {
                                ReactionCode                = new tCode();
                                ReactionCode.Code           = code.code;
                                ReactionCode.CodeSystem     = code.codeSystem;
                                ReactionCode.CodeSystemName = code.codeSystemName;
                                ReactionCode.Name           = code.name;

                                db.tCodes.Add(ReactionCode);
                                db.SaveChanges();
                            }

                            tXrefReactionsCode userXrefReactionsCode = null;
                            userXrefReactionsCode = db.tXrefReactionsCodes
                                                    .SingleOrDefault(x => x.CodeID == ReactionCode.ID &&
                                                                     x.ReactionID == reactionObj.ID);

                            if (userXrefReactionsCode == null)
                            {
                                userXrefReactionsCode            = new tXrefReactionsCode();
                                userXrefReactionsCode.tReaction  = reactionObj;
                                userXrefReactionsCode.tCode      = ReactionCode;
                                userXrefReactionsCode.CodeID     = ReactionCode.ID;
                                userXrefReactionsCode.ReactionID = reactionObj.ID;

                                db.tXrefReactionsCodes.Add(userXrefReactionsCode);
                            }
                        }
                    }
                }
            }
            return(userAllergy);
        }
        public IHttpActionResult Post(Allergies value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.access_token == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 1; //Medical
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.AccessToken == value.access_token &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tSourceOrganization userSourceOrganization = null;
                    if (value.organization != null)
                    {
                        //Get source org
                        userSourceOrganization = db.tSourceOrganizations
                                                 .Include("tOrganization")
                                                 .SingleOrDefault(x => x.SourceObjectID == value.organization.id);

                        if (userSourceOrganization == null)
                        {
                            //create org
                            tOrganization userOrganization = new tOrganization();
                            userOrganization.Name = value.organization.name;

                            //create new source org entry
                            userSourceOrganization = new tSourceOrganization();
                            userSourceOrganization.SourceObjectID  = value.organization.id;
                            userSourceOrganization.tOrganization   = userOrganization;
                            userSourceOrganization.OrganizationID  = userOrganization.ID;
                            userSourceOrganization.SourceServiceID = sourceServiceObj.ID;

                            db.tSourceOrganizations.Add(userSourceOrganization);
                        }
                    }

                    List <tUserAllergy> userAllergies = db.tUserAllergies
                                                        .Include("tReaction")
                                                        .Where(x => x.SourceObjectID == value.Id).ToList() ?? new List <tUserAllergy>();

                    tUserAllergy newUserAllergy = new tUserAllergy();

                    //matching records for the SourceObjectID provided - do update & possibly insert
                    if (userAllergies.Count > 0)
                    {
                        //if reactions
                        if (value.reactionsFull != null)
                        {
                            foreach (Reaction allergyReaction in value.reactionsFull)
                            {
                                bool foundMatch = false;
                                //loop to find existing allergy with current reaction
                                foreach (tUserAllergy userAllergy in userAllergies)
                                {
                                    if (userAllergy.tReaction != null &&
                                        userAllergy.tReaction.Name == allergyReaction.name)
                                    {
                                        //update allergy/reaction with new data
                                        UpdateAllergy(newUserAllergy, value, allergyReaction, credentialObj, userSourceOrganization);

                                        foundMatch = true;
                                    }
                                }

                                //insert new allergy/reaction
                                if (foundMatch == false)
                                {
                                    newUserAllergy = CreateAllergy(newUserAllergy, value, null, credentialObj,
                                                                   userSourceServiceObj, userSourceOrganization);

                                    userAllergies.Add(newUserAllergy);
                                }
                            }
                        }
                        else if (userAllergies.Count == 1 && value.reactionsFull == null) //one allergen and no reactions
                        {
                            //update allergy with new data
                            UpdateAllergy(userAllergies[0], value, null, credentialObj, userSourceOrganization);
                        }
                        else
                        {
                            //this means multiple entries were made for same allergy with each reaction previously,
                            //but now no reactions are listed in new values. We cant do anything because we dont know
                            //which to invalidate or update.
                        }
                    }
                    //no existing entries - do insert
                    else
                    {
                        //if reactions
                        if (value.reactionsFull != null)
                        {
                            foreach (Reaction allergyReaction in value.reactionsFull)
                            {
                                newUserAllergy = CreateAllergy(newUserAllergy, value, allergyReaction, credentialObj, userSourceServiceObj, userSourceOrganization);
                            }

                            userAllergies.Add(newUserAllergy);
                        }
                        else //no reactions
                        {
                            newUserAllergy = CreateAllergy(newUserAllergy, value, null, credentialObj, userSourceServiceObj, userSourceOrganization);

                            userAllergies.Add(newUserAllergy);
                        }
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userAllergies));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
        public IHttpActionResult Post(Narratives value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.access_token == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 1; //Medical
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.AccessToken == value.access_token &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tSourceOrganization userSourceOrganization = null;
                    if (value.organization != null)
                    {
                        //Get source org
                        userSourceOrganization =
                            db.tSourceOrganizations.SingleOrDefault(x => x.SourceObjectID == value.organization.id);
                        if (userSourceOrganization == null)
                        {
                            //create org
                            tOrganization userOrganization = new tOrganization();
                            userOrganization.Name = value.organization.name;

                            //create new source org entry
                            userSourceOrganization = new tSourceOrganization();
                            userSourceOrganization.SourceObjectID  = value.organization.id;
                            userSourceOrganization.tOrganization   = userOrganization;
                            userSourceOrganization.OrganizationID  = userOrganization.ID;
                            userSourceOrganization.SourceServiceID = sourceServiceObj.ID;

                            db.tSourceOrganizations.Add(userSourceOrganization);
                        }
                    }

                    tProvider userProvider = new tProvider();
                    if (value.author != null)
                    {
                        userProvider.Name = value.author;
                        if (userSourceOrganization != null)
                        {
                            userProvider.tOrganization  = userSourceOrganization.tOrganization;
                            userProvider.OrganizationID = userSourceOrganization.OrganizationID;
                        }

                        db.tProviders.Add(userProvider);
                    }

                    tUserNarrative userNarrative = null;
                    userNarrative = db.tUserNarratives
                                    .SingleOrDefault(x => x.SourceObjectID == value.Id);

                    if (userNarrative == null)
                    {
                        //insert
                        userNarrative = new tUserNarrative();
                        userNarrative.SourceObjectID = value.Id;
                        userNarrative.UserID         = credentialObj.UserID;
                        if (userSourceOrganization != null)
                        {
                            userNarrative.tSourceOrganization  = userSourceOrganization;
                            userNarrative.SourceOrganizationID = userSourceOrganization.ID;
                        }
                        userNarrative.tUserSourceService  = userSourceServiceObj;
                        userNarrative.UserSourceServiceID = userSourceServiceObj.ID;

                        if (value.author != null)
                        {
                            userNarrative.tProvider  = userProvider;
                            userNarrative.ProviderID = userProvider.ID;
                        }

                        userNarrative.StartDateTime  = value.dateTime;
                        userNarrative.SystemStatusID = 1;

                        int seqNum = 0;
                        foreach (entries narrativeEntry in value.entries)
                        {
                            tUserNarrativeEntry userNarrativeEntry = new tUserNarrativeEntry();
                            userNarrativeEntry.SectionSeqNum  = seqNum++;
                            userNarrativeEntry.SectionText    = narrativeEntry.text;
                            userNarrativeEntry.SectionTitle   = narrativeEntry.title;
                            userNarrativeEntry.NarrativeID    = userNarrative.ID;
                            userNarrativeEntry.SystemStatusID = 1;
                            userNarrative.tUserNarrativeEntries.Add(userNarrativeEntry);
                        }

                        db.tUserNarratives.Add(userNarrative);
                    }
                    else
                    {
                        //update
                        if (userSourceOrganization != null)
                        {
                            userNarrative.tSourceOrganization  = userSourceOrganization;
                            userNarrative.SourceOrganizationID = userSourceOrganization.ID;
                        }
                        userNarrative.tUserSourceService  = userSourceServiceObj;
                        userNarrative.UserSourceServiceID = userSourceServiceObj.ID;

                        if (value.author != null)
                        {
                            userNarrative.tProvider  = userProvider;
                            userNarrative.ProviderID = userProvider.ID;
                        }

                        userNarrative.StartDateTime = value.dateTime;

                        List <tUserNarrativeEntry> existingEntries = db.tUserNarrativeEntries
                                                                     .Where(x => x.NarrativeID == userNarrative.ID).ToList();
                        existingEntries.ForEach(e => e.SystemStatusID = 4);

                        int seqNum = 0;
                        foreach (entries narrativeEntry in value.entries)
                        {
                            tUserNarrativeEntry userNarrativeEntry = new tUserNarrativeEntry();
                            userNarrativeEntry.SectionSeqNum  = seqNum++;
                            userNarrativeEntry.SectionText    = narrativeEntry.text;
                            userNarrativeEntry.SectionTitle   = narrativeEntry.title;
                            userNarrativeEntry.NarrativeID    = userNarrative.ID;
                            userNarrativeEntry.SystemStatusID = 1;
                            userNarrative.tUserNarrativeEntries.Add(userNarrativeEntry);
                        }

                        userNarrative.LastUpdatedDateTime = DateTime.Now;
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userNarrative));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Beispiel #11
0
        public IHttpActionResult Post(Vitals value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.access_token == null)
            {
                return(BadRequest());
            }

            if (value.results == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 1; //Medical
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.AccessToken == value.access_token &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tSourceOrganization userSourceOrganization = null;
                    if (value.organization != null)
                    {
                        //Get source org
                        userSourceOrganization = db.tSourceOrganizations
                                                 .Include("tOrganization")
                                                 .SingleOrDefault(x => x.SourceObjectID == value.organization.id);

                        if (userSourceOrganization == null)
                        {
                            //create org
                            tOrganization userOrganization = new tOrganization();
                            userOrganization.Name = value.organization.name;

                            //create new source org entry
                            userSourceOrganization = new tSourceOrganization();
                            userSourceOrganization.SourceObjectID  = value.organization.id;
                            userSourceOrganization.tOrganization   = userOrganization;
                            userSourceOrganization.OrganizationID  = userOrganization.ID;
                            userSourceOrganization.SourceServiceID = sourceServiceObj.ID;

                            db.tSourceOrganizations.Add(userSourceOrganization);
                        }
                    }
                    else
                    {
                        //Get source org via sourceserviceid [hack]
                        userSourceOrganization =
                            db.tSourceOrganizations.SingleOrDefault(x => x.SourceServiceID == sourceServiceObj.ID);
                    }

                    tProvider userApprovingProvider = null;
                    if (value.author != null)
                    {
                        userApprovingProvider =
                            db.tProviders.SingleOrDefault(x => x.Name == value.author && x.OrganizationID == userSourceOrganization.OrganizationID);

                        if (userApprovingProvider == null)
                        {
                            userApprovingProvider      = new tProvider();
                            userApprovingProvider.Name = value.author;

                            if (userSourceOrganization != null)
                            {
                                userApprovingProvider.tOrganization  = userSourceOrganization.tOrganization;
                                userApprovingProvider.OrganizationID = userSourceOrganization.tOrganization.ID;
                            }

                            db.tProviders.Add(userApprovingProvider);
                        }
                    }

                    List <tUserVital> userVitalsList = new List <tUserVital>();

                    //loop
                    foreach (var result in value.results)
                    {
                        tUserVital userVitals = null;
                        userVitals = db.tUserVitals
                                     .SingleOrDefault(x => x.SourceObjectID == value.Id && x.Name == result.name);

                        //insert
                        if (userVitals == null)
                        {
                            userVitals = new tUserVital();
                            userVitals.SourceObjectID = value.Id;
                            userVitals.UserID         = credentialObj.UserID;
                            if (userSourceOrganization != null)
                            {
                                userVitals.tSourceOrganization  = userSourceOrganization;
                                userVitals.SourceOrganizationID = userSourceOrganization.ID;
                            }
                            userVitals.tUserSourceService  = userSourceServiceObj;
                            userVitals.UserSourceServiceID = userSourceServiceObj.ID;

                            if (value.author != null)
                            {
                                userVitals.tProvider  = userApprovingProvider;
                                userVitals.ProviderID = userApprovingProvider.ID;
                            }

                            userVitals.Name           = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(result.name.ToLower());
                            userVitals.ResultDateTime = value.dateTime;
                            userVitals.SystemStatusID = 1;

                            //parse value
                            if (result.value == null)
                            {
                                userVitals.Value = 0M;
                            }
                            else
                            {
                                if (result.unit == null && result.value.Split(' ').Length == 2)
                                {
                                    StringParser sParse = FindUOM(result.value);
                                    if (sParse.matchCount == 1)
                                    {
                                        userVitals.Value = decimal.Parse(sParse.newValue);
                                        userVitals.UOMID = sParse.uomID;
                                        result.unit      = sParse.newUnit;
                                    }
                                    else
                                    {
                                        userVitals.Value = decimal.Parse(result.value);
                                    }
                                }
                                else
                                {
                                    userVitals.Value = decimal.Parse(result.value);
                                }
                            }

                            //UOM
                            if (result.unit != null)
                            {
                                tUnitsOfMeasure uom = null;
                                uom = db.tUnitsOfMeasures.SingleOrDefault(x => x.UnitOfMeasure == result.unit);
                                if (uom == null)
                                {
                                    uom = new tUnitsOfMeasure();
                                    uom.UnitOfMeasure = result.unit;

                                    db.tUnitsOfMeasures.Add(uom);
                                    db.SaveChanges();
                                }

                                userVitals.tUnitsOfMeasure = uom;
                                userVitals.UOMID           = uom.ID;
                            }

                            //codes
                            if (result.codes != null)
                            {
                                foreach (Codes code in result.codes)
                                {
                                    if (code.code != null && code.codeSystem != null)
                                    {
                                        tCode vitalCode = null;
                                        vitalCode = db.tCodes
                                                    .SingleOrDefault(x => x.Code == code.code && x.CodeSystem == code.codeSystem);
                                        if (vitalCode == null)
                                        {
                                            vitalCode                = new tCode();
                                            vitalCode.Code           = code.code;
                                            vitalCode.CodeSystem     = code.codeSystem;
                                            vitalCode.CodeSystemName = code.codeSystemName;
                                            vitalCode.Name           = code.name;

                                            db.tCodes.Add(vitalCode);
                                            db.SaveChanges();
                                        }

                                        tXrefUserVitalsCode userXrefVitalsCodes = null;
                                        userXrefVitalsCodes = db.tXrefUserVitalsCodes
                                                              .SingleOrDefault(x => x.CodeID == vitalCode.ID &&
                                                                               x.UserVitalsID == userVitals.ID);

                                        if (userXrefVitalsCodes == null)
                                        {
                                            userXrefVitalsCodes              = new tXrefUserVitalsCode();
                                            userXrefVitalsCodes.tUserVital   = userVitals;
                                            userXrefVitalsCodes.tCode        = vitalCode;
                                            userXrefVitalsCodes.CodeID       = vitalCode.ID;
                                            userXrefVitalsCodes.UserVitalsID = userVitals.ID;

                                            db.tXrefUserVitalsCodes.Add(userXrefVitalsCodes);
                                        }
                                    }
                                }
                            }

                            db.tUserVitals.Add(userVitals);
                        }
                        else
                        {
                            //update
                            if (value.author != null)
                            {
                                userVitals.tProvider  = userApprovingProvider;
                                userVitals.ProviderID = userApprovingProvider.ID;
                            }

                            userVitals.Name                = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(result.name.ToLower());
                            userVitals.ResultDateTime      = value.dateTime;
                            userVitals.tUserSourceService  = userSourceServiceObj;
                            userVitals.LastUpdatedDateTime = DateTime.Now;

                            //parse value
                            if (result.value == null)
                            {
                                userVitals.Value = 0M;
                            }
                            else
                            {
                                if (result.unit == null && result.value.Split(' ').Length == 2)
                                {
                                    StringParser sParse = FindUOM(result.value);
                                    if (sParse.matchCount == 1)
                                    {
                                        userVitals.Value = decimal.Parse(sParse.newValue);
                                        userVitals.UOMID = sParse.uomID;
                                        result.unit      = sParse.newUnit;
                                    }
                                    else
                                    {
                                        userVitals.Value = decimal.Parse(result.value);
                                    }
                                }
                                else
                                {
                                    userVitals.Value = decimal.Parse(result.value);
                                }
                            }

                            //UOM
                            if (result.unit != null)
                            {
                                tUnitsOfMeasure uom = null;
                                uom = db.tUnitsOfMeasures.SingleOrDefault(x => x.UnitOfMeasure == result.unit);
                                if (uom == null)
                                {
                                    uom = new tUnitsOfMeasure();
                                    uom.UnitOfMeasure = result.unit;

                                    db.tUnitsOfMeasures.Add(uom);
                                    db.SaveChanges();
                                }

                                userVitals.tUnitsOfMeasure = uom;
                                userVitals.UOMID           = uom.ID;
                            }

                            //codes
                            if (result.codes != null)
                            {
                                foreach (Codes code in result.codes)
                                {
                                    if (code.code != null && code.codeSystem != null)
                                    {
                                        tCode vitalCode = null;
                                        vitalCode = db.tCodes
                                                    .SingleOrDefault(x => x.Code == code.code && x.CodeSystem == code.codeSystem);
                                        if (vitalCode == null)
                                        {
                                            vitalCode                = new tCode();
                                            vitalCode.Code           = code.code;
                                            vitalCode.CodeSystem     = code.codeSystem;
                                            vitalCode.CodeSystemName = code.codeSystemName;
                                            vitalCode.Name           = code.name;

                                            db.tCodes.Add(vitalCode);
                                            db.SaveChanges();
                                        }

                                        tXrefUserVitalsCode userXrefVitalsCodes = null;
                                        userXrefVitalsCodes = db.tXrefUserVitalsCodes
                                                              .SingleOrDefault(x => x.CodeID == vitalCode.ID &&
                                                                               x.UserVitalsID == userVitals.ID);

                                        if (userXrefVitalsCodes == null)
                                        {
                                            userXrefVitalsCodes              = new tXrefUserVitalsCode();
                                            userXrefVitalsCodes.tUserVital   = userVitals;
                                            userXrefVitalsCodes.tCode        = vitalCode;
                                            userXrefVitalsCodes.CodeID       = vitalCode.ID;
                                            userXrefVitalsCodes.UserVitalsID = userVitals.ID;

                                            db.tXrefUserVitalsCodes.Add(userXrefVitalsCodes);
                                        }
                                    }
                                }
                            }
                        }
                        userVitalsList.Add(userVitals);
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userVitalsList));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }