You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

profile.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. const Schmervice = require('@hapipal/schmervice')
  2. const haversine = require('haversine')
  3. const config = require('../../db/data-generator/config.json')
  4. const _isScorableResponse = res_key_id => {
  5. let isScorable = false
  6. if(config.resKeys.includes(res_key_id)) {
  7. isScorable = true
  8. }
  9. return isScorable
  10. }
  11. const scoreResponses = (seeker, potentialMatch, prescoreLookup) => {
  12. if (seeker.responses.length != potentialMatch.responses.length)
  13. return {
  14. error: `complete responses for profile: ${seeker.profile_id} unqeual to profile: ${potentialMatch.profile_id} | ${seeker.responses.length}:${potentialMatch.responses.length}`,
  15. }
  16. const aRes = seeker.responses.filter(
  17. res => _isScorableResponse(res.response_key_id)
  18. )
  19. const bRes = potentialMatch.responses.filter(
  20. res => _isScorableResponse(res.response_key_id)
  21. )
  22. const composite = []
  23. while (aRes.length + bRes.length > 0) {
  24. const mKey = resList => {
  25. let el = resList.shift()
  26. let pair = el.val
  27. el = resList.shift()
  28. return `${pair}:${el.val}`
  29. }
  30. composite.push(prescoreLookup[mKey(aRes)][mKey(bRes)])
  31. }
  32. return {
  33. total: Math.round(composite.reduce((a, b) => a + b) / composite.length),
  34. aspects: composite,
  35. }
  36. }
  37. const filterByDistance = (profileList, max) => {
  38. return profileList.filter(profile => {
  39. const profileDistance = Math.floor(parseFloat(profile.distance) * 100)
  40. const adjustedMaxDistance = Math.floor(parseFloat(max) * 100)
  41. return profileDistance <= adjustedMaxDistance
  42. })
  43. }
  44. const scoreAll = (profileList, userProfile, prescoreLookup) => {
  45. return profileList.map(profile => {
  46. return {
  47. // Uncomment to return the whole profile
  48. // ...profile,
  49. profile_id: profile.profile_id,
  50. score: scoreResponses(userProfile, profile, prescoreLookup),
  51. distance: profile.distance,
  52. }
  53. })
  54. }
  55. /**
  56. * Grab the zip code string
  57. */
  58. const getZipCodeFromProfile = profile => {
  59. // There should only be one zip code entry per profile
  60. let zipRes = profile.responses.find(
  61. res => res.response_key_id == 7
  62. )
  63. return zipRes.val
  64. }
  65. const makeScoreLookup = (aspects, labels) => {
  66. const labelLookup = {}
  67. labels.forEach(label => (labelLookup[label.aspect_id] = label))
  68. const scoreLookup = {}
  69. aspects.forEach(aspect => {
  70. const key = labelLookup[aspect.aspect_id]
  71. scoreLookup[`${key.a}:${key.b}`] = {}
  72. Object.keys(aspect).forEach(aspect_id => {
  73. if (!labelLookup[aspect_id]) return
  74. const comp = labelLookup[aspect_id]
  75. const score = aspect[aspect_id]
  76. scoreLookup[`${key.a}:${key.b}`][`${comp.a}:${comp.b}`] = score
  77. })
  78. })
  79. return scoreLookup
  80. }
  81. /**
  82. * Class to hold our retrieved profile information
  83. * in a convenient wrapper
  84. * !: This needs to match the responseSchema in profiles.js
  85. */
  86. class CompleteProfile {
  87. constructor(profile, type) {
  88. this.user_id = profile.user_id // int user_id
  89. this.profile_id = profile.profile_id // int profile_id
  90. this.user_name = profile.user.user_name // string user_name
  91. this.user_email = profile.user.user_email
  92. this.responses = []
  93. this.tags = profile.tags // [] of all tags
  94. this.user_type = type
  95. // TODO: generalize this for multiple images, and languages
  96. this.profile_description = ''
  97. this.profile_media = []
  98. this.profile_languages = []
  99. this.profile_prefs = {}
  100. if (profile?.responses?.length) {
  101. // [] of all "profile" responses
  102. this.responses = profile.responses
  103. // image, language, duration, presence, blurb, urgency, role, pronouns, distance
  104. const prefs = ['zipcode', 'duration', 'presence', 'urgency', 'role', 'pronouns', 'distance']
  105. const prefsKeys = config.prefKeys
  106. prefs.forEach((pref, i) => {
  107. this.profile_prefs[pref] = this.responses.filter(
  108. r => r.response_key_id === prefsKeys[i]
  109. )[0]
  110. })
  111. // TODO: filter these correctly
  112. this.profile_description = this.responses.filter(r => r.response_key_id === config.blurbKey).map(r => r.val)[0]
  113. this.profile_media = this.responses.filter(r => r.response_key_id === config.mediaKey).map(r => r.val)
  114. this.profile_languages = this.responses.filter(r => r.response_key_id === config.langKey).map(r => r.val)
  115. }
  116. }
  117. }
  118. module.exports = class ProfileService extends Schmervice.Service {
  119. constructor(...args) {
  120. super(...args)
  121. this.scoreLookup = {}
  122. this.tagLookup = {}
  123. // this.responseKeyLookup = ResponseKey.query()
  124. }
  125. async _setScoreLookup() {
  126. if (!Object.keys(this.scoreLookup).length) {
  127. const { Aspect, AspectLabel } = this.server.models()
  128. const aspects = await Aspect.query()
  129. const labels = await AspectLabel.query()
  130. this.scoreLookup = makeScoreLookup(aspects, labels)
  131. }
  132. }
  133. async _setTagLookup() {
  134. if (!Object.keys(this.tagLookup).length) {
  135. const { Tag } = this.server.models()
  136. const allTagDescriptions = await Tag.query()
  137. allTagDescriptions.forEach(
  138. desc =>
  139. (this.tagLookup[desc.tag_id] = {
  140. description: desc.tag_description,
  141. category: desc.tag_category,
  142. }),
  143. )
  144. }
  145. }
  146. /**
  147. * Internal method to get list of profile_ids for this user
  148. * @param {number} userId
  149. * @returns {Array} List of all profile_ids for user
  150. */
  151. async _getProfileIdsForUserId(userId) {
  152. const { Profile } = this.server.models()
  153. /** Grab every Profile associated with this id */
  154. const allProfiles = await Profile.query().where('user_id', userId)
  155. /** Copy a list of the just the Profiles */
  156. const profileIdsToGrab = allProfiles.map(profile => profile.profile_id)
  157. /** Uncomment to dedupe the list just in case */
  158. return [...new Set(profileIdsToGrab)]
  159. }
  160. async getProfile(profileId) {
  161. const { Profile } = this.server.models()
  162. await this._setTagLookup()
  163. const matchingProfile = await Profile.query()
  164. .where('profile_id', profileId)
  165. .first()
  166. .withGraphFetched('tags')
  167. .withGraphFetched('responses')
  168. .withGraphFetched('user')
  169. if(matchingProfile?.tags.length){
  170. matchingProfile.tags = matchingProfile.tags.map(
  171. tag => this.tagLookup[tag.tag_id],
  172. )
  173. }
  174. return new CompleteProfile(matchingProfile)
  175. }
  176. async getCompleteProfilesFor(userId, type) {
  177. const { Profile } = this.server.models()
  178. await this._setTagLookup()
  179. const dedupedProfileIds = await this._getProfileIdsForUserId(userId)
  180. const profilesEntries = await Profile.query()
  181. .whereIn('profile_id', dedupedProfileIds)
  182. .withGraphFetched('tags')
  183. .withGraphFetched('responses')
  184. // CHECKTHIS: Added this because we added user.user_name to CompleteProfile
  185. // so without this, we get undefined user_name
  186. .withGraphFetched('user')
  187. profilesEntries.forEach(profile => {
  188. profile.tags = profile.tags.map(tag => this.tagLookup[tag.tag_id])
  189. })
  190. //** Get responses asociated with each profile_id */
  191. return profilesEntries.map(profile => {
  192. return new CompleteProfile(profile, type)
  193. })
  194. }
  195. async getProfilesFor(profileIdArray, type, includeResponses = true) {
  196. const { Profile } = this.server.models()
  197. await this._setScoreLookup()
  198. await this._setTagLookup()
  199. // profilesEntries is profiles in dataaspect_labelsbase row order
  200. const profilesEntries = await Profile.query()
  201. .whereIn('profile_id', profileIdArray)
  202. .withGraphFetched('tags')
  203. .withGraphFetched('responses')
  204. .withGraphFetched('user')
  205. // taking the info from profilesEntries
  206. // to repack into completeProfiles
  207. // in same order as profileIdArray
  208. const completeProfiles = []
  209. profileIdArray.forEach(pid => {
  210. profilesEntries.forEach(entry => {
  211. if (entry.profile_id == pid) {
  212. const complete = new CompleteProfile(entry, type)
  213. if (!includeResponses) {
  214. delete complete['responses']
  215. }
  216. if (entry?.tags?.length) {
  217. complete.tags = entry.tags.map(
  218. tag => this.tagLookup[tag.tag_id],
  219. )
  220. }
  221. completeProfiles.push(complete)
  222. }
  223. })
  224. })
  225. return completeProfiles
  226. }
  227. /**
  228. * Save responses in a profile
  229. * @param {number} userId
  230. * @param {Array} responses
  231. * @returns {object}
  232. */
  233. async saveResponsesCreateProfileFor(userId, responses, txn) {
  234. const { Profile, Response } = this.server.models()
  235. const profile = await Profile.query(txn).insert({
  236. user_id: userId,
  237. })
  238. for (const responseToSave of responses) {
  239. /**
  240. * Convert indexes to actual score values
  241. * Using using the input and converting to index
  242. * of the generated possible prescore array in config
  243. * DUPLICATE:See saveResponseForProfile() line 343
  244. */
  245. let convertedResponse = responseToSave
  246. if(_isScorableResponse(responseToSave.response_key_id)) {
  247. // Convert -3 to 0, 0 to 3, 3 to 6
  248. const offset = (config.scoreVals.length - 1) / 2
  249. const indexFromInput = parseInt(responseToSave.val) + offset
  250. convertedResponse.val = config.scoreVals[indexFromInput].toString()
  251. }
  252. const responseInfo = {
  253. profile_id: profile.id,
  254. response_key_id: convertedResponse.response_key_id,
  255. val: convertedResponse.val,
  256. }
  257. await Response.query(txn).insert(responseInfo)
  258. }
  259. //** Work around for HAPI returning profile_id as id */
  260. return { user_id: profile.user_id, profile_id: profile.id }
  261. }
  262. /** Update responses in place
  263. * @param {number} profileId
  264. * @param {Array} responses
  265. * @returns {Array} updated responses
  266. */
  267. async updateResponsesInProfile(profileId, responses, txn) {
  268. const { Response } = this.server.models()
  269. for (const responseToSave of responses) {
  270. await Response.query(txn)
  271. .update({
  272. response_id: responseToSave.response_id,
  273. profile_id: responseToSave.profile_id,
  274. response_key_id: responseToSave.response_key_id,
  275. val: responseToSave.val,
  276. })
  277. .where({
  278. profile_id: profileId,
  279. })
  280. .where({
  281. response_id: responseToSave.response_id,
  282. })
  283. }
  284. return await Response.query(txn).where({
  285. profile_id: profileId,
  286. })
  287. }
  288. /** Add response
  289. * @param {Object} response to save
  290. * @returns {null} updated responses
  291. * @returns {Array} updated responses
  292. */
  293. async saveResponseForProfile(profileId, responseToSave) {
  294. const { Response } = this.server.models()
  295. let allResponses = await Response.query().where({
  296. profile_id: profileId,
  297. })
  298. // Delete matches
  299. // ?:Maybe bad idea
  300. const matchingResponses = allResponses.filter(
  301. response =>
  302. response.response_key_id == responseToSave.response_key_id,
  303. )
  304. if (matchingResponses.length > 0) {
  305. const alreadyAnswered = matchingResponses.map(
  306. matchingRes => matchingRes.response_key_id
  307. )
  308. await Response.query()
  309. .where({ profile_id: profileId })
  310. .delete()
  311. .whereIn('response_key_id', alreadyAnswered)
  312. }
  313. /**
  314. * Convert indexes to actual score values
  315. * Using using the input and converting to index
  316. * of the generated possible prescore array in config
  317. */
  318. let convertedResponse = responseToSave
  319. if(_isScorableResponse(responseToSave.response_key_id)) {
  320. // Convert -3 to 0, 0 to 3, 3 to 6
  321. const offset = (config.scoreVals.length - 1) / 2
  322. const indexFromInput = parseInt(responseToSave.val) + offset
  323. convertedResponse.val = config.scoreVals[indexFromInput].toString()
  324. }
  325. await Response.query().insert(convertedResponse)
  326. return allResponses
  327. }
  328. /**
  329. * Delete a profile
  330. * @param {number} userId
  331. * @param {number} profileId
  332. * @returns
  333. */
  334. async deleteProfile(userId, profileId) {
  335. const { Profile } = this.server.models()
  336. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  337. /** Do NOTHING if NOT in Grouping */
  338. if (!dedupedGroupings.includes(profileId)) return
  339. return await Profile.query().delete().where('profile_id', profileId)
  340. }
  341. /**
  342. * Score a profile
  343. * @param {number} profileId
  344. * @returns {Array} Ordered and scored Profiles
  345. */
  346. async scoreProfilesFor(profileId, maxDistance, distanceUnit) {
  347. const { Profile } = this.server.models()
  348. await this._setScoreLookup()
  349. // Our User Profile to score for
  350. const userProfile = await Profile.query()
  351. .findOne('profile_id', profileId)
  352. .withGraphFetched('responses')
  353. .withGraphFetched('user')
  354. // Move unneeded responses
  355. const userZip = getZipCodeFromProfile(userProfile)
  356. // Find all Profiles that are NOT of our userProfile.type
  357. // ie. If userProfile.type == seeker, then find: poster
  358. let profileIdsOfOppositeType = await Profile.query()
  359. .withGraphFetched('responses')
  360. .withGraphFetched('user')
  361. // TODO: Let Objection optimize this
  362. const isPosterOpposite = userProfile.user.is_poster == 1 ? 0 : 1
  363. profileIdsOfOppositeType = profileIdsOfOppositeType.filter(profile => {
  364. return profile.user.is_poster == isPosterOpposite
  365. }).filter(profile => {
  366. // Only include profiles that included zipcode response
  367. return getZipCodeFromProfile(profile) ? true : false
  368. })
  369. const profilePlusDistance = await Promise.all(
  370. profileIdsOfOppositeType.map(async profile => {
  371. const targetZip = getZipCodeFromProfile(profile)
  372. if (!userZip || !targetZip)
  373. return { ...profile, distance: [9999, distanceUnit] }
  374. const distance = await this._compareDistance(
  375. userZip,
  376. targetZip,
  377. distanceUnit,
  378. )
  379. return {
  380. ...profile,
  381. distance: [distance.toFixed(2), distanceUnit],
  382. }
  383. }),
  384. )
  385. const distanceFilteredProfiles = filterByDistance(
  386. profilePlusDistance,
  387. maxDistance,
  388. )
  389. const scoredProfilesWithDistance = scoreAll(
  390. distanceFilteredProfiles,
  391. userProfile,
  392. this.scoreLookup,
  393. )
  394. // Order by score
  395. return scoredProfilesWithDistance.sort(
  396. (a, b) => b.score.total - a.score.total,
  397. )
  398. }
  399. /**
  400. * Use the db for zipcode info
  401. * @param {string} zipCode
  402. * @param {object}
  403. */
  404. async _latLonForZip(zipCode) {
  405. const { ZipCode } = this.server.models()
  406. const zipInfo = await ZipCode.query().findOne(
  407. 'zip_code_id',
  408. parseInt(zipCode),
  409. )
  410. if (!zipInfo) {
  411. console.error('zip:', zipCode)
  412. }
  413. return {
  414. latitude: parseFloat(zipInfo.latitude),
  415. longitude: parseFloat(zipInfo.longitude),
  416. }
  417. }
  418. /**
  419. * Get the distance between two zipcodes
  420. * using the haversine formula
  421. * @param {string} start_zip
  422. * @param {string} end_zip
  423. * @param {number} distance in miles
  424. */
  425. async _compareDistance(start_zip, end_zip, distanceUnit) {
  426. if (!start_zip || !end_zip || isNaN(start_zip) || isNaN(end_zip)) return
  427. const start = await this._latLonForZip(start_zip)
  428. const end = await this._latLonForZip(end_zip)
  429. return haversine(start, end, { unit: distanceUnit })
  430. }
  431. }