ProjectListController.js 21 KB

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