ProjectListController.js 21 KB

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