Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. <<<<<<< HEAD
  8. const { response } = require('@hapi/hapi/lib/validation')
  9. =======
  10. const tagger = require('./tagger')
  11. <<<<<<< HEAD
  12. const filter = require('./filter')
  13. >>>>>>> 154d171 (:construction: new filter service to preprocess a users match pool before scoring)
  14. =======
  15. const filter = require('../filter')
  16. >>>>>>> 2f11270 (:construction: extended the score endpoint to support filter query params- duration, presence and certifications)
  17. module.exports = class ProfileService extends Schmervice.Service {
  18. constructor(...args) {
  19. super(...args)
  20. /** Scores available in the db to map against score indices*/
  21. this.scoreLookup = {}
  22. /** Tags available in the db to map against tag_associations*/
  23. this.tagLookup = {}
  24. // this.responseKeyLookup = ResponseKey.query()
  25. }
  26. async _setScoreLookup() {
  27. if (!Object.keys(this.scoreLookup).length) {
  28. const { Aspect, AspectLabel } = this.server.models()
  29. const aspects = await Aspect.query()
  30. const labels = await AspectLabel.query()
  31. this.scoreLookup = scoring.makeScoreLookup(aspects, labels)
  32. }
  33. }
  34. async _setTagLookup() {
  35. /** Grab tag descriptions if they do NOT exist: Needed once per app load */
  36. if (Object.keys(this.tagLookup).length) return
  37. const { Tag } = this.server.models()
  38. const allTagDescriptions = await Tag.query()
  39. allTagDescriptions.forEach(desc => {
  40. if (!desc.is_active) return
  41. this.tagLookup[desc.tag_id] = desc
  42. })
  43. }
  44. /**
  45. * Internal method to get list of profile_ids for this user
  46. * @param {number} userId
  47. * @returns {Array} List of all profile_ids for user
  48. */
  49. async _getProfileIdsForUserId(userId) {
  50. const { Profile } = this.server.models()
  51. /** Grab every Profile associated with this id */
  52. const allProfiles = await Profile.query().where('user_id', userId)
  53. /** Copy a list of the just the Profiles */
  54. const profileIdsToGrab = allProfiles.map(profile => profile.profile_id)
  55. /** Uncomment to dedupe the list just in case */
  56. return [...new Set(profileIdsToGrab)]
  57. }
  58. /**
  59. * Convert indexes to actual score values
  60. * Using using the input and converting to index
  61. * of the generated possible prescore array in config
  62. */
  63. _convertResponse(responseToSave) {
  64. if (scoring._isScorableResponse(responseToSave.response_key_id)) {
  65. // Convert -3 to 0, 0 to 3, 3 to 6
  66. const offset = (config.scoreVals.length - 1) / 2
  67. const scoreFromInput = parseInt(responseToSave.val) + offset
  68. const scoreFromConfig = config.scoreVals.indexOf(scoreFromInput)
  69. if (scoreFromConfig < 0) {
  70. console.error('score not found in possible config responses')
  71. }
  72. responseToSave.val = scoreFromConfig.toString()
  73. }
  74. return responseToSave
  75. }
  76. async getProfile(profileId) {
  77. const { Profile } = this.server.models()
  78. await this._setTagLookup()
  79. const matchingProfile = await Profile.query()
  80. .where('profile_id', profileId)
  81. .first()
  82. .withGraphFetched('tags')
  83. .withGraphFetched('responses')
  84. .withGraphFetched('user')
  85. matchingProfile.tags = matchingProfile.tags.map(
  86. tag => this.tagLookup[tag.tag_id],
  87. )
  88. return new profiler.CompleteProfile(matchingProfile)
  89. }
  90. async getCompleteProfilesFor(userId, type) {
  91. const { Profile } = this.server.models()
  92. await this._setTagLookup()
  93. const dedupedProfileIds = await this._getProfileIdsForUserId(userId)
  94. const profilesEntries = await Profile.query()
  95. .whereIn('profile_id', dedupedProfileIds)
  96. .withGraphFetched('tags')
  97. .withGraphFetched('responses')
  98. .withGraphFetched('user')
  99. return profiler.makeCompleteFromProfileEntries(
  100. profilesEntries,
  101. type,
  102. this.tagLookup,
  103. )
  104. }
  105. async getProfilesFor(profileIdArray, type) {
  106. const { Profile } = this.server.models()
  107. await this._setScoreLookup()
  108. await this._setTagLookup()
  109. // profilesEntries is profiles in database row order
  110. const profilesEntries = await Profile.query()
  111. .whereIn('profile_id', profileIdArray)
  112. .withGraphFetched('tags')
  113. .withGraphFetched('responses')
  114. .withGraphFetched('user')
  115. // taking the info from profilesEntries
  116. // to repack into completeProfiles
  117. // in same order as profileIdArray
  118. return profiler.makeOrderedCompleteProfiles(
  119. profileIdArray,
  120. profilesEntries,
  121. type,
  122. this.tagLookup,
  123. )
  124. }
  125. /**
  126. * Save responses in a profile
  127. * @param {number} userId
  128. * @param {Array} responses
  129. * @returns {object}
  130. */
  131. async saveResponsesCreateProfileFor(userId, responses, txn) {
  132. const { Profile, Response } = this.server.models()
  133. try {
  134. const profile = await Profile.query(txn).insert({
  135. user_id: userId,
  136. })
  137. for (const responseToSave of responses) {
  138. const convertedResponse = this._convertResponse(responseToSave)
  139. const responseInfo = {
  140. profile_id: profile.id,
  141. response_key_id: convertedResponse.response_key_id,
  142. val: convertedResponse.val,
  143. }
  144. await Response.query(txn).insert(responseInfo)
  145. }
  146. //** Work around for HAPI returning profile_id as id */
  147. return { user_id: profile.user_id, profile_id: profile.id }
  148. } catch (err) {
  149. throw new Error(err)
  150. }
  151. }
  152. /** Update responses in place
  153. * @param {number} profileId
  154. * @param {Array} responses
  155. * @returns {Array} updated responses
  156. */
  157. async updateResponsesInProfile(profileId, responses, txn) {
  158. const { Response } = this.server.models()
  159. for (const responseToSave of responses) {
  160. await Response.query(txn)
  161. .update({
  162. response_id: responseToSave.response_id,
  163. profile_id: responseToSave.profile_id,
  164. response_key_id: responseToSave.response_key_id,
  165. val: responseToSave.val,
  166. })
  167. .where({
  168. profile_id: profileId,
  169. })
  170. .where({
  171. response_id: responseToSave.response_id,
  172. })
  173. }
  174. return await Response.query(txn).where({
  175. profile_id: profileId,
  176. })
  177. }
  178. async insertSingleResponseForProfile(responseToSave) {
  179. const { Response } = this.server.models()
  180. const convertedResponse = this._convertResponse(responseToSave)
  181. const savedResponse = await Response.query().insert(convertedResponse)
  182. delete savedResponse.id
  183. return savedResponse
  184. }
  185. /** Add response
  186. * @param {Object} response to save
  187. * @returns {null} updated responses
  188. * @returns {Array} updated responses
  189. */
  190. async saveResponseForProfile(profileId, responseToSave) {
  191. const { Response } = this.server.models()
  192. let allResponses = await Response.query().where({
  193. profile_id: profileId,
  194. })
  195. // Delete matches
  196. // ?:Maybe bad idea
  197. const matchingResponses = allResponses.filter(
  198. response =>
  199. response.response_key_id == responseToSave.response_key_id,
  200. )
  201. if (matchingResponses.length > 0) {
  202. const alreadyAnswered = matchingResponses.map(
  203. matchingRes => matchingRes.response_key_id,
  204. )
  205. await Response.query()
  206. .where({ profile_id: profileId })
  207. .delete()
  208. .whereIn('response_key_id', alreadyAnswered)
  209. }
  210. const convertedResponse = this._convertResponse(responseToSave)
  211. await Response.query().insert(convertedResponse)
  212. return allResponses
  213. }
  214. /**
  215. * Delete a profile
  216. * @param {number} userId
  217. * @param {number} profileId
  218. * @returns
  219. */
  220. async deleteProfile(userId, profileId) {
  221. const { Profile } = this.server.models()
  222. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  223. /** Do NOTHING if NOT in Grouping */
  224. if (!dedupedGroupings.includes(profileId)) return
  225. return await Profile.query().delete().where('profile_id', profileId)
  226. }
  227. /**
  228. * Score a profile
  229. * @param {number} profileId
  230. * @returns {Array} Ordered and scored Profiles
  231. */
  232. async scoreProfilesFor(profileId, maxDistance, distanceUnit, duration, presence, certifications) {
  233. const { Profile } = this.server.models()
  234. await this._setScoreLookup()
  235. // Our User Profile to score for
  236. const userProfile = await Profile.query()
  237. .findOne('profile_id', profileId)
  238. .withGraphFetched('responses')
  239. .withGraphFetched('user')
  240. const userZip = zipcoder.getZipCodeFromProfile(userProfile)
  241. // preprocess potential match pool with filter service methods
  242. let matchPool = await Profile.query()
  243. .withGraphFetched('responses')
  244. .withGraphFetched('user')
  245. matchPool = filter.byProfileType(matchPool, userProfile.user)
  246. matchPool = filter.byNullZip(matchPool)
  247. // attach distance to pool profiles for max distance filter
  248. matchPool = await this.calcProfileDistances(matchPool, distanceUnit, userZip)
  249. matchPool = filter.byMaxDistance(matchPool, maxDistance)
  250. matchPool = filter.byDuration(matchPool, duration)
  251. matchPool = filter.byPresence(matchPool, presence)
  252. matchPool = filter.byCertifications(matchPool, certifications)
  253. const scoredProfilesWithDistance = scoring.scoreAll(
  254. matchPool,
  255. userProfile,
  256. this.scoreLookup,
  257. )
  258. // Order by score
  259. return scoredProfilesWithDistance.sort(
  260. (a, b) => b.score.total - a.score.total,
  261. )
  262. }
  263. async calcProfileDistances(matchPool, distanceUnit, userZip){
  264. await Promise.all(
  265. matchPool.map(async profile => {
  266. const targetZip = zipcoder.getZipCodeFromProfile(profile)
  267. if (!userZip || !targetZip)
  268. return { ...profile, distance: [9999, distanceUnit] }
  269. const distance = await this._compareDistance(
  270. userZip,
  271. targetZip,
  272. distanceUnit,
  273. )
  274. return {
  275. ...profile,
  276. distance: [distance.toFixed(2), distanceUnit],
  277. }
  278. })
  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('ERROR =>: tag association already exists')
  356. }
  357. }
  358. }