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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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, true)
  61. return this.setDefaults(complete)
  62. }
  63. async getCompleteProfilesFor(userId, type) {
  64. const { Profile } = this.server.models()
  65. await this._setTagLookup()
  66. const dedupedProfileIds = await this._getProfileIdsForUserId(userId)
  67. const profilesEntries = await Profile.query()
  68. .whereIn('profile_id', dedupedProfileIds)
  69. .withGraphFetched('tags')
  70. .withGraphFetched('responses')
  71. // CHECKTHIS: Added this because we added user.user_name to CompleteProfile
  72. // so without this, we get undefined user_name
  73. .withGraphFetched('user')
  74. return profiler.makeCompleteProfilesFromProfile(
  75. profilesEntries,
  76. type,
  77. this.tagLookup,
  78. )
  79. }
  80. async getProfilesFor(profileIdArray, type, includeResponses = true) {
  81. const { Profile } = this.server.models()
  82. await this._setScoreLookup()
  83. await this._setTagLookup()
  84. // profilesEntries is profiles in dataaspect_labelsbase row order
  85. const profilesEntries = await Profile.query()
  86. .whereIn('profile_id', profileIdArray)
  87. .withGraphFetched('tags')
  88. .withGraphFetched('responses')
  89. .withGraphFetched('user')
  90. // taking the info from profilesEntries
  91. // to repack into completeProfiles
  92. // in same order as profileIdArray
  93. return profiler.makeCompleteProfiles(
  94. profileIdArray,
  95. profilesEntries,
  96. type,
  97. includeResponses,
  98. this.tagLookup,
  99. )
  100. }
  101. /**
  102. * Save responses in a profile
  103. * @param {number} userId
  104. * @param {Array} responses
  105. * @returns {object}
  106. */
  107. async saveResponsesCreateProfileFor(userId, responses, txn) {
  108. const { Profile, Response } = this.server.models()
  109. const profile = await Profile.query(txn).insert({
  110. user_id: userId,
  111. })
  112. for (const responseToSave of responses) {
  113. /**
  114. * Convert indexes to actual score values
  115. * Using using the input and converting to index
  116. * of the generated possible prescore array in config
  117. * DUPLICATE:See saveResponseForProfile() line 343
  118. */
  119. let convertedResponse = responseToSave
  120. if (scoring._isScorableResponse(responseToSave.response_key_id)) {
  121. // Convert -3 to 0, 0 to 3, 3 to 6
  122. const offset = (config.scoreVals.length - 1) / 2
  123. const indexFromInput = parseInt(responseToSave.val) + offset
  124. convertedResponse.val =
  125. config.scoreVals[indexFromInput].toString()
  126. }
  127. const responseInfo = {
  128. profile_id: profile.id,
  129. response_key_id: convertedResponse.response_key_id,
  130. val: convertedResponse.val,
  131. }
  132. await Response.query(txn).insert(responseInfo)
  133. }
  134. //** Work around for HAPI returning profile_id as id */
  135. return { user_id: profile.user_id, profile_id: profile.id }
  136. }
  137. /** Update responses in place
  138. * @param {number} profileId
  139. * @param {Array} responses
  140. * @returns {Array} updated responses
  141. */
  142. async updateResponsesInProfile(profileId, responses, txn) {
  143. const { Response } = this.server.models()
  144. for (const responseToSave of responses) {
  145. await Response.query(txn)
  146. .update({
  147. response_id: responseToSave.response_id,
  148. profile_id: responseToSave.profile_id,
  149. response_key_id: responseToSave.response_key_id,
  150. val: responseToSave.val,
  151. })
  152. .where({
  153. profile_id: profileId,
  154. })
  155. .where({
  156. response_id: responseToSave.response_id,
  157. })
  158. }
  159. return await Response.query(txn).where({
  160. profile_id: profileId,
  161. })
  162. }
  163. /** Add response
  164. * @param {Object} response to save
  165. * @returns {null} updated responses
  166. * @returns {Array} updated responses
  167. */
  168. async saveResponseForProfile(profileId, responseToSave) {
  169. const { Response } = this.server.models()
  170. let allResponses = await Response.query().where({
  171. profile_id: profileId,
  172. })
  173. // Delete matches
  174. // ?:Maybe bad idea
  175. const matchingResponses = allResponses.filter(
  176. response =>
  177. response.response_key_id == responseToSave.response_key_id,
  178. )
  179. if (matchingResponses.length > 0) {
  180. const alreadyAnswered = matchingResponses.map(
  181. matchingRes => matchingRes.response_key_id,
  182. )
  183. await Response.query()
  184. .where({ profile_id: profileId })
  185. .delete()
  186. .whereIn('response_key_id', alreadyAnswered)
  187. }
  188. /**
  189. * Convert indexes to actual score values
  190. * Using using the input and converting to index
  191. * of the generated possible prescore array in config
  192. */
  193. let convertedResponse = responseToSave
  194. if (scoring._isScorableResponse(responseToSave.response_key_id)) {
  195. // Convert -3 to 0, 0 to 3, 3 to 6
  196. const offset = (config.scoreVals.length - 1) / 2
  197. const scoreFromInput = parseInt(responseToSave.val) + offset
  198. const scoreFromConfig = config.scoreVals.indexOf(scoreFromInput)
  199. if (scoreFromConfig < 0) {
  200. console.error('score not found in possible config responses')
  201. }
  202. convertedResponse.val = scoreFromConfig.toString()
  203. }
  204. await Response.query().insert(convertedResponse)
  205. return allResponses
  206. }
  207. /**
  208. * Sets default profile attributes
  209. * @param {object} complete
  210. * @returns {object} updated profile
  211. */
  212. setDefaults(complete){
  213. let defaultValues = {
  214. user_email: 'hidden@email.com',
  215. user_name: 'Hidden Name'
  216. }
  217. let defaultProfile = {
  218. ...complete,
  219. user_email: defaultValues.user_email,
  220. user_name: defaultValues.user_name,
  221. }
  222. console.log('defaultProfile: ', defaultProfile)
  223. if(!complete.reveal.length) return defaultProfile // nothing to reveal
  224. // swap out values of keys that are not found as complete.reveal.tag.tag_description values
  225. for(let [attribute, defaultVal] of Object.entries(defaultValues)){
  226. if(typeof complete.reveal.find(tag => tag.tag_description == attribute) == 'undefined') complete[attribute] = defaultVal
  227. }
  228. console.log('complete: ', complete)
  229. return complete
  230. }
  231. /**
  232. * Delete a profile
  233. * @param {number} userId
  234. * @param {number} profileId
  235. * @returns
  236. */
  237. async deleteProfile(userId, profileId) {
  238. const { Profile } = this.server.models()
  239. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  240. /** Do NOTHING if NOT in Grouping */
  241. if (!dedupedGroupings.includes(profileId)) return
  242. return await Profile.query().delete().where('profile_id', profileId)
  243. }
  244. /**
  245. * Score a profile
  246. * @param {number} profileId
  247. * @returns {Array} Ordered and scored Profiles
  248. */
  249. async scoreProfilesFor(profileId, maxDistance, distanceUnit) {
  250. const { Profile } = this.server.models()
  251. await this._setScoreLookup()
  252. // Our User Profile to score for
  253. const userProfile = await Profile.query()
  254. .findOne('profile_id', profileId)
  255. .withGraphFetched('responses')
  256. .withGraphFetched('user')
  257. // Move unneeded responses
  258. const userZip = zipcoder.getZipCodeFromProfile(userProfile)
  259. // Find all Profiles that are NOT of our userProfile.type
  260. // ie. If userProfile.type == seeker, then find: poster
  261. let profileIdsOfOppositeType = await Profile.query()
  262. .withGraphFetched('responses')
  263. .withGraphFetched('user')
  264. // TODO: Let Objection optimize this
  265. const isPosterOpposite = userProfile.user.is_poster == 1 ? 0 : 1
  266. profileIdsOfOppositeType = profileIdsOfOppositeType
  267. .filter(profile => {
  268. return profile.user.is_poster == isPosterOpposite
  269. })
  270. .filter(profile => {
  271. // Only include profiles that included zipcode response
  272. return zipcoder.getZipCodeFromProfile(profile) ? true : false
  273. })
  274. const profilePlusDistance = await Promise.all(
  275. profileIdsOfOppositeType.map(async profile => {
  276. const targetZip = zipcoder.getZipCodeFromProfile(profile)
  277. if (!userZip || !targetZip)
  278. return { ...profile, distance: [9999, distanceUnit] }
  279. const distance = await this._compareDistance(
  280. userZip,
  281. targetZip,
  282. distanceUnit,
  283. )
  284. return {
  285. ...profile,
  286. distance: [distance.toFixed(2), distanceUnit],
  287. }
  288. }),
  289. )
  290. const distanceFilteredProfiles = zipcoder.filterByDistance(
  291. profilePlusDistance,
  292. maxDistance,
  293. )
  294. const scoredProfilesWithDistance = scoring.scoreAll(
  295. distanceFilteredProfiles,
  296. userProfile,
  297. this.scoreLookup,
  298. )
  299. // Order by score
  300. return scoredProfilesWithDistance.sort(
  301. (a, b) => b.score.total - a.score.total,
  302. )
  303. }
  304. /**
  305. * Use the db for zipcode info
  306. * @param {string} zipCode
  307. * @param {object}
  308. */
  309. async _latLonForZip(zipCode) {
  310. const { ZipCode } = this.server.models()
  311. const zipInfo = await ZipCode.query().findOne(
  312. 'zip_code_id',
  313. parseInt(zipCode),
  314. )
  315. if (!zipInfo) {
  316. console.error('zip:', zipCode)
  317. }
  318. return {
  319. latitude: parseFloat(zipInfo.latitude),
  320. longitude: parseFloat(zipInfo.longitude),
  321. }
  322. }
  323. /**
  324. * Get the distance between two zipcodes
  325. * using the haversine formula
  326. * @param {string} start_zip
  327. * @param {string} end_zip
  328. * @param {number} distance in miles
  329. */
  330. async _compareDistance(start_zip, end_zip, distanceUnit) {
  331. if (!start_zip || !end_zip || isNaN(start_zip) || isNaN(end_zip)) return
  332. const start = await this._latLonForZip(start_zip)
  333. const end = await this._latLonForZip(end_zip)
  334. return haversine(start, end, { unit: distanceUnit })
  335. }
  336. /**
  337. * Use the db to grab tag associations
  338. * by profile and match them to tag types
  339. * @param {number} profileId
  340. * @param {object}
  341. */
  342. async getTagsFor(profileId, groupingId, category) {
  343. const { TagAssociation } = this.server.models()
  344. await this._setTagLookup()
  345. let associations = groupingId
  346. ? await TagAssociation.query()
  347. .where('grouping_id', groupingId)
  348. .andWhere('profile_id', profileId)
  349. : await TagAssociation.query().andWhere('profile_id', profileId)
  350. return associations
  351. .map(assoc => ({
  352. ...assoc,
  353. tag: this.tagLookup[assoc.tag_id],
  354. }))
  355. .filter(tagWithAssoc => {
  356. return category
  357. ? tagWithAssoc.tag.tag_category == category
  358. : true
  359. })
  360. }
  361. /**
  362. * Use the db to grab tag associations
  363. * by profile, grouping, tag, and insert
  364. * it if it already exists
  365. * @param {object} association
  366. */
  367. async revealProfileInfo(association) {
  368. const { TagAssociation } = this.server.models()
  369. const existingAssociations = await TagAssociation.query()
  370. .where('profile_id', `${association.profile_id}`)
  371. .where('grouping_id', `${association.grouping_id}`)
  372. .where('tag_id', `${association.tag_id}`)
  373. .where('is_deleted', 0)
  374. if (!existingAssociations.length) {
  375. await TagAssociation.query().insert(association)
  376. return await this.getTagsFor(association.profile_id)
  377. } else {
  378. return console.error('tag association already exists')
  379. }
  380. }
  381. }