Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

profile.js 11KB

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