useUserDetail.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { storeToRefs } from 'pinia'
  3. import { computed, ref, type Ref } from 'vue'
  4. import { useUserQuery } from '#shared/entities/user/graphql/queries/user.api.ts'
  5. import { useUserObjectAttributesStore } from '#shared/entities/user/stores/objectAttributes.ts'
  6. import { UserUpdatesDocument } from '#shared/graphql/subscriptions/userUpdates.api.ts'
  7. import type {
  8. UserUpdatesSubscriptionVariables,
  9. UserUpdatesSubscription,
  10. } from '#shared/graphql/types.ts'
  11. import { convertToGraphQLId } from '#shared/graphql/utils.ts'
  12. import { QueryHandler } from '#shared/server/apollo/handler/index.ts'
  13. import type { GraphQLHandlerError } from '#shared/types/error.ts'
  14. import { normalizeEdges } from '#shared/utils/helpers.ts'
  15. import type { WatchQueryFetchPolicy } from '@apollo/client/core'
  16. export const useUserDetail = (
  17. internalId: Ref<number | undefined>,
  18. errorCallback?: (error: GraphQLHandlerError) => boolean,
  19. fetchPolicy?: WatchQueryFetchPolicy,
  20. ) => {
  21. const userId = computed(() => {
  22. if (!internalId.value) return
  23. return convertToGraphQLId('User', internalId.value)
  24. })
  25. const fetchSecondaryOrganizationsCount = ref<Maybe<number>>(3)
  26. const userQuery = new QueryHandler(
  27. useUserQuery(
  28. () => ({
  29. userInternalId: internalId.value,
  30. secondaryOrganizationsCount: 3,
  31. }),
  32. () => ({ enabled: Boolean(internalId.value), fetchPolicy }),
  33. ),
  34. {
  35. errorCallback,
  36. },
  37. )
  38. userQuery.subscribeToMore<
  39. UserUpdatesSubscriptionVariables,
  40. UserUpdatesSubscription
  41. >(() => ({
  42. document: UserUpdatesDocument,
  43. variables: {
  44. userId: userId.value!,
  45. secondaryOrganizationsCount: fetchSecondaryOrganizationsCount.value,
  46. },
  47. }))
  48. const loadAllSecondaryOrganizations = () => {
  49. userQuery
  50. .refetch({
  51. userInternalId: internalId.value,
  52. secondaryOrganizationsCount: null,
  53. })
  54. .then(() => {
  55. fetchSecondaryOrganizationsCount.value = null
  56. })
  57. }
  58. const userResult = userQuery.result()
  59. const loading = userQuery.loading()
  60. const user = computed(() => userResult.value?.user)
  61. const { viewScreenAttributes } = storeToRefs(useUserObjectAttributesStore())
  62. const secondaryOrganizations = computed(() =>
  63. normalizeEdges(user.value?.secondaryOrganizations),
  64. )
  65. return {
  66. loading,
  67. user,
  68. userQuery,
  69. objectAttributes: viewScreenAttributes,
  70. secondaryOrganizations,
  71. loadAllSecondaryOrganizations,
  72. }
  73. }