您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

index.js 14KB

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