Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

profile.js 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. const Schmervice = require('@hapipal/schmervice')
  2. const cosineSimilarity = require('compute-cosine-similarity')
  3. const haversine = require('haversine')
  4. const magic = 1000
  5. const scoreResponses = (seeker, potentialMatch) => {
  6. if (seeker.responses.length != potentialMatch.responses.length)
  7. return {
  8. error: `complete responses for profile: ${seeker.profile_id} unqeual to profile: ${potentialMatch.profile_id} | ${seeker.responses.length}:${potentialMatch.responses.length}`,
  9. }
  10. const checkValCb = res => {
  11. const val = parseInt(res.val)
  12. return isNaN(val) ? 0 : val
  13. }
  14. return Math.floor(
  15. cosineSimilarity(
  16. seeker.responses.map(checkValCb),
  17. potentialMatch.responses.map(checkValCb),
  18. ) * magic,
  19. )
  20. }
  21. const filterByDistance = (profileList, max) => {
  22. return profileList.filter(profile => {
  23. const profileDistance = Math.floor(parseFloat(profile.distance) * 100)
  24. const adjustedMaxDistance = Math.floor(parseFloat(max) * 100)
  25. return profileDistance <= adjustedMaxDistance
  26. })
  27. }
  28. const scoreAll = (profileList, userProfile) => {
  29. return profileList.map(profile => {
  30. return {
  31. // Uncomment to return the whole profile
  32. // ...profile,
  33. profile_id: profile.profile_id,
  34. score: scoreResponses(userProfile, profile),
  35. distance: profile.distance,
  36. }
  37. })
  38. }
  39. /**
  40. * Grab the zip code string
  41. */
  42. const getZipCodeFromProfile = profile => {
  43. // There should only be one zip code entry per profile
  44. let zip = profile.responses.filter(
  45. response => response.response_key_id == 16,
  46. )[0]
  47. const responseIndexForZip = profile.responses.indexOf(zip)
  48. if (responseIndexForZip >= 0) {
  49. profile.responses.splice(responseIndexForZip, 1)
  50. }
  51. return zip.val
  52. }
  53. /**
  54. * Class to hold our retrieved profile information
  55. * in a convenient wrapper
  56. * !: This needs to match the responseSchema in profiles.js
  57. */
  58. class CompleteProfile {
  59. constructor(profile, type) {
  60. this.user_id = profile.user_id // int user_id
  61. this.profile_id = profile.profile_id // int profile_id
  62. this.responses = profile.responses // [] of all responses
  63. this.user_type = type
  64. }
  65. }
  66. module.exports = class ProfileService extends Schmervice.Service {
  67. constructor(...args) {
  68. super(...args)
  69. }
  70. /**
  71. * Internal method to get list of profile_ids for this user
  72. * @param {number} userId
  73. * @returns {Array} List of all profile_ids for user
  74. */
  75. async _getProfileIdsForUserId(userId) {
  76. const { Profile } = this.server.models()
  77. /** Grab every Profile associated with this id */
  78. const allProfiles = await Profile.query().where('user_id', userId)
  79. /** Copy a list of the just the Profiles */
  80. const profileIdsToGrab = allProfiles.map(profile => profile.profile_id)
  81. /** Uncomment to dedupe the list just in case */
  82. return [...new Set(profileIdsToGrab)]
  83. }
  84. async getCompleteProfilesFor(userId, type) {
  85. const { Profile } = this.server.models()
  86. const dedupedProfileIds = await this._getProfileIdsForUserId(userId)
  87. const profilesEntries = await Profile.query()
  88. .whereIn('profile_id', dedupedProfileIds)
  89. .withGraphFetched('responses')
  90. //** Get responses asociated with each profile_id */
  91. return profilesEntries.map(profile => {
  92. return new CompleteProfile(profile, type)
  93. })
  94. }
  95. async getProfilesFor(profileIdArray, type) {
  96. const { Profile } = this.server.models()
  97. const profilesEntries = await Profile.query()
  98. .whereIn('profile_id', profileIdArray)
  99. .withGraphFetched('responses')
  100. return profilesEntries.map(profile => {
  101. return new CompleteProfile(profile, type)
  102. })
  103. }
  104. /**
  105. * Save responses in a profile
  106. * @param {number} userId
  107. * @param {Array} responses
  108. * @returns {object}
  109. */
  110. async saveResponsesCreateProfileFor(userId, responses, txn) {
  111. const { Profile, Response } = this.server.models()
  112. const profile = await Profile.query(txn).insert({
  113. user_id: userId,
  114. })
  115. for (const responseToSave of responses) {
  116. const responseInfo = {
  117. profile_id: profile.id,
  118. response_key_id: responseToSave.response_key_id,
  119. val: responseToSave.val,
  120. }
  121. await Response.query(txn).insert(responseInfo)
  122. }
  123. //** Work around for HAPI returning profile_id as id */
  124. return { user_id: profile.user_id, profile_id: profile.id }
  125. }
  126. /** Update responses in place
  127. * @param {number} profileId
  128. * @param {Array} responses
  129. * @returns {Array} updated responses
  130. */
  131. async updateResponsesInProfile(profileId, responses, txn) {
  132. const { Response } = this.server.models()
  133. for (const responseToSave of responses) {
  134. await Response.query(txn)
  135. .update({
  136. response_id: responseToSave.response_id,
  137. profile_id: responseToSave.profile_id,
  138. response_key_id: responseToSave.response_key_id,
  139. val: responseToSave.val,
  140. })
  141. .where({
  142. profile_id: profileId,
  143. })
  144. .where({
  145. response_id: responseToSave.response_id,
  146. })
  147. }
  148. return await Response.query(txn).where({
  149. profile_id: profileId,
  150. })
  151. }
  152. /** Add response
  153. * @param {Object} response to save
  154. * @returns {null} updated responses
  155. * @returns {Array} updated responses
  156. */
  157. async saveResponseForProfile(profileId, responseToSave) {
  158. const { Response } = this.server.models()
  159. let allResponses = await Response.query().where({
  160. profile_id: profileId,
  161. })
  162. const matchingResponses = allResponses.filter(
  163. response =>
  164. response.response_key_id == responseToSave.response_key_id,
  165. )
  166. // ?:Maybe bad idea
  167. if (matchingResponses.length > 0) {
  168. return null
  169. }
  170. await await Response.query().insert(responseToSave)
  171. return allResponses
  172. }
  173. /**
  174. * Delete a profile
  175. * @param {number} userId
  176. * @param {number} profileId
  177. * @returns
  178. */
  179. async deleteProfile(userId, profileId) {
  180. const { Profile } = this.server.models()
  181. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  182. /** Do NOTHING if NOT in Grouping */
  183. if (!dedupedGroupings.includes(profileId)) return
  184. return await Profile.query().delete().where('profile_id', profileId)
  185. }
  186. /**
  187. * Score a profile
  188. * @param {number} profileId
  189. * @returns {Array} Ordered and scored Profiles
  190. */
  191. async scoreProfilesFor(profileId, maxDistance, distanceUnit) {
  192. const { Profile } = this.server.models()
  193. // Our User Profile to score for
  194. const userProfile = await Profile.query()
  195. .findOne('profile_id', profileId)
  196. .withGraphFetched('responses')
  197. .withGraphFetched('user')
  198. // Move unneeded responses
  199. const userZip = getZipCodeFromProfile(userProfile)
  200. // Find all Profiles that are NOT of our userProfile.type
  201. // ie. If userProfile.type == seeker, then find: poster
  202. let profileIdsOfOppositeType = await Profile.query()
  203. .withGraphFetched('responses')
  204. .withGraphFetched('user')
  205. // TODO: Let Objection optimize this
  206. const isPosterOpposite = userProfile.user.is_poster == 1 ? 0 : 1
  207. profileIdsOfOppositeType = profileIdsOfOppositeType.filter(
  208. profile => profile.user.is_poster == isPosterOpposite,
  209. )
  210. const profilePlusDistance = await Promise.all(
  211. profileIdsOfOppositeType.map(async profile => {
  212. const targetZip = getZipCodeFromProfile(profile)
  213. const distance = await this._compareDistance(
  214. userZip,
  215. targetZip,
  216. distanceUnit,
  217. )
  218. return {
  219. ...profile,
  220. distance: [distance.toFixed(2), distanceUnit],
  221. }
  222. }),
  223. )
  224. const distanceFilteredProfiles = filterByDistance(
  225. profilePlusDistance,
  226. maxDistance,
  227. )
  228. const scoredProfilesWithDistance = scoreAll(
  229. distanceFilteredProfiles,
  230. userProfile,
  231. )
  232. // Order by score
  233. return scoredProfilesWithDistance.sort((a, b) => a.score - b.score)
  234. }
  235. /**
  236. * Use the db for zipcode info
  237. * @param {string} zipCode
  238. * @param {object}
  239. */
  240. async _latLonForZip(zipCode) {
  241. const { ZipCode } = this.server.models()
  242. const zipInfo = await ZipCode.query().findOne(
  243. 'zip_code_id',
  244. parseInt(zipCode),
  245. )
  246. if (!zipInfo) {
  247. console.log(zipCode)
  248. }
  249. return {
  250. latitude: parseFloat(zipInfo.latitude),
  251. longitude: parseFloat(zipInfo.longitude),
  252. }
  253. }
  254. /**
  255. * Get the distance between two zipcodes
  256. * using the haversine formula
  257. * @param {string} start_zip
  258. * @param {string} end_zip
  259. * @param {number} distance in miles
  260. */
  261. async _compareDistance(start_zip, end_zip, distanceUnit) {
  262. if (!start_zip || !end_zip) return
  263. const start = await this._latLonForZip(start_zip)
  264. const end = await this._latLonForZip(end_zip)
  265. return haversine(start, end, { unit: distanceUnit })
  266. }
  267. }