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

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