useObjectAttributeFormData.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type {
  3. FormFieldValue,
  4. FormValues,
  5. } from '#shared/components/Form/types.ts'
  6. import type { ObjectAttributeValueInput } from '#shared/graphql/types.ts'
  7. import { convertToGraphQLId, isGraphQLId } from '#shared/graphql/utils.ts'
  8. import { camelize, toClassName } from '#shared/utils/formatter.ts'
  9. import type { ObjectAttribute } from '../types/store.ts'
  10. import type { Primitive } from 'type-fest'
  11. export const useObjectAttributeFormData = (
  12. objectAttributes: Map<string, ObjectAttribute>,
  13. values: FormValues,
  14. ) => {
  15. const internalObjectAttributeValues: Record<string, FormFieldValue> = {}
  16. const additionalObjectAttributeValues: ObjectAttributeValueInput[] = []
  17. const fullRelationId = (relation: string, value: number | string) => {
  18. return convertToGraphQLId(toClassName(relation), value)
  19. }
  20. const ensureRelationId = (
  21. attribute: ObjectAttribute,
  22. value: FormFieldValue,
  23. ) => {
  24. const { relation } = attribute.dataOption || {}
  25. const isInternalID =
  26. typeof value === 'number' ||
  27. (typeof value === 'string' && !isGraphQLId(value))
  28. if (relation && isInternalID) {
  29. return fullRelationId(relation, value)
  30. }
  31. return value
  32. }
  33. Object.keys(values).forEach((fieldName) => {
  34. const objectAttribute = objectAttributes.get(fieldName)
  35. const value = values[fieldName]
  36. if (!objectAttribute || value === undefined) return
  37. if (objectAttribute.isInternal) {
  38. const name = camelize(fieldName)
  39. let newValue: FormFieldValue
  40. if (Array.isArray(value)) {
  41. newValue = value.map((elem) => {
  42. return ensureRelationId(objectAttribute, elem) as Primitive
  43. })
  44. }
  45. // When the attribute has guess support and is a string count it as an guess (=unknown value).
  46. else if (objectAttribute.dataOption?.guess && typeof value === 'string') {
  47. newValue = value
  48. } else {
  49. newValue = ensureRelationId(objectAttribute, value)
  50. }
  51. internalObjectAttributeValues[name] = newValue
  52. } else {
  53. additionalObjectAttributeValues.push({
  54. name: objectAttribute.name,
  55. value,
  56. })
  57. }
  58. })
  59. return {
  60. internalObjectAttributeValues,
  61. additionalObjectAttributeValues,
  62. }
  63. }