ProjectListController.mjs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. // ts-check
  2. import _ from 'lodash'
  3. import Metrics from '@overleaf/metrics'
  4. import Settings from '@overleaf/settings'
  5. import ProjectHelper from './ProjectHelper.js'
  6. import ProjectGetter from './ProjectGetter.js'
  7. import PrivilegeLevels from '../Authorization/PrivilegeLevels.js'
  8. import SessionManager from '../Authentication/SessionManager.js'
  9. import Sources from '../Authorization/Sources.js'
  10. import UserGetter from '../User/UserGetter.js'
  11. import SurveyHandler from '../Survey/SurveyHandler.mjs'
  12. import TagsHandler from '../Tags/TagsHandler.js'
  13. import { expressify } from '@overleaf/promise-utils'
  14. import logger from '@overleaf/logger'
  15. import Features from '../../infrastructure/Features.js'
  16. import SubscriptionViewModelBuilder from '../Subscription/SubscriptionViewModelBuilder.js'
  17. import NotificationsHandler from '../Notifications/NotificationsHandler.js'
  18. import Modules from '../../infrastructure/Modules.js'
  19. import { OError, V1ConnectionError } from '../Errors/Errors.js'
  20. import { User } from '../../models/User.js'
  21. import UserPrimaryEmailCheckHandler from '../User/UserPrimaryEmailCheckHandler.js'
  22. import UserController from '../User/UserController.js'
  23. import LimitationsManager from '../Subscription/LimitationsManager.js'
  24. import NotificationsBuilder from '../Notifications/NotificationsBuilder.js'
  25. import GeoIpLookup from '../../infrastructure/GeoIpLookup.js'
  26. import SplitTestHandler from '../SplitTests/SplitTestHandler.js'
  27. import SplitTestSessionHandler from '../SplitTests/SplitTestSessionHandler.js'
  28. import SubscriptionLocator from '../Subscription/SubscriptionLocator.js'
  29. import TutorialHandler from '../Tutorial/TutorialHandler.js'
  30. /**
  31. * @import { GetProjectsRequest, GetProjectsResponse, AllUsersProjects, MongoProject } from "./types"
  32. * @import { ProjectApi, Filters, Page, Sort } from "../../../../types/project/dashboard/api"
  33. * @import { Tag } from "../Tags/types"
  34. */
  35. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  36. if (!affiliation.institution) return false
  37. // institution.confirmed is for the domain being confirmed, not the email
  38. // Do not show SSO UI for unconfirmed domains
  39. if (!affiliation.institution.confirmed) return false
  40. // Could have multiple emails at the same institution, and if any are
  41. // linked to the institution then do not show notification for others
  42. if (
  43. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  44. ) {
  45. if (affiliation.institution.ssoEnabled) return true
  46. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  47. return false
  48. }
  49. return false
  50. }
  51. const _buildPortalTemplatesList = affiliations => {
  52. if (affiliations == null) {
  53. affiliations = []
  54. }
  55. const portalTemplates = []
  56. const uniqueAffiliations = _.uniqBy(affiliations, 'institution.id')
  57. for (const aff of uniqueAffiliations) {
  58. const hasSlug = aff.portal?.slug
  59. const hasTemplates = aff.portal?.templates_count > 0
  60. if (hasSlug && hasTemplates) {
  61. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  62. const portalTemplateURL = Settings.siteUrl + portalPath + aff.portal?.slug
  63. portalTemplates.push({
  64. name: aff.institution.name,
  65. url: portalTemplateURL,
  66. })
  67. }
  68. }
  69. return portalTemplates
  70. }
  71. function cleanupSession(req) {
  72. // cleanup redirects at the end of the redirect chain
  73. delete req.session.postCheckoutRedirect
  74. delete req.session.postLoginRedirect
  75. delete req.session.postOnboardingRedirect
  76. // cleanup details from register page
  77. delete req.session.sharedProjectData
  78. delete req.session.templateData
  79. }
  80. /**
  81. * @param {import("express").Request} req
  82. * @param {import("express").Response} res
  83. * @param {import("express").NextFunction} next
  84. * @returns {Promise<void>}
  85. */
  86. async function projectListPage(req, res, next) {
  87. cleanupSession(req)
  88. // can have two values:
  89. // - undefined - when there's no "saas" feature or couldn't get subscription data
  90. // - object - the subscription data object
  91. let usersBestSubscription
  92. let survey
  93. let userIsMemberOfGroupSubscription = false
  94. let groupSubscriptionsPendingEnrollment = []
  95. const isSaas = Features.hasFeature('saas')
  96. const userId = SessionManager.getLoggedInUserId(req.session)
  97. const projectsBlobPending = _getProjects(userId).catch(err => {
  98. logger.err({ err, userId }, 'projects listing in background failed')
  99. return undefined
  100. })
  101. const user = await User.findById(
  102. userId,
  103. `email emails features alphaProgram betaProgram lastPrimaryEmailCheck signUpDate${
  104. isSaas ? ' enrollment writefull completedTutorials' : ''
  105. }`
  106. )
  107. // Handle case of deleted user
  108. if (user == null) {
  109. UserController.logout(req, res, next)
  110. return
  111. }
  112. if (isSaas) {
  113. await SplitTestSessionHandler.promises.sessionMaintenance(req, user)
  114. try {
  115. usersBestSubscription =
  116. await SubscriptionViewModelBuilder.promises.getBestSubscription({
  117. _id: userId,
  118. })
  119. } catch (error) {
  120. logger.err(
  121. { err: error, userId },
  122. "Failed to get user's best subscription"
  123. )
  124. }
  125. try {
  126. const { isMember, subscriptions } =
  127. await LimitationsManager.promises.userIsMemberOfGroupSubscription(user)
  128. userIsMemberOfGroupSubscription = isMember
  129. // TODO use helper function
  130. if (!user.enrollment?.managedBy) {
  131. groupSubscriptionsPendingEnrollment = subscriptions.filter(
  132. subscription => subscription.groupPlan && subscription.groupPolicy
  133. )
  134. }
  135. } catch (error) {
  136. logger.error(
  137. { err: error },
  138. 'Failed to check whether user is a member of group subscription'
  139. )
  140. }
  141. try {
  142. survey = await SurveyHandler.promises.getSurvey(userId)
  143. } catch (error) {
  144. logger.err({ err: error, userId }, 'Failed to load the active survey')
  145. }
  146. if (user && UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck(user)) {
  147. return res.redirect('/user/emails/primary-email-check')
  148. }
  149. }
  150. const tags = await TagsHandler.promises.getAllTags(userId)
  151. let userEmailsData = { list: [], allInReconfirmNotificationPeriods: [] }
  152. try {
  153. const fullEmails = await UserGetter.promises.getUserFullEmails(userId)
  154. if (!Features.hasFeature('affiliations')) {
  155. userEmailsData.list = fullEmails
  156. } else {
  157. try {
  158. const results = await Modules.promises.hooks.fire(
  159. 'allInReconfirmNotificationPeriodsForUser',
  160. fullEmails
  161. )
  162. const allInReconfirmNotificationPeriods = (results && results[0]) || []
  163. userEmailsData = {
  164. list: fullEmails,
  165. allInReconfirmNotificationPeriods,
  166. }
  167. } catch (error) {
  168. userEmailsData = error
  169. }
  170. }
  171. } catch (error) {
  172. if (!(error instanceof V1ConnectionError)) {
  173. logger.error({ err: error, userId }, 'Failed to get user full emails')
  174. }
  175. }
  176. const userEmails = userEmailsData.list || []
  177. const userAffiliations = userEmails
  178. .filter(emailData => !!emailData.affiliation)
  179. .map(emailData => {
  180. const result = emailData.affiliation
  181. result.email = emailData.email
  182. return result
  183. })
  184. const portalTemplates = _buildPortalTemplatesList(userAffiliations)
  185. const { allInReconfirmNotificationPeriods } = userEmailsData
  186. const notifications =
  187. await NotificationsHandler.promises.getUserNotifications(userId)
  188. for (const notification of notifications) {
  189. notification.html = req.i18n.translate(
  190. notification.templateKey,
  191. notification.messageOpts
  192. )
  193. }
  194. const notificationsInstitution = []
  195. // Institution and group SSO Notifications
  196. let groupSsoSetupSuccess
  197. let reconfirmedViaSAML
  198. if (Features.hasFeature('saml')) {
  199. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  200. const samlSession = req.session.saml
  201. // Notification: SSO Available
  202. const linkedInstitutionIds = []
  203. userEmails.forEach(email => {
  204. if (email.samlProviderId) {
  205. linkedInstitutionIds.push(email.samlProviderId)
  206. }
  207. })
  208. if (Array.isArray(userAffiliations)) {
  209. userAffiliations.forEach(affiliation => {
  210. if (_ssoAvailable(affiliation, req.session, linkedInstitutionIds)) {
  211. notificationsInstitution.push({
  212. email: affiliation.email,
  213. institutionId: affiliation.institution.id,
  214. institutionName: affiliation.institution.name,
  215. templateKey: 'notification_institution_sso_available',
  216. })
  217. }
  218. })
  219. }
  220. if (samlSession) {
  221. // Notification institution SSO: After SSO Linked
  222. if (samlSession.linked) {
  223. notificationsInstitution.push({
  224. email: samlSession.institutionEmail,
  225. institutionName:
  226. samlSession.linked.universityName ||
  227. samlSession.linked.providerName,
  228. templateKey: 'notification_institution_sso_linked',
  229. })
  230. }
  231. // Notification group SSO: After SSO Linked
  232. if (samlSession.linkedGroup) {
  233. groupSsoSetupSuccess = true
  234. }
  235. // Notification institution SSO: After SSO Linked or Logging in
  236. // The requested email does not match primary email returned from
  237. // the institution
  238. if (
  239. samlSession.requestedEmail &&
  240. samlSession.emailNonCanonical &&
  241. !samlSession.error
  242. ) {
  243. notificationsInstitution.push({
  244. institutionEmail: samlSession.emailNonCanonical,
  245. requestedEmail: samlSession.requestedEmail,
  246. templateKey: 'notification_institution_sso_non_canonical',
  247. })
  248. }
  249. // Notification institution SSO: Tried to register, but account already existed
  250. // registerIntercept is set before the institution callback.
  251. // institutionEmail is set after institution callback.
  252. // Check for both in case SSO flow was abandoned
  253. if (
  254. samlSession.registerIntercept &&
  255. samlSession.institutionEmail &&
  256. !samlSession.error
  257. ) {
  258. notificationsInstitution.push({
  259. email: samlSession.institutionEmail,
  260. templateKey: 'notification_institution_sso_already_registered',
  261. })
  262. }
  263. // Notification: When there is a session error
  264. if (samlSession.error) {
  265. notificationsInstitution.push({
  266. templateKey: 'notification_institution_sso_error',
  267. error: samlSession.error,
  268. })
  269. }
  270. }
  271. delete req.session.saml
  272. }
  273. function fakeDelay() {
  274. return new Promise(resolve => {
  275. setTimeout(() => resolve(undefined), 0)
  276. })
  277. }
  278. const prefetchedProjectsBlob = await Promise.race([
  279. projectsBlobPending,
  280. fakeDelay(),
  281. ])
  282. Metrics.inc('project-list-prefetch-projects', 1, {
  283. status: prefetchedProjectsBlob ? 'success' : 'too-slow',
  284. })
  285. // in v2 add notifications for matching university IPs
  286. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  287. try {
  288. await NotificationsBuilder.promises
  289. .ipMatcherAffiliation(user._id)
  290. .create(req.ip)
  291. } catch (err) {
  292. logger.error(
  293. { err },
  294. 'failed to create institutional IP match notification'
  295. )
  296. }
  297. }
  298. const hasPaidAffiliation = userAffiliations.some(
  299. affiliation => affiliation.licence && affiliation.licence !== 'free'
  300. )
  301. const inactiveTutorials = TutorialHandler.getInactiveTutorials(user)
  302. const usGovBannerHooksResponse = await Modules.promises.hooks.fire(
  303. 'getUSGovBanner',
  304. userEmails,
  305. hasPaidAffiliation,
  306. inactiveTutorials.includes('us-gov-banner')
  307. )
  308. const usGovBanner = (usGovBannerHooksResponse &&
  309. usGovBannerHooksResponse[0]) || {
  310. showUSGovBanner: false,
  311. usGovBannerVariant: null,
  312. }
  313. const { showUSGovBanner, usGovBannerVariant } = usGovBanner
  314. const showGroupsAndEnterpriseBanner =
  315. Features.hasFeature('saas') &&
  316. !showUSGovBanner &&
  317. !userIsMemberOfGroupSubscription &&
  318. !hasPaidAffiliation
  319. const groupsAndEnterpriseBannerVariant =
  320. showGroupsAndEnterpriseBanner &&
  321. _.sample(['on-premise', 'FOMO', 'FOMO', 'FOMO'])
  322. let showWritefullPromoBanner = false
  323. if (Features.hasFeature('saas') && !req.session.justRegistered) {
  324. try {
  325. const { variant } = await SplitTestHandler.promises.getAssignment(
  326. req,
  327. res,
  328. 'writefull-promo-banner'
  329. )
  330. showWritefullPromoBanner = variant === 'enabled'
  331. } catch (error) {
  332. logger.warn(
  333. { err: error },
  334. 'failed to get "writefull-promo-banner" split test assignment'
  335. )
  336. }
  337. }
  338. let showInrGeoBanner = false
  339. let showBrlGeoBanner = false
  340. let showLATAMBanner = false
  341. let recommendedCurrency
  342. if (
  343. usersBestSubscription?.type === 'free' ||
  344. usersBestSubscription?.type === 'standalone-ai-add-on'
  345. ) {
  346. const latamGeoPricingAssignment =
  347. await SplitTestHandler.promises.getAssignment(
  348. req,
  349. res,
  350. 'geo-pricing-latam-v2'
  351. )
  352. const { countryCode, currencyCode } =
  353. await GeoIpLookup.promises.getCurrencyCode(req.ip)
  354. if (countryCode === 'IN') {
  355. showInrGeoBanner = true
  356. }
  357. showBrlGeoBanner = countryCode === 'BR'
  358. showLATAMBanner =
  359. latamGeoPricingAssignment.variant === 'latam' &&
  360. ['MX', 'CO', 'CL', 'PE'].includes(countryCode)
  361. // LATAM Banner needs to know which currency to display
  362. if (showLATAMBanner) {
  363. recommendedCurrency = currencyCode
  364. }
  365. }
  366. let hasIndividualRecurlySubscription = false
  367. try {
  368. const individualSubscription =
  369. await SubscriptionLocator.promises.getUsersSubscription(userId)
  370. hasIndividualRecurlySubscription =
  371. individualSubscription?.groupPlan === false &&
  372. individualSubscription?.recurlyStatus?.state !== 'canceled' &&
  373. individualSubscription?.recurlySubscription_id !== ''
  374. } catch (error) {
  375. logger.error({ err: error }, 'Failed to get individual subscription')
  376. }
  377. try {
  378. await SplitTestHandler.promises.getAssignment(req, res, 'paywall-cta')
  379. } catch (error) {
  380. logger.error(
  381. { err: error },
  382. 'failed to get "paywall-cta" split test assignment'
  383. )
  384. }
  385. // Get the user's assignment for the DS unified nav split test, which
  386. // populates splitTestVariants with a value for the split test name and allows
  387. // Pug to send it to the browser
  388. await SplitTestHandler.promises.getAssignment(
  389. req,
  390. res,
  391. 'sidebar-navigation-ui-update'
  392. )
  393. res.render('project/list-react', {
  394. title: 'your_projects',
  395. usersBestSubscription,
  396. notifications,
  397. notificationsInstitution,
  398. user,
  399. userAffiliations,
  400. userEmails,
  401. reconfirmedViaSAML,
  402. allInReconfirmNotificationPeriods,
  403. survey,
  404. tags,
  405. portalTemplates,
  406. prefetchedProjectsBlob,
  407. showGroupsAndEnterpriseBanner,
  408. groupsAndEnterpriseBannerVariant,
  409. showUSGovBanner,
  410. usGovBannerVariant,
  411. showWritefullPromoBanner,
  412. showLATAMBanner,
  413. recommendedCurrency,
  414. showInrGeoBanner,
  415. showBrlGeoBanner,
  416. projectDashboardReact: true, // used in navbar
  417. groupSsoSetupSuccess,
  418. groupSubscriptionsPendingEnrollment:
  419. groupSubscriptionsPendingEnrollment.map(subscription => ({
  420. groupId: subscription._id,
  421. groupName: subscription.teamName,
  422. })),
  423. hasIndividualRecurlySubscription,
  424. userRestrictions: Array.from(req.userRestrictions || []),
  425. })
  426. }
  427. /**
  428. * Load user's projects with pagination, sorting and filters
  429. *
  430. * @param {GetProjectsRequest} req the request
  431. * @param {GetProjectsResponse} res the response
  432. * @returns {Promise<void>}
  433. */
  434. async function getProjectsJson(req, res) {
  435. const { filters, page, sort } = req.body
  436. const userId = SessionManager.getLoggedInUserId(req.session)
  437. const projectsPage = await _getProjects(userId, filters, sort, page)
  438. res.json(projectsPage)
  439. }
  440. /**
  441. * @param {string} userId
  442. * @param {Filters} filters
  443. * @param {Sort} sort
  444. * @param {Page} page
  445. * @returns {Promise<{totalSize: number, projects: ProjectApi[]}>}
  446. * @private
  447. */
  448. async function _getProjects(
  449. userId,
  450. filters = {},
  451. sort = { by: 'lastUpdated', order: 'desc' },
  452. page = { size: 20 }
  453. ) {
  454. const [
  455. /** @type {AllUsersProjects} **/ allProjects,
  456. /** @type {Tag[]} **/ tags,
  457. ] = await Promise.all([
  458. ProjectGetter.promises.findAllUsersProjects(
  459. userId,
  460. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens'
  461. ),
  462. TagsHandler.promises.getAllTags(userId),
  463. ])
  464. const formattedProjects = _formatProjects(allProjects, userId)
  465. const filteredProjects = _applyFilters(
  466. formattedProjects,
  467. tags,
  468. filters,
  469. userId
  470. )
  471. const pagedProjects = _sortAndPaginate(filteredProjects, sort, page)
  472. await _injectProjectUsers(pagedProjects)
  473. return {
  474. totalSize: filteredProjects.length,
  475. projects: pagedProjects,
  476. }
  477. }
  478. /**
  479. * @param {AllUsersProjects} projects
  480. * @param {string} userId
  481. * @returns {Project[]}
  482. * @private
  483. */
  484. function _formatProjects(projects, userId) {
  485. const { owned, readAndWrite, readOnly, tokenReadAndWrite, tokenReadOnly } =
  486. projects
  487. const formattedProjects = /** @type {Project[]} **/ []
  488. for (const project of owned) {
  489. formattedProjects.push(
  490. _formatProjectInfo(project, 'owner', Sources.OWNER, userId)
  491. )
  492. }
  493. // Invite-access
  494. for (const project of readAndWrite) {
  495. formattedProjects.push(
  496. _formatProjectInfo(project, 'readWrite', Sources.INVITE, userId)
  497. )
  498. }
  499. for (const project of readOnly) {
  500. formattedProjects.push(
  501. _formatProjectInfo(project, 'readOnly', Sources.INVITE, userId)
  502. )
  503. }
  504. // Token-access
  505. // Only add these formattedProjects if they're not already present, this gives us cascading access
  506. // from 'owner' => 'token-read-only'
  507. for (const project of tokenReadAndWrite) {
  508. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  509. formattedProjects.push(
  510. _formatProjectInfo(project, 'readAndWrite', Sources.TOKEN, userId)
  511. )
  512. }
  513. }
  514. for (const project of tokenReadOnly) {
  515. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  516. formattedProjects.push(
  517. _formatProjectInfo(project, 'readOnly', Sources.TOKEN, userId)
  518. )
  519. }
  520. }
  521. return formattedProjects
  522. }
  523. /**
  524. * @param {Project[]} projects
  525. * @param {Tag[]} tags
  526. * @param {Filters} filters
  527. * @param {string} userId
  528. * @returns {Project[]}
  529. * @private
  530. */
  531. function _applyFilters(projects, tags, filters, userId) {
  532. if (!_hasActiveFilter(filters)) {
  533. return projects
  534. }
  535. return projects.filter(project => _matchesFilters(project, tags, filters))
  536. }
  537. /**
  538. * @param {Project[]} projects
  539. * @param {Sort} sort
  540. * @param {Page} page
  541. * @returns {Project[]}
  542. * @private
  543. */
  544. function _sortAndPaginate(projects, sort, page) {
  545. if (
  546. (sort.by && !['lastUpdated', 'title', 'owner'].includes(sort.by)) ||
  547. (sort.order && !['asc', 'desc'].includes(sort.order))
  548. ) {
  549. throw new OError('Invalid sorting criteria', { sort })
  550. }
  551. const sortedProjects = _.orderBy(
  552. projects,
  553. [sort.by || 'lastUpdated'],
  554. [sort.order || 'desc']
  555. )
  556. // TODO handle pagination
  557. return sortedProjects
  558. }
  559. /**
  560. * @param {MongoProject} project
  561. * @param {string} accessLevel
  562. * @param {'owner' | 'invite' | 'token'} source
  563. * @param {string} userId
  564. * @returns {object}
  565. * @private
  566. */
  567. function _formatProjectInfo(project, accessLevel, source, userId) {
  568. const archived = ProjectHelper.isArchived(project, userId)
  569. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  570. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  571. const model = {
  572. id: project._id.toString(),
  573. name: project.name,
  574. owner_ref: project.owner_ref,
  575. lastUpdated: project.lastUpdated,
  576. lastUpdatedBy: project.lastUpdatedBy,
  577. accessLevel,
  578. source,
  579. archived,
  580. trashed,
  581. }
  582. if (accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN) {
  583. model.owner_ref = null
  584. model.lastUpdatedBy = null
  585. }
  586. return model
  587. }
  588. /**
  589. * @param {Project[]} projects
  590. * @returns {Promise<void>}
  591. * @private
  592. */
  593. async function _injectProjectUsers(projects) {
  594. const userIds = new Set()
  595. for (const project of projects) {
  596. if (project.owner_ref != null) {
  597. userIds.add(project.owner_ref.toString())
  598. }
  599. if (project.lastUpdatedBy != null) {
  600. userIds.add(project.lastUpdatedBy.toString())
  601. }
  602. }
  603. const projection = {
  604. first_name: 1,
  605. last_name: 1,
  606. email: 1,
  607. }
  608. const users = {}
  609. for (const user of await UserGetter.promises.getUsers(userIds, projection)) {
  610. const userId = user._id.toString()
  611. users[userId] = {
  612. id: userId,
  613. email: user.email,
  614. firstName: user.first_name,
  615. lastName: user.last_name,
  616. }
  617. }
  618. for (const project of projects) {
  619. if (project.owner_ref != null) {
  620. project.owner = users[project.owner_ref.toString()]
  621. }
  622. if (project.lastUpdatedBy != null) {
  623. project.lastUpdatedBy = users[project.lastUpdatedBy.toString()] || null
  624. }
  625. delete project.owner_ref
  626. }
  627. }
  628. /**
  629. * @param {any} project
  630. * @param {Tag[]} tags
  631. * @param {Filters} filters
  632. * @private
  633. */
  634. function _matchesFilters(project, tags, filters) {
  635. if (filters.ownedByUser && project.accessLevel !== 'owner') {
  636. return false
  637. }
  638. if (filters.sharedWithUser && project.accessLevel === 'owner') {
  639. return false
  640. }
  641. if (filters.archived && !project.archived) {
  642. return false
  643. }
  644. if (filters.trashed && !project.trashed) {
  645. return false
  646. }
  647. if (
  648. filters.tag &&
  649. !_.find(
  650. tags,
  651. tag =>
  652. filters.tag === tag.name && (tag.project_ids || []).includes(project.id)
  653. )
  654. ) {
  655. return false
  656. }
  657. if (
  658. filters.search?.length &&
  659. project.name.toLowerCase().indexOf(filters.search.toLowerCase()) === -1
  660. ) {
  661. return false
  662. }
  663. return true
  664. }
  665. /**
  666. * @param {Filters} filters
  667. * @returns {boolean}
  668. * @private
  669. */
  670. function _hasActiveFilter(filters) {
  671. return (
  672. filters.ownedByUser ||
  673. filters.sharedWithUser ||
  674. filters.archived ||
  675. filters.trashed ||
  676. filters.tag === null ||
  677. filters.tag?.length ||
  678. filters.search?.length
  679. )
  680. }
  681. export default {
  682. projectListPage: expressify(projectListPage),
  683. getProjectsJson: expressify(getProjectsJson),
  684. }