Notification.vue 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. <template>
  2. <v-btn ref="btn" icon size="small" class="ml-2">
  3. <v-badge
  4. color="warning"
  5. offset-x="-4"
  6. offset-y="17"
  7. :model-value="unreadNotification.length > 0"
  8. :content="unreadNotification.length"
  9. >
  10. <v-icon class="on-primary"> fa fa-bell </v-icon>
  11. </v-badge>
  12. </v-btn>
  13. <v-tooltip v-if="btn !== null" :activator="btn" location="bottom">
  14. <span>{{ $t('notification') }}</span>
  15. </v-tooltip>
  16. <v-menu
  17. v-if="btn !== null"
  18. v-model="isOpen"
  19. :activator="btn"
  20. location="bottom left"
  21. >
  22. <v-card max-width="400">
  23. <v-card-title class="bg-neutral text-body-2 font-weight-bold">
  24. {{ $t('notification') }}
  25. </v-card-title>
  26. <v-card-text class="ma-0 pa-0 header-menu">
  27. <v-list density="compact" :subheader="true" class="pa-0">
  28. <v-list-item
  29. v-for="(notification, index) in notifications"
  30. :key="index"
  31. :class="
  32. 'list_item py-3' +
  33. `${notification.notificationUsers.length === 0 ? ' unread' : ''}`
  34. "
  35. >
  36. <span class="">{{ getMessage(notification) }}</span>
  37. <template #append>
  38. <v-icon
  39. v-if="notification.link"
  40. icon="mdi:mdi-download"
  41. class="pt-4"
  42. @click="download(notification.link)"
  43. />
  44. </template>
  45. </v-list-item>
  46. <v-divider/>
  47. <!--suppress VueUnrecognizedDirective -->
  48. <span v-intersect="onLastNotificationIntersect" />
  49. <v-row
  50. v-if="pending"
  51. class="fill-height mt-3 mb-3"
  52. align="center"
  53. justify="center"
  54. >
  55. <v-progress-circular indeterminate color="neutral" />
  56. </v-row>
  57. </v-list>
  58. </v-card-text>
  59. <v-card-actions class="ma-0 pa-0">
  60. <v-list-item
  61. :key="$t('all_notification')"
  62. :href="notificationUrl"
  63. router
  64. class="theme-primary"
  65. style="width: 100%; height: 52px"
  66. >
  67. <v-list-item-title class="text-body-2">
  68. <span v-text="$t('all_notification')" />
  69. </v-list-item-title>
  70. </v-list-item>
  71. </v-card-actions>
  72. </v-card>
  73. </v-menu>
  74. </template>
  75. <script setup lang="ts">
  76. import { computed, ref } from 'vue'
  77. import type { ComputedRef, Ref } from 'vue'
  78. import { useRepo } from 'pinia-orm'
  79. import { NOTIFICATION_TYPE } from '~/types/enum/enums'
  80. import Notification from '~/models/Core/Notification'
  81. import NotificationUsers from '~/models/Core/NotificationUsers'
  82. import { useAccessProfileStore } from '~/stores/accessProfile'
  83. import { useEntityFetch } from '~/composables/data/useEntityFetch'
  84. import type { AnyJson, Pagination } from '~/types/data'
  85. import { useEntityManager } from '~/composables/data/useEntityManager'
  86. import UrlUtils from '~/services/utils/urlUtils'
  87. import NotificationRepository from '~/stores/repositories/NotificationRepository'
  88. import Query from '~/services/data/Query'
  89. import PageFilter from '~/services/data/Filters/PageFilter'
  90. const accessProfileStore = useAccessProfileStore()
  91. const isOpen: Ref<boolean> = ref(false)
  92. const page: Ref<number> = ref(1)
  93. const itemsPerPage: Ref<number> = ref(5)
  94. const i18n = useI18n()
  95. const runtimeConfig = useRuntimeConfig()
  96. const btn = ref(null)
  97. const { em } = useEntityManager()
  98. const { fetchCollection } = useEntityFetch()
  99. const notificationRepo = useRepo(NotificationRepository)
  100. const query = new Query(new PageFilter(page, itemsPerPage))
  101. const {
  102. data: collection,
  103. pending,
  104. refresh,
  105. } = fetchCollection(Notification, null, query)
  106. /**
  107. * On récupère les Notifications via le store
  108. */
  109. const notifications: ComputedRef<Array<Notification>> = computed(() => {
  110. return notificationRepo.getNotifications()
  111. })
  112. /**
  113. * Retourne les notifications non lues
  114. */
  115. const unreadNotification: ComputedRef<Array<Notification>> = computed(() => {
  116. return notificationRepo.getUnreadNotifications()
  117. })
  118. /**
  119. * Les metadata dépendront de la dernière valeur du GET lancé
  120. */
  121. const pagination: ComputedRef<Pagination> = computed(() => {
  122. return collection.value !== null ? collection.value.pagination : {}
  123. })
  124. const notificationUrl = UrlUtils.join(
  125. runtimeConfig.baseUrlAdminLegacy,
  126. '#/notifications/list/',
  127. )
  128. /**
  129. * L'utilisateur a fait défiler le menu jusqu'à la dernière notification affichée
  130. * @param isIntersecting
  131. */
  132. const onLastNotificationIntersect = (isIntersecting: boolean) => {
  133. if (isIntersecting) {
  134. update()
  135. }
  136. }
  137. /**
  138. * Lorsque l'utilisateur scroll on regarde la nextPage à charger et on le fait que si le pending du fetch est false
  139. * (si on a fini de télécharger les éléments précédents)
  140. */
  141. const update = async () => {
  142. if (
  143. !pending.value &&
  144. pagination.value &&
  145. pagination.value.next &&
  146. pagination.value.next > 0
  147. ) {
  148. pending.value = true
  149. page.value = pagination.value.next
  150. await refresh()
  151. // Si des notifications n'avaient pas été marquées comme lues, on le fait immédiatement.
  152. markNotificationsAsRead()
  153. }
  154. }
  155. /**
  156. * On construit le message qui va devoir s'afficher pour une notification
  157. * @param notification
  158. */
  159. const getMessage = (notification: Notification) => {
  160. switch (notification.type) {
  161. case NOTIFICATION_TYPE.FILE:
  162. return `${i18n.t('your_file')} ${notification.message?.fileName} ${i18n.t(
  163. 'is_ready_to_be_downloaded',
  164. )}`
  165. case NOTIFICATION_TYPE.MESSAGE:
  166. if (notification.message?.action)
  167. return `${i18n.t('your_message')} ${
  168. notification.message?.fileName
  169. } ${i18n.t('is_ready_to_be')} ${notification.message.action}`
  170. return `${i18n.t('your_message')} ${
  171. notification.message?.about ?? ''
  172. } ${i18n.t('has_been_sent')} `
  173. case NOTIFICATION_TYPE.SYSTEM:
  174. if (notification.message?.about)
  175. return `${i18n.t(notification.message.about)}`
  176. break
  177. default:
  178. return i18n.t(notification.name)
  179. }
  180. }
  181. /**
  182. * Dès la fermeture du menu, on indique que les notifications non lues, le sont.
  183. */
  184. const unwatch = watch(isOpen, (newValue, _) => {
  185. if (!newValue) {
  186. markNotificationsAsRead()
  187. }
  188. })
  189. onUnmounted(() => {
  190. unwatch()
  191. })
  192. /**
  193. * Marque une notification comme lue
  194. */
  195. const markNotificationAsRead = (notification: Notification) => {
  196. if (accessProfileStore.id === null) {
  197. throw new Error('Current access id is null')
  198. }
  199. const notificationUsers = em.newInstance(NotificationUsers, {
  200. access: `/api/accesses/${accessProfileStore.currentAccessId}`,
  201. notification: `/api/notifications/${notification.id}`,
  202. isRead: true,
  203. })
  204. em.persist(notificationUsers)
  205. notification.notificationUsers = ['read']
  206. em.save(notification)
  207. }
  208. /**
  209. * Marque toutes les notifications non lues comme lues
  210. */
  211. const markNotificationsAsRead = () => {
  212. unreadNotification.value.map((notification: Notification) => {
  213. return markNotificationAsRead(notification)
  214. })
  215. }
  216. /**
  217. * Download la cible du lien
  218. * @param link
  219. */
  220. const download = (link: string) => {
  221. if (accessProfileStore.id === null) {
  222. throw new Error('Current access id is null')
  223. }
  224. // TODO: passer cette logique dans un service ; tester ; voir si possible de réunir avec composables/utils/useDownloadFile.ts
  225. const path: string = link.split('/api')[1]
  226. // En switch : https://api.test5.opentalent.fr/api/{accessId}/{switchId}/files/{fileId}/download
  227. // Sans switch : https://local.api.opentalent.fr/api/{accessId}/files/{fileId}/download
  228. const url = UrlUtils.join(
  229. runtimeConfig.baseUrlLegacy,
  230. 'api',
  231. String(accessProfileStore.id),
  232. String(accessProfileStore.switchId || ''),
  233. path,
  234. )
  235. window.open(url)
  236. }
  237. </script>
  238. <style scoped lang="scss">
  239. .list_item {
  240. white-space: normal;
  241. }
  242. .unread {
  243. background: rgb(var(--v-theme-neutral-soft, white));
  244. }
  245. </style>