Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. module.exports = class ProfileService extends Schmervice.Service {
  8. constructor(...args) {
  9. super(...args)
  10. /** Scores available in the db to map against score indices*/
  11. this.scoreLookup = {}
  12. /** Tags available in the db to map against tag_associations*/
  13. this.tagLookup = {}
  14. // this.responseKeyLookup = ResponseKey.query()
  15. }
  16. async _setScoreLookup() {
  17. if (!Object.keys(this.scoreLookup).length) {
  18. const { Aspect, AspectLabel } = this.server.models()
  19. const aspects = await Aspect.query()
  20. const labels = await AspectLabel.query()
  21. this.scoreLookup = scoring.makeScoreLookup(aspects, labels)
  22. }
  23. }
  24. async _setTagLookup() {
  25. /** Grab tag descriptions if they do NOT exist: Needed once per app load */
  26. if (Object.keys(this.tagLookup).length) return
  27. const { Tag } = this.server.models()
  28. const allTagDescriptions = await Tag.query()
  29. allTagDescriptions.forEach(desc => {
  30. if (!desc.is_active) return
  31. this.tagLookup[desc.tag_id] = desc
  32. })
  33. }
  34. /**
  35. * Internal method to get list of profile_ids for this user
  36. * @param {number} userId
  37. * @returns {Array} List of all profile_ids for user
  38. */
  39. async _getProfileIdsForUserId(userId) {
  40. const { Profile } = this.server.models()
  41. /** Grab every Profile associated with this id */
  42. const allProfiles = await Profile.query().where('user_id', userId)
  43. /** Copy a list of the just the Profiles */
  44. const profileIdsToGrab = allProfiles.map(profile => profile.profile_id)
  45. /** Uncomment to dedupe the list just in case */
  46. return [...new Set(profileIdsToGrab)]
  47. }
  48. async getProfile(profileId) {
  49. const { Profile } = this.server.models()
  50. await this._setTagLookup()
  51. const matchingProfile = await Profile.query()
  52. .where('profile_id', profileId)
  53. .first()
  54. .withGraphFetched('tags')
  55. .withGraphFetched('responses')
  56. .withGraphFetched('user')
  57. matchingProfile.tags = matchingProfile.tags.map(
  58. tag => this.tagLookup[tag.tag_id],
  59. )
  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.makeCompleteFromProfileEntries(
  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.makeOrderedCompleteProfiles(
  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('---')
  223. console.log('defaultProfile: ', defaultProfile.user_email)
  224. if (!complete.reveal.length) return defaultProfile // nothing to reveal
  225. // swap out values of keys that are not found as complete.reveal.tag.tag_description values
  226. for (let [attribute, defaultVal] of Object.entries(defaultValues)) {
  227. if (
  228. typeof complete.reveal.find(
  229. tag => tag.tag_description == attribute,
  230. ) == 'undefined'
  231. )
  232. complete[attribute] = defaultVal
  233. }
  234. console.log('complete: ', complete.user_email)
  235. return complete
  236. }
  237. /**
  238. * Delete a profile
  239. * @param {number} userId
  240. * @param {number} profileId
  241. * @returns
  242. */
  243. async deleteProfile(userId, profileId) {
  244. const { Profile } = this.server.models()
  245. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  246. /** Do NOTHING if NOT in Grouping */
  247. if (!dedupedGroupings.includes(profileId)) return
  248. return await Profile.query().delete().where('profile_id', profileId)
  249. }
  250. /**
  251. * Score a profile
  252. * @param {number} profileId
  253. * @returns {Array} Ordered and scored Profiles
  254. */
  255. async scoreProfilesFor(profileId, maxDistance, distanceUnit) {
  256. const { Profile } = this.server.models()
  257. await this._setScoreLookup()
  258. // Our User Profile to score for
  259. const userProfile = await Profile.query()
  260. .findOne('profile_id', profileId)
  261. .withGraphFetched('responses')
  262. .withGraphFetched('user')
  263. // Move unneeded responses
  264. const userZip = zipcoder.getZipCodeFromProfile(userProfile)
  265. // Find all Profiles that are NOT of our userProfile.type
  266. // ie. If userProfile.type == seeker, then find: poster
  267. let profileIdsOfOppositeType = await Profile.query()
  268. .withGraphFetched('responses')
  269. .withGraphFetched('user')
  270. // TODO: Let Objection optimize this
  271. const isPosterOpposite = userProfile.user.is_poster == 1 ? 0 : 1
  272. profileIdsOfOppositeType = profileIdsOfOppositeType
  273. .filter(profile => {
  274. return profile.user.is_poster == isPosterOpposite
  275. })
  276. .filter(profile => {
  277. // Only include profiles that included zipcode response
  278. return zipcoder.getZipCodeFromProfile(profile) ? true : false
  279. })
  280. const profilePlusDistance = await Promise.all(
  281. profileIdsOfOppositeType.map(async profile => {
  282. const targetZip = zipcoder.getZipCodeFromProfile(profile)
  283. if (!userZip || !targetZip)
  284. return { ...profile, distance: [9999, distanceUnit] }
  285. const distance = await this._compareDistance(
  286. userZip,
  287. targetZip,
  288. distanceUnit,
  289. )
  290. return {
  291. ...profile,
  292. distance: [distance.toFixed(2), distanceUnit],
  293. }
  294. }),
  295. )
  296. const distanceFilteredProfiles = zipcoder.filterByDistance(
  297. profilePlusDistance,
  298. maxDistance,
  299. )
  300. const scoredProfilesWithDistance = scoring.scoreAll(
  301. distanceFilteredProfiles,
  302. userProfile,
  303. this.scoreLookup,
  304. )
  305. // Order by score
  306. return scoredProfilesWithDistance.sort(
  307. (a, b) => b.score.total - a.score.total,
  308. )
  309. }
  310. /**
  311. * Use the db for zipcode info
  312. * @param {string} zipCode
  313. * @param {object}
  314. */
  315. async _latLonForZip(zipCode) {
  316. const { ZipCode } = this.server.models()
  317. const zipInfo = await ZipCode.query().findOne(
  318. 'zip_code_id',
  319. parseInt(zipCode),
  320. )
  321. if (!zipInfo) {
  322. console.error('zip:', zipCode)
  323. }
  324. return {
  325. latitude: parseFloat(zipInfo.latitude),
  326. longitude: parseFloat(zipInfo.longitude),
  327. }
  328. }
  329. /**
  330. * Get the distance between two zipcodes
  331. * using the haversine formula
  332. * @param {string} start_zip
  333. * @param {string} end_zip
  334. * @param {number} distance in miles
  335. */
  336. async _compareDistance(start_zip, end_zip, distanceUnit) {
  337. if (!start_zip || !end_zip || isNaN(start_zip) || isNaN(end_zip)) return
  338. const start = await this._latLonForZip(start_zip)
  339. const end = await this._latLonForZip(end_zip)
  340. return haversine(start, end, { unit: distanceUnit })
  341. }
  342. /**
  343. * Use the db to grab tag associations
  344. * by profile and match them to tag types
  345. * @param {number} profileId
  346. * @param {object}
  347. */
  348. async getTagsFor(profileId, groupingId, category) {
  349. const { TagAssociation } = this.server.models()
  350. await this._setTagLookup()
  351. let associations = groupingId
  352. ? await TagAssociation.query()
  353. .where('grouping_id', groupingId)
  354. .andWhere('profile_id', profileId)
  355. : await TagAssociation.query().andWhere('profile_id', profileId)
  356. return associations
  357. .map(assoc => ({
  358. ...assoc,
  359. tag: this.tagLookup[assoc.tag_id],
  360. }))
  361. .filter(tagWithAssoc => {
  362. return category
  363. ? tagWithAssoc.tag.tag_category == category
  364. : true
  365. })
  366. }
  367. /**
  368. * Use the db to grab tag associations
  369. * by profile, grouping, tag, and insert
  370. * it if it already exists
  371. * @param {object} association
  372. */
  373. async revealProfileInfo(association) {
  374. const { TagAssociation } = this.server.models()
  375. const existingAssociations = await TagAssociation.query()
  376. .where('profile_id', `${association.profile_id}`)
  377. .where('grouping_id', `${association.grouping_id}`)
  378. .where('tag_id', `${association.tag_id}`)
  379. .where('is_deleted', 0)
  380. if (!existingAssociations.length) {
  381. await TagAssociation.query().insert(association)
  382. return await this.getTagsFor(association.profile_id)
  383. } else {
  384. return console.error('tag association already exists')
  385. }
  386. }
  387. }