useUserDetail.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, nextTick, ref, watch } from 'vue'
  3. import { useUserObjectAttributesStore } from '#shared/entities/user/stores/objectAttributes.ts'
  4. import { useErrorHandler } from '#shared/errors/useErrorHandler.ts'
  5. import { UserUpdatesDocument } from '#shared/graphql/subscriptions/userUpdates.api.ts'
  6. import type {
  7. UserUpdatesSubscriptionVariables,
  8. UserUpdatesSubscription,
  9. } from '#shared/graphql/types.ts'
  10. import { QueryHandler } from '#shared/server/apollo/handler/index.ts'
  11. import { useUserLazyQuery } from '../graphql/queries/user.api.ts'
  12. export const useUserDetail = () => {
  13. const internalId = ref(0)
  14. const fetchSecondaryOrganizationsCount = ref<Maybe<number>>(3)
  15. const { createQueryErrorHandler } = useErrorHandler()
  16. const userQuery = new QueryHandler(
  17. useUserLazyQuery(
  18. () => ({
  19. userInternalId: internalId.value,
  20. secondaryOrganizationsCount: 3,
  21. }),
  22. () => ({ enabled: internalId.value > 0 }),
  23. ),
  24. {
  25. errorCallback: createQueryErrorHandler({
  26. notFound: __(
  27. 'User with specified ID was not found. Try checking the URL for errors.',
  28. ),
  29. forbidden: __('You have insufficient rights to view this user.'),
  30. }),
  31. },
  32. )
  33. const loadUser = (id: number) => {
  34. internalId.value = id
  35. nextTick(() => {
  36. userQuery.load()
  37. })
  38. }
  39. const loadAllSecondaryOrganizations = () => {
  40. userQuery
  41. .refetch({
  42. userInternalId: internalId.value,
  43. secondaryOrganizationsCount: null,
  44. })
  45. .then(() => {
  46. fetchSecondaryOrganizationsCount.value = null
  47. })
  48. }
  49. const userResult = userQuery.result()
  50. const loading = userQuery.loading()
  51. const user = computed(() => userResult.value?.user)
  52. const objectAttributesManager = useUserObjectAttributesStore()
  53. const objectAttributes = computed(
  54. () => objectAttributesManager.viewScreenAttributes || [],
  55. )
  56. watch(
  57. () => user.value?.id,
  58. (userId) => {
  59. if (!userId) return
  60. userQuery.subscribeToMore<
  61. UserUpdatesSubscriptionVariables,
  62. UserUpdatesSubscription
  63. >(() => ({
  64. document: UserUpdatesDocument,
  65. variables: {
  66. userId,
  67. secondaryOrganizationsCount: fetchSecondaryOrganizationsCount.value,
  68. },
  69. }))
  70. },
  71. { immediate: true },
  72. )
  73. return {
  74. loading,
  75. user,
  76. userQuery,
  77. objectAttributes,
  78. loadAllSecondaryOrganizations,
  79. loadUser,
  80. }
  81. }