Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

profile.js 11KB

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