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

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