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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 filter = require('../filter')
  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(
  224. profileId,
  225. maxDistance,
  226. distanceUnit,
  227. duration,
  228. presence,
  229. certifications,
  230. ) {
  231. const { Profile } = this.server.models()
  232. await this._setScoreLookup()
  233. // Our User Profile to score for
  234. const userProfile = await Profile.query()
  235. .findOne('profile_id', profileId)
  236. .withGraphFetched('responses')
  237. .withGraphFetched('user')
  238. const userZip = zipcoder.getZipCodeFromProfile(userProfile)
  239. // preprocess potential match pool with filter service methods
  240. let matchPool = await Profile.query()
  241. .withGraphFetched('responses')
  242. .withGraphFetched('user')
  243. matchPool = filter.byProfileType(matchPool, userProfile.user)
  244. matchPool = filter.byNullZip(matchPool)
  245. // attach distance to pool profiles for max distance filter
  246. matchPool = await this.calcProfileDistances(
  247. matchPool,
  248. distanceUnit,
  249. userZip,
  250. )
  251. matchPool = filter.byDistance(matchPool, maxDistance)
  252. matchPool = filter.byDuration(matchPool, duration)
  253. matchPool = filter.byPresence(matchPool, presence)
  254. matchPool = filter.byCertifications(matchPool, certifications)
  255. const scoredProfilesWithDistance = scoring.scoreAll(
  256. matchPool,
  257. userProfile,
  258. this.scoreLookup,
  259. )
  260. // Order by score
  261. return scoredProfilesWithDistance.sort(
  262. (a, b) => b.score.total - a.score.total,
  263. )
  264. }
  265. async calcProfileDistances(matchPool, distanceUnit, userZip) {
  266. await Promise.all(
  267. matchPool.map(async profile => {
  268. const targetZip = zipcoder.getZipCodeFromProfile(profile)
  269. if (!userZip || !targetZip)
  270. return { ...profile, distance: [9999, distanceUnit] }
  271. const distance = await this._compareDistance(
  272. userZip,
  273. targetZip,
  274. distanceUnit,
  275. )
  276. return {
  277. ...profile,
  278. distance: [distance.toFixed(2), distanceUnit],
  279. }
  280. }),
  281. )
  282. }
  283. /**
  284. * Use the db for zipcode info
  285. * @param {string} zipCode
  286. * @param {object}
  287. */
  288. async _latLonForZip(zipCode) {
  289. const { ZipCode } = this.server.models()
  290. const zipInfo = await ZipCode.query().findOne(
  291. 'zip_code_id',
  292. parseInt(zipCode),
  293. )
  294. if (!zipInfo) {
  295. console.error('zip:', zipCode)
  296. }
  297. return {
  298. latitude: parseFloat(zipInfo.latitude),
  299. longitude: parseFloat(zipInfo.longitude),
  300. }
  301. }
  302. /**
  303. * Get the distance between two zipcodes
  304. * using the haversine formula
  305. * @param {string} start_zip
  306. * @param {string} end_zip
  307. * @param {number} distance in miles
  308. */
  309. async _compareDistance(start_zip, end_zip, distanceUnit) {
  310. if (!start_zip || !end_zip || isNaN(start_zip) || isNaN(end_zip)) return
  311. const start = await this._latLonForZip(start_zip)
  312. const end = await this._latLonForZip(end_zip)
  313. return haversine(start, end, { unit: distanceUnit })
  314. }
  315. /**
  316. * Use the db to grab tag associations
  317. * by profile and match them to tag types
  318. * @param {number} profileId
  319. * @param {object}
  320. */
  321. async getTagsFor(profileId, groupingId, category) {
  322. const { TagAssociation } = this.server.models()
  323. await this._setTagLookup()
  324. let associations = groupingId
  325. ? await TagAssociation.query()
  326. .where('grouping_id', groupingId)
  327. .andWhere('profile_id', profileId)
  328. : await TagAssociation.query().andWhere('profile_id', profileId)
  329. return associations
  330. .map(assoc => ({
  331. ...assoc,
  332. tag: this.tagLookup[assoc.tag_id],
  333. }))
  334. .filter(tagWithAssoc => {
  335. return category
  336. ? tagWithAssoc.tag.tag_category == category
  337. : true
  338. })
  339. }
  340. /**
  341. * Use the db to grab tag associations
  342. * by profile, grouping, tag, and insert
  343. * it if it already exists
  344. * @param {object} association
  345. */
  346. async revealProfileInfo(association) {
  347. const { TagAssociation } = this.server.models()
  348. const existingAssociations = await TagAssociation.query()
  349. .where('profile_id', `${association.profile_id}`)
  350. .where('grouping_id', `${association.grouping_id}`)
  351. .where('tag_id', `${association.tag_id}`)
  352. .where('is_deleted', 0)
  353. if (!existingAssociations.length) {
  354. await TagAssociation.query().insert(association)
  355. return await this.getTagsFor(association.profile_id)
  356. } else {
  357. return console.error('ERROR =>: tag association already exists')
  358. }
  359. }
  360. }