Notification.vue 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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></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(
  101. new PageFilter(page, itemsPerPage)
  102. )
  103. const {
  104. data: collection,
  105. pending,
  106. refresh,
  107. } = fetchCollection(Notification, null, query)
  108. /**
  109. * On récupère les Notifications via le store
  110. */
  111. const notifications: ComputedRef<Array<Notification>> = computed(() => {
  112. return notificationRepo.getNotifications()
  113. })
  114. /**
  115. * Retourne les notifications non lues
  116. */
  117. const unreadNotification: ComputedRef<Array<Notification>> = computed(() => {
  118. return notificationRepo.getUnreadNotifications()
  119. })
  120. /**
  121. * Les metadata dépendront de la dernière valeur du GET lancé
  122. */
  123. const pagination: ComputedRef<Pagination> = computed(() => {
  124. return collection.value !== null
  125. ? collection.value.pagination
  126. : {}
  127. })
  128. const notificationUrl = UrlUtils.join(
  129. runtimeConfig.baseUrlAdminLegacy,
  130. '#/notifications/list/'
  131. )
  132. /**
  133. * L'utilisateur a fait défiler le menu jusqu'à la dernière notification affichée
  134. * @param isIntersecting
  135. */
  136. const onLastNotificationIntersect = (isIntersecting: boolean) => {
  137. if (isIntersecting) {
  138. update()
  139. }
  140. }
  141. /**
  142. * Lorsque l'utilisateur scroll on regarde la nextPage à charger et on le fait que si le pending du fetch est false
  143. * (si on a fini de télécharger les éléments précédents)
  144. */
  145. const update = async () => {
  146. if (
  147. !pending.value &&
  148. pagination.value &&
  149. pagination.value.next &&
  150. pagination.value.next > 0
  151. ) {
  152. pending.value = true
  153. page.value = pagination.value.next
  154. await refresh()
  155. console.log(page.value)
  156. // Si des notifications n'avaient pas été marquées comme lues, on le fait immédiatement.
  157. markNotificationsAsRead()
  158. }
  159. }
  160. /**
  161. * On construit le message qui va devoir s'afficher pour une notification
  162. * @param notification
  163. */
  164. const getMessage = (notification: Notification) => {
  165. switch (notification.type) {
  166. case NOTIFICATION_TYPE.FILE:
  167. return `${i18n.t('your_file')} ${notification.message?.fileName} ${i18n.t(
  168. 'is_ready_to_be_downloaded'
  169. )}`
  170. case NOTIFICATION_TYPE.MESSAGE:
  171. if (notification.message?.action)
  172. return `${i18n.t('your_message')} ${
  173. notification.message?.fileName
  174. } ${i18n.t('is_ready_to_be')} ${notification.message.action}`
  175. return `${i18n.t('your_message')} ${
  176. notification.message?.about ?? ''
  177. } ${i18n.t('has_been_sent')} `
  178. case NOTIFICATION_TYPE.SYSTEM:
  179. if (notification.message?.about)
  180. return `${i18n.t(notification.message.about)}`
  181. break
  182. default:
  183. return i18n.t(notification.name)
  184. }
  185. }
  186. /**
  187. * Dès la fermeture du menu, on indique que les notifications non lues, le sont.
  188. */
  189. const unwatch = watch(isOpen, (newValue, _) => {
  190. if (!newValue) {
  191. markNotificationsAsRead()
  192. }
  193. })
  194. onUnmounted(() => {
  195. unwatch()
  196. })
  197. /**
  198. * Marque une notification comme lue
  199. */
  200. const markNotificationAsRead = (notification: Notification) => {
  201. if (accessProfileStore.id === null) {
  202. throw new Error('Current access id is null')
  203. }
  204. const notificationUsers = em.newInstance(NotificationUsers, {
  205. access: `/api/accesses/${accessProfileStore.currentAccessId}`,
  206. notification: `/api/notifications/${notification.id}`,
  207. isRead: true,
  208. })
  209. em.persist(NotificationUsers, notificationUsers)
  210. notification.notificationUsers = ['read']
  211. em.save(Notification, notification)
  212. }
  213. /**
  214. * Marque toutes les notifications non lues comme lues
  215. */
  216. const markNotificationsAsRead = () => {
  217. unreadNotification.value.map((notification: Notification) => {
  218. return markNotificationAsRead(notification)
  219. })
  220. }
  221. /**
  222. * Download la cible du lien
  223. * @param link
  224. */
  225. const download = (link: string) => {
  226. if (accessProfileStore.id === null) {
  227. throw new Error('Current access id is null')
  228. }
  229. // TODO: passer cette logique dans un service ; tester ; voir si possible de réunir avec composables/utils/useDownloadFile.ts
  230. const path: string = link.split('/api')[1]
  231. // En switch : https://api.test5.opentalent.fr/api/{accessId}/{switchId}/files/{fileId}/download
  232. // Sans switch : https://local.api.opentalent.fr/api/{accessId}/files/{fileId}/download
  233. const url = UrlUtils.join(
  234. runtimeConfig.baseUrlLegacy,
  235. 'api',
  236. String(accessProfileStore.id),
  237. String(accessProfileStore.switchId || ''),
  238. path
  239. )
  240. window.open(url)
  241. }
  242. </script>
  243. <style scoped lang="scss">
  244. .list_item {
  245. white-space: normal;
  246. }
  247. .unread {
  248. background: rgb(var(--v-theme-neutral-soft, white));
  249. }
  250. </style>