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 14KB

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