const Joi = require('joi') const apiSchema = require('../../schemas/api') const errorSchema = require('../../schemas/errors') const pluginConfig = { handlerType: 'reveal', docs: { description: 'reveal', notes: 'Reveal profile information to a grouping by membership', }, } const validators = { params: Joi.object({ grouping_id: Joi.number() }), query: Joi.object({ profile_id: Joi.number(), tag_id: Joi.number() }), } const responseSchemas = { response: Joi.object({ tags: Joi.array().items(), }), error: errorSchema.single, } module.exports = { method: 'POST', path: '/{grouping_id}/reveal', options: { ...pluginConfig.docs, tags: ['api'], auth: false, cors: true, handler: async function (request, h) { const { membershipService, profileService, userService } = request.server.services() const grouping_id = request.params.grouping_id const { profile_id, tag_id } = request.query try { const associations = await profileService.revealProfileInfo({ profile_id, grouping_id, tag_id, is_deleted: false, }) // Notify both profiles that information has been revealed const memberships = await membershipService.findMemberships([ grouping_id, ]) const idsInGroup = memberships.map( membership => membership.profile_id, ) if (idsInGroup.length > 2) return console.error( 'ERROR: idsInGroup cannot have more than 2 entries: ', idsInGroup, ) // Grab User Info from Users Table const completeProfile = await profileService.getProfilesFor( [profile_id], 'participant', ) const userInfo = await userService.findById( completeProfile[0].user_id, ) // Grab the TagAssociation that matches the revealed profile // TODO: Check if there are multiple matching associations(?)(there shouldn't be) let matchingAssociation = null associations.forEach(tagAssoc => { if ( tagAssoc.grouping_id === grouping_id && tagAssoc.profile_id === profile_id && tagAssoc.tag_id === tag_id ) { matchingAssociation = tagAssoc } }) const description = matchingAssociation.tag.tag_description idsInGroup.forEach(profile_id => { request.server.methods.notify( `${profile_id}.stonk`, { name: 'REVEALED_INFO', revealed_info: userInfo[description], profile_id: completeProfile[0].profile_id, grouping_id: grouping_id, tag: tag_id, description, type: 'info', url: `url` }, h, ) }) return h .response({ ok: true, handler: pluginConfig.handlerType, data: { tags: associations }, }) .code(200) } catch (err) { return h .response({ ok: false, handler: pluginConfig.handlerType, data: { error: `${err}` }, }) .code(409) } }, /** Validate based on validators object */ validate: { ...validators, failAction: 'log', }, /** Validate the server response */ response: { status: { 200: apiSchema.single .append({ data: responseSchemas.response, }) .label('reveal_res'), 409: apiSchema.single .append({ data: responseSchemas.error, }) .label('error_single_res'), }, }, }, }