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

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