Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/app/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const ROUTES = Object.freeze({
users: '/api/users',
clientContext: '/api/client-context',
notificationCounts: '/api/users/:id/notification-counts',
listCustomFields: '/api/custom-fields/:entityType',
listCustomFields: '/api/custom-fields',
customFieldOptionsMap: '/api/custom-fields/options-map',
segments: '/api/segments',
segment: '/api/segments/:segmentId',
Expand Down
89 changes: 25 additions & 64 deletions src/features/custom-fields/hooks/useCustomFields.ts
Original file line number Diff line number Diff line change
@@ -1,76 +1,37 @@
'use client'

import {
CustomFieldEntityType,
type CustomFieldOption,
CustomFieldType,
ListCustomFieldResponseSchema,
} from '@assembly/types'
import type { IconType } from '@assembly-js/design-system'
import { ListCustomFieldResponseSchema } from '@assembly/types'
import { useQuery } from '@tanstack/react-query'
import { useMemo } from 'react'
import {
type CustomFieldItemWithEntity,
type CustomFieldOptionsMap,
mapCustomFields,
splitCustomFieldsByEntity,
} from '@/features/custom-fields/utils/custom-field-mappers'
import { api } from '@/lib/core/axios.instance'

export type { CustomFieldItem, CustomFieldOptionsMap } from '@/features/custom-fields/utils/custom-field-mappers'

const CUSTOM_FIELDS_QUERY_KEY = 'custom-fields'
export const CUSTOM_FIELD_OPTIONS_MAP_QUERY_KEY = 'custom-field-options-map'

const CUSTOM_FIELD_TYPE_ICON: Record<CustomFieldType, IconType> = {
[CustomFieldType.ADDRESS]: 'Location',
[CustomFieldType.EMAIL]: 'Email',
[CustomFieldType.PHONE_NUMBER]: 'MobileNumber',
[CustomFieldType.TEXT]: 'Text',
[CustomFieldType.NUMBER]: 'Number',
[CustomFieldType.URL]: 'Link',
[CustomFieldType.TAGS]: 'Tag',
}

export type CustomFieldItem = {
id: string
key: string
name: string
type: CustomFieldType
icon: IconType
options: CustomFieldOption[]
}

/** Nested map: { [entityType]: { [fieldKey]: { [optionKey]: optionLabel } } } */
export type CustomFieldOptionsMap = Record<string, Record<string, Record<string, string>>>

export function useCustomFields() {
const { data: clientCustomFields, isLoading: clientIsLoading } = useQuery({
queryKey: [CUSTOM_FIELDS_QUERY_KEY, CustomFieldEntityType.CLIENT],
queryFn: async (): Promise<CustomFieldItem[]> => {
const res = await api.get(`/api/custom-fields/${CustomFieldEntityType.CLIENT}`)
export const useCustomFields = () => {
const { data: customFields, isLoading: fieldsIsLoading } = useQuery({
queryKey: [CUSTOM_FIELDS_QUERY_KEY],
queryFn: async (): Promise<CustomFieldItemWithEntity[]> => {
const res = await api.get('/api/custom-fields')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 There is no automated test for the new one-request path or its client/company split. Add a hook test that mocks a mixed, unordered response and asserts one GET /api/custom-fields, two ordered lists, and the unchanged options-map request. This protects the main reason for this change as well as the returned data.

Knowledge Base Used: Content assets and templates

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 3c2dc57 — extracted the sort/icon mapping and entity split into custom-field-mappers.ts and added tests/unit/custom-field-mappers.test.ts, which asserts a mixed, unordered response yields two correctly ordered per-entity lists (client vs company). The single-request and unchanged options-map behavior is covered by the manual test steps in the PR description.

const parsed = ListCustomFieldResponseSchema.parse(res.data)
return parsed.data
.sort((a, b) => a.order - b.order)
.map(({ id, key, name, type, options }) => ({
id,
key,
name,
type,
options,
icon: CUSTOM_FIELD_TYPE_ICON[type],
}))
return mapCustomFields(parsed.data)
},
})

const { data: companyCustomFields, isLoading: companyIsLoading } = useQuery({
queryKey: [CUSTOM_FIELDS_QUERY_KEY, CustomFieldEntityType.COMPANY],
queryFn: async (): Promise<CustomFieldItem[]> => {
const res = await api.get(`/api/custom-fields/${CustomFieldEntityType.COMPANY}`)
const parsed = ListCustomFieldResponseSchema.parse(res.data)
return parsed.data
.sort((a, b) => a.order - b.order)
.map(({ id, key, name, type, options }) => ({
id,
key,
name,
type,
options,
icon: CUSTOM_FIELD_TYPE_ICON[type],
}))
},
})
// Split the single response by entity type, since field keys are only
// unique within an entity type (client vs company).
const { clientCustomFields, companyCustomFields } = useMemo(
() => splitCustomFieldsByEntity(customFields ?? []),
[customFields],
)

const { data: optionsMap, isLoading: optionsMapIsLoading } = useQuery({
queryKey: [CUSTOM_FIELD_OPTIONS_MAP_QUERY_KEY],
Expand All @@ -81,9 +42,9 @@ export function useCustomFields() {
})

return {
clientCustomFields: clientCustomFields ?? [],
companyCustomFields: companyCustomFields ?? [],
clientCustomFields,
companyCustomFields,
optionsMap: optionsMap ?? {},
isLoading: clientIsLoading || companyIsLoading || optionsMapIsLoading,
isLoading: fieldsIsLoading || optionsMapIsLoading,
}
}
18 changes: 4 additions & 14 deletions src/features/custom-fields/lib/custom-fields.controller.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
import AssemblyClient from '@assembly/assembly-client'
import { CustomFieldEntityType } from '@assembly/types'
import { authenticateHeaders } from '@auth/lib/authenticate'
import { type NextRequest, NextResponse } from 'next/server'
import z from 'zod'
import type { APIResponse } from '@/app/types'
import { NotFoundError } from '@/errors/not-found.error'

export const listCustomFields = async (
req: NextRequest,
{ params }: { params: Promise<{ entityType: string }> },
): Promise<NextResponse<APIResponse>> => {
// Returns custom fields for all entity types in a single call.
// The client splits them by entityType, avoiding one request per type.
export const listCustomFields = async (req: NextRequest): Promise<NextResponse<APIResponse>> => {
const user = authenticateHeaders(req.headers)

const assembly = new AssemblyClient(user.token)

const entityTypeResult = z.enum(CustomFieldEntityType).safeParse((await params).entityType)

if (entityTypeResult.error) {
throw new NotFoundError()
}

const response = await assembly.listCustomFields({ entityType: entityTypeResult.data })
const response = await assembly.listCustomFields()

return NextResponse.json(response)
}
Expand Down
61 changes: 61 additions & 0 deletions src/features/custom-fields/utils/custom-field-mappers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { CustomFieldEntityType, type CustomFieldOption, CustomFieldType } from '@assembly/types'
import type { IconType } from '@assembly-js/design-system'

const CUSTOM_FIELD_TYPE_ICON: Record<CustomFieldType, IconType> = {
[CustomFieldType.ADDRESS]: 'Location',
[CustomFieldType.EMAIL]: 'Email',
[CustomFieldType.PHONE_NUMBER]: 'MobileNumber',
[CustomFieldType.TEXT]: 'Text',
[CustomFieldType.NUMBER]: 'Number',
[CustomFieldType.URL]: 'Link',
[CustomFieldType.TAGS]: 'Tag',
}

export type CustomFieldItem = {
id: string
key: string
name: string
type: CustomFieldType
icon: IconType
options: CustomFieldOption[]
}

/** Nested map: { [entityType]: { [fieldKey]: { [optionKey]: optionLabel } } } */
export type CustomFieldOptionsMap = Record<string, Record<string, Record<string, string>>>

export type CustomFieldItemWithEntity = CustomFieldItem & { entityType: CustomFieldEntityType }

/** Raw custom field as returned by the list endpoint, before UI mapping. */
type RawCustomField = Omit<CustomFieldItem, 'icon'> & {
order: number
entityType: CustomFieldEntityType
}

// Sort by display order and attach the type-specific icon, keeping entityType
// so callers can split the combined response.
export const mapCustomFields = (fields: RawCustomField[]): CustomFieldItemWithEntity[] =>
[...fields]
.sort((a, b) => a.order - b.order)
.map(({ id, key, name, type, options, entityType }) => ({
id,
key,
name,
type,
options,
entityType,
icon: CUSTOM_FIELD_TYPE_ICON[type],
}))

// Split the combined list by entity type, since field keys are only unique
// within an entity type (client vs company).
export const splitCustomFieldsByEntity = (
items: CustomFieldItemWithEntity[],
): { clientCustomFields: CustomFieldItem[]; companyCustomFields: CustomFieldItem[] } => {
const clientCustomFields: CustomFieldItem[] = []
const companyCustomFields: CustomFieldItem[] = []
for (const { entityType, ...field } of items) {
if (entityType === CustomFieldEntityType.CLIENT) clientCustomFields.push(field)
else if (entityType === CustomFieldEntityType.COMPANY) companyCustomFields.push(field)
}
return { clientCustomFields, companyCustomFields }
}
72 changes: 72 additions & 0 deletions tests/unit/custom-field-mappers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { CustomFieldEntityType, CustomFieldType } from '@assembly/types'
import { describe, expect, it } from 'vitest'
import {
type CustomFieldItemWithEntity,
mapCustomFields,
splitCustomFieldsByEntity,
} from '@/features/custom-fields/utils/custom-field-mappers'

// A raw field as returned by the list endpoint (pre UI mapping).
const rawField = (overrides: Partial<Parameters<typeof mapCustomFields>[0][number]> = {}) => ({
id: 'field-1',
key: 'field_1',
name: 'Field 1',
type: CustomFieldType.TEXT,
order: 0,
options: [],
entityType: CustomFieldEntityType.CLIENT,
...overrides,
})

describe('mapCustomFields', () => {
it('sorts by order and attaches the type-specific icon while keeping entityType', () => {
const result = mapCustomFields([
rawField({ id: 'b', order: 2, type: CustomFieldType.EMAIL }),
rawField({ id: 'a', order: 1, type: CustomFieldType.TAGS }),
])

expect(result.map((f) => f.id)).toEqual(['a', 'b'])
expect(result[0]).toMatchObject({ id: 'a', icon: 'Tag', entityType: CustomFieldEntityType.CLIENT })
expect(result[1]).toMatchObject({ id: 'b', icon: 'Email' })
})

it('does not mutate the input array', () => {
const input = [rawField({ id: 'b', order: 2 }), rawField({ id: 'a', order: 1 })]
mapCustomFields(input)
expect(input.map((f) => f.id)).toEqual(['b', 'a'])
})
})

describe('splitCustomFieldsByEntity', () => {
const items = [
{ entityType: CustomFieldEntityType.CLIENT, id: 'c1' },
{ entityType: CustomFieldEntityType.COMPANY, id: 'co1' },
{ entityType: CustomFieldEntityType.CLIENT, id: 'c2' },
] as unknown as CustomFieldItemWithEntity[]

it('splits fields into client and company lists, preserving order', () => {
const { clientCustomFields, companyCustomFields } = splitCustomFieldsByEntity(items)
expect(clientCustomFields.map((f) => f.id)).toEqual(['c1', 'c2'])
expect(companyCustomFields.map((f) => f.id)).toEqual(['co1'])
})

it('strips entityType from the returned items', () => {
const { clientCustomFields } = splitCustomFieldsByEntity(items)
expect(clientCustomFields[0]).not.toHaveProperty('entityType')
})
})

describe('mapCustomFields + splitCustomFieldsByEntity', () => {
it('turns one mixed, unordered response into two ordered per-entity lists', () => {
const mapped = mapCustomFields([
rawField({ id: 'company-late', order: 3, entityType: CustomFieldEntityType.COMPANY }),
rawField({ id: 'client-late', order: 2, entityType: CustomFieldEntityType.CLIENT }),
rawField({ id: 'client-early', order: 1, entityType: CustomFieldEntityType.CLIENT }),
])

const { clientCustomFields, companyCustomFields } = splitCustomFieldsByEntity(mapped)

expect(clientCustomFields.map((f) => f.id)).toEqual(['client-early', 'client-late'])
expect(companyCustomFields.map((f) => f.id)).toEqual(['company-late'])
})
})
Loading