You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

profile.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. const profilesEntries = await Profile.query()
  107. .whereIn('profile_id', profileIdArray)
  108. .withGraphFetched('responses')
  109. .withGraphFetched('user')
  110. return profilesEntries.map(profile => {
  111. return new CompleteProfile(profile, type)
  112. })
  113. }
  114. /**
  115. * Save responses in a profile
  116. * @param {number} userId
  117. * @param {Array} responses
  118. * @returns {object}
  119. */
  120. async saveResponsesCreateProfileFor(userId, responses, txn) {
  121. const { Profile, Response } = this.server.models()
  122. const profile = await Profile.query(txn).insert({
  123. user_id: userId,
  124. })
  125. for (const responseToSave of responses) {
  126. const responseInfo = {
  127. profile_id: profile.id,
  128. response_key_id: responseToSave.response_key_id,
  129. val: responseToSave.val,
  130. }
  131. await Response.query(txn).insert(responseInfo)
  132. }
  133. //** Work around for HAPI returning profile_id as id */
  134. return { user_id: profile.user_id, profile_id: profile.id }
  135. }
  136. /** Update responses in place
  137. * @param {number} profileId
  138. * @param {Array} responses
  139. * @returns {Array} updated responses
  140. */
  141. async updateResponsesInProfile(profileId, responses, txn) {
  142. const { Response } = this.server.models()
  143. for (const responseToSave of responses) {
  144. await Response.query(txn)
  145. .update({
  146. response_id: responseToSave.response_id,
  147. profile_id: responseToSave.profile_id,
  148. response_key_id: responseToSave.response_key_id,
  149. val: responseToSave.val,
  150. })
  151. .where({
  152. profile_id: profileId,
  153. })
  154. .where({
  155. response_id: responseToSave.response_id,
  156. })
  157. }
  158. return await Response.query(txn).where({
  159. profile_id: profileId,
  160. })
  161. }
  162. /** Add response
  163. * @param {Object} response to save
  164. * @returns {null} updated responses
  165. * @returns {Array} updated responses
  166. */
  167. async saveResponseForProfile(profileId, responseToSave) {
  168. const { Response } = this.server.models()
  169. let allResponses = await Response.query().where({
  170. profile_id: profileId,
  171. })
  172. const matchingResponses = allResponses.filter(
  173. response =>
  174. response.response_key_id == responseToSave.response_key_id,
  175. )
  176. // ?:Maybe bad idea
  177. if (matchingResponses.length > 0) {
  178. return null
  179. }
  180. await await Response.query().insert(responseToSave)
  181. return allResponses
  182. }
  183. /**
  184. * Delete a profile
  185. * @param {number} userId
  186. * @param {number} profileId
  187. * @returns
  188. */
  189. async deleteProfile(userId, profileId) {
  190. const { Profile } = this.server.models()
  191. const dedupedGroupings = await this._getProfileIdsForUserId(userId)
  192. /** Do NOTHING if NOT in Grouping */
  193. if (!dedupedGroupings.includes(profileId)) return
  194. return await Profile.query().delete().where('profile_id', profileId)
  195. }
  196. /**
  197. * Score a profile
  198. * @param {number} profileId
  199. * @returns {Array} Ordered and scored Profiles
  200. */
  201. async scoreProfilesFor(profileId, maxDistance, distanceUnit) {
  202. const { Profile } = this.server.models()
  203. // Our User Profile to score for
  204. const userProfile = await Profile.query()
  205. .findOne('profile_id', profileId)
  206. .withGraphFetched('responses')
  207. .withGraphFetched('user')
  208. // Move unneeded responses
  209. const userZip = getZipCodeFromProfile(userProfile)
  210. // Find all Profiles that are NOT of our userProfile.type
  211. // ie. If userProfile.type == seeker, then find: poster
  212. let profileIdsOfOppositeType = await Profile.query()
  213. .withGraphFetched('responses')
  214. .withGraphFetched('user')
  215. // TODO: Let Objection optimize this
  216. const isPosterOpposite = userProfile.user.is_poster == 1 ? 0 : 1
  217. profileIdsOfOppositeType = profileIdsOfOppositeType.filter(
  218. profile => profile.user.is_poster == isPosterOpposite,
  219. )
  220. // Only include profiles that included zipcode response
  221. profileIdsOfOppositeType = profileIdsOfOppositeType.filter(profile => {
  222. const zipcodeResponses = profile.responses.filter(response => response.response_key_id == zipcodeKey)
  223. return zipcodeResponses.length > 0
  224. })
  225. const profilePlusDistance = await Promise.all(
  226. profileIdsOfOppositeType.map(async profile => {
  227. const targetZip = getZipCodeFromProfile(profile)
  228. if(!userZip || !targetZip) return { ...profile, distance: [9999, distanceUnit] }
  229. const distance = await this._compareDistance(
  230. userZip,
  231. targetZip,
  232. distanceUnit,
  233. )
  234. return {
  235. ...profile,
  236. distance: [distance.toFixed(2), distanceUnit],
  237. }
  238. }),
  239. )
  240. const distanceFilteredProfiles = filterByDistance(
  241. profilePlusDistance,
  242. maxDistance,
  243. )
  244. const scoredProfilesWithDistance = scoreAll(
  245. distanceFilteredProfiles,
  246. userProfile,
  247. )
  248. // Order by score
  249. return scoredProfilesWithDistance.sort((a, b) => a.score - b.score)
  250. }
  251. /**
  252. * Use the db for zipcode info
  253. * @param {string} zipCode
  254. * @param {object}
  255. */
  256. async _latLonForZip(zipCode) {
  257. const { ZipCode } = this.server.models()
  258. const zipInfo = await ZipCode.query().findOne(
  259. 'zip_code_id',
  260. parseInt(zipCode),
  261. )
  262. if (!zipInfo) {
  263. console.log('zip:', zipCode)
  264. }
  265. return {
  266. latitude: parseFloat(zipInfo.latitude),
  267. longitude: parseFloat(zipInfo.longitude),
  268. }
  269. }
  270. /**
  271. * Get the distance between two zipcodes
  272. * using the haversine formula
  273. * @param {string} start_zip
  274. * @param {string} end_zip
  275. * @param {number} distance in miles
  276. */
  277. async _compareDistance(start_zip, end_zip, distanceUnit) {
  278. if (!start_zip || !end_zip || isNaN(start_zip) || isNaN(end_zip)) return
  279. const start = await this._latLonForZip(start_zip)
  280. const end = await this._latLonForZip(end_zip)
  281. return haversine(start, end, { unit: distanceUnit })
  282. }
  283. }