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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. try {
  125. const profile = await Profile.query(txn).insert({
  126. user_id: userId,
  127. })
  128. for (const responseToSave of responses) {
  129. const convertedResponse = this._convertResponse(responseToSave)
  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. } catch (err) {
  140. throw new Error(err)
  141. }
  142. }
  143. /** Update responses in place
  144. * @param {number} profileId
  145. * @param {Array} responses
  146. * @returns {Array} updated responses
  147. */
  148. async updateResponsesInProfile(profileId, responses, txn) {
  149. const { Response } = this.server.models()
  150. for (const responseToSave of responses) {
  151. await Response.query(txn)
  152. .update({
  153. response_id: responseToSave.response_id,
  154. profile_id: responseToSave.profile_id,
  155. response_key_id: responseToSave.response_key_id,
  156. val: responseToSave.val,
  157. })
  158. .where({
  159. profile_id: profileId,
  160. })
  161. .where({
  162. response_id: responseToSave.response_id,
  163. })
  164. }
  165. return await Response.query(txn).where({
  166. profile_id: profileId,
  167. })
  168. }
  169. async insertSingleResponseForProfile(responseToSave) {
  170. const { Response } = this.server.models()
  171. const convertedResponse = this._convertResponse(responseToSave)
  172. const savedResponse = await Response.query().insert(convertedResponse)
  173. delete savedResponse.id
  174. return savedResponse
  175. }
  176. /** Add response
  177. * @param {Object} response to save
  178. * @returns {null} updated responses
  179. * @returns {Array} updated responses
  180. */
  181. async saveResponseForProfile(profileId, responseToSave) {
  182. const { Response } = this.server.models()
  183. let allResponses = await Response.query().where({
  184. profile_id: profileId,
  185. })
  186. // Delete matches
  187. // ?:Maybe bad idea
  188. const matchingResponses = allResponses.filter(
  189. response =>
  190. response.response_key_id == responseToSave.response_key_id,
  191. )
  192. if (matchingResponses.length > 0) {
  193. const alreadyAnswered = matchingResponses.map(
  194. matchingRes => matchingRes.response_key_id,
  195. )
  196. await Response.query()
  197. .where({ profile_id: profileId })
  198. .delete()
  199. .whereIn('response_key_id', alreadyAnswered)
  200. }
  201. const convertedResponse = this._convertResponse(responseToSave)
  202. await Response.query().insert(convertedResponse)
  203. return allResponses
  204. }
  205. /**
  206. * Delete a profile
  207. * @param {number} userId
  208. * @param {number} profileId
  209. * @returns
  210. */
  211. async deleteProfile(userId, profileId) {
  212. const { Profile } = this.server.models()
  213. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  214. /** Do NOTHING if NOT in Grouping */
  215. if (!dedupedGroupings.includes(profileId)) return
  216. return await Profile.query().delete().where('profile_id', profileId)
  217. }
  218. /**
  219. * Score a profile
  220. * @param {number} profileId
  221. * @returns {Array} Ordered and scored Profiles
  222. */
  223. async scoreProfilesFor(profileId, maxDistance, distanceUnit) {
  224. const { Profile } = this.server.models()
  225. await this._setScoreLookup()
  226. // Our User Profile to score for
  227. const userProfile = await Profile.query()
  228. .findOne('profile_id', profileId)
  229. .withGraphFetched('responses')
  230. .withGraphFetched('user')
  231. // Move unneeded responses
  232. const userZip = zipcoder.getZipCodeFromProfile(userProfile)
  233. // Find all Profiles that are NOT of our userProfile.type
  234. // ie. If userProfile.type == seeker, then find: poster
  235. let profileIdsOfOppositeType = await Profile.query()
  236. .withGraphFetched('responses')
  237. .withGraphFetched('user')
  238. // TODO: Let Objection optimize this
  239. const isPosterOpposite = userProfile.user.is_poster == 1 ? 0 : 1
  240. profileIdsOfOppositeType = profileIdsOfOppositeType
  241. .filter(profile => {
  242. return profile.user.is_poster == isPosterOpposite
  243. })
  244. .filter(profile => {
  245. // Only include profiles that included zipcode response
  246. return zipcoder.getZipCodeFromProfile(profile) ? true : false
  247. })
  248. const profilePlusDistance = await Promise.all(
  249. profileIdsOfOppositeType.map(async profile => {
  250. const targetZip = zipcoder.getZipCodeFromProfile(profile)
  251. if (!userZip || !targetZip)
  252. return { ...profile, distance: [9999, distanceUnit] }
  253. const distance = await this._compareDistance(
  254. userZip,
  255. targetZip,
  256. distanceUnit,
  257. )
  258. return {
  259. ...profile,
  260. distance: [distance.toFixed(2), distanceUnit],
  261. }
  262. }),
  263. )
  264. const distanceFilteredProfiles = zipcoder.filterByDistance(
  265. profilePlusDistance,
  266. maxDistance,
  267. )
  268. const scoredProfilesWithDistance = scoring.scoreAll(
  269. distanceFilteredProfiles,
  270. userProfile,
  271. this.scoreLookup,
  272. )
  273. // Order by score
  274. return scoredProfilesWithDistance.sort(
  275. (a, b) => b.score.total - a.score.total,
  276. )
  277. }
  278. /**
  279. * Use the db for zipcode info
  280. * @param {string} zipCode
  281. * @param {object}
  282. */
  283. async _latLonForZip(zipCode) {
  284. const { ZipCode } = this.server.models()
  285. const zipInfo = await ZipCode.query().findOne(
  286. 'zip_code_id',
  287. parseInt(zipCode),
  288. )
  289. if (!zipInfo) {
  290. console.error('zip:', zipCode)
  291. }
  292. return {
  293. latitude: parseFloat(zipInfo.latitude),
  294. longitude: parseFloat(zipInfo.longitude),
  295. }
  296. }
  297. /**
  298. * Get the distance between two zipcodes
  299. * using the haversine formula
  300. * @param {string} start_zip
  301. * @param {string} end_zip
  302. * @param {number} distance in miles
  303. */
  304. async _compareDistance(start_zip, end_zip, distanceUnit) {
  305. if (!start_zip || !end_zip || isNaN(start_zip) || isNaN(end_zip)) return
  306. const start = await this._latLonForZip(start_zip)
  307. const end = await this._latLonForZip(end_zip)
  308. return haversine(start, end, { unit: distanceUnit })
  309. }
  310. /**
  311. * Use the db to grab tag associations
  312. * by profile and match them to tag types
  313. * @param {number} profileId
  314. * @param {object}
  315. */
  316. async getTagsFor(profileId, groupingId, category) {
  317. const { TagAssociation } = this.server.models()
  318. await this._setTagLookup()
  319. let associations = groupingId
  320. ? await TagAssociation.query()
  321. .where('grouping_id', groupingId)
  322. .andWhere('profile_id', profileId)
  323. : await TagAssociation.query().andWhere('profile_id', profileId)
  324. return associations
  325. .map(assoc => ({
  326. ...assoc,
  327. tag: this.tagLookup[assoc.tag_id],
  328. }))
  329. .filter(tagWithAssoc => {
  330. return category
  331. ? tagWithAssoc.tag.tag_category == category
  332. : true
  333. })
  334. }
  335. /**
  336. * Use the db to grab tag associations
  337. * by profile, grouping, tag, and insert
  338. * it if it already exists
  339. * @param {object} association
  340. */
  341. async revealProfileInfo(association) {
  342. const { TagAssociation } = this.server.models()
  343. const existingAssociations = await TagAssociation.query()
  344. .where('profile_id', `${association.profile_id}`)
  345. .where('grouping_id', `${association.grouping_id}`)
  346. .where('tag_id', `${association.tag_id}`)
  347. .where('is_deleted', 0)
  348. if (!existingAssociations.length) {
  349. await TagAssociation.query().insert(association)
  350. return await this.getTagsFor(association.profile_id)
  351. } else {
  352. return console.error('ERROR =>: tag association already exists')
  353. }
  354. }
  355. }