// sonarignore:start import { authenticate, AuthenticationBindings, STRATEGY, } from 'loopback4-authentication'; import {authorize, AuthorizeErrorKeys} from 'loopback4-authorization'; import { get, getModelSchemaRef, HttpErrors, param, patch, Request, requestBody, RestBindings, } from '@loopback/rest'; import {inject} from '@loopback/context'; import { DailyCheckInsService, DiPatientCaregiverUserService, ExploreService, MoodFactorLogsService, PatientOthersDetailsService, } from '../services'; import { IAuthUserWithPermissions, PermissionKey, STATUS_CODE, SuccessResponse, } from '@sourcefuse-npm/alivio-lib'; import { BpmConfig, EngagementExplore, Explore, PatientOthersDetailsDTO, } from '../models'; import { ERROR_KEYS, Patient, PatientOnboardingService, PatientService, UsersService, } from '@sourcefuse-npm/patient-facade'; import moment from 'moment'; import {ContentPosts} from '../models/content-posts.model'; const explore = '/patients/{patientId}/explore'; const engagementExplores = 'engagement-explores'; export class ExploreController { constructor( @inject('services.DailyCheckInsService') public dailyCheckIns: DailyCheckInsService, @inject('services.PatientService') protected patientService: PatientService, @inject('services.MoodFactorLogsService') protected moodFactorLogsService: MoodFactorLogsService, @inject('services.UsersService') protected usersService: UsersService, @inject('services.PatientOnboardingService') protected patientOnbService: PatientOnboardingService, @inject('services.ExploreService') protected readonly exploreService: ExploreService, @inject('services.DiPatientCaregiverUserService') protected readonly patientCgUserService: DiPatientCaregiverUserService, @inject('services.PatientOthersDetailsService') protected readonly patientOthersDetailsService: PatientOthersDetailsService, ) {} @authenticate(STRATEGY.BEARER, { passReqToCallback: true, }) @authorize({permissions: ['*']}) @get(`${explore}/check-in`, { responses: { [STATUS_CODE.OK]: { description: 'Get Contenet for CheckIns', content: {'application/json': {schema: Object}}, }, }, }) // eslint-disable-next-line @typescript-eslint/no-explicit-any async getEngagementExplore( @param.path.number('patientId') patientId: number, @param.header.string('Authorization') token: string, @inject(AuthenticationBindings.CURRENT_USER) currentUser: IAuthUserWithPermissions, ): Promise { const isAccessAllowed = await this.patientCgUserService.isPatientAccessAllowed( currentUser, Number(patientId), // eslint-disable-next-line @typescript-eslint/no-explicit-any PermissionKey.UpdateOwnPatient, token, ); if (!isAccessAllowed) { throw new HttpErrors.Forbidden(AuthorizeErrorKeys.NotAllowedAccess); } const loggedData = await this.exploreService.getChecinDataLatest( patientId, token, ); let data = {} as EngagementExplore; if ( loggedData.mood && loggedData.moodFactor.length && loggedData.food && loggedData.sleep ) { const cmsData = await this.exploreService.engagementExplore( loggedData.mood, loggedData.moodFactor, loggedData.sleep, loggedData.food, '', token, ); const exploredata = cmsData.data; const converData = this.exploreService.prepareEngagementExploreData(exploredata); data = converData?.length ? converData[0] : ({} as EngagementExplore); const patientResp = await this.patientOnbService.findPatientById( patientId, token, ); if (data.id) { const convertedata = data; const post = new ContentPosts(); post.collectionType = engagementExplores; post.collectionTypeId = convertedata.id; post.segment = 'check-in'; post.type = ''; post.patientId = patientId; post.userId = Number(patientResp.userId); const postSaved = await this.dailyCheckIns.createContentPosts( post, token, ); data.contentPostId = Number(postSaved.id); } return data; } else { return data; } } @authenticate(STRATEGY.BEARER, { passReqToCallback: true, }) @authorize({permissions: ['*']}) @get(`${explore}/check-in/recomended`, { responses: { [STATUS_CODE.OK]: { description: 'Recomended CheckIns model count', content: {'application/json': {schema: Object}}, }, }, }) // eslint-disable-next-line @typescript-eslint/no-explicit-any async getEngagementExploreRecommend( @param.path.number('patientId') patientId: number, @param.header.string('Authorization') token: string, @inject(AuthenticationBindings.CURRENT_USER) currentUser: IAuthUserWithPermissions, ): Promise { const isAccessAllowed = await this.patientCgUserService.isPatientAccessAllowed( currentUser, Number(patientId), // eslint-disable-next-line @typescript-eslint/no-explicit-any PermissionKey.UpdateOwnPatient, token, ); if (!isAccessAllowed) { throw new HttpErrors.Forbidden(AuthorizeErrorKeys.NotAllowedAccess); } const loggedData = await this.exploreService.getChecinDataLatest( patientId, token, ); const posts = await this.dailyCheckIns.getContentPosts( { where: { patientId: patientId, segment: 'recomended', collectionType: engagementExplores, isRead: false, }, order: ['id ASC'], }, token, ); const unReadPostIds = posts.map(p => p.collectionTypeId); let data: EngagementExplore[] = []; if ( loggedData.mood && loggedData.moodFactor.length && loggedData.food && loggedData.sleep ) { const cmsDataForMoodMoodTactoor = await this.exploreService.engagementExploreRecommndedMoodMoodFactor( loggedData.mood, loggedData.moodFactor, ['Blog'], token, ); const cmsDataForSleepAppetite = await this.exploreService.engagementExploreRecommnded( '', null, loggedData.sleep, loggedData.food, ['Blog'], '', token, ); const cmsData = cmsDataForMoodMoodTactoor.concat(cmsDataForSleepAppetite); const unReadcmsData = await this.exploreService.engagementExploreRecommnded( '', [], '', '', ['Blog'], '', token, unReadPostIds, ); cmsData.forEach(c => { data.push(...this.exploreService.prepareEngagementExploreData(c.data)); }); const patientResp = await this.patientOnbService.findPatientById( patientId, token, ); const dataWithpostIds = data.map(async d => { // if (d.id) { const convertedata = d; const post = new ContentPosts(); post.collectionType = engagementExplores; post.collectionTypeId = convertedata.id; post.segment = 'recomended'; post.type = ''; post.patientId = patientId; post.userId = Number(patientResp.userId); const postSaved = await this.dailyCheckIns.createContentPosts( post, token, ); d.contentPostId = Number(postSaved.id); d.contentWebUrl = `${process.env.PORTAL_URL}/explore/${engagementExplores}/${d.id}`; return d; // } }); data = await Promise.all(dataWithpostIds); unReadcmsData.forEach(c => { let unreadpostdata = this.exploreService.prepareEngagementExploreData( c.data, true, ); unreadpostdata = unreadpostdata.filter(up => { const post = posts.find(p => p.collectionTypeId === up.id); if (post) { if (post?.createdOn) { up.createdPostAt = post?.createdOn; } if (post?.id) { up.contentPostId = Number(post.id); } up.contentWebUrl = `${process.env.PORTAL_URL}/explore/${engagementExplores}/${up.id}`; return up; } }); data.push(...unreadpostdata); }); } return data; } @authenticate(STRATEGY.BEARER, { passReqToCallback: true, }) @authorize({permissions: ['*']}) @get(`${explore}/`, { responses: { [STATUS_CODE.OK]: { description: 'explore data ', content: {'application/json': {schema: Object}}, }, }, }) // eslint-disable-next-line @typescript-eslint/no-explicit-any async getExploreRecommend( @param.path.number('patientId') patientId: number, @param.query.string('segment', {required: true}) segment: string, @param.query.string('type', {required: true}) type: string, @param.header.string('Authorization') token: string, @inject(RestBindings.Http.REQUEST) request: Request, @inject(AuthenticationBindings.CURRENT_USER) currentUser: IAuthUserWithPermissions, ): Promise { const isAccessAllowed = await this.patientCgUserService.isPatientAccessAllowed( currentUser, Number(patientId), // eslint-disable-next-line @typescript-eslint/no-explicit-any PermissionKey.UpdateOwnPatient, token, ); if (!isAccessAllowed) { throw new HttpErrors.Forbidden(AuthorizeErrorKeys.NotAllowedAccess); } const bpmConfigs = await this.dailyCheckIns.getBpmConfigs( { where: { name: segment, processId: type, }, }, token, ); const dailyBpmConfig = bpmConfigs.find( bpmConfig => bpmConfig.triggerEventName === 'Daily' && bpmConfig.processId === "Today's", ); const weeklyBpmConfig = bpmConfigs.find( bpmConfig => bpmConfig.triggerEventName === 'Weekly' && bpmConfig.processId === "Today's", ); const dailyBpmConfigForYou = bpmConfigs.find( bpmConfig => bpmConfig.triggerEventName === 'Daily' && bpmConfig.processId === 'For You', ); const weeklyBpmConfigForYou = bpmConfigs.find( bpmConfig => bpmConfig.triggerEventName === 'Weekly' && bpmConfig.processId === 'For You', ); const patientResp = await this.patientOnbService.findPatientById( patientId, request.headers.authorization, ); const result: { daily: any; weekly: any; recomended: any; } = {daily: {}, weekly: {}, recomended: []}; if (['Onboarding', 'Exploration'].includes(segment)) { if ( !patientResp.userId || (patientResp.caregiver && !patientResp.caregiver.userId) ) { throw new HttpErrors.NotFound(ERROR_KEYS.PatientCGUserNotFound); } const patientUserInfo: any = await this.usersService.getUserById( patientResp.userId, request.headers.authorization, ); const firstLoginDate = moment(new Date(patientUserInfo.firstLogin)); const currentDate = moment(); const diffDays = currentDate.diff(firstLoginDate, 'days'); const diffWeeks = currentDate.diff(firstLoginDate, 'weeks'); if (type === "Today's") { if ( diffDays % 7 === 0 && weeklyBpmConfig && (weeklyBpmConfig?.defaultParams?.duration ? diffWeeks <= Number(weeklyBpmConfig?.defaultParams?.duration) : true) ) { if (segment === 'Onboarding') { const data = await this.exploreService.explore( { reccurence: 'Weekly', offsetStart: weeklyBpmConfig?.defaultParams?.start, offsetEnd: weeklyBpmConfig?.defaultParams?.duration, type: type, segmentName: segment, } as Explore, token, ); const convertedStrapiData = this.exploreService.prepareExploreData( data.data, ); const getEngagementExploreData = convertedStrapiData.length ? convertedStrapiData[0]?.engagementExplores : []; const selectContentPiece = this.selectContentPieceBasedOnDisease( getEngagementExploreData, patientUserInfo.cancerType, ); const getAllPostsGenerated = await this.dailyCheckIns.getContentPosts( { where: { patientId: patientId, segment: segment, reccurence: 'Weekly', type: type, collectionType: engagementExplores, }, order: ['id ASC'], }, token, ); const getSinglePost = await this.generateSinglePost( selectContentPiece, getAllPostsGenerated, segment, type, 'Weekly', patientResp, token, ); result.weekly = getSinglePost; } else { const data = await this.exploreService.explore( { reccurence: 'Weekly', offsetStart: weeklyBpmConfig?.defaultParams?.start, offsetEnd: weeklyBpmConfig?.defaultParams?.duration, type: type, segmentName: segment, } as Explore, token, ); const convertedStrapiData = this.exploreService.prepareExploreData( data.data, ); const getEngagementExploreData = convertedStrapiData.length ? convertedStrapiData[0]?.engagementExplores : []; const selectContentPiece = getEngagementExploreData; const getAllPostsGenerated = await this.dailyCheckIns.getContentPosts( { where: { patientId: patientId, segment: segment, reccurence: 'Weekly', type: type, collectionType: engagementExplores, }, order: ['id ASC'], }, token, ); const getSinglePost = await this.generateSinglePost( selectContentPiece, getAllPostsGenerated, segment, type, 'Weekly', patientResp, token, ); result.weekly = getSinglePost; } } if ( dailyBpmConfig && (dailyBpmConfig?.defaultParams?.duration ? diffDays <= Number(dailyBpmConfig?.defaultParams?.duration) : true) ) { if (segment === 'Onboarding') { const data = await this.exploreService.explore( { reccurence: 'Daily', offsetStart: dailyBpmConfig?.defaultParams?.start, offsetEnd: dailyBpmConfig?.defaultParams?.duration, type: type, segmentName: segment, } as Explore, token, ); const convertedStrapiData = this.exploreService.prepareExploreData( data.data, ); const getEngagementExploreData = convertedStrapiData.length ? convertedStrapiData[0]?.engagementExplores : []; const selectContentPiece = this.selectContentPieceBasedOnDisease( getEngagementExploreData, patientUserInfo.cancerType, ); const getAllPostsGenerated = await this.dailyCheckIns.getContentPosts( { where: { patientId: patientId, segment: segment, reccurence: 'Daily', type: type, collectionType: engagementExplores, }, order: ['id ASC'], }, token, ); const getSinglePost = await this.generateSinglePost( selectContentPiece, getAllPostsGenerated, segment, type, 'Daily', patientResp, token, ); result.daily = getSinglePost; } else if ('Exploration') { const data = await this.exploreService.explore( { reccurence: 'Daily', offsetStart: dailyBpmConfig?.defaultParams?.start, offsetEnd: dailyBpmConfig?.defaultParams?.duration, type: type, segmentName: segment, } as Explore, token, ); const convertedStrapiData = this.exploreService.prepareExploreData( data.data, ); const getEngagementExploreData = convertedStrapiData.length ? convertedStrapiData[0]?.engagementExplores : []; const selectContentPiece = getEngagementExploreData; const getAllPostsGenerated = await this.dailyCheckIns.getContentPosts( { where: { patientId: patientId, segment: segment, reccurence: 'Daily', type: type, collectionType: engagementExplores, }, order: ['id ASC'], }, token, ); const getSinglePost = await this.generateSinglePost( selectContentPiece, getAllPostsGenerated, segment, type, 'Daily', patientResp, token, ); result.daily = getSinglePost; } } } else if (type === 'For You') { if (segment === 'Onboarding') { const otherDetailsArr = await this.patientOthersDetailsService.find( { where: { patientId: Number(patientResp.id), }, }, request.headers.authorization, ); const otherDetails = otherDetailsArr.length ? otherDetailsArr[0] : ({} as PatientOthersDetailsDTO); const symptoms = otherDetails.symptoms; const data = await this.exploreService.explore( { reccurence: 'Daily', offsetStart: dailyBpmConfigForYou?.defaultParams?.start, offsetEnd: dailyBpmConfigForYou?.defaultParams?.duration, type: type, segmentName: segment, } as Explore, token, ); const convertedStrapiData = this.exploreService.prepareExploreData( data.data, ); const getEngagementExploreData = convertedStrapiData.length ? convertedStrapiData[0]?.engagementExplores : []; const selectContentPiece = this.gerenateSypotomPosts( getEngagementExploreData, symptoms, ); const getAllPostsGenerated = await this.dailyCheckIns.getContentPosts( { where: { patientId: patientId, segment: segment, reccurence: 'Daily', type: type, collectionType: engagementExplores, }, order: ['id ASC'], }, token, ); const getmultiplePost = await this.generateMultiplePost( selectContentPiece, getAllPostsGenerated, segment, type, 'Daily', patientResp, token, ); result.recomended = getmultiplePost; } else { const data = await this.exploreService.explore( { reccurence: 'Daily', offsetStart: dailyBpmConfigForYou?.defaultParams?.start, offsetEnd: dailyBpmConfigForYou?.defaultParams?.duration, type: type, segmentName: segment, } as Explore, token, ); const convertedStrapiData = this.exploreService.prepareExploreData( data.data, ); const getEngagementExploreData = convertedStrapiData.length ? convertedStrapiData[0]?.engagementExplores : []; const selectContentPiece = getEngagementExploreData; const getAllPostsGenerated = await this.dailyCheckIns.getContentPosts( { where: { patientId: patientId, segment: segment, reccurence: 'Daily', type: type, collectionType: engagementExplores, }, order: ['id ASC'], }, token, ); const getmultiplePost = await this.generateMultiplePost( selectContentPiece, getAllPostsGenerated, segment, type, 'Daily', patientResp, token, ); result.recomended = getmultiplePost; } return result; } } else { const data = await this.getExploreOnCheckin(patientId, token); result.recomended = data; } return result; } gerenateSypotomPosts( engagementExplore: EngagementExplore[], symptoms: string[], ) { return engagementExplore.filter(ee => symptoms.includes(ee.symptoms)); } async generateSinglePost( engagementExplore: EngagementExplore[], savedPosts: ContentPosts[], segment: string, type: string, reccurence: string, patientRes: Patient, token: string, ) { let result: EngagementExplore = new EngagementExplore(); const todaypost = savedPosts.find( sp => moment(new Date(`${sp.createdOn}`)).format('YYYY-MM-DD') === moment(new Date()).format('YYYY-MM-DD'), ); if (!todaypost) { const latestPost = savedPosts[savedPosts.length - 1]; const findIndex = latestPost ? engagementExplore.findIndex( ee => ee.id === latestPost.collectionTypeId, ) : 0; const createEngagementPostId = findIndex < engagementExplore.length - 1 ? findIndex + 1 : 0; const createPost = engagementExplore[createEngagementPostId]; if (createPost?.id) { const convertedata = createPost; const post = new ContentPosts(); post.collectionType = engagementExplores; post.collectionTypeId = convertedata.id; post.segment = segment; post.type = type; post.reccurence = reccurence; post.patientId = Number(patientRes.id); post.userId = Number(patientRes.userId); const postSaved = await this.dailyCheckIns.createContentPosts( post, token, ); createPost.createdPostAt = new Date(); createPost.contentPostId = Number(postSaved.id); createPost.contentWebUrl = `${process.env.PORTAL_URL}/explore/${engagementExplores}/${createPost.id}`; result = createPost; } } else { let todayPost = ( engagementExplore?.length ? engagementExplore.find(ee => ee.id === todaypost.collectionTypeId) : {} ) as EngagementExplore; todayPost = (await this.exploreService.getEngagementExploreById( todayPost.id, token, )) as EngagementExplore; todayPost.createdPostAt = todaypost.createdOn; todayPost.contentPostId = Number(todaypost.id); todayPost.contentWebUrl = `${process.env.PORTAL_URL}/explore/${engagementExplores}/${todayPost.id}`; result = todayPost; } return result; } async generateMultiplePost( engagementExplore: EngagementExplore[], savedPosts: ContentPosts[], segment: string, type: string, reccurence: string, patientRes: Patient, token: string, ) { let result: EngagementExplore[] = []; const todayposts = savedPosts.filter( sp => moment(new Date(`${sp.createdOn}`)).format('YYYY-MM-DD') === moment(new Date()).format('YYYY-MM-DD'), ); if (!todayposts.length) { const allposts = await Promise.all( engagementExplore.map(ee => { const createPost = ee; if (createPost?.id) { const convertedata = createPost; const post = new ContentPosts(); post.collectionType = engagementExplores; post.collectionTypeId = convertedata.id; post.segment = segment; post.type = type; post.reccurence = reccurence; post.patientId = Number(patientRes.id); post.userId = Number(patientRes.userId); return this.dailyCheckIns.createContentPosts(post, token); } }), ); const enexplore = await Promise.all( allposts.map(post => { return this.exploreService.getEngagementExploreById( Number(post?.collectionTypeId), token, ); }), ); const todayPosts = allposts.map(post => { const eepost = enexplore.find( ee => ee.id === post?.collectionTypeId, ) as EngagementExplore; eepost.createdPostAt = new Date(); eepost.contentPostId = Number(post?.id); eepost.contentWebUrl = `${process.env.PORTAL_URL}/explore/${engagementExplores}/${eepost?.id}`; return eepost; }); result = todayPosts; } else { const enexplore = await Promise.all( todayposts.map(post => { return this.exploreService.getEngagementExploreById( Number(post?.collectionTypeId), token, ); }), ); const todayPosts = todayposts.map(post => { const eepost = enexplore.find( ee => ee.id === post?.collectionTypeId, ) as EngagementExplore; eepost.createdPostAt = new Date(); eepost.contentPostId = Number(post?.id); eepost.contentWebUrl = `${process.env.PORTAL_URL}/explore/${engagementExplores}/${eepost?.id}`; return eepost; }); result = todayPosts; } return result; } selectContentPieceBasedOnDisease( engagementExploreData: EngagementExplore[], diagaonosis: string, ) { return engagementExploreData.filter(ee => { return ee.diagnosis === diagaonosis; }); //.sort((a, b) => a.id - b.id); } findIndex(savedIds: number[], actualIds: number[]) { const latest = savedIds[savedIds.length - 1]; const findActualIndex = actualIds.findIndex(id => id === latest); return findActualIndex < actualIds.length - 1 ? findActualIndex + 1 : 0; } async findOnBoardData( patientUserInfo: any, patientId: number, segment: string, type: string, token: string, ) { const cmsData = await this.exploreService.engagementExplore( '', [], '', '', patientUserInfo.cancerType, token, ); const exploredata = cmsData.data; const converData = this.exploreService.prepareEngagementExploreData(exploredata); const posts = await this.dailyCheckIns.getContentPosts( { where: { patientId: patientId, segment: segment, type: type, collectionType: engagementExplores, }, order: ['id ASC'], }, token, ); const todaypost = posts.find( p => moment(new Date(`${p.createdOn}`)).format('YYYY-MM-DD') === moment(new Date()).format('YYYY-MM-DD'), ); let daily = todaypost ? converData.find(cd => cd.id === todaypost.collectionTypeId) : {}; if (!todaypost) { const postids = posts.filter(p => !p.isRead).map(p => p.collectionTypeId); const filteredData = converData.filter(cd => !postids.includes(cd.id)); daily = filteredData?.length ? filteredData[0] : converData.length ? converData[ this.findIndex( postids, converData.map(d => d.id), ) ] : ({} as Explore); if ((daily as Explore).id) { const convertedata = daily as Explore; const post = new ContentPosts(); post.collectionType = engagementExplores; post.collectionTypeId = convertedata.id; post.segment = segment; post.type = type; post.patientId = patientId; post.userId = patientUserInfo.userId; await this.dailyCheckIns.createContentPosts(post, token); } } return daily as any; } @authenticate(STRATEGY.BEARER, { passReqToCallback: true, }) @authorize({permissions: ['*']}) @patch('/content-posts/{id}', { responses: { [STATUS_CODE.NO_CONTENT]: { description: 'ContentPosts PATCH success', }, }, }) async updateById( @param.path.number('id') id: number, @requestBody({ content: { 'application/json': { schema: getModelSchemaRef(ContentPosts, {partial: true}), }, }, }) post: ContentPosts, @param.header.string('Authorization') token: string, ): Promise { await this.dailyCheckIns.updateContentPosts(id, post, token); return new SuccessResponse({success: true}); } async getPostFromExploreSegement( patientResp: any, reccurence: string, dailyBpmConfig: BpmConfig, type: string, segment: string, patientId: number, token: string, ) { const weeklydata = await this.exploreService.explore( { reccurence: reccurence, offsetStart: dailyBpmConfig?.defaultParams?.start, offsetEnd: dailyBpmConfig?.defaultParams?.duration, type: type, segmentName: segment, } as Explore, token, ); const converData = this.exploreService.prepareExploreData(weeklydata.data); const posts = await this.dailyCheckIns.getContentPosts( { where: { reccurence: reccurence, patientId: patientId, segment: segment, type: type, collectionType: 'explores', }, order: ['id ASC'], }, token, ); const subPostposts = await this.dailyCheckIns.getContentPosts( { where: { reccurence: reccurence, patientId: patientId, segment: segment, type: type, collectionType: 'engagement-explores', }, order: ['id ASC'], }, token, ); const todaypost = posts.find( p => moment(new Date(`${p.createdOn}`)).format('YYYY-MM-DD') === moment(new Date()).format('YYYY-MM-DD'), ); const unreadPost = posts.filter( p => todaypost?.id !== p.id && p.isRead === false, ); const unreadPostFiltered = [ ...unreadPost.map(up => { const data: Explore = [...converData].find( d => up.collectionTypeId === d.id, ) as Explore; if (up?.createdOn) { data.createdPostAt = up?.createdOn; } if (up?.id) { data.contentPostId = Number(up.id); } data.isUnReadPreviousPost = true; return data; }), ]; const todayPostFromStrapi = [...converData].find(d => { return d.id === todaypost?.collectionTypeId; }) as Explore; if (!todayPostFromStrapi) { const postids = posts.filter(p => !p.isRead).map(p => p.collectionTypeId); const filteredData = converData.filter(cd => !postids.includes(cd.id)); const weekly = filteredData?.length ? filteredData[0] : converData.length ? converData[ this.findIndex( postids, converData.map(d => d.id), ) ] : ({} as Explore); // const daily = converData?.length ? converData[0] : ({} as Explore); if ((weekly as Explore).id) { const convertedata = weekly as Explore; const post = new ContentPosts(); post.collectionType = 'explores'; post.reccurence = reccurence; post.collectionTypeId = convertedata.id; post.segment = segment; post.type = type; post.patientId = patientId; post.userId = Number(patientResp.userId); const postSaved = await this.dailyCheckIns.createContentPosts( post, token, ); weekly.contentPostId = Number(postSaved.id); return {today: weekly, previousPosts: unreadPostFiltered}; } } else { // todayPostFromStrapi.contentPostId = Number(todaypost?.id); return { today: {...todayPostFromStrapi, contentPostId: Number(todaypost?.id)}, previousPosts: unreadPostFiltered, }; } } async getExploreOnCheckin(patientId: number, token: string) { const loggedData = await this.exploreService.getChecinDataLatest( patientId, token, ); const posts = await this.dailyCheckIns.getContentPosts( { where: { patientId: patientId, segment: 'Exploration', collectionType: engagementExplores, type: 'For You', }, order: ['id ASC'], }, token, ); const unReadPosts = posts.filter( p => p.isRead === false && moment(new Date(`${p.createdOn}`)).format('YYYY-MM-DD') !== moment(new Date()).format('YYYY-MM-DD'), ); const unReadPostIds = unReadPosts.map(p => p.collectionTypeId); let data: EngagementExplore[] = []; if ( loggedData.mood && loggedData.moodFactor.length && loggedData.food && loggedData.sleep ) { const cmsData = await this.exploreService.engagementExploreRecommnded( loggedData.mood, loggedData.moodFactor, loggedData.sleep, loggedData.food, ['Audio', 'Video', 'Images', 'Blog'], '', token, ); const unReadcmsData = await this.exploreService.engagementExploreRecommnded( '', [], '', '', [], '', token, unReadPostIds, ); cmsData.forEach(c => { data.push(...this.exploreService.prepareEngagementExploreData(c.data)); }); const unReadPostsCOnverted: EngagementExplore[] = []; unReadcmsData.forEach(c => { const unreadpostdata = this.exploreService.prepareEngagementExploreData( c.data, true, ); unReadPostsCOnverted.push(...unreadpostdata); }); const patientResp = await this.patientOnbService.findPatientById( patientId, token, ); const todaypost = posts.filter( p => moment(new Date(`${p.createdOn}`)).format('YYYY-MM-DD') === moment(new Date()).format('YYYY-MM-DD'), ); if (!todaypost.length) { const dataWithpostIds = data.map(async d => { // if (d.id) { const convertedata = d; const post = new ContentPosts(); post.collectionType = engagementExplores; post.collectionTypeId = convertedata.id; post.segment = 'Exploration'; post.type = 'For You'; post.patientId = patientId; post.userId = Number(patientResp.userId); const postSaved = await this.dailyCheckIns.createContentPosts( post, token, ); d.contentPostId = Number(postSaved.id); d.contentWebUrl = `${process.env.PORTAL_URL}/explore/${engagementExplores}/${d.id}`; return d; }); data = await Promise.all(dataWithpostIds); } else { const previousdata: EngagementExplore[] = []; todaypost.forEach(tp => { if (!tp.isRead) { const tPost = data.find(upc => upc.id === tp.collectionTypeId); if (tPost) { tPost.contentPostId = Number(tp?.id); tPost.createdPostAt = tp?.createdOn; tPost.contentWebUrl = `${process.env.PORTAL_URL}/explore/${engagementExplores}/${tPost.id}`; previousdata.push(tPost as EngagementExplore); } } }); data = previousdata; } unReadPosts.forEach(up => { const unreasPost = unReadPostsCOnverted.find( upc => upc.id === up.collectionTypeId, ); if (unreasPost) { unreasPost.contentPostId = Number(up?.id); unreasPost.createdPostAt = up?.createdOn; unreasPost.contentWebUrl = `${process.env.PORTAL_URL}/explore/${engagementExplores}/${unreasPost.id}`; data.push(unreasPost); } }); } return data; } // sonarignore:end }