Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

profile.js 11KB

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