ProjectListController.mjs 21 KB

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