user-email-context.tsx 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import {
  2. createContext,
  3. useEffect,
  4. useContext,
  5. useReducer,
  6. useCallback,
  7. } from 'react'
  8. import useSafeDispatch from '../../../shared/hooks/use-safe-dispatch'
  9. import * as ActionCreators from '../utils/action-creators'
  10. import { UserEmailData } from '../../../../../types/user-email'
  11. import { Nullable } from '../../../../../types/utils'
  12. import { Affiliation } from '../../../../../types/affiliation'
  13. import { normalize, NormalizedObject } from '../../../utils/normalize'
  14. import { getJSON } from '../../../infrastructure/fetch-json'
  15. import useAsync from '../../../shared/hooks/use-async'
  16. import usePersistedState from '../../../shared/hooks/use-persisted-state'
  17. const ONE_WEEK_IN_MS = 7 * 24 * 60 * 60 * 1000
  18. // eslint-disable-next-line no-unused-vars
  19. export enum Actions {
  20. SET_DATA = 'SET_DATA', // eslint-disable-line no-unused-vars
  21. SET_LOADING_STATE = 'SET_LOADING_STATE', // eslint-disable-line no-unused-vars
  22. MAKE_PRIMARY = 'MAKE_PRIMARY', // eslint-disable-line no-unused-vars
  23. DELETE_EMAIL = 'DELETE_EMAIL', // eslint-disable-line no-unused-vars
  24. SET_EMAIL_AFFILIATION_BEING_EDITED = 'SET_EMAIL_AFFILIATION_BEING_EDITED', // eslint-disable-line no-unused-vars
  25. UPDATE_AFFILIATION = 'UPDATE_AFFILIATION', // eslint-disable-line no-unused-vars
  26. }
  27. export type ActionSetData = {
  28. type: Actions.SET_DATA
  29. payload: UserEmailData[]
  30. }
  31. export type ActionSetLoading = {
  32. type: Actions.SET_LOADING_STATE
  33. payload: boolean
  34. }
  35. export type ActionMakePrimary = {
  36. type: Actions.MAKE_PRIMARY
  37. payload: UserEmailData['email']
  38. }
  39. export type ActionDeleteEmail = {
  40. type: Actions.DELETE_EMAIL
  41. payload: UserEmailData['email']
  42. }
  43. export type ActionSetEmailAffiliationBeingEdited = {
  44. type: Actions.SET_EMAIL_AFFILIATION_BEING_EDITED
  45. payload: Nullable<UserEmailData['email']>
  46. }
  47. export type ActionUpdateAffiliation = {
  48. type: Actions.UPDATE_AFFILIATION
  49. payload: {
  50. email: UserEmailData['email']
  51. role: Affiliation['role']
  52. department: Affiliation['department']
  53. }
  54. }
  55. export type State = {
  56. isLoading: boolean
  57. data: {
  58. byId: NormalizedObject<UserEmailData>
  59. linkedInstitutionIds: NonNullable<UserEmailData['samlProviderId']>[]
  60. emailAffiliationBeingEdited: Nullable<UserEmailData['email']>
  61. }
  62. }
  63. type Action =
  64. | ActionSetData
  65. | ActionSetLoading
  66. | ActionMakePrimary
  67. | ActionDeleteEmail
  68. | ActionSetEmailAffiliationBeingEdited
  69. | ActionUpdateAffiliation
  70. const setData = (state: State, action: ActionSetData) => {
  71. const normalized = normalize<UserEmailData>(action.payload, {
  72. idAttribute: 'email',
  73. })
  74. const byId = normalized || {}
  75. return {
  76. ...state,
  77. data: {
  78. ...initialState.data,
  79. byId,
  80. },
  81. }
  82. }
  83. const setLoadingAction = (state: State, action: ActionSetLoading) => ({
  84. ...state,
  85. isLoading: action.payload,
  86. })
  87. const makePrimaryAction = (state: State, action: ActionMakePrimary) => {
  88. const byId: State['data']['byId'] = {}
  89. for (const id of Object.keys(state.data.byId)) {
  90. byId[id] = {
  91. ...state.data.byId[id],
  92. default: state.data.byId[id].email === action.payload,
  93. }
  94. }
  95. return {
  96. ...state,
  97. data: {
  98. ...state.data,
  99. byId,
  100. },
  101. }
  102. }
  103. const deleteEmailAction = (state: State, action: ActionDeleteEmail) => {
  104. const { [action.payload]: _, ...byId } = state.data.byId
  105. return {
  106. ...state,
  107. data: {
  108. ...state.data,
  109. byId,
  110. },
  111. }
  112. }
  113. const setEmailAffiliationBeingEditedAction = (
  114. state: State,
  115. action: ActionSetEmailAffiliationBeingEdited
  116. ) => ({
  117. ...state,
  118. data: {
  119. ...state.data,
  120. emailAffiliationBeingEdited: action.payload,
  121. },
  122. })
  123. const updateAffiliationAction = (
  124. state: State,
  125. action: ActionUpdateAffiliation
  126. ) => {
  127. const { email, role, department } = action.payload
  128. const affiliation = state.data.byId[email].affiliation
  129. return {
  130. ...state,
  131. data: {
  132. ...state.data,
  133. byId: {
  134. ...state.data.byId,
  135. [email]: {
  136. ...state.data.byId[email],
  137. ...(affiliation && {
  138. affiliation: {
  139. ...affiliation,
  140. role,
  141. department,
  142. },
  143. }),
  144. },
  145. },
  146. emailAffiliationBeingEdited: null,
  147. },
  148. }
  149. }
  150. const initialState: State = {
  151. isLoading: false,
  152. data: {
  153. byId: {},
  154. linkedInstitutionIds: [],
  155. emailAffiliationBeingEdited: null,
  156. },
  157. }
  158. const reducer = (state: State, action: Action) => {
  159. switch (action.type) {
  160. case Actions.SET_DATA:
  161. return setData(state, action)
  162. case Actions.SET_LOADING_STATE:
  163. return setLoadingAction(state, action)
  164. case Actions.MAKE_PRIMARY:
  165. return makePrimaryAction(state, action)
  166. case Actions.DELETE_EMAIL:
  167. return deleteEmailAction(state, action)
  168. case Actions.SET_EMAIL_AFFILIATION_BEING_EDITED:
  169. return setEmailAffiliationBeingEditedAction(state, action)
  170. case Actions.UPDATE_AFFILIATION:
  171. return updateAffiliationAction(state, action)
  172. default:
  173. return state
  174. }
  175. }
  176. function useUserEmails() {
  177. const [, setExpirationDate] = usePersistedState(
  178. 'showInstitutionalLeaversSurveyUntil',
  179. 0
  180. )
  181. const [state, unsafeDispatch] = useReducer(reducer, initialState)
  182. const dispatch = useSafeDispatch(unsafeDispatch)
  183. const { data, isLoading, isError, isSuccess, runAsync } = useAsync()
  184. const getEmails = useCallback(() => {
  185. runAsync(getJSON<UserEmailData[]>('/user/emails?ensureAffiliation=true'))
  186. .then(data => {
  187. dispatch(ActionCreators.setData(data))
  188. })
  189. .catch(() => {})
  190. }, [runAsync, dispatch])
  191. // Get emails on page load
  192. useEffect(() => {
  193. getEmails()
  194. }, [getEmails])
  195. const resetLeaversSurveyExpiration = useCallback(
  196. (deletedEmail: UserEmailData) => {
  197. if (!data) {
  198. return
  199. }
  200. const emailData = data as UserEmailData[]
  201. if (
  202. deletedEmail.emailHasInstitutionLicence ||
  203. deletedEmail.affiliation?.pastReconfirmDate
  204. ) {
  205. const stillHasLicenseAccess = emailData.some(
  206. userEmail => userEmail.emailHasInstitutionLicence
  207. )
  208. if (stillHasLicenseAccess) {
  209. setExpirationDate(Date.now() + ONE_WEEK_IN_MS)
  210. }
  211. }
  212. },
  213. [data, setExpirationDate]
  214. )
  215. return {
  216. state,
  217. isInitializing: isLoading && !data,
  218. isInitializingSuccess: isSuccess,
  219. isInitializingError: isError,
  220. getEmails,
  221. resetLeaversSurveyExpiration,
  222. setLoading: useCallback(
  223. (flag: boolean) => dispatch(ActionCreators.setLoading(flag)),
  224. [dispatch]
  225. ),
  226. makePrimary: useCallback(
  227. (email: UserEmailData['email']) =>
  228. dispatch(ActionCreators.makePrimary(email)),
  229. [dispatch]
  230. ),
  231. deleteEmail: useCallback(
  232. (email: UserEmailData['email']) =>
  233. dispatch(ActionCreators.deleteEmail(email)),
  234. [dispatch]
  235. ),
  236. setEmailAffiliationBeingEdited: useCallback(
  237. (email: Nullable<UserEmailData['email']>) =>
  238. dispatch(ActionCreators.setEmailAffiliationBeingEdited(email)),
  239. [dispatch]
  240. ),
  241. updateAffiliation: useCallback(
  242. (
  243. email: UserEmailData['email'],
  244. role: Affiliation['role'],
  245. department: Affiliation['department']
  246. ) => dispatch(ActionCreators.updateAffiliation(email, role, department)),
  247. [dispatch]
  248. ),
  249. }
  250. }
  251. const UserEmailsContext = createContext<
  252. ReturnType<typeof useUserEmails> | undefined
  253. >(undefined)
  254. UserEmailsContext.displayName = 'UserEmailsContext'
  255. type UserEmailsProviderProps = {
  256. children: React.ReactNode
  257. } & Record<string, unknown>
  258. function UserEmailsProvider(props: UserEmailsProviderProps) {
  259. const value = useUserEmails()
  260. return <UserEmailsContext.Provider value={value} {...props} />
  261. }
  262. const useUserEmailsContext = () => {
  263. const context = useContext(UserEmailsContext)
  264. if (context === undefined) {
  265. throw new Error('useUserEmailsContext must be used in a UserEmailsProvider')
  266. }
  267. return context
  268. }
  269. export { UserEmailsProvider, useUserEmailsContext }