useObjectAttributeFormData.ts 2.3 KB

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