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

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

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

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

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public async Task <IHttpActionResult> GettUserSourceService(int id)
        {
            tUserSourceService tUserSourceService = await db.tUserSourceServices.FindAsync(id);

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

            return(Ok(tUserSourceService));
        }
        public async Task <IHttpActionResult> PosttUserSourceService(tUserSourceService tUserSourceService)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.tUserSourceServices.Add(tUserSourceService);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = tUserSourceService.ID }, tUserSourceService));
        }
        public async Task <IHttpActionResult> DeletetUserSourceService(int id)
        {
            tUserSourceService tUserSourceService = await db.tUserSourceServices.FindAsync(id);

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

            db.tUserSourceServices.Remove(tUserSourceService);
            await db.SaveChangesAsync();

            return(Ok(tUserSourceService));
        }
        public async Task <IHttpActionResult> GetUserSourceServiceByUserIdAndCategory(int userId, string category)
        {
            tUserSourceService _item = null;

            switch (category)
            {
            case "Allergies":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Care Plans":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Encounters":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Functional Statuses":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Immunizations":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Instructions":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Narratives":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Prescriptions":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Problems":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Procedures":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Test Results":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "Vitals":
                _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12).ToList().FirstOrDefault();
                if (_item == null)
                {
                    _item = new tUserSourceService();
                    _item.SourceServiceID = 12;
                    _item.UserID          = userId;
                    _item.ObjectID        = Guid.NewGuid();
                    _item.StatusID        = 1;
                    db.tUserSourceServices.Add(_item);
                    await db.SaveChangesAsync();
                }
                break;

            case "BloodGlucose":
                try
                {
                    _item = db.tUserSourceServices.Where(a => a.UserID == userId & a.SourceServiceID == 12 && a.SystemStatusID == 1).ToList().FirstOrDefault();
                    if (_item == null)
                    {
                        var credentials = db.tCredentials.FirstOrDefault(u => u.UserID == userId);

                        _item = new tUserSourceService();
                        _item.SourceServiceID = 12;
                        _item.UserID          = userId;
                        _item.ObjectID        = Guid.NewGuid();
                        _item.StatusID        = 1;
                        _item.SystemStatusID  = 1;
                        if (credentials != null)
                        {
                            _item.CredentialID = credentials.ID;
                        }

                        db.tUserSourceServices.Add(_item);
                        await db.SaveChangesAsync();
                    }
                    break;
                }
                catch (Exception ex)
                {
                    throw;
                }

            default:
                break;
            }
            return(Ok(_item));
        }
        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));
                }
            }
        }
        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 #8
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(Activities value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tActivity activityObj = db.tActivities.SingleOrDefault(x => x.Name == value.type);

                    if (activityObj == null)
                    {
                        activityObj      = new tActivity();
                        activityObj.Name = value.type;

                        db.tActivities.Add(activityObj);
                    }

                    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      = 2; //Wellness
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.SourceUserID == value.humanId &&
                                                        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;
                            }
                        }
                    }

                    tUserActivity userActivity = null;
                    userActivity = db.tUserActivities
                                   .SingleOrDefault(x => x.SourceObjectID == value.id);

                    if (userActivity == null)
                    {
                        userActivity                     = new tUserActivity();
                        userActivity.UserID              = credentialObj.UserID;
                        userActivity.SourceObjectID      = value.id;
                        userActivity.UserSourceServiceID = sourceServiceObj.ID;
                        userActivity.ActivityID          = activityObj.ID;

                        //Dates
                        DateTimeOffset dtoStart, dtoEnd;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.startTime,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userActivity.StartDateTime = dtoStart;
                        }
                        else
                        {
                            userActivity.StartDateTime = value.startTime;
                        }

                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.endTime, value.tzOffset,
                                                                                         out dtoEnd))
                        {
                            userActivity.EndDateTime = dtoEnd;
                        }
                        else
                        {
                            userActivity.EndDateTime = value.endTime;
                        }

                        userActivity.Duration           = value.duration;
                        userActivity.DurationUOMID      = 8;
                        userActivity.Distance           = value.distance;
                        userActivity.DistanceUOMID      = 9;
                        userActivity.Steps              = value.steps;
                        userActivity.Calories           = value.calories;
                        userActivity.SystemStatusID     = 1;
                        userActivity.tUserSourceService = userSourceServiceObj;

                        db.tUserActivities.Add(userActivity);
                    }
                    else
                    {
                        userActivity.ActivityID = activityObj.ID;

                        //Dates
                        DateTimeOffset dtoStart, dtoEnd;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.startTime,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userActivity.StartDateTime = dtoStart;
                        }
                        else
                        {
                            userActivity.StartDateTime = value.startTime;
                        }

                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.endTime, value.tzOffset,
                                                                                         out dtoEnd))
                        {
                            userActivity.EndDateTime = dtoEnd;
                        }
                        else
                        {
                            userActivity.EndDateTime = value.endTime;
                        }

                        userActivity.Duration            = value.duration;
                        userActivity.DurationUOMID       = 8;
                        userActivity.Distance            = value.distance;
                        userActivity.DistanceUOMID       = 9;
                        userActivity.Steps               = value.steps;
                        userActivity.Calories            = value.calories;
                        userActivity.SystemStatusID      = 1;
                        userActivity.tUserSourceService  = userSourceServiceObj;
                        userActivity.LastUpdatedDateTime = DateTime.Now;
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userActivity));
                }
                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 #10
0
        public IHttpActionResult Post(GeneticTrait value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 && x.SourceUserID == value.humanId &&
                                                        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 == 1 && x.CredentialID == credentialObj.ID &&
                                                                x.SystemStatusID == 1);

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

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            userSourceServiceObj.LatestDateTime = DateTime.Now;
                        }
                    }

                    tGeneticTrait geneticTrait = db.tGeneticTraits
                                                 .SingleOrDefault(x => x.Description == value.description && x.Trait == value.trait);
                    if (geneticTrait == null)
                    {
                        geneticTrait             = new tGeneticTrait();
                        geneticTrait.Description = value.description;
                        geneticTrait.Trait       = value.trait;

                        db.tGeneticTraits.Add(geneticTrait);
                        db.SaveChanges();
                    }

                    tUserGeneticTrait userGeneticTrait = db.tUserGeneticTraits
                                                         .SingleOrDefault(x => x.UserID == credentialObj.UserID && x.GeneticTraitID == geneticTrait.ID);

                    if (userGeneticTrait == null)
                    {
                        //insert
                        userGeneticTrait                     = new tUserGeneticTrait();
                        userGeneticTrait.UserID              = credentialObj.UserID;
                        userGeneticTrait.tUserSourceService  = userSourceServiceObj;
                        userGeneticTrait.UserSourceServiceID = userSourceServiceObj.ID;
                        userGeneticTrait.tGeneticTrait       = geneticTrait;

                        userGeneticTrait.SystemStatusID = 1;

                        userGeneticTrait.GeneticTraitID = geneticTrait.ID;

                        db.tUserGeneticTraits.Add(userGeneticTrait);
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userGeneticTrait));
                }
                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(BloodPressure value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.humanId == 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      = 2; //Wellness
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 && x.SourceUserID == value.humanId &&
                                                        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;
                            }
                        }
                    }

                    string[]          vitalNameArray  = { "Systolic Blood Pressure", "Diastolic Blood Pressure", "Heart Rate" };
                    List <tUserVital> userVitalsArray = new List <tUserVital>();

                    foreach (string vitalNameItem in vitalNameArray)
                    {
                        tUserVital userVital = null;
                        userVital = db.tUserVitals
                                    .SingleOrDefault(x => x.SourceObjectID == value.id && x.Name == vitalNameItem);

                        if (userVital == null)
                        {
                            userVital = new tUserVital();
                            userVital.tUserSourceService  = userSourceServiceObj;
                            userVital.UserID              = credentialObj.UserID;
                            userVital.SourceObjectID      = value.id;
                            userVital.UserSourceServiceID = sourceServiceObj.ID;
                            userVital.Name = vitalNameItem;

                            switch (vitalNameItem)
                            {
                            case "Systolic Blood Pressure":
                                userVital.Value = decimal.Parse(value.systolic);
                                userVital.UOMID = 470;    //mmHg
                                break;

                            case "Diastolic Blood Pressure":
                                userVital.Value = decimal.Parse(value.diastolic);
                                userVital.UOMID = 470;    //mmHg
                                break;

                            case "Heart Rate":
                                userVital.Value = decimal.Parse(value.heartRate);
                                userVital.UOMID = 30;    //bpm
                                break;
                            }

                            //Dates
                            DateTimeOffset dtoStart;
                            if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                             value.tzOffset,
                                                                                             out dtoStart))
                            {
                                userVital.ResultDateTime = dtoStart;
                            }
                            else
                            {
                                userVital.ResultDateTime = value.timestamp;
                            }

                            userVital.SystemStatusID = 1;

                            db.tUserVitals.Add(userVital);
                        }
                        else
                        {
                            userVital.Name = vitalNameItem;

                            switch (vitalNameItem)
                            {
                            case "Systolic Blood Pressure":
                                userVital.Value = decimal.Parse(value.systolic);
                                userVital.UOMID = 470;    //mm[Hg]
                                break;

                            case "Diastolic Blood Pressure":
                                userVital.Value = decimal.Parse(value.diastolic);
                                userVital.UOMID = 470;    //mm[Hg]
                                break;

                            case "Heart Rate":
                                userVital.Value = decimal.Parse(value.heartRate);
                                userVital.UOMID = 30;    //bpm
                                break;
                            }

                            //Dates
                            DateTimeOffset dtoStart;
                            if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                             value.tzOffset,
                                                                                             out dtoStart))
                            {
                                userVital.ResultDateTime = dtoStart;
                            }
                            else
                            {
                                userVital.ResultDateTime = value.timestamp;
                            }

                            userVital.LastUpdatedDateTime = DateTime.Now;
                            userVital.tUserSourceService  = userSourceServiceObj;
                        }
                        userVitalsArray.Add(userVital);
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userVitalsArray));
                }
                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));
                }
            }
        }
Beispiel #13
0
        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));
                }
            }
        }
Beispiel #14
0
        private tUserAllergy CreateAllergy(tUserAllergy newUserAllergy,
                                           Allergies newValues,
                                           Reaction userReaction,
                                           tCredential credentialObj,
                                           tUserSourceService userSourceServiceObj,
                                           tSourceOrganization userSourceOrganization)
        {
            newUserAllergy.SystemStatusID = 1;
            newUserAllergy.SourceObjectID = newValues.Id;
            newUserAllergy.UserID         = credentialObj.UserID;

            if (userSourceOrganization != null)
            {
                newUserAllergy.tSourceOrganization  = userSourceOrganization;
                newUserAllergy.SourceOrganizationID = userSourceOrganization.ID;
            }

            newUserAllergy.tUserSourceService  = userSourceServiceObj;
            newUserAllergy.UserSourceServiceID = userSourceServiceObj.ID;

            //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);

                newUserAllergy.tAllergen  = allergenObj;
                newUserAllergy.AllergenID = allergenObj.ID;
            }
            else //check to see if allergen has a mapped parent
            {
                if (allergenObj.ParentID != null)
                {
                    newUserAllergy.tAllergen  = allergenObj.tAllergen1;
                    newUserAllergy.AllergenID = allergenObj.tAllergen1.ID;
                }
                else
                {
                    newUserAllergy.tAllergen  = allergenObj;
                    newUserAllergy.AllergenID = allergenObj.ID;
                }
            }

            //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);

                    newUserAllergy.tAllergyStatus = allergyStatusObj;
                    newUserAllergy.StatusID       = allergyStatusObj.ID;
                }
                else //check to see if reaction has a mapped parent
                {
                    if (allergyStatusObj.ParentID != null)
                    {
                        newUserAllergy.tAllergyStatus = allergyStatusObj.tAllergyStatus1;
                        newUserAllergy.StatusID       = allergyStatusObj.tAllergyStatus1.ID;
                    }
                    else
                    {
                        newUserAllergy.tAllergyStatus = allergyStatusObj;
                        newUserAllergy.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);

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

            //Dates
            if (newValues.dateRange.start != null && newValues.dateRange.start != DateTime.MinValue)
            {
                newUserAllergy.StartDateTime = newValues.dateRange.start;
            }
            if (newValues.dateRange.end != null && newValues.dateRange.end != DateTime.MinValue)
            {
                newUserAllergy.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 == newUserAllergy.ID);

                        if (userXrefAllergensCodes == null)
                        {
                            userXrefAllergensCodes = new tXrefUserAllergiesCode();
                            userXrefAllergensCodes.tUserAllergy    = newUserAllergy;
                            userXrefAllergensCodes.tCode           = AllergyCode;
                            userXrefAllergensCodes.CodeID          = AllergyCode.ID;
                            userXrefAllergensCodes.UserAllergiesID = newUserAllergy.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);

                        newUserAllergy.tReaction  = reactionObj;
                        newUserAllergy.ReactionID = reactionObj.ID;
                    }
                    else //check to see if reaction has a mapped parent
                    {
                        if (reactionObj.ParentID != null)
                        {
                            newUserAllergy.tReaction  = reactionObj.tReaction1;
                            newUserAllergy.ReactionID = reactionObj.tReaction1.ID;
                        }
                        else
                        {
                            newUserAllergy.tReaction  = reactionObj;
                            newUserAllergy.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);
                            }
                        }
                    }
                }
            }

            db.tUserAllergies.Add(newUserAllergy);

            return(newUserAllergy);
        }
        public IHttpActionResult Post(SleepSummaries value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.humanId == 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      = 2; //Wellness
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 && x.SourceUserID == value.humanId &&
                                                        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;
                            }
                        }
                    }

                    tUserSleep userSleep = db.tUserSleeps
                                           .SingleOrDefault(x => x.SourceObjectID == value.id);

                    if (userSleep == null)
                    {
                        //insert
                        userSleep = new tUserSleep();
                        userSleep.SourceObjectID      = value.id;
                        userSleep.UserID              = credentialObj.UserID;
                        userSleep.tUserSourceService  = userSourceServiceObj;
                        userSleep.UserSourceServiceID = userSourceServiceObj.ID;

                        userSleep.SystemStatusID    = 1;
                        userSleep.PrimarySleepEvent = Convert.ToByte(value.mainSleep);
                        userSleep.TimeAsleep        = value.timeAsleep;
                        userSleep.TimeAwake         = value.timeAwake;
                        userSleep.StartDateTime     = value.endTime;
                        userSleep.EndDateTime       = value.endTime;

                        db.tUserSleeps.Add(userSleep);
                    }
                    else
                    {
                        //update
                        userSleep.PrimarySleepEvent = Convert.ToByte(value.mainSleep);
                        userSleep.TimeAsleep        = value.timeAsleep;
                        userSleep.TimeAwake         = value.timeAwake;
                        userSleep.StartDateTime     = value.endTime;
                        userSleep.EndDateTime       = value.endTime;

                        userSleep.LastUpdatedDateTime = DateTime.Now;
                        userSleep.tUserSourceService  = userSourceServiceObj;
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userSleep));
                }
                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(BloodOxygen value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.humanId == 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      = 2; //Wellness
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 && x.SourceUserID == value.humanId &&
                                                        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;
                            }
                        }
                    }

                    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;
                        userTestResult.tUserSourceService  = userSourceServiceObj;
                        userTestResult.UserSourceServiceID = userSourceServiceObj.ID;
                        userTestResult.Name           = "Blood Oxygen";
                        userTestResult.StatusID       = 3; //captured
                        userTestResult.SystemStatusID = 1;

                        //Dates
                        DateTimeOffset dtoStart;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userTestResult.ResultDateTime = dtoStart;
                        }
                        else
                        {
                            userTestResult.ResultDateTime = value.timestamp;
                        }

                        tUserTestResultComponent userTestResultComponent = new tUserTestResultComponent();
                        userTestResultComponent.SystemStatusID = 1;
                        userTestResultComponent.Name           = "Blood Oxygen";
                        userTestResultComponent.Value          = value.value.ToString();

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

                                db.tUnitsOfMeasures.Add(uom);
                            }

                            userTestResultComponent.tUnitsOfMeasure = uom;
                            userTestResultComponent.UOMID           = uom.ID;
                        }
                        userTestResult.tUserTestResultComponents.Add(userTestResultComponent);

                        tXrefUserTestResultComponentsCode xRefComponentCode = new tXrefUserTestResultComponentsCode();
                        xRefComponentCode.UserTestResultComponentID = userTestResultComponent.ID;
                        xRefComponentCode.CodeID = 6720;
                        userTestResultComponent.tXrefUserTestResultComponentsCodes.Add(xRefComponentCode);

                        userTestResult.tUserSourceService = userSourceServiceObj;

                        db.tUserTestResults.Add(userTestResult);
                    }
                    else
                    {
                        //update

                        //Dates
                        DateTimeOffset dtoStart;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userTestResult.ResultDateTime = dtoStart;
                        }
                        else
                        {
                            userTestResult.ResultDateTime = value.timestamp;
                        }


                        tUserTestResultComponent userTestResultComponent = db.tUserTestResultComponents
                                                                           .SingleOrDefault(x => x.TestResultID == userTestResult.ID);
                        if (userTestResultComponent != null)
                        {
                            userTestResultComponent.Value = value.value.ToString();

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

                                    db.tUnitsOfMeasures.Add(uom);
                                }

                                if (!uom.UnitOfMeasure.Equals(value.unit))
                                {
                                    userTestResultComponent.tUnitsOfMeasure = uom;
                                    userTestResultComponent.UOMID           = uom.ID;
                                }
                            }

                            userTestResult.tUserTestResultComponents.Add(userTestResultComponent);
                        }

                        userTestResult.LastUpdatedDateTime = DateTime.Now;
                        userTestResult.tUserSourceService  = userSourceServiceObj;
                    }

                    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));
                }
            }
        }
Beispiel #17
0
        public IHttpActionResult Post(Meals value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.humanId == null)
            {
                return(BadRequest());
            }
            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tDietCategory dietCategoryObj = db.tDietCategories.SingleOrDefault(x => x.Name == value.type);

                    if (dietCategoryObj == null)
                    {
                        dietCategoryObj      = new tDietCategory();
                        dietCategoryObj.Name = value.type;

                        db.tDietCategories.Add(dietCategoryObj);
                    }

                    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      = 2; //Wellness
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj = db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                                                x.SourceUserID == value.humanId &&
                                                                                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;
                            }
                        }
                    }

                    tUserDiet userDiet = null;
                    userDiet = db.tUserDiets
                               .SingleOrDefault(x => x.SourceObjectID == value.id);

                    if (userDiet == null)
                    {
                        userDiet = new tUserDiet();
                        userDiet.tUserSourceService  = userSourceServiceObj;
                        userDiet.tDietCategory       = dietCategoryObj;
                        userDiet.UserID              = credentialObj.UserID;
                        userDiet.SourceObjectID      = value.id;
                        userDiet.UserSourceServiceID = sourceServiceObj.ID;
                        userDiet.Name = value.name;
                        if (value.amount != null)
                        {
                            userDiet.Servings = value.amount.value;

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

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

                                userDiet.tUnitsOfMeasure = uom;
                                userDiet.ServingUOMID    = uom.ID;
                            }
                        }
                        userDiet.DietCategoryID = dietCategoryObj.ID;

                        //Dates
                        DateTimeOffset dtoStart;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userDiet.EnteredDateTime = dtoStart;
                        }
                        else
                        {
                            userDiet.EnteredDateTime = value.timestamp;
                        }

                        userDiet.SystemStatusID = 1;

                        db.tUserDiets.Add(userDiet);
                    }
                    else
                    {
                        userDiet.tUserSourceService = userSourceServiceObj;
                        userDiet.Name = value.name;
                        if (value.amount != null)
                        {
                            userDiet.Servings = value.amount.value;

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

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

                                userDiet.tUnitsOfMeasure = uom;
                                userDiet.ServingUOMID    = uom.ID;
                            }
                        }
                        userDiet.DietCategoryID = dietCategoryObj.ID;

                        //Dates
                        DateTimeOffset dtoStart;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userDiet.EnteredDateTime = dtoStart;
                        }
                        else
                        {
                            userDiet.EnteredDateTime = value.timestamp;
                        }

                        userDiet.LastUpdatedDateTime = DateTime.Now;
                    }

                    AddorUpdateNutrients(userDiet.ID, 170, value.calories, 460);
                    AddorUpdateNutrients(userDiet.ID, 161, value.carbohydrate, 5);
                    AddorUpdateNutrients(userDiet.ID, 248, value.fat, 5);
                    AddorUpdateNutrients(userDiet.ID, 209, value.protein, 5);
                    AddorUpdateNutrients(userDiet.ID, 214, value.sodium, 5);
                    AddorUpdateNutrients(userDiet.ID, 218, value.sugar, 5);
                    AddorUpdateNutrients(userDiet.ID, 177, value.fiber, 5);
                    AddorUpdateNutrients(userDiet.ID, 173, value.saturatedFat, 5);
                    AddorUpdateNutrients(userDiet.ID, 171, value.monounsaturatedFat, 5);
                    AddorUpdateNutrients(userDiet.ID, 172, value.polyunsaturatedFat, 5);
                    AddorUpdateNutrients(userDiet.ID, 164, value.cholesterol, 7);
                    AddorUpdateNutrients(userDiet.ID, 233, value.vitaminA, 7);
                    AddorUpdateNutrients(userDiet.ID, 238, value.vitaminC, 7);
                    AddorUpdateNutrients(userDiet.ID, 159, value.calcium, 7);
                    AddorUpdateNutrients(userDiet.ID, 190, value.iron, 7);
                    AddorUpdateNutrients(userDiet.ID, 207, value.potassium, 7);

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userDiet));
                }
                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 #18
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));
                }
            }
        }