Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 tagg_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(
  30. desc =>
  31. (this.tagLookup[desc.tag_id] = {
  32. description: desc.tag_description,
  33. category: desc.tag_category,
  34. }),
  35. )
  36. }
  37. }
  38. /**
  39. * Internal method to get list of profile_ids for this user
  40. * @param {number} userId
  41. * @returns {Array} List of all profile_ids for user
  42. */
  43. async _getProfileIdsForUserId(userId) {
  44. const { Profile } = this.server.models()
  45. /** Grab every Profile associated with this id */
  46. const allProfiles = await Profile.query().where('user_id', userId)
  47. /** Copy a list of the just the Profiles */
  48. const profileIdsToGrab = allProfiles.map(profile => profile.profile_id)
  49. /** Uncomment to dedupe the list just in case */
  50. return [...new Set(profileIdsToGrab)]
  51. }
  52. async getProfile(profileId) {
  53. const { Profile } = this.server.models()
  54. await this._setTagLookup()
  55. const matchingProfile = await Profile.query()
  56. .where('profile_id', profileId)
  57. .first()
  58. .withGraphFetched('tags')
  59. .withGraphFetched('responses')
  60. .withGraphFetched('user')
  61. tagger.setProfileTags(matchingProfile, matchingProfile, this.tagLookup)
  62. return new profiler.CompleteProfile(matchingProfile)
  63. }
  64. async getCompleteProfilesFor(userId, type) {
  65. const { Profile } = this.server.models()
  66. await this._setTagLookup()
  67. const dedupedProfileIds = await this._getProfileIdsForUserId(userId)
  68. const profilesEntries = await Profile.query()
  69. .whereIn('profile_id', dedupedProfileIds)
  70. .withGraphFetched('tags')
  71. .withGraphFetched('responses')
  72. // CHECKTHIS: Added this because we added user.user_name to CompleteProfile
  73. // so without this, we get undefined user_name
  74. .withGraphFetched('user')
  75. return profiler.makeCompleteProfilesFromProfile(profilesEntries, type, this.tagLookup)
  76. }
  77. async getProfilesFor(profileIdArray, type, includeResponses = true) {
  78. const { Profile } = this.server.models()
  79. await this._setScoreLookup()
  80. await this._setTagLookup()
  81. // profilesEntries is profiles in dataaspect_labelsbase row order
  82. const profilesEntries = await Profile.query()
  83. .whereIn('profile_id', profileIdArray)
  84. .withGraphFetched('tags')
  85. .withGraphFetched('responses')
  86. .withGraphFetched('user')
  87. // taking the info from profilesEntries
  88. // to repack into completeProfiles
  89. // in same order as profileIdArray
  90. return profiler.makeCompleteProfiles(
  91. profileIdArray,
  92. profilesEntries,
  93. type,
  94. includeResponses,
  95. this.tagLookup
  96. )
  97. }
  98. /**
  99. * Save responses in a profile
  100. * @param {number} userId
  101. * @param {Array} responses
  102. * @returns {object}
  103. */
  104. async saveResponsesCreateProfileFor(userId, responses, txn) {
  105. const { Profile, Response } = this.server.models()
  106. const profile = await Profile.query(txn).insert({
  107. user_id: userId,
  108. })
  109. for (const responseToSave of responses) {
  110. /**
  111. * Convert indexes to actual score values
  112. * Using using the input and converting to index
  113. * of the generated possible prescore array in config
  114. * DUPLICATE:See saveResponseForProfile() line 343
  115. */
  116. let convertedResponse = responseToSave
  117. if(scoring._isScorableResponse(responseToSave.response_key_id)) {
  118. // Convert -3 to 0, 0 to 3, 3 to 6
  119. const offset = (config.scoreVals.length - 1) / 2
  120. const indexFromInput = parseInt(responseToSave.val) + offset
  121. convertedResponse.val = config.scoreVals[indexFromInput].toString()
  122. }
  123. const responseInfo = {
  124. profile_id: profile.id,
  125. response_key_id: convertedResponse.response_key_id,
  126. val: convertedResponse.val,
  127. }
  128. await Response.query(txn).insert(responseInfo)
  129. }
  130. //** Work around for HAPI returning profile_id as id */
  131. return { user_id: profile.user_id, profile_id: profile.id }
  132. }
  133. /** Update responses in place
  134. * @param {number} profileId
  135. * @param {Array} responses
  136. * @returns {Array} updated responses
  137. */
  138. async updateResponsesInProfile(profileId, responses, txn) {
  139. const { Response } = this.server.models()
  140. for (const responseToSave of responses) {
  141. await Response.query(txn)
  142. .update({
  143. response_id: responseToSave.response_id,
  144. profile_id: responseToSave.profile_id,
  145. response_key_id: responseToSave.response_key_id,
  146. val: responseToSave.val,
  147. })
  148. .where({
  149. profile_id: profileId,
  150. })
  151. .where({
  152. response_id: responseToSave.response_id,
  153. })
  154. }
  155. return await Response.query(txn).where({
  156. profile_id: profileId,
  157. })
  158. }
  159. /** Add response
  160. * @param {Object} response to save
  161. * @returns {null} updated responses
  162. * @returns {Array} updated responses
  163. */
  164. async saveResponseForProfile(profileId, responseToSave) {
  165. const { Response } = this.server.models()
  166. let allResponses = await Response.query().where({
  167. profile_id: profileId,
  168. })
  169. // Delete matches
  170. // ?:Maybe bad idea
  171. const matchingResponses = allResponses.filter(
  172. response =>
  173. response.response_key_id == responseToSave.response_key_id,
  174. )
  175. if (matchingResponses.length > 0) {
  176. const alreadyAnswered = matchingResponses.map(
  177. matchingRes => matchingRes.response_key_id
  178. )
  179. await Response.query()
  180. .where({ profile_id: profileId })
  181. .delete()
  182. .whereIn('response_key_id', alreadyAnswered)
  183. }
  184. /**
  185. * Convert indexes to actual score values
  186. * Using using the input and converting to index
  187. * of the generated possible prescore array in config
  188. */
  189. let convertedResponse = responseToSave
  190. if(scoring._isScorableResponse(responseToSave.response_key_id)) {
  191. // Convert -3 to 0, 0 to 3, 3 to 6
  192. const offset = (config.scoreVals.length - 1) / 2
  193. const indexFromInput = parseInt(responseToSave.val) + offset
  194. convertedResponse.val = config.scoreVals[indexFromInput].toString()
  195. }
  196. await Response.query().insert(convertedResponse)
  197. return allResponses
  198. }
  199. /**
  200. * Delete a profile
  201. * @param {number} userId
  202. * @param {number} profileId
  203. * @returns
  204. */
  205. async deleteProfile(userId, profileId) {
  206. const { Profile } = this.server.models()
  207. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  208. /** Do NOTHING if NOT in Grouping */
  209. if (!dedupedGroupings.includes(profileId)) return
  210. return await Profile.query().delete().where('profile_id', profileId)
  211. }
  212. /**
  213. * Score a profile
  214. * @param {number} profileId
  215. * @returns {Array} Ordered and scored Profiles
  216. */
  217. async scoreProfilesFor(profileId, maxDistance, distanceUnit) {
  218. const { Profile } = this.server.models()
  219. await this._setScoreLookup()
  220. // Our User Profile to score for
  221. const userProfile = await Profile.query()
  222. .findOne('profile_id', profileId)
  223. .withGraphFetched('responses')
  224. .withGraphFetched('user')
  225. // Move unneeded responses
  226. const userZip = zipcoder.getZipCodeFromProfile(userProfile)
  227. // Find all Profiles that are NOT of our userProfile.type
  228. // ie. If userProfile.type == seeker, then find: poster
  229. let profileIdsOfOppositeType = await Profile.query()
  230. .withGraphFetched('responses')
  231. .withGraphFetched('user')
  232. // TODO: Let Objection optimize this
  233. const isPosterOpposite = userProfile.user.is_poster == 1 ? 0 : 1
  234. profileIdsOfOppositeType = profileIdsOfOppositeType.filter(profile => {
  235. return profile.user.is_poster == isPosterOpposite
  236. }).filter(profile => {
  237. // Only include profiles that included zipcode response
  238. return zipcoder.getZipCodeFromProfile(profile) ? true : false
  239. })
  240. const profilePlusDistance = await Promise.all(
  241. profileIdsOfOppositeType.map(async profile => {
  242. const targetZip = zipcoder.getZipCodeFromProfile(profile)
  243. if (!userZip || !targetZip)
  244. return { ...profile, distance: [9999, distanceUnit] }
  245. const distance = await this._compareDistance(
  246. userZip,
  247. targetZip,
  248. distanceUnit,
  249. )
  250. return {
  251. ...profile,
  252. distance: [distance.toFixed(2), distanceUnit],
  253. }
  254. }),
  255. )
  256. const distanceFilteredProfiles = zipcoder.filterByDistance(
  257. profilePlusDistance,
  258. maxDistance,
  259. )
  260. const scoredProfilesWithDistance = scoring.scoreAll(
  261. distanceFilteredProfiles,
  262. userProfile,
  263. this.scoreLookup,
  264. )
  265. // Order by score
  266. return scoredProfilesWithDistance.sort(
  267. (a, b) => b.score.total - a.score.total,
  268. )
  269. }
  270. /**
  271. * Use the db for zipcode info
  272. * @param {string} zipCode
  273. * @param {object}
  274. */
  275. async _latLonForZip(zipCode) {
  276. const { ZipCode } = this.server.models()
  277. const zipInfo = await ZipCode.query().findOne(
  278. 'zip_code_id',
  279. parseInt(zipCode),
  280. )
  281. if (!zipInfo) { console.error('zip:', zipCode) }
  282. return {
  283. latitude: parseFloat(zipInfo.latitude),
  284. longitude: parseFloat(zipInfo.longitude),
  285. }
  286. }
  287. /**
  288. * Get the distance between two zipcodes
  289. * using the haversine formula
  290. * @param {string} start_zip
  291. * @param {string} end_zip
  292. * @param {number} distance in miles
  293. */
  294. async _compareDistance(start_zip, end_zip, distanceUnit) {
  295. if (!start_zip || !end_zip || isNaN(start_zip) || isNaN(end_zip)) return
  296. const start = await this._latLonForZip(start_zip)
  297. const end = await this._latLonForZip(end_zip)
  298. return haversine(start, end, { unit: distanceUnit })
  299. }
  300. }