ProjectListController.mjs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. // @ts-check
  2. import _ from 'lodash'
  3. import moment from 'moment'
  4. import Metrics from '@overleaf/metrics'
  5. import Settings from '@overleaf/settings'
  6. import ProjectHelper from './ProjectHelper.mjs'
  7. import ProjectGetter from './ProjectGetter.mjs'
  8. import PrivilegeLevels from '../Authorization/PrivilegeLevels.mjs'
  9. import SessionManager from '../Authentication/SessionManager.mjs'
  10. import Sources from '../Authorization/Sources.mjs'
  11. import UserGetter from '../User/UserGetter.mjs'
  12. import SurveyHandler from '../Survey/SurveyHandler.mjs'
  13. import TagsHandler from '../Tags/TagsHandler.mjs'
  14. import { expressify } from '@overleaf/promise-utils'
  15. import logger from '@overleaf/logger'
  16. import Features from '../../infrastructure/Features.mjs'
  17. import SubscriptionViewModelBuilder from '../Subscription/SubscriptionViewModelBuilder.mjs'
  18. import NotificationsHandler from '../Notifications/NotificationsHandler.mjs'
  19. import Modules from '../../infrastructure/Modules.mjs'
  20. import { OError, V1ConnectionError } from '../Errors/Errors.js'
  21. import { User } from '../../models/User.mjs'
  22. import UserPrimaryEmailCheckHandler from '../User/UserPrimaryEmailCheckHandler.mjs'
  23. import UserController from '../User/UserController.mjs'
  24. import NotificationsBuilder from '../Notifications/NotificationsBuilder.mjs'
  25. import GeoIpLookup from '../../infrastructure/GeoIpLookup.mjs'
  26. import SplitTestHandler from '../SplitTests/SplitTestHandler.mjs'
  27. import SplitTestSessionHandler from '../SplitTests/SplitTestSessionHandler.mjs'
  28. import TutorialHandler from '../Tutorial/TutorialHandler.mjs'
  29. import SubscriptionHelper from '../Subscription/SubscriptionHelper.mjs'
  30. import CustomerIoPlanHelpers from '../Subscription/CustomerIoPlanHelpers.mjs'
  31. import PermissionsManager from '../Authorization/PermissionsManager.mjs'
  32. import AnalyticsManager from '../Analytics/AnalyticsManager.mjs'
  33. import { OnboardingDataCollection } from '../../models/OnboardingDataCollection.mjs'
  34. import UserSettingsHelper from './UserSettingsHelper.mjs'
  35. /**
  36. * @import { GetProjectsRequest, GetProjectsResponse, AllUsersProjects, MongoProject, FormattedProject, MongoTag, SubscriptionRecord } from "./types"
  37. * @import { Project, ProjectApi, ProjectAccessLevel, Filters, Page, Sort, UserRef } from "../../../../types/project/dashboard/api"
  38. * @import { Affiliation } from "../../../../types/affiliation"
  39. * @import { Source } from "../Authorization/types"
  40. */
  41. /**
  42. * @param {Affiliation} affiliation
  43. * @param {any} session
  44. * @param {string[]} linkedInstitutionIds
  45. * @returns {boolean}
  46. * @private
  47. */
  48. const _ssoAvailable = (affiliation, session, linkedInstitutionIds) => {
  49. if (!affiliation.institution) return false
  50. // institution.confirmed is for the domain being confirmed, not the email
  51. // Do not show SSO UI for unconfirmed domains
  52. if (!affiliation.institution.confirmed) return false
  53. // If ssoEnabled = true and group.domainCaptureEnabled = true
  54. // then Commons is migrating to group subscription and we do not want to prompt
  55. // linking through Commons SSO
  56. if (affiliation?.group?.domainCaptureEnabled) return false
  57. // Could have multiple emails at the same institution, and if any are
  58. // linked to the institution then do not show notification for others
  59. if (
  60. linkedInstitutionIds.indexOf(affiliation.institution.id.toString()) === -1
  61. ) {
  62. if (affiliation.institution.ssoEnabled) return true
  63. if (affiliation.institution.ssoBeta && session.samlBeta) return true
  64. return false
  65. }
  66. return false
  67. }
  68. /**
  69. * @param {Affiliation[]} affiliations
  70. * @returns {Array<{ name: string, url: string }>}
  71. */
  72. const _buildPortalTemplatesList = affiliations => {
  73. if (affiliations == null) {
  74. affiliations = []
  75. }
  76. const portalTemplates = []
  77. const uniqueAffiliations = _.uniqBy(affiliations, 'institution.id')
  78. for (const aff of uniqueAffiliations) {
  79. const hasSlug = aff.portal?.slug
  80. const hasTemplates = (aff.portal?.templates_count || 0) > 0
  81. if (hasSlug && hasTemplates) {
  82. const portalPath = aff.institution.isUniversity ? '/edu/' : '/org/'
  83. const portalTemplateURL = Settings.siteUrl + portalPath + aff.portal?.slug
  84. portalTemplates.push({
  85. name: aff.institution.name,
  86. url: portalTemplateURL,
  87. })
  88. }
  89. }
  90. return portalTemplates
  91. }
  92. /**
  93. * @param {any} req
  94. */
  95. function cleanupSession(req) {
  96. // cleanup redirects at the end of the redirect chain
  97. delete req.session.postCheckoutRedirect
  98. delete req.session.postLoginRedirect
  99. delete req.session.postOnboardingRedirect
  100. // cleanup details from register page
  101. delete req.session.sharedProjectData
  102. delete req.session.templateData
  103. }
  104. /**
  105. * @param {import("express").Request} req
  106. * @param {import("express").Response} res
  107. * @param {import("express").NextFunction} next
  108. * @returns {Promise<void>}
  109. */
  110. async function projectListPage(req, res, next) {
  111. cleanupSession(req)
  112. // can have two values:
  113. // - undefined - when there's no "saas" feature or couldn't get subscription data
  114. // - object - the subscription data object
  115. let usersBestSubscription
  116. let usersIndividualSubscription
  117. /** @type {any[]} */
  118. let usersGroupSubscriptions = []
  119. /** @type {any[]} */
  120. let usersManagedGroupSubscriptions = []
  121. let survey
  122. let userIsMemberOfGroupSubscription = false
  123. /** @type {any[]} */
  124. let groupSubscriptionsPendingEnrollment = []
  125. const isSaas = Features.hasFeature('saas')
  126. const userId = SessionManager.getLoggedInUserId(req.session)
  127. if (isSaas) {
  128. const { variant: domainCaptureRedirect } =
  129. await SplitTestHandler.promises.getAssignment(
  130. req,
  131. res,
  132. 'domain-capture-redirect'
  133. )
  134. if (domainCaptureRedirect === 'enabled') {
  135. const groupsWithEmails = (
  136. await Modules.promises.hooks.fire(
  137. 'findDomainCaptureGroupsUserCouldBePartOf',
  138. userId
  139. )
  140. )?.[0]
  141. if (groupsWithEmails && groupsWithEmails.length > 0) {
  142. if (
  143. groupsWithEmails.some(
  144. (/** @type {any} */ { subscription }) =>
  145. subscription.managedUsersEnabled
  146. )
  147. ) {
  148. return res.redirect('/domain-capture')
  149. } else {
  150. // TODO show notification or anything else
  151. }
  152. }
  153. }
  154. }
  155. const projectsBlobPending = _getProjects(userId).catch(err => {
  156. logger.err({ err, userId }, 'projects listing in background failed')
  157. return undefined
  158. })
  159. const user = await User.findById(
  160. userId,
  161. `email isAdmin emails features alphaProgram betaProgram lastPrimaryEmailCheck lastActive signUpDate ace refProviders${
  162. isSaas
  163. ? ' enrollment writefull completedTutorials aiFeatures aiErrorAssistant labsProgram'
  164. : ''
  165. }`
  166. )
  167. // Handle case of deleted user
  168. if (user == null) {
  169. UserController.logout(req, res, next)
  170. return
  171. }
  172. user.refProviders = _.mapValues(user.refProviders, Boolean)
  173. let onboardingDataCollection
  174. let customerIoEnabled = false
  175. let subjectArea
  176. let usedLatex
  177. let primaryOccupation
  178. let role
  179. if (isSaas) {
  180. if (user.isAdmin) await _checkForOldDebugProjects(userId)
  181. await SplitTestSessionHandler.promises.sessionMaintenance(req, user)
  182. try {
  183. ;({
  184. bestSubscription: usersBestSubscription,
  185. individualSubscription: usersIndividualSubscription,
  186. memberGroupSubscriptions: usersGroupSubscriptions,
  187. managedGroupSubscriptions: usersManagedGroupSubscriptions,
  188. } = await SubscriptionViewModelBuilder.promises.getUsersSubscriptionDetails(
  189. { _id: userId }
  190. ))
  191. } catch (error) {
  192. logger.err(
  193. { err: error, userId },
  194. "Failed to get user's best subscription"
  195. )
  196. }
  197. userIsMemberOfGroupSubscription =
  198. usersGroupSubscriptions.length > 0 ||
  199. usersManagedGroupSubscriptions.length > 0
  200. // TODO use helper function
  201. if (!user.enrollment?.managedBy) {
  202. groupSubscriptionsPendingEnrollment = usersGroupSubscriptions.filter(
  203. subscription =>
  204. subscription.groupPlan && subscription.managedUsersEnabled
  205. )
  206. }
  207. try {
  208. survey = await SurveyHandler.promises.getSurvey(userId)
  209. } catch (error) {
  210. logger.err({ err: error, userId }, 'Failed to load the active survey')
  211. }
  212. if (
  213. user &&
  214. UserPrimaryEmailCheckHandler.requiresPrimaryEmailCheck({
  215. email: user.email,
  216. emails: user.emails,
  217. lastPrimaryEmailCheck: user.lastPrimaryEmailCheck,
  218. signUpDate: user.signUpDate,
  219. })
  220. ) {
  221. return res.redirect('/user/emails/primary-email-check')
  222. }
  223. onboardingDataCollection = await OnboardingDataCollection.findById(
  224. userId,
  225. 'subjectArea usedLatex primaryOccupation role'
  226. )
  227. if (onboardingDataCollection) {
  228. subjectArea = onboardingDataCollection.subjectArea
  229. usedLatex = onboardingDataCollection.usedLatex
  230. primaryOccupation = onboardingDataCollection.primaryOccupation
  231. role = onboardingDataCollection.role
  232. }
  233. customerIoEnabled = true
  234. AnalyticsManager.setUserPropertyForUserInBackground(
  235. userId,
  236. 'customer-io-integration',
  237. true
  238. )
  239. }
  240. const tags = await TagsHandler.promises.getAllTags(userId)
  241. /** @type {{ list: any[], allInReconfirmNotificationPeriods?: any[], error?: any }} */
  242. let userEmailsData = {
  243. list: [],
  244. }
  245. try {
  246. const fullEmails = await UserGetter.promises.getUserFullEmails(userId)
  247. if (!Features.hasFeature('affiliations')) {
  248. userEmailsData.list = fullEmails
  249. } else {
  250. try {
  251. const results = await Modules.promises.hooks.fire(
  252. 'allInReconfirmNotificationPeriodsForUser',
  253. fullEmails
  254. )
  255. const allInReconfirmNotificationPeriods = (results && results[0]) || []
  256. userEmailsData = {
  257. list: fullEmails,
  258. allInReconfirmNotificationPeriods,
  259. }
  260. } catch (error) {
  261. userEmailsData.error = error
  262. }
  263. }
  264. } catch (error) {
  265. if (!(error instanceof V1ConnectionError)) {
  266. logger.error({ err: error, userId }, 'Failed to get user full emails')
  267. }
  268. }
  269. const userEmails = userEmailsData.list || []
  270. const userAffiliations = userEmails
  271. .filter(emailData => !!emailData.affiliation)
  272. .map(emailData => {
  273. const result = emailData.affiliation
  274. result.email = emailData.email
  275. return result
  276. })
  277. const commonsInstitution = userAffiliations.find(
  278. affiliation => affiliation.institution?.commonsAccount
  279. )?.institution?.name
  280. const portalTemplates = _buildPortalTemplatesList(userAffiliations)
  281. const { allInReconfirmNotificationPeriods } = userEmailsData
  282. const notifications =
  283. await NotificationsHandler.promises.getUserNotifications(userId)
  284. for (const notification of notifications) {
  285. notification.html = req.i18n.translate(
  286. notification.templateKey,
  287. notification.messageOpts
  288. )
  289. }
  290. const notificationsInstitution = []
  291. // Institution and group SSO Notifications
  292. let groupSsoSetupSuccess
  293. let viaDomainCapture
  294. let joinedGroupName = ''
  295. let reconfirmedViaSAML
  296. if (Features.hasFeature('saml')) {
  297. reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
  298. const samlSession = req.session.saml
  299. // Notification: SSO Available
  300. /** @type {string[]} */
  301. const linkedInstitutionIds = []
  302. userEmails.forEach(email => {
  303. if (email.samlProviderId) {
  304. linkedInstitutionIds.push(email.samlProviderId)
  305. }
  306. })
  307. if (Array.isArray(userAffiliations)) {
  308. userAffiliations.forEach(affiliation => {
  309. if (_ssoAvailable(affiliation, req.session, linkedInstitutionIds)) {
  310. notificationsInstitution.push({
  311. email: affiliation.email,
  312. institutionId: affiliation.institution.id,
  313. institutionName: affiliation.institution.name,
  314. templateKey: 'notification_institution_sso_available',
  315. })
  316. }
  317. })
  318. }
  319. if (samlSession) {
  320. // Notification institution SSO: After SSO Linked
  321. if (samlSession.linked) {
  322. let templateKey = 'notification_institution_sso_linked'
  323. if (
  324. samlSession.userCreatedViaDomainCapture &&
  325. samlSession.managedUsersEnabled
  326. ) {
  327. templateKey =
  328. 'notification_account_created_via_group_domain_capture_and_managed_users_enabled'
  329. } else if (samlSession.domainCaptureEnabled) {
  330. templateKey = 'notification_group_sso_linked'
  331. }
  332. notificationsInstitution.push({
  333. email: samlSession.institutionEmail,
  334. institutionName:
  335. samlSession.linked.universityName ||
  336. samlSession.linked.providerName,
  337. templateKey,
  338. })
  339. }
  340. // Notification group SSO: After SSO Linked
  341. if (samlSession.linkedGroup) {
  342. groupSsoSetupSuccess = true
  343. viaDomainCapture = samlSession.domainCaptureJoin
  344. joinedGroupName = samlSession.universityName
  345. }
  346. // Notification institution SSO: After SSO Linked or Logging in
  347. // The requested email does not match primary email returned from
  348. // the institution
  349. if (
  350. samlSession.requestedEmail &&
  351. samlSession.emailNonCanonical &&
  352. !samlSession.error
  353. ) {
  354. notificationsInstitution.push({
  355. institutionEmail: samlSession.emailNonCanonical,
  356. requestedEmail: samlSession.requestedEmail,
  357. templateKey: 'notification_institution_sso_non_canonical',
  358. })
  359. }
  360. // Notification institution SSO: Tried to register, but account already existed
  361. // registerIntercept is set before the institution callback.
  362. // institutionEmail is set after institution callback.
  363. // Check for both in case SSO flow was abandoned
  364. if (
  365. samlSession.registerIntercept &&
  366. samlSession.institutionEmail &&
  367. !samlSession.error
  368. ) {
  369. notificationsInstitution.push({
  370. email: samlSession.institutionEmail,
  371. templateKey: 'notification_institution_sso_already_registered',
  372. })
  373. }
  374. // Notification: When there is a session error
  375. if (samlSession.error) {
  376. notificationsInstitution.push({
  377. templateKey: 'notification_institution_sso_error',
  378. error: samlSession.error,
  379. })
  380. }
  381. }
  382. delete req.session.saml
  383. }
  384. const prefetchedProjectsBlob = await projectsBlobPending
  385. Metrics.inc('project-list-prefetch-projects', 1, {
  386. status: prefetchedProjectsBlob ? 'success' : 'error',
  387. })
  388. // in v2 add notifications for matching university IPs
  389. if (Settings.overleaf != null && req.ip !== user.lastLoginIp) {
  390. try {
  391. await NotificationsBuilder.promises
  392. .ipMatcherAffiliation(user._id.toString())
  393. .create(req.ip)
  394. } catch (err) {
  395. logger.error(
  396. { err },
  397. 'failed to create institutional IP match notification'
  398. )
  399. }
  400. }
  401. const hasPaidAffiliation = userAffiliations.some(
  402. affiliation => affiliation.licence && affiliation.licence !== 'free'
  403. )
  404. const inactiveTutorials = TutorialHandler.getInactiveTutorials(user)
  405. const usGovBannerHooksResponse = await Modules.promises.hooks.fire(
  406. 'getUSGovBanner',
  407. userEmails,
  408. hasPaidAffiliation,
  409. inactiveTutorials
  410. )
  411. const usGovBanner = (usGovBannerHooksResponse &&
  412. usGovBannerHooksResponse[0]) || {
  413. showUSGovBanner: false,
  414. usGovBannerVariant: null,
  415. }
  416. const { showUSGovBanner, usGovBannerVariant } = usGovBanner
  417. const isUser30DaysOld = moment.utc().diff(user.signUpDate, 'days') > 30
  418. const showGroupsAndEnterpriseBanner =
  419. Features.hasFeature('saas') &&
  420. !showUSGovBanner &&
  421. !userIsMemberOfGroupSubscription &&
  422. !hasPaidAffiliation &&
  423. !inactiveTutorials.includes('groups-enterprise-banner-repeat') &&
  424. isUser30DaysOld
  425. const groupsAndEnterpriseBannerVariant =
  426. showGroupsAndEnterpriseBanner &&
  427. _.sample(['on-premise', 'FOMO', 'FOMO', 'FOMO'])
  428. let showInrGeoBanner = false
  429. let showLATAMBanner = false
  430. let recommendedCurrency
  431. const { countryCode, currencyCode } =
  432. await GeoIpLookup.promises.getCurrencyCode(req.ip)
  433. if (
  434. usersBestSubscription?.type === 'free' ||
  435. usersBestSubscription?.type === 'standalone-ai-add-on'
  436. ) {
  437. if (countryCode === 'IN') {
  438. showInrGeoBanner = true
  439. }
  440. showLATAMBanner =
  441. !!countryCode && ['MX', 'CO', 'CL', 'PE'].includes(countryCode)
  442. // LATAM Banner needs to know which currency to display
  443. if (showLATAMBanner) {
  444. recommendedCurrency = currencyCode
  445. }
  446. }
  447. let hasIndividualPaidSubscription = false
  448. try {
  449. hasIndividualPaidSubscription =
  450. SubscriptionHelper.isIndividualActivePaidSubscription(
  451. usersIndividualSubscription
  452. )
  453. } catch (error) {
  454. logger.error({ err: error }, 'Failed to get individual subscription')
  455. }
  456. const aiBlocked =
  457. Features.hasFeature('saas') && !(await _canUseAIAssist(user))
  458. const hasAiAssist =
  459. Features.hasFeature('saas') && (await _userHasAIAssist(user))
  460. const splitTests = [
  461. // Split tests that will be made available to the frontend
  462. 'import-docx',
  463. 'overleaf-library',
  464. 'import-markdown',
  465. ].filter(Boolean)
  466. await Promise.all(
  467. splitTests.map(splitTestName =>
  468. SplitTestHandler.promises.getAssignment(req, res, splitTestName)
  469. )
  470. )
  471. const userSettings = await UserSettingsHelper.buildUserSettings(
  472. req,
  473. res,
  474. user
  475. )
  476. let groupRole
  477. if (userIsMemberOfGroupSubscription) {
  478. const userIdStr = userId.toString()
  479. const isGroupAdmin = usersManagedGroupSubscriptions?.some(
  480. sub => sub.admin_id?._id?.toString() === userIdStr
  481. )
  482. const isGroupManager =
  483. usersManagedGroupSubscriptions?.length > 0 ||
  484. usersGroupSubscriptions?.some(sub => sub.userIsGroupManager)
  485. if (isGroupAdmin) {
  486. groupRole = 'admin'
  487. } else if (isGroupManager) {
  488. groupRole = 'manager'
  489. } else {
  490. groupRole = 'member'
  491. }
  492. }
  493. Modules.promises.hooks
  494. .fire('setUserProperties', userId, {
  495. overleaf_id: userId,
  496. last_active: user.lastActive
  497. ? Math.floor(user.lastActive.getTime() / 1000)
  498. : null,
  499. sign_up_date: user.signUpDate
  500. ? Math.floor(user.signUpDate.getTime() / 1000)
  501. : null,
  502. ...(usersBestSubscription?.type && {
  503. best_subscription_type: usersBestSubscription.type,
  504. }),
  505. ai_blocked: aiBlocked,
  506. has_ai_assist: hasAiAssist,
  507. ...(subjectArea && { subject_area: subjectArea }),
  508. ...(role && { role }),
  509. ...(primaryOccupation && { primary_occupation: primaryOccupation }),
  510. ...(usedLatex && { used_latex: usedLatex }),
  511. ...(countryCode && { country: countryCode }),
  512. ...(commonsInstitution && { commons_institution: commonsInstitution }),
  513. ...CustomerIoPlanHelpers.getAffiliationProperties(userEmails),
  514. ...(groupRole && { group_role: groupRole }),
  515. is_managed_user: Boolean(user.enrollment?.managedBy),
  516. ...(user.email && { email: user.email }),
  517. })
  518. .catch(err => {
  519. logger.error({ err }, 'Failed to set user properties for customer.io')
  520. })
  521. res.render('project/list-react', {
  522. title: 'your_projects',
  523. usersBestSubscription,
  524. notifications,
  525. notificationsInstitution,
  526. user,
  527. userAffiliations,
  528. userEmails,
  529. userSettings,
  530. reconfirmedViaSAML,
  531. allInReconfirmNotificationPeriods,
  532. survey,
  533. tags,
  534. portalTemplates,
  535. prefetchedProjectsBlob,
  536. showGroupsAndEnterpriseBanner,
  537. groupsAndEnterpriseBannerVariant,
  538. showUSGovBanner,
  539. usGovBannerVariant,
  540. showLATAMBanner,
  541. recommendedCurrency,
  542. showInrGeoBanner,
  543. projectDashboardReact: true, // used in navbar
  544. groupSsoSetupSuccess,
  545. joinedGroupName,
  546. viaDomainCapture,
  547. groupSubscriptionsPendingEnrollment:
  548. groupSubscriptionsPendingEnrollment.map(subscription => ({
  549. groupId: subscription._id,
  550. groupName: subscription.teamName,
  551. })),
  552. hasIndividualPaidSubscription,
  553. userRestrictions: Array.from(req.userRestrictions || []),
  554. customerIoEnabled,
  555. inactiveTutorials,
  556. })
  557. }
  558. /**
  559. * Load user's projects with pagination, sorting and filters
  560. *
  561. * @param {GetProjectsRequest} req the request
  562. * @param {GetProjectsResponse} res the response
  563. * @returns {Promise<void>}
  564. */
  565. async function getProjectsJson(req, res) {
  566. const { filters, page, sort } = req.body
  567. const userId = SessionManager.getLoggedInUserId(req.session)
  568. const projectsPage = await _getProjects(userId, filters, sort, page)
  569. res.json(projectsPage)
  570. }
  571. /**
  572. * @param {string} userId
  573. * @private
  574. */
  575. async function _checkForOldDebugProjects(userId) {
  576. const exists = await ProjectGetter.promises.existUsersDebugProjectsOlderThan(
  577. userId,
  578. 7
  579. )
  580. if (exists) {
  581. await NotificationsBuilder.promises.oldDebugProjects(userId).create()
  582. } else {
  583. await NotificationsBuilder.promises.oldDebugProjects(userId).read()
  584. }
  585. }
  586. /**
  587. * @param {string} userId
  588. * @param {Filters} filters
  589. * @param {Sort} sort
  590. * @param {Page} page
  591. * @returns {Promise<{totalSize: number, projects: Project[]}>}
  592. * @private
  593. */
  594. async function _getProjects(
  595. userId,
  596. filters = {},
  597. sort = { by: 'lastUpdated', order: 'desc' },
  598. page = { size: 20 }
  599. ) {
  600. /** @type {[AllUsersProjects, MongoTag[]]} */
  601. const results = await Promise.all([
  602. ProjectGetter.promises.findAllUsersProjects(
  603. userId,
  604. 'name lastUpdated lastUpdatedBy publicAccesLevel archived trashed owner_ref tokens'
  605. ),
  606. TagsHandler.promises.getAllTags(userId),
  607. ])
  608. const [allProjects, tags] = results
  609. const formattedProjects = _formatProjects(allProjects, userId)
  610. const filteredProjects = _applyFilters(
  611. formattedProjects,
  612. tags,
  613. filters,
  614. userId
  615. )
  616. const pagedProjects = _sortAndPaginate(filteredProjects, sort, page)
  617. const projects = await _injectProjectUsers(pagedProjects)
  618. return {
  619. totalSize: filteredProjects.length,
  620. projects,
  621. }
  622. }
  623. /**
  624. * @param {AllUsersProjects} projects
  625. * @param {string} userId
  626. * @returns {FormattedProject[]}
  627. * @private
  628. */
  629. function _formatProjects(projects, userId) {
  630. const {
  631. owned,
  632. review,
  633. readAndWrite,
  634. readOnly,
  635. tokenReadAndWrite,
  636. tokenReadOnly,
  637. } = projects
  638. const formattedProjects = /** @type {FormattedProject[]} **/ []
  639. for (const project of owned) {
  640. formattedProjects.push(
  641. _formatProjectInfo(project, 'owner', Sources.OWNER, userId)
  642. )
  643. }
  644. // Invite-access
  645. for (const project of readAndWrite) {
  646. formattedProjects.push(
  647. _formatProjectInfo(project, 'readWrite', Sources.INVITE, userId)
  648. )
  649. }
  650. for (const project of review) {
  651. formattedProjects.push(
  652. _formatProjectInfo(project, 'review', Sources.INVITE, userId)
  653. )
  654. }
  655. for (const project of readOnly) {
  656. formattedProjects.push(
  657. _formatProjectInfo(project, 'readOnly', Sources.INVITE, userId)
  658. )
  659. }
  660. // Token-access
  661. // Only add these formattedProjects if they're not already present, this gives us cascading access
  662. // from 'owner' => 'token-read-only'
  663. for (const project of tokenReadAndWrite) {
  664. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  665. formattedProjects.push(
  666. _formatProjectInfo(project, 'readAndWrite', Sources.TOKEN, userId)
  667. )
  668. }
  669. }
  670. for (const project of tokenReadOnly) {
  671. if (!formattedProjects.some(p => p.id === project._id.toString())) {
  672. formattedProjects.push(
  673. _formatProjectInfo(project, 'readOnly', Sources.TOKEN, userId)
  674. )
  675. }
  676. }
  677. return formattedProjects
  678. }
  679. /**
  680. * @param {FormattedProject[]} projects
  681. * @param {MongoTag[]} tags
  682. * @param {Filters} filters
  683. * @param {string} userId
  684. * @returns {FormattedProject[]}
  685. * @private
  686. */
  687. function _applyFilters(projects, tags, filters, userId) {
  688. if (!_hasActiveFilter(filters)) {
  689. return projects
  690. }
  691. return projects.filter(project => _matchesFilters(project, tags, filters))
  692. }
  693. /**
  694. * @param {FormattedProject[]} projects
  695. * @param {Sort} sort
  696. * @param {Page} page
  697. * @returns {FormattedProject[]}
  698. * @private
  699. */
  700. function _sortAndPaginate(projects, sort, page) {
  701. if (
  702. (sort.by && !['lastUpdated', 'title', 'owner'].includes(sort.by)) ||
  703. (sort.order && !['asc', 'desc'].includes(sort.order))
  704. ) {
  705. throw new OError('Invalid sorting criteria', { sort })
  706. }
  707. const sortedProjects = _.orderBy(
  708. projects,
  709. [sort.by || 'lastUpdated'],
  710. [sort.order || 'desc']
  711. )
  712. // TODO handle pagination
  713. return sortedProjects
  714. }
  715. /**
  716. * @param {MongoProject} project
  717. * @param {ProjectAccessLevel} accessLevel
  718. * @param {Source} source
  719. * @param {string} userId
  720. * @returns {FormattedProject}
  721. * @private
  722. */
  723. function _formatProjectInfo(project, accessLevel, source, userId) {
  724. const archived = ProjectHelper.isArchived(project, userId)
  725. // If a project is simultaneously trashed and archived, we will consider it archived but not trashed.
  726. const trashed = ProjectHelper.isTrashed(project, userId) && !archived
  727. const readOnlyTokenAccess =
  728. accessLevel === PrivilegeLevels.READ_ONLY && source === Sources.TOKEN
  729. return {
  730. id: project._id.toString(),
  731. name: project.name,
  732. owner_ref: readOnlyTokenAccess ? null : project.owner_ref,
  733. lastUpdated: project.lastUpdated,
  734. lastUpdatedBy: readOnlyTokenAccess ? null : project.lastUpdatedBy,
  735. accessLevel,
  736. source,
  737. archived,
  738. trashed,
  739. }
  740. }
  741. /**
  742. * @param {FormattedProject[]} projects
  743. * @returns {Promise<Project[]>}
  744. * @private
  745. */
  746. async function _injectProjectUsers(projects) {
  747. const userIds = new Set()
  748. for (const project of projects) {
  749. if (project.owner_ref != null) {
  750. userIds.add(project.owner_ref.toString())
  751. }
  752. if (project.lastUpdatedBy != null) {
  753. userIds.add(project.lastUpdatedBy.toString())
  754. }
  755. }
  756. const projection = {
  757. first_name: 1,
  758. last_name: 1,
  759. email: 1,
  760. }
  761. /** @type {Record<string, UserRef>} */
  762. const users = {}
  763. for (const user of await UserGetter.promises.getUsers(userIds, projection)) {
  764. const userId = user._id.toString()
  765. users[userId] = {
  766. id: userId,
  767. email: user.email,
  768. firstName: user.first_name,
  769. lastName: user.last_name,
  770. }
  771. }
  772. return projects.map(project => ({
  773. id: project.id,
  774. name: project.name,
  775. archived: project.archived,
  776. trashed: project.trashed,
  777. accessLevel: project.accessLevel,
  778. source: project.source,
  779. lastUpdated: project.lastUpdated.toISOString(),
  780. lastUpdatedBy:
  781. project.lastUpdatedBy == null
  782. ? null
  783. : users[project.lastUpdatedBy.toString()] || null,
  784. owner:
  785. project.owner_ref == null
  786. ? undefined
  787. : users[project.owner_ref.toString()],
  788. owner_ref: undefined,
  789. }))
  790. }
  791. /**
  792. * @param {any} project
  793. * @param {MongoTag[]} tags
  794. * @param {Filters} filters
  795. * @private
  796. */
  797. function _matchesFilters(project, tags, filters) {
  798. if (filters.ownedByUser && project.accessLevel !== 'owner') {
  799. return false
  800. }
  801. if (filters.sharedWithUser && project.accessLevel === 'owner') {
  802. return false
  803. }
  804. if (filters.archived && !project.archived) {
  805. return false
  806. }
  807. if (filters.trashed && !project.trashed) {
  808. return false
  809. }
  810. if (
  811. filters.tag &&
  812. !_.find(
  813. tags,
  814. tag =>
  815. filters.tag === tag.name && (tag.project_ids || []).includes(project.id)
  816. )
  817. ) {
  818. return false
  819. }
  820. if (
  821. filters.search?.length &&
  822. project.name.toLowerCase().indexOf(filters.search.toLowerCase()) === -1
  823. ) {
  824. return false
  825. }
  826. return true
  827. }
  828. /**
  829. * @param {Filters} filters
  830. * @returns {boolean}
  831. * @private
  832. */
  833. function _hasActiveFilter(filters) {
  834. return Boolean(
  835. filters.ownedByUser ||
  836. filters.sharedWithUser ||
  837. filters.archived ||
  838. filters.trashed ||
  839. filters.tag === null ||
  840. filters.tag?.length ||
  841. filters.search?.length
  842. )
  843. }
  844. /**
  845. * @param {any} user
  846. */
  847. // todo: quota clean-up: rename function and vars
  848. async function _userHasAIAssist(user) {
  849. let hasPremiumAiFeatures
  850. const inQuotaSplitTest =
  851. await SplitTestHandler.promises.featureFlagEnabledForUser(
  852. user._id,
  853. 'plans-2026-phase-1'
  854. )
  855. if (inQuotaSplitTest) {
  856. hasPremiumAiFeatures =
  857. user.features?.aiUsageQuota === Settings.aiFeatures.unlimitedQuota
  858. } else {
  859. hasPremiumAiFeatures = user.features?.aiErrorAssistant === true
  860. }
  861. // Check if the user has a non free trial version of our AI features
  862. if (hasPremiumAiFeatures) {
  863. return true
  864. }
  865. // Check if the user has AI Assist enabled via Writefull
  866. const { isPremium: hasAiAssistViaWritefull } =
  867. await UserGetter.promises.getWritefullData(user._id)
  868. if (hasAiAssistViaWritefull) {
  869. return true
  870. }
  871. return false
  872. }
  873. // Determines if user is able to enable AI assist
  874. // based on their permissions and settings
  875. // It does NOT determine if the user has AI Assist enabled
  876. /**
  877. * @param {any} user
  878. */
  879. async function _canUseAIAssist(user) {
  880. // Check if the assistant has been manually disabled by the user
  881. // post https://github.com/overleaf/internal/pull/31273 we can rely on user.aiFeatures being populated
  882. if (user.aiFeatures?.enabled === false) {
  883. return false
  884. }
  885. // Check if the user can use AI features (policy check)
  886. return await PermissionsManager.promises.checkUserPermissions(user, [
  887. 'use-ai',
  888. ])
  889. }
  890. export default {
  891. projectListPage: expressify(projectListPage),
  892. getProjectsJson: expressify(getProjectsJson),
  893. }