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.

index.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. const Schmervice = require('@hapipal/schmervice')
  2. const haversine = require('haversine')
  3. const config = require('../../../db/data-generator/config.json')
  4. const profiler = require('./profiler')
  5. const scoring = require('./scorer')
  6. const zipcoder = require('./zipcoder')
  7. module.exports = class ProfileService extends Schmervice.Service {
  8. constructor(...args) {
  9. super(...args)
  10. /** Scores available in the db to map against score indices*/
  11. this.scoreLookup = {}
  12. /** Tags available in the db to map against tag_associations*/
  13. this.tagLookup = {}
  14. // this.responseKeyLookup = ResponseKey.query()
  15. }
  16. async _setScoreLookup() {
  17. if (!Object.keys(this.scoreLookup).length) {
  18. const { Aspect, AspectLabel } = this.server.models()
  19. const aspects = await Aspect.query()
  20. const labels = await AspectLabel.query()
  21. this.scoreLookup = scoring.makeScoreLookup(aspects, labels)
  22. }
  23. }
  24. async _setTagLookup() {
  25. /** Grab tag descriptions if they do NOT exist: Needed once per app load */
  26. if (Object.keys(this.tagLookup).length) return
  27. const { Tag } = this.server.models()
  28. const allTagDescriptions = await Tag.query()
  29. allTagDescriptions.forEach(desc => {
  30. if (!desc.is_active) return
  31. this.tagLookup[desc.tag_id] = desc
  32. })
  33. }
  34. /**
  35. * Internal method to get list of profile_ids for this user
  36. * @param {number} userId
  37. * @returns {Array} List of all profile_ids for user
  38. */
  39. async _getProfileIdsForUserId(userId) {
  40. const { Profile } = this.server.models()
  41. /** Grab every Profile associated with this id */
  42. const allProfiles = await Profile.query().where('user_id', userId)
  43. /** Copy a list of the just the Profiles */
  44. const profileIdsToGrab = allProfiles.map(profile => profile.profile_id)
  45. /** Uncomment to dedupe the list just in case */
  46. return [...new Set(profileIdsToGrab)]
  47. }
  48. async getProfile(profileId) {
  49. const { Profile } = this.server.models()
  50. await this._setTagLookup()
  51. const matchingProfile = await Profile.query()
  52. .where('profile_id', profileId)
  53. .first()
  54. .withGraphFetched('tags')
  55. .withGraphFetched('responses')
  56. .withGraphFetched('user')
  57. matchingProfile.tags = matchingProfile.tags.map(
  58. tag => this.tagLookup[tag.tag_id],
  59. )
  60. const complete = new profiler.CompleteProfile(matchingProfile, true)
  61. // TODO: Refactor to use this.setDefaults(), currently does not play
  62. // nice with reveal functionality
  63. return complete
  64. // return this.setDefaults(complete)
  65. }
  66. async getCompleteProfilesFor(userId, type) {
  67. const { Profile } = this.server.models()
  68. await this._setTagLookup()
  69. const dedupedProfileIds = await this._getProfileIdsForUserId(userId)
  70. const profilesEntries = await Profile.query()
  71. .whereIn('profile_id', dedupedProfileIds)
  72. .withGraphFetched('tags')
  73. .withGraphFetched('responses')
  74. // CHECKTHIS: Added this because we added user.user_name to CompleteProfile
  75. // so without this, we get undefined user_name
  76. .withGraphFetched('user')
  77. return profiler.makeCompleteFromProfileEntries(
  78. profilesEntries,
  79. type,
  80. this.tagLookup,
  81. )
  82. }
  83. async getProfilesFor(profileIdArray, type, includeResponses = true) {
  84. const { Profile } = this.server.models()
  85. await this._setScoreLookup()
  86. await this._setTagLookup()
  87. // profilesEntries is profiles in dataaspect_labelsbase row order
  88. const profilesEntries = await Profile.query()
  89. .whereIn('profile_id', profileIdArray)
  90. .withGraphFetched('tags')
  91. .withGraphFetched('responses')
  92. .withGraphFetched('user')
  93. // taking the info from profilesEntries
  94. // to repack into completeProfiles
  95. // in same order as profileIdArray
  96. return profiler.makeOrderedCompleteProfiles(
  97. profileIdArray,
  98. profilesEntries,
  99. type,
  100. includeResponses,
  101. this.tagLookup,
  102. )
  103. }
  104. /**
  105. * Save responses in a profile
  106. * @param {number} userId
  107. * @param {Array} responses
  108. * @returns {object}
  109. */
  110. async saveResponsesCreateProfileFor(userId, responses, txn) {
  111. const { Profile, Response } = this.server.models()
  112. const profile = await Profile.query(txn).insert({
  113. user_id: userId,
  114. })
  115. for (const responseToSave of responses) {
  116. /**
  117. * Convert indexes to actual score values
  118. * Using using the input and converting to index
  119. * of the generated possible prescore array in config
  120. * DUPLICATE:See saveResponseForProfile() line 343
  121. */
  122. let convertedResponse = responseToSave
  123. if (scoring._isScorableResponse(responseToSave.response_key_id)) {
  124. // Convert -3 to 0, 0 to 3, 3 to 6
  125. const offset = (config.scoreVals.length - 1) / 2
  126. const indexFromInput = parseInt(responseToSave.val) + offset
  127. convertedResponse.val =
  128. config.scoreVals[indexFromInput].toString()
  129. }
  130. const responseInfo = {
  131. profile_id: profile.id,
  132. response_key_id: convertedResponse.response_key_id,
  133. val: convertedResponse.val,
  134. }
  135. await Response.query(txn).insert(responseInfo)
  136. }
  137. //** Work around for HAPI returning profile_id as id */
  138. return { user_id: profile.user_id, profile_id: profile.id }
  139. }
  140. /** Update responses in place
  141. * @param {number} profileId
  142. * @param {Array} responses
  143. * @returns {Array} updated responses
  144. */
  145. async updateResponsesInProfile(profileId, responses, txn) {
  146. const { Response } = this.server.models()
  147. for (const responseToSave of responses) {
  148. await Response.query(txn)
  149. .update({
  150. response_id: responseToSave.response_id,
  151. profile_id: responseToSave.profile_id,
  152. response_key_id: responseToSave.response_key_id,
  153. val: responseToSave.val,
  154. })
  155. .where({
  156. profile_id: profileId,
  157. })
  158. .where({
  159. response_id: responseToSave.response_id,
  160. })
  161. }
  162. return await Response.query(txn).where({
  163. profile_id: profileId,
  164. })
  165. }
  166. /** Add response
  167. * @param {Object} response to save
  168. * @returns {null} updated responses
  169. * @returns {Array} updated responses
  170. */
  171. async saveResponseForProfile(profileId, responseToSave) {
  172. const { Response } = this.server.models()
  173. let allResponses = await Response.query().where({
  174. profile_id: profileId,
  175. })
  176. // Delete matches
  177. // ?:Maybe bad idea
  178. const matchingResponses = allResponses.filter(
  179. response =>
  180. response.response_key_id == responseToSave.response_key_id,
  181. )
  182. if (matchingResponses.length > 0) {
  183. const alreadyAnswered = matchingResponses.map(
  184. matchingRes => matchingRes.response_key_id,
  185. )
  186. await Response.query()
  187. .where({ profile_id: profileId })
  188. .delete()
  189. .whereIn('response_key_id', alreadyAnswered)
  190. }
  191. /**
  192. * Convert indexes to actual score values
  193. * Using using the input and converting to index
  194. * of the generated possible prescore array in config
  195. */
  196. let convertedResponse = responseToSave
  197. if (scoring._isScorableResponse(responseToSave.response_key_id)) {
  198. // Convert -3 to 0, 0 to 3, 3 to 6
  199. const offset = (config.scoreVals.length - 1) / 2
  200. const scoreFromInput = parseInt(responseToSave.val) + offset
  201. const scoreFromConfig = config.scoreVals.indexOf(scoreFromInput)
  202. if (scoreFromConfig < 0) {
  203. console.error('score not found in possible config responses')
  204. }
  205. convertedResponse.val = scoreFromConfig.toString()
  206. }
  207. await Response.query().insert(convertedResponse)
  208. return allResponses
  209. }
  210. /**
  211. * Sets default profile attributes
  212. * @param {object} complete
  213. * @returns {object} updated profile
  214. */
  215. setDefaults(complete) {
  216. let defaultValues = {
  217. user_email: 'hidden@email.com',
  218. user_name: 'Hidden Name',
  219. }
  220. let defaultProfile = {
  221. ...complete,
  222. user_email: defaultValues.user_email,
  223. user_name: defaultValues.user_name,
  224. }
  225. console.log('---')
  226. console.log('defaultProfile: ', defaultProfile.user_email)
  227. if (!complete.reveal.length) return defaultProfile // nothing to reveal
  228. // swap out values of keys that are not found as complete.reveal.tag.tag_description values
  229. for (let [attribute, defaultVal] of Object.entries(defaultValues)) {
  230. if (
  231. typeof complete.reveal.find(
  232. tag => tag.tag_description == attribute,
  233. ) == 'undefined'
  234. )
  235. complete[attribute] = defaultVal
  236. }
  237. console.log('complete: ', complete.user_email)
  238. return complete
  239. }
  240. /**
  241. * Delete a profile
  242. * @param {number} userId
  243. * @param {number} profileId
  244. * @returns
  245. */
  246. async deleteProfile(userId, profileId) {
  247. const { Profile } = this.server.models()
  248. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  249. /** Do NOTHING if NOT in Grouping */
  250. if (!dedupedGroupings.includes(profileId)) return
  251. return await Profile.query().delete().where('profile_id', profileId)
  252. }
  253. /**
  254. * Score a profile
  255. * @param {number} profileId
  256. * @returns {Array} Ordered and scored Profiles
  257. */
  258. async scoreProfilesFor(profileId, maxDistance, distanceUnit) {
  259. const { Profile } = this.server.models()
  260. await this._setScoreLookup()
  261. // Our User Profile to score for
  262. const userProfile = await Profile.query()
  263. .findOne('profile_id', profileId)
  264. .withGraphFetched('responses')
  265. .withGraphFetched('user')
  266. // Move unneeded responses
  267. const userZip = zipcoder.getZipCodeFromProfile(userProfile)
  268. // Find all Profiles that are NOT of our userProfile.type
  269. // ie. If userProfile.type == seeker, then find: poster
  270. let profileIdsOfOppositeType = await Profile.query()
  271. .withGraphFetched('responses')
  272. .withGraphFetched('user')
  273. // TODO: Let Objection optimize this
  274. const isPosterOpposite = userProfile.user.is_poster == 1 ? 0 : 1
  275. profileIdsOfOppositeType = profileIdsOfOppositeType
  276. .filter(profile => {
  277. return profile.user.is_poster == isPosterOpposite
  278. })
  279. .filter(profile => {
  280. // Only include profiles that included zipcode response
  281. return zipcoder.getZipCodeFromProfile(profile) ? true : false
  282. })
  283. const profilePlusDistance = await Promise.all(
  284. profileIdsOfOppositeType.map(async profile => {
  285. const targetZip = zipcoder.getZipCodeFromProfile(profile)
  286. if (!userZip || !targetZip)
  287. return { ...profile, distance: [9999, distanceUnit] }
  288. const distance = await this._compareDistance(
  289. userZip,
  290. targetZip,
  291. distanceUnit,
  292. )
  293. return {
  294. ...profile,
  295. distance: [distance.toFixed(2), distanceUnit],
  296. }
  297. }),
  298. )
  299. const distanceFilteredProfiles = zipcoder.filterByDistance(
  300. profilePlusDistance,
  301. maxDistance,
  302. )
  303. const scoredProfilesWithDistance = scoring.scoreAll(
  304. distanceFilteredProfiles,
  305. userProfile,
  306. this.scoreLookup,
  307. )
  308. // Order by score
  309. return scoredProfilesWithDistance.sort(
  310. (a, b) => b.score.total - a.score.total,
  311. )
  312. }
  313. /**
  314. * Use the db for zipcode info
  315. * @param {string} zipCode
  316. * @param {object}
  317. */
  318. async _latLonForZip(zipCode) {
  319. const { ZipCode } = this.server.models()
  320. const zipInfo = await ZipCode.query().findOne(
  321. 'zip_code_id',
  322. parseInt(zipCode),
  323. )
  324. if (!zipInfo) {
  325. console.error('zip:', zipCode)
  326. }
  327. return {
  328. latitude: parseFloat(zipInfo.latitude),
  329. longitude: parseFloat(zipInfo.longitude),
  330. }
  331. }
  332. /**
  333. * Get the distance between two zipcodes
  334. * using the haversine formula
  335. * @param {string} start_zip
  336. * @param {string} end_zip
  337. * @param {number} distance in miles
  338. */
  339. async _compareDistance(start_zip, end_zip, distanceUnit) {
  340. if (!start_zip || !end_zip || isNaN(start_zip) || isNaN(end_zip)) return
  341. const start = await this._latLonForZip(start_zip)
  342. const end = await this._latLonForZip(end_zip)
  343. return haversine(start, end, { unit: distanceUnit })
  344. }
  345. /**
  346. * Use the db to grab tag associations
  347. * by profile and match them to tag types
  348. * @param {number} profileId
  349. * @param {object}
  350. */
  351. async getTagsFor(profileId, groupingId, category) {
  352. const { TagAssociation } = this.server.models()
  353. await this._setTagLookup()
  354. let associations = groupingId
  355. ? await TagAssociation.query()
  356. .where('grouping_id', groupingId)
  357. .andWhere('profile_id', profileId)
  358. : await TagAssociation.query().andWhere('profile_id', profileId)
  359. return associations
  360. .map(assoc => ({
  361. ...assoc,
  362. tag: this.tagLookup[assoc.tag_id],
  363. }))
  364. .filter(tagWithAssoc => {
  365. return category
  366. ? tagWithAssoc.tag.tag_category == category
  367. : true
  368. })
  369. }
  370. /**
  371. * Use the db to grab tag associations
  372. * by profile, grouping, tag, and insert
  373. * it if it already exists
  374. * @param {object} association
  375. */
  376. async revealProfileInfo(association) {
  377. const { TagAssociation } = this.server.models()
  378. const existingAssociations = await TagAssociation.query()
  379. .where('profile_id', `${association.profile_id}`)
  380. .where('grouping_id', `${association.grouping_id}`)
  381. .where('tag_id', `${association.tag_id}`)
  382. .where('is_deleted', 0)
  383. if (!existingAssociations.length) {
  384. await TagAssociation.query().insert(association)
  385. return await this.getTagsFor(association.profile_id)
  386. } else {
  387. return console.error('tag association already exists')
  388. }
  389. }
  390. }