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.

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