useObjectAttributes.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, toRefs } from 'vue'
  3. import type { FormSchemaField } from '#shared/components/Form/types.ts'
  4. import type { EnumObjectManagerObjects } from '#shared/graphql/types.ts'
  5. import { QueryHandler } from '#shared/server/apollo/handler/index.ts'
  6. import getFieldFromAttribute from '../form/getFieldFromAttribute.ts'
  7. import { useObjectManagerFrontendAttributesQuery } from '../graphql/queries/objectManagerFrontendAttributes.api.ts'
  8. import {
  9. staticObjectAttributesByEntity,
  10. useObjectAttributesStore,
  11. } from '../stores/objectAttributes.ts'
  12. import type { ObjectAttribute } from '../types/store.ts'
  13. export const useObjectAttributes = (object: EnumObjectManagerObjects) => {
  14. const objectAttributes = useObjectAttributesStore()
  15. // Check if we have already a instance of the requested object
  16. // attribute object, otherwise trigger the query.
  17. if (!objectAttributes.objectAttributesObjectLookup[object]) {
  18. const handler = new QueryHandler(
  19. useObjectManagerFrontendAttributesQuery({
  20. object,
  21. }),
  22. )
  23. const attributesRaw = handler.result()
  24. const attributesLoading = handler.loading()
  25. const attributes = computed<ObjectAttribute[]>(() => {
  26. return [
  27. ...(staticObjectAttributesByEntity[object] || []),
  28. ...(attributesRaw.value?.objectManagerFrontendAttributes?.attributes ||
  29. []),
  30. ]
  31. })
  32. const screens = computed(() => {
  33. return (
  34. attributesRaw.value?.objectManagerFrontendAttributes?.screens.reduce(
  35. (screens: Record<string, string[]>, screen) => {
  36. screens[screen.name] = screen.attributes
  37. return screens
  38. },
  39. {},
  40. ) || {}
  41. )
  42. })
  43. const attributesLookup = computed(() => {
  44. const lookup: Map<string, ObjectAttribute> = new Map()
  45. attributes.value?.forEach((attribute) =>
  46. lookup.set(attribute.name, attribute),
  47. )
  48. return lookup
  49. })
  50. const formFieldAttributesLookup = computed(() => {
  51. const lookup: Map<string, FormSchemaField> = new Map()
  52. attributes.value?.forEach((attribute) => {
  53. if (!attribute.isStatic) {
  54. lookup.set(attribute.name, getFieldFromAttribute(object, attribute))
  55. }
  56. })
  57. return lookup
  58. })
  59. objectAttributes.setObjectAttributesForObject(object, {
  60. attributes,
  61. screens,
  62. attributesLookup,
  63. formFieldAttributesLookup,
  64. loading: attributesLoading,
  65. })
  66. }
  67. return {
  68. ...toRefs(objectAttributes.objectAttributesObjectLookup[object]),
  69. }
  70. }