useTicketSubscribe.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed } from 'vue'
  3. import { useTicketView } from '#shared/entities/ticket/composables/useTicketView.ts'
  4. import { useMentionSubscribeMutation } from '#shared/entities/ticket/graphql/mutations/subscribe.api.ts'
  5. import { useMentionUnsubscribeMutation } from '#shared/entities/ticket/graphql/mutations/unsubscribe.api.ts'
  6. import type { TicketById } from '#shared/entities/ticket/types.ts'
  7. import type { TicketQuery } from '#shared/graphql/types.ts'
  8. import { MutationHandler } from '#shared/server/apollo/handler/index.ts'
  9. import type { Ref } from 'vue'
  10. export const useTicketSubscribe = (ticket: Ref<TicketById | undefined>) => {
  11. const { isTicketAgent } = useTicketView(ticket)
  12. const canManageSubscription = computed(() => isTicketAgent.value)
  13. const createTicketCacheUpdater = (subscribed: boolean) => {
  14. return (previousQuery: Record<string, unknown>) => {
  15. const prev = previousQuery as TicketQuery
  16. if (!ticket.value || !prev || prev.ticket?.id !== ticket.value.id) {
  17. return prev
  18. }
  19. return {
  20. ticket: {
  21. ...prev.ticket,
  22. subscribed,
  23. },
  24. }
  25. }
  26. }
  27. const subscribeHanler = new MutationHandler(
  28. useMentionSubscribeMutation({
  29. updateQueries: {
  30. ticket: createTicketCacheUpdater(true),
  31. },
  32. }),
  33. )
  34. const unsubscribeMutation = new MutationHandler(
  35. useMentionUnsubscribeMutation({
  36. updateQueries: {
  37. ticket: createTicketCacheUpdater(false),
  38. },
  39. }),
  40. )
  41. const isSubscriptionLoading = computed(() => {
  42. return (
  43. subscribeHanler.loading().value || unsubscribeMutation.loading().value
  44. )
  45. })
  46. const subscribe = async (ticketId: string) => {
  47. const result = await subscribeHanler.send({ ticketId })
  48. return !!result?.mentionSubscribe?.success
  49. }
  50. const unsubscribe = async (ticketId: string) => {
  51. const result = await unsubscribeMutation.send({ ticketId })
  52. return !!result?.mentionUnsubscribe?.success
  53. }
  54. const toggleSubscribe = async () => {
  55. if (!ticket.value || isSubscriptionLoading.value) return false
  56. const { id, subscribed } = ticket.value
  57. if (!subscribed) {
  58. return subscribe(id)
  59. }
  60. return unsubscribe(id)
  61. }
  62. const isSubscribed = computed(() => !!ticket.value?.subscribed)
  63. return {
  64. isSubscriptionLoading,
  65. isSubscribed,
  66. toggleSubscribe,
  67. canManageSubscription,
  68. }
  69. }