ProjectListController.mjs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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 NotificationsBuilder from '../Notifications/NotificationsBuilder.js'
  24. import GeoIpLookup from '../../infrastructure/GeoIpLookup.js'
  25. import SplitTestHandler from '../SplitTests/SplitTestHandler.js'
  26. import SplitTestSessionHandler from '../SplitTests/SplitTestSessionHandler.js'
  27. import TutorialHandler from '../Tutorial/TutorialHandler.js'
  28. import SubscriptionHelper from '../Subscription/SubscriptionHelper.js'
  29. import PermissionsManager from '../Authorization/PermissionsManager.js'
  30. import SubscriptionLocator from '../Subscription/SubscriptionLocator.js'
  31. /**
  32. * @import { GetProjectsRequest, GetProjectsResponse, AllUsersProjects, MongoProject } from "./types"
  33. * @import { ProjectApi, Filters, Page, Sort } from "../../../../types/project/dashboard/api"
  34. * @import { Tag } from "../Tags/types"
  35. */
  36. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  37. if (!affiliation.institution) return false
  38. // institution.confirmed is for the domain being confirmed, not the email
  39. // Do not show SSO UI for unconfirmed domains
  40. if (!affiliation.institution.confirmed) return false
  41. // Could have multiple emails at the same institution, and if any are
  42. // linked to the institution then do not show notification for others
  43. if (
  44. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  45. ) {
  46. if (affiliation.institution.ssoEnabled) return true
  47. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  48. return false
  49. }
  50. return false
  51. }
  52. const _buildPortalTemplatesList = affiliations => {
  53. if (affiliations == null) {
  54. affiliations = []
  55. }
  56. const portalTemplates = []
  57. const uniqueAffiliations = _.uniqBy(affiliations, 'institution.id')
  58. for (const aff of uniqueAffiliations) {
  59. const hasSlug = aff.portal?.slug
  60. const hasTemplates = aff.portal?.templates_count > 0
  61. if (hasSlug && hasTemplates) {
  62. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  63. const portalTemplateURL = Settings.siteUrl + portalPath + aff.portal?.slug
  64. portalTemplates.push({
  65. name: aff.institution.name,
  66. url: portalTemplateURL,
  67. })
  68. }
  69. }
  70. return portalTemplates
  71. }
  72. function cleanupSession(req) {
  73. // cleanup redirects at the end of the redirect chain
  74. delete req.session.postCheckoutRedirect
  75. delete req.session.postLoginRedirect
  76. delete req.session.postOnboardingRedirect
  77. // cleanup details from register page
  78. delete req.session.sharedProjectData
  79. delete req.session.templateData
  80. }
  81. /**
  82. * @param {import("express").Request} req
  83. * @param {import("express").Response} res
  84. * @param {import("express").NextFunction} next
  85. * @returns {Promise<void>}
  86. */
  87. async function projectListPage(req, res, next) {
  88. cleanupSession(req)
  89. // can have two values:
  90. // - undefined - when there's no "saas" feature or couldn't get subscription data
  91. // - object - the subscription data object
  92. let usersBestSubscription
  93. let usersIndividualSubscription
  94. let usersGroupSubscriptions = []
  95. let survey
  96. let userIsMemberOfGroupSubscription = false
  97. let groupSubscriptionsPendingEnrollment = []
  98. const isSaas = Features.hasFeature('saas')
  99. const userId = SessionManager.getLoggedInUserId(req.session)
  100. const projectsBlobPending = _getProjects(userId).catch(err => {
  101. logger.err({ err, userId }, 'projects listing in background failed')
  102. return undefined
  103. })
  104. const user = await User.findById(
  105. userId,
  106. `email emails features alphaProgram betaProgram lastPrimaryEmailCheck signUpDate refProviders${
  107. isSaas ? ' enrollment writefull completedTutorials aiErrorAssistant' : ''
  108. }`
  109. )
  110. // Handle case of deleted user
  111. if (user == null) {
  112. UserController.logout(req, res, next)
  113. return
  114. }
  115. user.refProviders = _.mapValues(user.refProviders, Boolean)
  116. if (isSaas) {
  117. await SplitTestSessionHandler.promises.sessionMaintenance(req, user)
  118. try {
  119. ;({
  120. bestSubscription: usersBestSubscription,
  121. individualSubscription: usersIndividualSubscription,
  122. memberGroupSubscriptions: usersGroupSubscriptions,
  123. } = await SubscriptionViewModelBuilder.promises.getUsersSubscriptionDetails(
  124. { _id: userId }
  125. ))
  126. } catch (error) {
  127. logger.err(
  128. { err: error, userId },
  129. "Failed to get user's best subscription"
  130. )
  131. }
  132. try {
  133. userIsMemberOfGroupSubscription = usersGroupSubscriptions?.length > 0
  134. // TODO use helper function
  135. if (!user.enrollment?.managedBy) {
  136. groupSubscriptionsPendingEnrollment = usersGroupSubscriptions.filter(
  137. subscription =>
  138. subscription.groupPlan && subscription.managedUsersEnabled
  139. )
  140. }
  141. } catch (error) {
  142. logger.error(
  143. { err: error },
  144. 'Failed to check whether user is a member of group subscription'
  145. )
  146. }
  147. try {
  148. survey = await SurveyHandler.promises.getSurvey(userId)
  149. } catch (error) {
  150. logger.err({ err: error, userId }, 'Failed to load the active survey')
  151. }
  152. if (user && UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck(user)) {
  153. return res.redirect('/user/emails/primary-email-check')
  154. }
  155. }
  156. const tags = await TagsHandler.promises.getAllTags(userId)
  157. let userEmailsData = { list: [], allInReconfirmNotificationPeriods: [] }
  158. try {
  159. const fullEmails = await UserGetter.promises.getUserFullEmails(userId)
  160. if (!Features.hasFeature('affiliations')) {
  161. userEmailsData.list = fullEmails
  162. } else {
  163. try {
  164. const results = await Modules.promises.hooks.fire(
  165. 'allInReconfirmNotificationPeriodsForUser',
  166. fullEmails
  167. )
  168. const allInReconfirmNotificationPeriods = (results && results[0]) || []
  169. userEmailsData = {
  170. list: fullEmails,
  171. allInReconfirmNotificationPeriods,
  172. }
  173. } catch (error) {
  174. userEmailsData = error
  175. }
  176. }
  177. } catch (error) {
  178. if (!(error instanceof V1ConnectionError)) {
  179. logger.error({ err: error, userId }, 'Failed to get user full emails')
  180. }
  181. }
  182. const userEmails = userEmailsData.list || []
  183. const userAffiliations = userEmails
  184. .filter(emailData => !!emailData.affiliation)
  185. .map(emailData => {
  186. const result = emailData.affiliation
  187. result.email = emailData.email
  188. return result
  189. })
  190. const portalTemplates = _buildPortalTemplatesList(userAffiliations)
  191. const { allInReconfirmNotificationPeriods } = userEmailsData
  192. const notifications =
  193. await NotificationsHandler.promises.getUserNotifications(userId)
  194. for (const notification of notifications) {
  195. notification.html = req.i18n.translate(
  196. notification.templateKey,
  197. notification.messageOpts
  198. )
  199. }
  200. const notificationsInstitution = []
  201. // Institution and group SSO Notifications
  202. let groupSsoSetupSuccess
  203. let reconfirmedViaSAML
  204. if (Features.hasFeature('saml')) {
  205. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  206. const samlSession = req.session.saml
  207. // Notification: SSO Available
  208. const linkedInstitutionIds = []
  209. userEmails.forEach(email => {
  210. if (email.samlProviderId) {
  211. linkedInstitutionIds.push(email.samlProviderId)
  212. }
  213. })
  214. if (Array.isArray(userAffiliations)) {
  215. userAffiliations.forEach(affiliation => {
  216. if (_ssoAvailable(affiliation, req.session, linkedInstitutionIds)) {
  217. notificationsInstitution.push({
  218. email: affiliation.email,
  219. institutionId: affiliation.institution.id,
  220. institutionName: affiliation.institution.name,
  221. templateKey: 'notification_institution_sso_available',
  222. })
  223. }
  224. })
  225. }
  226. if (samlSession) {
  227. // Notification institution SSO: After SSO Linked
  228. if (samlSession.linked) {
  229. notificationsInstitution.push({
  230. email: samlSession.institutionEmail,
  231. institutionName:
  232. samlSession.linked.universityName ||
  233. samlSession.linked.providerName,
  234. templateKey: 'notification_institution_sso_linked',
  235. })
  236. }
  237. // Notification group SSO: After SSO Linked
  238. if (samlSession.linkedGroup) {
  239. groupSsoSetupSuccess = true
  240. }
  241. // Notification institution SSO: After SSO Linked or Logging in
  242. // The requested email does not match primary email returned from
  243. // the institution
  244. if (
  245. samlSession.requestedEmail &&
  246. samlSession.emailNonCanonical &&
  247. !samlSession.error
  248. ) {
  249. notificationsInstitution.push({
  250. institutionEmail: samlSession.emailNonCanonical,
  251. requestedEmail: samlSession.requestedEmail,
  252. templateKey: 'notification_institution_sso_non_canonical',
  253. })
  254. }
  255. // Notification institution SSO: Tried to register, but account already existed
  256. // registerIntercept is set before the institution callback.
  257. // institutionEmail is set after institution callback.
  258. // Check for both in case SSO flow was abandoned
  259. if (
  260. samlSession.registerIntercept &&
  261. samlSession.institutionEmail &&
  262. !samlSession.error
  263. ) {
  264. notificationsInstitution.push({
  265. email: samlSession.institutionEmail,
  266. templateKey: 'notification_institution_sso_already_registered',
  267. })
  268. }
  269. // Notification: When there is a session error
  270. if (samlSession.error) {
  271. notificationsInstitution.push({
  272. templateKey: 'notification_institution_sso_error',
  273. error: samlSession.error,
  274. })
  275. }
  276. }
  277. delete req.session.saml
  278. }
  279. const prefetchedProjectsBlob = await projectsBlobPending
  280. Metrics.inc('project-list-prefetch-projects', 1, {
  281. status: prefetchedProjectsBlob ? 'success' : 'error',
  282. })
  283. // in v2 add notifications for matching university IPs
  284. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  285. try {
  286. await NotificationsBuilder.promises
  287. .ipMatcherAffiliation(user._id)
  288. .create(req.ip)
  289. } catch (err) {
  290. logger.error(
  291. { err },
  292. 'failed to create institutional IP match notification'
  293. )
  294. }
  295. }
  296. const hasPaidAffiliation = userAffiliations.some(
  297. affiliation => affiliation.licence && affiliation.licence !== 'free'
  298. )
  299. const inactiveTutorials = TutorialHandler.getInactiveTutorials(user)
  300. const usGovBannerHooksResponse = await Modules.promises.hooks.fire(
  301. 'getUSGovBanner',
  302. userEmails,
  303. hasPaidAffiliation,
  304. inactiveTutorials
  305. )
  306. const usGovBanner = (usGovBannerHooksResponse &&
  307. usGovBannerHooksResponse[0]) || {
  308. showUSGovBanner: false,
  309. usGovBannerVariant: null,
  310. }
  311. const { showUSGovBanner, usGovBannerVariant } = usGovBanner
  312. const showGroupsAndEnterpriseBanner =
  313. Features.hasFeature('saas') &&
  314. !showUSGovBanner &&
  315. !userIsMemberOfGroupSubscription &&
  316. !hasPaidAffiliation
  317. const groupsAndEnterpriseBannerVariant =
  318. showGroupsAndEnterpriseBanner &&
  319. _.sample(['on-premise', 'FOMO', 'FOMO', 'FOMO'])
  320. let showInrGeoBanner = false
  321. let showBrlGeoBanner = false
  322. let showLATAMBanner = false
  323. let recommendedCurrency
  324. if (
  325. usersBestSubscription?.type === 'free' ||
  326. usersBestSubscription?.type === 'standalone-ai-add-on'
  327. ) {
  328. const { countryCode, currencyCode } =
  329. await GeoIpLookup.promises.getCurrencyCode(req.ip)
  330. if (countryCode === 'IN') {
  331. showInrGeoBanner = true
  332. }
  333. showBrlGeoBanner = countryCode === 'BR'
  334. showLATAMBanner = ['MX', 'CO', 'CL', 'PE'].includes(countryCode)
  335. // LATAM Banner needs to know which currency to display
  336. if (showLATAMBanner) {
  337. recommendedCurrency = currencyCode
  338. }
  339. }
  340. let hasIndividualPaidSubscription = false
  341. try {
  342. hasIndividualPaidSubscription =
  343. SubscriptionHelper.isIndividualActivePaidSubscription(
  344. usersIndividualSubscription
  345. )
  346. } catch (error) {
  347. logger.error({ err: error }, 'Failed to get individual subscription')
  348. }
  349. // Get the user's assignment for the papers notification banner split test,
  350. // which populates splitTestVariants with a value for the split test name and
  351. // allows Pug to send it to the browser
  352. await SplitTestHandler.promises.getAssignment(
  353. req,
  354. res,
  355. 'papers-notification-banner'
  356. )
  357. const aiAssistNotificationAssignment =
  358. await SplitTestHandler.promises.getAssignment(
  359. req,
  360. res,
  361. 'ai-assist-notification'
  362. )
  363. let showAiAssistNotification = false
  364. if (aiAssistNotificationAssignment.variant !== 'default') {
  365. showAiAssistNotification = await _showAiAssistNotification(user)
  366. }
  367. const customerIoEnabled =
  368. await SplitTestHandler.promises.hasUserBeenAssignedToVariant(
  369. req,
  370. userId,
  371. 'customer-io-trial-conversion',
  372. 'enabled',
  373. true
  374. )
  375. res.render('project/list-react', {
  376. title: 'your_projects',
  377. usersBestSubscription,
  378. notifications,
  379. notificationsInstitution,
  380. user,
  381. userAffiliations,
  382. userEmails,
  383. reconfirmedViaSAML,
  384. allInReconfirmNotificationPeriods,
  385. survey,
  386. tags,
  387. portalTemplates,
  388. prefetchedProjectsBlob,
  389. showGroupsAndEnterpriseBanner,
  390. groupsAndEnterpriseBannerVariant,
  391. showUSGovBanner,
  392. usGovBannerVariant,
  393. showLATAMBanner,
  394. recommendedCurrency,
  395. showInrGeoBanner,
  396. showBrlGeoBanner,
  397. projectDashboardReact: true, // used in navbar
  398. groupSsoSetupSuccess,
  399. groupSubscriptionsPendingEnrollment:
  400. groupSubscriptionsPendingEnrollment.map(subscription => ({
  401. groupId: subscription._id,
  402. groupName: subscription.teamName,
  403. })),
  404. hasIndividualPaidSubscription,
  405. userRestrictions: Array.from(req.userRestrictions || []),
  406. customerIoEnabled,
  407. showAiAssistNotification,
  408. })
  409. }
  410. /**
  411. * Load user's projects with pagination, sorting and filters
  412. *
  413. * @param {GetProjectsRequest} req the request
  414. * @param {GetProjectsResponse} res the response
  415. * @returns {Promise<void>}
  416. */
  417. async function getProjectsJson(req, res) {
  418. const { filters, page, sort } = req.body
  419. const userId = SessionManager.getLoggedInUserId(req.session)
  420. const projectsPage = await _getProjects(userId, filters, sort, page)
  421. res.json(projectsPage)
  422. }
  423. /**
  424. * @param {string} userId
  425. * @param {Filters} filters
  426. * @param {Sort} sort
  427. * @param {Page} page
  428. * @returns {Promise<{totalSize: number, projects: ProjectApi[]}>}
  429. * @private
  430. */
  431. async function _getProjects(
  432. userId,
  433. filters = {},
  434. sort = { by: 'lastUpdated', order: 'desc' },
  435. page = { size: 20 }
  436. ) {
  437. const [
  438. /** @type {AllUsersProjects} **/ allProjects,
  439. /** @type {Tag[]} **/ tags,
  440. ] = await Promise.all([
  441. ProjectGetter.promises.findAllUsersProjects(
  442. userId,
  443. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens'
  444. ),
  445. TagsHandler.promises.getAllTags(userId),
  446. ])
  447. const formattedProjects = _formatProjects(allProjects, userId)
  448. const filteredProjects = _applyFilters(
  449. formattedProjects,
  450. tags,
  451. filters,
  452. userId
  453. )
  454. const pagedProjects = _sortAndPaginate(filteredProjects, sort, page)
  455. await _injectProjectUsers(pagedProjects)
  456. return {
  457. totalSize: filteredProjects.length,
  458. projects: pagedProjects,
  459. }
  460. }
  461. /**
  462. * @param {AllUsersProjects} projects
  463. * @param {string} userId
  464. * @returns {Project[]}
  465. * @private
  466. */
  467. function _formatProjects(projects, userId) {
  468. const {
  469. owned,
  470. review,
  471. readAndWrite,
  472. readOnly,
  473. tokenReadAndWrite,
  474. tokenReadOnly,
  475. } = projects
  476. const formattedProjects = /** @type {Project[]} **/ []
  477. for (const project of owned) {
  478. formattedProjects.push(
  479. _formatProjectInfo(project, 'owner', Sources.OWNER, userId)
  480. )
  481. }
  482. // Invite-access
  483. for (const project of readAndWrite) {
  484. formattedProjects.push(
  485. _formatProjectInfo(project, 'readWrite', Sources.INVITE, userId)
  486. )
  487. }
  488. for (const project of review) {
  489. formattedProjects.push(
  490. _formatProjectInfo(project, 'review', 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. async function _showAiAssistNotification(user) {
  676. // Check if the assistant has been manually disabled by the user
  677. if (user.aiErrorAssistant?.enabled === false) {
  678. return false
  679. }
  680. // Check if the user can use AI features (policy check)
  681. const canUseAi = await PermissionsManager.promises.checkUserPermissions(
  682. user,
  683. ['use-ai']
  684. )
  685. if (!canUseAi) {
  686. return false
  687. }
  688. // Check if the user has a subscription with manually collected group admins (#22822)
  689. const subscription = await SubscriptionLocator.promises.getUsersSubscription(
  690. user._id
  691. )
  692. if (subscription?.collectionMethod === 'manual') {
  693. return false
  694. }
  695. // Check if the user already has AI Assist via Overleaf
  696. if (user.features?.aiErrorAssistant) {
  697. return false
  698. }
  699. // Check if the user already has AI Assist via Writefull
  700. const { isPremium: hasAiAssistViaWritefull } =
  701. await UserGetter.promises.getWritefullData(user._id)
  702. if (hasAiAssistViaWritefull) {
  703. return false
  704. }
  705. return true
  706. }
  707. export default {
  708. projectListPage: expressify(projectListPage),
  709. getProjectsJson: expressify(getProjectsJson),
  710. }