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

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