ticketTemplate.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { without } from 'lodash-es'
  3. import { defineStore } from 'pinia'
  4. import { computed, nextTick, ref } from 'vue'
  5. import type {
  6. TemplatesQuery,
  7. TemplateUpdatesSubscription,
  8. TemplateUpdatesSubscriptionVariables,
  9. } from '#shared/graphql/types.ts'
  10. import QueryHandler from '#shared/server/apollo/handler/QueryHandler.ts'
  11. import { useSessionStore } from '#shared/stores/session.ts'
  12. import { useTemplatesQuery } from '../graphql/queries/templates.api.ts'
  13. import { TemplateUpdatesDocument } from '../graphql/subscriptions/templateUpdates.api.ts'
  14. export const useTicketTemplateStore = defineStore('ticketTemplate', () => {
  15. const usageKeys = ref<string[]>([])
  16. const activate = (usageKey: string) => {
  17. usageKeys.value.push(usageKey)
  18. }
  19. const session = useSessionStore()
  20. const enabled = computed(
  21. () => session.hasPermission('ticket.agent') && usageKeys.value.length > 0,
  22. )
  23. const templateListQuery = new QueryHandler(
  24. useTemplatesQuery(
  25. () => ({
  26. onlyActive: true,
  27. }),
  28. () => ({ enabled }),
  29. ),
  30. )
  31. templateListQuery.subscribeToMore<
  32. TemplateUpdatesSubscriptionVariables,
  33. TemplateUpdatesSubscription
  34. >({
  35. document: TemplateUpdatesDocument,
  36. variables: {
  37. onlyActive: true,
  38. },
  39. updateQuery: (prev, { subscriptionData }) => {
  40. if (!subscriptionData.data?.templateUpdates.templates) {
  41. return null as unknown as TemplatesQuery
  42. }
  43. return {
  44. templates: subscriptionData.data.templateUpdates.templates,
  45. }
  46. },
  47. })
  48. const result = templateListQuery.result()
  49. const templateList = computed(() => result.value?.templates || [])
  50. const deactivate = (usageKey: string) => {
  51. if (!usageKeys.value.includes(usageKey)) return
  52. nextTick(() => {
  53. usageKeys.value = without(usageKeys.value, usageKey)
  54. })
  55. }
  56. return {
  57. usageKeys,
  58. templateList,
  59. activate,
  60. deactivate,
  61. }
  62. })