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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. <<<<<<< HEAD
  8. const { response } = require('@hapi/hapi/lib/validation')
  9. =======
  10. const tagger = require('./tagger')
  11. const filter = require('./filter')
  12. >>>>>>> 154d171 (:construction: new filter service to preprocess a users match pool before scoring)
  13. module.exports = class ProfileService extends Schmervice.Service {
  14. constructor(...args) {
  15. super(...args)
  16. /** Scores available in the db to map against score indices*/
  17. this.scoreLookup = {}
  18. /** Tags available in the db to map against tag_associations*/
  19. this.tagLookup = {}
  20. // this.responseKeyLookup = ResponseKey.query()
  21. }
  22. async _setScoreLookup() {
  23. if (!Object.keys(this.scoreLookup).length) {
  24. const { Aspect, AspectLabel } = this.server.models()
  25. const aspects = await Aspect.query()
  26. const labels = await AspectLabel.query()
  27. this.scoreLookup = scoring.makeScoreLookup(aspects, labels)
  28. }
  29. }
  30. async _setTagLookup() {
  31. /** Grab tag descriptions if they do NOT exist: Needed once per app load */
  32. if (Object.keys(this.tagLookup).length) return
  33. const { Tag } = this.server.models()
  34. const allTagDescriptions = await Tag.query()
  35. allTagDescriptions.forEach(desc => {
  36. if (!desc.is_active) return
  37. this.tagLookup[desc.tag_id] = desc
  38. })
  39. }
  40. /**
  41. * Internal method to get list of profile_ids for this user
  42. * @param {number} userId
  43. * @returns {Array} List of all profile_ids for user
  44. */
  45. async _getProfileIdsForUserId(userId) {
  46. const { Profile } = this.server.models()
  47. /** Grab every Profile associated with this id */
  48. const allProfiles = await Profile.query().where('user_id', userId)
  49. /** Copy a list of the just the Profiles */
  50. const profileIdsToGrab = allProfiles.map(profile => profile.profile_id)
  51. /** Uncomment to dedupe the list just in case */
  52. return [...new Set(profileIdsToGrab)]
  53. }
  54. /**
  55. * Convert indexes to actual score values
  56. * Using using the input and converting to index
  57. * of the generated possible prescore array in config
  58. */
  59. _convertResponse(responseToSave) {
  60. if (scoring._isScorableResponse(responseToSave.response_key_id)) {
  61. // Convert -3 to 0, 0 to 3, 3 to 6
  62. const offset = (config.scoreVals.length - 1) / 2
  63. const scoreFromInput = parseInt(responseToSave.val) + offset
  64. const scoreFromConfig = config.scoreVals.indexOf(scoreFromInput)
  65. if (scoreFromConfig < 0) {
  66. console.error('score not found in possible config responses')
  67. }
  68. responseToSave.val = scoreFromConfig.toString()
  69. }
  70. return responseToSave
  71. }
  72. async getProfile(profileId) {
  73. const { Profile } = this.server.models()
  74. await this._setTagLookup()
  75. const matchingProfile = await Profile.query()
  76. .where('profile_id', profileId)
  77. .first()
  78. .withGraphFetched('tags')
  79. .withGraphFetched('responses')
  80. .withGraphFetched('user')
  81. matchingProfile.tags = matchingProfile.tags.map(
  82. tag => this.tagLookup[tag.tag_id],
  83. )
  84. return new profiler.CompleteProfile(matchingProfile)
  85. }
  86. async getCompleteProfilesFor(userId, type) {
  87. const { Profile } = this.server.models()
  88. await this._setTagLookup()
  89. const dedupedProfileIds = await this._getProfileIdsForUserId(userId)
  90. const profilesEntries = await Profile.query()
  91. .whereIn('profile_id', dedupedProfileIds)
  92. .withGraphFetched('tags')
  93. .withGraphFetched('responses')
  94. .withGraphFetched('user')
  95. return profiler.makeCompleteFromProfileEntries(
  96. profilesEntries,
  97. type,
  98. this.tagLookup,
  99. )
  100. }
  101. async getProfilesFor(profileIdArray, type) {
  102. const { Profile } = this.server.models()
  103. await this._setScoreLookup()
  104. await this._setTagLookup()
  105. // profilesEntries is profiles in database row order
  106. const profilesEntries = await Profile.query()
  107. .whereIn('profile_id', profileIdArray)
  108. .withGraphFetched('tags')
  109. .withGraphFetched('responses')
  110. .withGraphFetched('user')
  111. // taking the info from profilesEntries
  112. // to repack into completeProfiles
  113. // in same order as profileIdArray
  114. return profiler.makeOrderedCompleteProfiles(
  115. profileIdArray,
  116. profilesEntries,
  117. type,
  118. this.tagLookup,
  119. )
  120. }
  121. /**
  122. * Save responses in a profile
  123. * @param {number} userId
  124. * @param {Array} responses
  125. * @returns {object}
  126. */
  127. async saveResponsesCreateProfileFor(userId, responses, txn) {
  128. const { Profile, Response } = this.server.models()
  129. try {
  130. const profile = await Profile.query(txn).insert({
  131. user_id: userId,
  132. })
  133. for (const responseToSave of responses) {
  134. const convertedResponse = this._convertResponse(responseToSave)
  135. const responseInfo = {
  136. profile_id: profile.id,
  137. response_key_id: convertedResponse.response_key_id,
  138. val: convertedResponse.val,
  139. }
  140. await Response.query(txn).insert(responseInfo)
  141. }
  142. //** Work around for HAPI returning profile_id as id */
  143. return { user_id: profile.user_id, profile_id: profile.id }
  144. } catch (err) {
  145. throw new Error(err)
  146. }
  147. }
  148. /** Update responses in place
  149. * @param {number} profileId
  150. * @param {Array} responses
  151. * @returns {Array} updated responses
  152. */
  153. async updateResponsesInProfile(profileId, responses, txn) {
  154. const { Response } = this.server.models()
  155. for (const responseToSave of responses) {
  156. await Response.query(txn)
  157. .update({
  158. response_id: responseToSave.response_id,
  159. profile_id: responseToSave.profile_id,
  160. response_key_id: responseToSave.response_key_id,
  161. val: responseToSave.val,
  162. })
  163. .where({
  164. profile_id: profileId,
  165. })
  166. .where({
  167. response_id: responseToSave.response_id,
  168. })
  169. }
  170. return await Response.query(txn).where({
  171. profile_id: profileId,
  172. })
  173. }
  174. async insertSingleResponseForProfile(responseToSave) {
  175. const { Response } = this.server.models()
  176. const convertedResponse = this._convertResponse(responseToSave)
  177. const savedResponse = await Response.query().insert(convertedResponse)
  178. delete savedResponse.id
  179. return savedResponse
  180. }
  181. /** Add response
  182. * @param {Object} response to save
  183. * @returns {null} updated responses
  184. * @returns {Array} updated responses
  185. */
  186. async saveResponseForProfile(profileId, responseToSave) {
  187. const { Response } = this.server.models()
  188. let allResponses = await Response.query().where({
  189. profile_id: profileId,
  190. })
  191. // Delete matches
  192. // ?:Maybe bad idea
  193. const matchingResponses = allResponses.filter(
  194. response =>
  195. response.response_key_id == responseToSave.response_key_id,
  196. )
  197. if (matchingResponses.length > 0) {
  198. const alreadyAnswered = matchingResponses.map(
  199. matchingRes => matchingRes.response_key_id,
  200. )
  201. await Response.query()
  202. .where({ profile_id: profileId })
  203. .delete()
  204. .whereIn('response_key_id', alreadyAnswered)
  205. }
  206. const convertedResponse = this._convertResponse(responseToSave)
  207. await Response.query().insert(convertedResponse)
  208. return allResponses
  209. }
  210. /**
  211. * Delete a profile
  212. * @param {number} userId
  213. * @param {number} profileId
  214. * @returns
  215. */
  216. async deleteProfile(userId, profileId) {
  217. const { Profile } = this.server.models()
  218. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  219. /** Do NOTHING if NOT in Grouping */
  220. if (!dedupedGroupings.includes(profileId)) return
  221. return await Profile.query().delete().where('profile_id', profileId)
  222. }
  223. /**
  224. * Score a profile
  225. * @param {number} profileId
  226. * @returns {Array} Ordered and scored Profiles
  227. */
  228. async scoreProfilesFor(profileId, maxDistance, distanceUnit) {
  229. const { Profile } = this.server.models()
  230. await this._setScoreLookup()
  231. // Our User Profile to score for
  232. const userProfile = await Profile.query()
  233. .findOne('profile_id', profileId)
  234. .withGraphFetched('responses')
  235. .withGraphFetched('user')
  236. const userZip = zipcoder.getZipCodeFromProfile(userProfile)
  237. // preprocess potential match pool with filter service methods
  238. let matchPool = await Profile.query()
  239. .withGraphFetched('responses')
  240. .withGraphFetched('user')
  241. matchPool = filter.byProfileType(matchPool, userProfile.user)
  242. matchPool = filter.byNullZip(matchPool)
  243. // attach distance to pool profiles for max distance filter
  244. matchPool = await this.calcProfileDistances(matchPool, distanceUnit, userZip)
  245. // filter with matchPool profiles that have distance
  246. matchPool = filter.byMaxDistance(matchPool, maxDistance)
  247. const scoredProfilesWithDistance = scoring.scoreAll(
  248. matchPool,
  249. userProfile,
  250. this.scoreLookup,
  251. )
  252. // Order by score
  253. return scoredProfilesWithDistance.sort(
  254. (a, b) => b.score.total - a.score.total,
  255. )
  256. }
  257. async calcProfileDistances(matchPool, distanceUnit, userZip){
  258. await Promise.all(
  259. matchPool.map(async profile => {
  260. const targetZip = zipcoder.getZipCodeFromProfile(profile)
  261. if (!userZip || !targetZip)
  262. return { ...profile, distance: [9999, distanceUnit] }
  263. const distance = await this._compareDistance(
  264. userZip,
  265. targetZip,
  266. distanceUnit,
  267. )
  268. return {
  269. ...profile,
  270. distance: [distance.toFixed(2), distanceUnit],
  271. }
  272. })
  273. )
  274. }
  275. /**
  276. * Use the db for zipcode info
  277. * @param {string} zipCode
  278. * @param {object}
  279. */
  280. async _latLonForZip(zipCode) {
  281. const { ZipCode } = this.server.models()
  282. const zipInfo = await ZipCode.query().findOne(
  283. 'zip_code_id',
  284. parseInt(zipCode),
  285. )
  286. if (!zipInfo) {
  287. console.error('zip:', zipCode)
  288. }
  289. return {
  290. latitude: parseFloat(zipInfo.latitude),
  291. longitude: parseFloat(zipInfo.longitude),
  292. }
  293. }
  294. /**
  295. * Get the distance between two zipcodes
  296. * using the haversine formula
  297. * @param {string} start_zip
  298. * @param {string} end_zip
  299. * @param {number} distance in miles
  300. */
  301. async _compareDistance(start_zip, end_zip, distanceUnit) {
  302. if (!start_zip || !end_zip || isNaN(start_zip) || isNaN(end_zip)) return
  303. const start = await this._latLonForZip(start_zip)
  304. const end = await this._latLonForZip(end_zip)
  305. return haversine(start, end, { unit: distanceUnit })
  306. }
  307. /**
  308. * Use the db to grab tag associations
  309. * by profile and match them to tag types
  310. * @param {number} profileId
  311. * @param {object}
  312. */
  313. async getTagsFor(profileId, groupingId, category) {
  314. const { TagAssociation } = this.server.models()
  315. await this._setTagLookup()
  316. let associations = groupingId
  317. ? await TagAssociation.query()
  318. .where('grouping_id', groupingId)
  319. .andWhere('profile_id', profileId)
  320. : await TagAssociation.query().andWhere('profile_id', profileId)
  321. return associations
  322. .map(assoc => ({
  323. ...assoc,
  324. tag: this.tagLookup[assoc.tag_id],
  325. }))
  326. .filter(tagWithAssoc => {
  327. return category
  328. ? tagWithAssoc.tag.tag_category == category
  329. : true
  330. })
  331. }
  332. /**
  333. * Use the db to grab tag associations
  334. * by profile, grouping, tag, and insert
  335. * it if it already exists
  336. * @param {object} association
  337. */
  338. async revealProfileInfo(association) {
  339. const { TagAssociation } = this.server.models()
  340. const existingAssociations = await TagAssociation.query()
  341. .where('profile_id', `${association.profile_id}`)
  342. .where('grouping_id', `${association.grouping_id}`)
  343. .where('tag_id', `${association.tag_id}`)
  344. .where('is_deleted', 0)
  345. if (!existingAssociations.length) {
  346. await TagAssociation.query().insert(association)
  347. return await this.getTagsFor(association.profile_id)
  348. } else {
  349. return console.error('ERROR =>: tag association already exists')
  350. }
  351. }
  352. }