ProjectListController.mjs 21 KB

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