選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. return new profiler.CompleteProfile(matchingProfile)
  61. }
  62. async getCompleteProfilesFor(userId, type) {
  63. const { Profile } = this.server.models()
  64. await this._setTagLookup()
  65. const dedupedProfileIds = await this._getProfileIdsForUserId(userId)
  66. const profilesEntries = await Profile.query()
  67. .whereIn('profile_id', dedupedProfileIds)
  68. .withGraphFetched('tags')
  69. .withGraphFetched('responses')
  70. .withGraphFetched('user')
  71. return profiler.makeCompleteFromProfileEntries(
  72. profilesEntries,
  73. type,
  74. this.tagLookup,
  75. )
  76. }
  77. async getProfilesFor(profileIdArray, type) {
  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.makeOrderedCompleteProfiles(
  91. profileIdArray,
  92. profilesEntries,
  93. type,
  94. this.tagLookup,
  95. )
  96. }
  97. /**
  98. * Save responses in a profile
  99. * @param {number} userId
  100. * @param {Array} responses
  101. * @returns {object}
  102. */
  103. async saveResponsesCreateProfileFor(userId, responses, txn) {
  104. const { Profile, Response } = this.server.models()
  105. const profile = await Profile.query(txn).insert({
  106. user_id: userId,
  107. })
  108. for (const responseToSave of responses) {
  109. /**
  110. * Convert indexes to actual score values
  111. * Using using the input and converting to index
  112. * of the generated possible prescore array in config
  113. * DUPLICATE:See saveResponseForProfile() line 343
  114. */
  115. let convertedResponse = responseToSave
  116. if (scoring._isScorableResponse(responseToSave.response_key_id)) {
  117. // Convert -3 to 0, 0 to 3, 3 to 6
  118. const offset = (config.scoreVals.length - 1) / 2
  119. const indexFromInput = parseInt(responseToSave.val) + offset
  120. convertedResponse.val =
  121. 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 scoreFromInput = parseInt(responseToSave.val) + offset
  194. const scoreFromConfig = config.scoreVals.indexOf(scoreFromInput)
  195. if (scoreFromConfig < 0) {
  196. console.error('score not found in possible config responses')
  197. }
  198. convertedResponse.val = scoreFromConfig.toString()
  199. }
  200. await Response.query().insert(convertedResponse)
  201. return allResponses
  202. }
  203. /**
  204. * Delete a profile
  205. * @param {number} userId
  206. * @param {number} profileId
  207. * @returns
  208. */
  209. async deleteProfile(userId, profileId) {
  210. const { Profile } = this.server.models()
  211. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  212. /** Do NOTHING if NOT in Grouping */
  213. if (!dedupedGroupings.includes(profileId)) return
  214. return await Profile.query().delete().where('profile_id', profileId)
  215. }
  216. /**
  217. * Score a profile
  218. * @param {number} profileId
  219. * @returns {Array} Ordered and scored Profiles
  220. */
  221. async scoreProfilesFor(profileId, maxDistance, distanceUnit) {
  222. const { Profile } = this.server.models()
  223. await this._setScoreLookup()
  224. // Our User Profile to score for
  225. const userProfile = await Profile.query()
  226. .findOne('profile_id', profileId)
  227. .withGraphFetched('responses')
  228. .withGraphFetched('user')
  229. // Move unneeded responses
  230. const userZip = zipcoder.getZipCodeFromProfile(userProfile)
  231. // Find all Profiles that are NOT of our userProfile.type
  232. // ie. If userProfile.type == seeker, then find: poster
  233. let profileIdsOfOppositeType = await Profile.query()
  234. .withGraphFetched('responses')
  235. .withGraphFetched('user')
  236. // TODO: Let Objection optimize this
  237. const isPosterOpposite = userProfile.user.is_poster == 1 ? 0 : 1
  238. profileIdsOfOppositeType = profileIdsOfOppositeType
  239. .filter(profile => {
  240. return profile.user.is_poster == isPosterOpposite
  241. })
  242. .filter(profile => {
  243. // Only include profiles that included zipcode response
  244. return zipcoder.getZipCodeFromProfile(profile) ? true : false
  245. })
  246. const profilePlusDistance = await Promise.all(
  247. profileIdsOfOppositeType.map(async profile => {
  248. const targetZip = zipcoder.getZipCodeFromProfile(profile)
  249. if (!userZip || !targetZip)
  250. return { ...profile, distance: [9999, distanceUnit] }
  251. const distance = await this._compareDistance(
  252. userZip,
  253. targetZip,
  254. distanceUnit,
  255. )
  256. return {
  257. ...profile,
  258. distance: [distance.toFixed(2), distanceUnit],
  259. }
  260. }),
  261. )
  262. const distanceFilteredProfiles = zipcoder.filterByDistance(
  263. profilePlusDistance,
  264. maxDistance,
  265. )
  266. const scoredProfilesWithDistance = scoring.scoreAll(
  267. distanceFilteredProfiles,
  268. userProfile,
  269. this.scoreLookup,
  270. )
  271. // Order by score
  272. return scoredProfilesWithDistance.sort(
  273. (a, b) => b.score.total - a.score.total,
  274. )
  275. }
  276. /**
  277. * Use the db for zipcode info
  278. * @param {string} zipCode
  279. * @param {object}
  280. */
  281. async _latLonForZip(zipCode) {
  282. const { ZipCode } = this.server.models()
  283. const zipInfo = await ZipCode.query().findOne(
  284. 'zip_code_id',
  285. parseInt(zipCode),
  286. )
  287. if (!zipInfo) {
  288. console.error('zip:', zipCode)
  289. }
  290. return {
  291. latitude: parseFloat(zipInfo.latitude),
  292. longitude: parseFloat(zipInfo.longitude),
  293. }
  294. }
  295. /**
  296. * Get the distance between two zipcodes
  297. * using the haversine formula
  298. * @param {string} start_zip
  299. * @param {string} end_zip
  300. * @param {number} distance in miles
  301. */
  302. async _compareDistance(start_zip, end_zip, distanceUnit) {
  303. if (!start_zip || !end_zip || isNaN(start_zip) || isNaN(end_zip)) return
  304. const start = await this._latLonForZip(start_zip)
  305. const end = await this._latLonForZip(end_zip)
  306. return haversine(start, end, { unit: distanceUnit })
  307. }
  308. /**
  309. * Use the db to grab tag associations
  310. * by profile and match them to tag types
  311. * @param {number} profileId
  312. * @param {object}
  313. */
  314. async getTagsFor(profileId, groupingId, category) {
  315. const { TagAssociation } = this.server.models()
  316. await this._setTagLookup()
  317. let associations = groupingId
  318. ? await TagAssociation.query()
  319. .where('grouping_id', groupingId)
  320. .andWhere('profile_id', profileId)
  321. : await TagAssociation.query().andWhere('profile_id', profileId)
  322. return associations
  323. .map(assoc => ({
  324. ...assoc,
  325. tag: this.tagLookup[assoc.tag_id],
  326. }))
  327. .filter(tagWithAssoc => {
  328. return category
  329. ? tagWithAssoc.tag.tag_category == category
  330. : true
  331. })
  332. }
  333. /**
  334. * Use the db to grab tag associations
  335. * by profile, grouping, tag, and insert
  336. * it if it already exists
  337. * @param {object} association
  338. */
  339. async revealProfileInfo(association) {
  340. const { TagAssociation } = this.server.models()
  341. const existingAssociations = await TagAssociation.query()
  342. .where('profile_id', `${association.profile_id}`)
  343. .where('grouping_id', `${association.grouping_id}`)
  344. .where('tag_id', `${association.tag_id}`)
  345. .where('is_deleted', 0)
  346. if (!existingAssociations.length) {
  347. await TagAssociation.query().insert(association)
  348. return await this.getTagsFor(association.profile_id)
  349. } else {
  350. return console.error('ERROR =>: tag association already exists')
  351. }
  352. }
  353. }