Skip to content
Open
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 assets/build/api/docs.jsonopenapi.json

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,18 @@ const injectedRtkApi = api
}),
invalidatesTags: ["Class Definition"],
}),
classSelectOptionExport: build.query<ClassSelectOptionExportApiResponse, ClassSelectOptionExportApiArg>({
query: (queryArg) => ({ url: `/pimcore-studio/api/class/select-option/${queryArg.id}/export` }),
providesTags: ["Class Definition"],
}),
classSelectOptionImport: build.mutation<ClassSelectOptionImportApiResponse, ClassSelectOptionImportApiArg>({
query: (queryArg) => ({
url: `/pimcore-studio/api/class/select-option/${queryArg.id}/import`,
method: "POST",
body: queryArg.body,
}),
invalidatesTags: ["Class Definition"],
}),
classSelectOptionGetTree: build.query<ClassSelectOptionGetTreeApiResponse, ClassSelectOptionGetTreeApiArg>({
query: (queryArg) => ({
url: `/pimcore-studio/api/class/select-option/tree`,
Expand Down Expand Up @@ -1004,6 +1016,21 @@ export type ClassSelectOptionDeleteApiArg = {
/** Select option configuration ID */
id: string;
};
export type ClassSelectOptionExportApiResponse = /** status 200 Exported select option configuration as JSON */ Blob;
export type ClassSelectOptionExportApiArg = {
/** Select option configuration ID */
id: string;
};
export type ClassSelectOptionImportApiResponse =
/** status 200 Successfully imported select option configuration */ SelectOptionDetail;
export type ClassSelectOptionImportApiArg = {
/** Select option configuration ID */
id: string;
body: {
/** Select option configuration JSON export file to upload */
file: Blob;
};
};
export type ClassSelectOptionGetTreeApiResponse = /** status 200 Select options data for the tree view */ {
totalItems: number;
items: (SelectOptionTreeItem | SelectOptionTreeFolder)[];
Expand Down Expand Up @@ -1815,6 +1842,8 @@ export const {
useClassSelectOptionGetQuery,
useClassSelectOptionUpdateMutation,
useClassSelectOptionDeleteMutation,
useClassSelectOptionExportQuery,
useClassSelectOptionImportMutation,
useClassSelectOptionGetTreeQuery,
useClassSelectOptionGetUsagesQuery,
} = injectedRtkApi;
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* This source file is available under the terms of the
* Pimcore Open Core License (POCL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (https://www.pimcore.com)
* @license Pimcore Open Core License (POCL)
*/

import React from 'react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'

const SELECT_OPTION = { id: 'Colors', group: 'old', isWriteable: true, selectOptions: [] }
const FRESH = { ...SELECT_OPTION, group: 'imported' }

const getSelectOptionById = jest.fn()
const updateSelectOption = jest.fn()
const setSelectOptions = jest.fn()
const setFieldsValue = jest.fn()

jest.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))

jest.mock('../../hooks/use-select-option-editor', () => ({
useSelectOptionEditor: () => ({
getSelectOptionById,
updateSelectOption,
removeWithConfirmation: jest.fn(),
isLoading: false
})
}))

jest.mock('../../context/hooks/use-select-option-editor-context', () => ({
useSelectOptionEditorContext: () => ({ setSelectOptions, closeSelectOption: jest.fn() })
}))

jest.mock('@Pimcore/components/form/form', () => ({
Form: { useForm: () => [{ setFieldsValue }] }
}))

jest.mock('@Pimcore/components/form/form-kit', () => ({
FormKit: ({ children, formProps }: any) => (
<div>
<button onClick={ () => { void formProps.onFinish(formProps.initialValues) } }>finish</button>
{children}
</div>
)
}))

jest.mock('../select-option-editor/general-settings-form-fields', () => ({
SelectOptionGeneralSettingsFormFields: () => null
}))

jest.mock('./select-option-import-export-actions', () => ({
SelectOptionImportExportActions: ({ onImported }: any) => <button onClick={ onImported }>imported</button>
}))

jest.mock('@Pimcore/components/button/button', () => ({ Button: ({ children }: any) => <button>{children}</button> }))
jest.mock('@Pimcore/components/content/content', () => ({ Content: ({ children }: any) => <div>{children}</div> }))
jest.mock('@Pimcore/components/flex/flex', () => ({ Flex: ({ children }: any) => <div>{children}</div> }))
jest.mock('@Pimcore/components/icon-button/icon-button', () => ({ IconButton: () => null }))
jest.mock('@Pimcore/components/toolbar/toolbar', () => ({ Toolbar: ({ children }: any) => <div>{children}</div> }))
jest.mock('@Pimcore/components/tooltip/tooltip', () => ({
actionTooltipDelay: 0,
Tooltip: ({ children }: any) => <>{children}</>
}))

const { SelectOptionForm } = jest.requireActual('./select-option-form')

const expectReloaded = async (): Promise<void> => {
await waitFor(() => { expect(setFieldsValue).toHaveBeenCalledWith(FRESH) })

expect(getSelectOptionById).toHaveBeenCalledWith(SELECT_OPTION.id)

const updateTree = setSelectOptions.mock.calls[0][0]
expect(updateTree([SELECT_OPTION, { id: 'Other' }])).toEqual([FRESH, { id: 'Other' }])
}

describe('SelectOptionForm', () => {
beforeEach(() => {
getSelectOptionById.mockReset().mockResolvedValue(FRESH)
updateSelectOption.mockReset()
setSelectOptions.mockClear()
setFieldsValue.mockClear()
})

it('reloads the select option into the tree and the form after an import', async () => {
render(<SelectOptionForm selectOption={ SELECT_OPTION } />)

fireEvent.click(screen.getByText('imported'))

await expectReloaded()
})

it('reloads it the same way after a save', async () => {
updateSelectOption.mockImplementation(async (_id: string, _config: unknown, onFinish: () => void) => { onFinish() })
render(<SelectOptionForm selectOption={ SELECT_OPTION } />)

fireEvent.click(screen.getByText('finish'))

await expectReloaded()
expect(updateSelectOption).toHaveBeenCalledWith(SELECT_OPTION.id, expect.objectContaining({ group: 'old' }), expect.any(Function))
})

it('leaves the tree and the form alone when the reload finds nothing', async () => {
getSelectOptionById.mockResolvedValue(undefined)
render(<SelectOptionForm selectOption={ SELECT_OPTION } />)

fireEvent.click(screen.getByText('imported'))

await waitFor(() => { expect(getSelectOptionById).toHaveBeenCalledTimes(1) })
expect(setSelectOptions).not.toHaveBeenCalled()
expect(setFieldsValue).not.toHaveBeenCalled()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ import { IconButton } from '@Pimcore/components/icon-button/icon-button'
import { Toolbar } from '@Pimcore/components/toolbar/toolbar'
import { actionTooltipDelay, Tooltip } from '@Pimcore/components/tooltip/tooltip'
import type { SelectOptionDetail, SchemaUsedToUpdateSelectOptionConfigurations } from '@Pimcore/modules/class-definition/class-definition-slice.gen'
import { isUndefined } from 'lodash'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { useSelectOptionEditorContext } from '../../context/hooks/use-select-option-editor-context'
import { useSelectOptionEditor } from '../../hooks/use-select-option-editor'
import { SelectOptionGeneralSettingsFormFields } from '../select-option-editor/general-settings-form-fields'
import { SelectOptionImportExportActions } from './select-option-import-export-actions'

export interface SelectOptionFormProps {
selectOption: SelectOptionDetail
Expand All @@ -37,6 +39,16 @@ export const SelectOptionForm = ({ selectOption }: SelectOptionFormProps): React
}
const isWriteable = selectOption.isWriteable

const reload = async (): Promise<void> => {
const fresh = await getSelectOptionById(selectOption.id)
if (!isUndefined(fresh)) {
setSelectOptions((prev) =>
prev.map((s) => s.id === fresh.id ? fresh : s)
)
form.setFieldsValue(fresh)
}
}

return (
<FormKit
formProps={ {
Expand All @@ -51,15 +63,7 @@ export const SelectOptionForm = ({ selectOption }: SelectOptionFormProps): React
selectOptions: values.selectOptions ?? []
}

await updateSelectOption(selectOption.id, config, async () => {
const fresh = await getSelectOptionById(selectOption.id)
if (fresh !== undefined) {
setSelectOptions((prev) =>
prev.map((s) => s.id === fresh.id ? fresh : s)
)
form.setFieldsValue(fresh)
}
})
await updateSelectOption(selectOption.id, config, () => { void reload() })
}
} }
>
Expand All @@ -84,18 +88,15 @@ export const SelectOptionForm = ({ selectOption }: SelectOptionFormProps): React
aria-label={ t('toolbar.reload') }
disabled={ isLoading }
icon={ { value: 'refresh' } }
onClick={ async () => {
const fresh = await getSelectOptionById(selectOption.id)
if (fresh !== undefined) {
setSelectOptions((prev) =>
prev.map((s) => s.id === fresh.id ? fresh : s)
)
form.setFieldsValue(fresh)
}
} }
onClick={ reload }
tooltip={ { title: t('toolbar.reload') } }
/>

<SelectOptionImportExportActions
id={ selectOption.id }
onImported={ () => { void reload() } }
/>

<Tooltip
mouseEnterDelay={ actionTooltipDelay }
title={ isWriteable ? '' : t('config_not_writeable') }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/**
* This source file is available under the terms of the
* Pimcore Open Core License (POCL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (https://www.pimcore.com)
* @license Pimcore Open Core License (POCL)
*/

import React from 'react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'

const SELECT_OPTION_ID = 'Colors'
const SELECT_OPTION_PATH = `/pimcore-studio/api/class/select-option/${SELECT_OPTION_ID}`
const EXPORT = 'export'
const IMPORT = 'import'
const IMPORT_MODAL = 'import-modal'

const dispatch = jest.fn()
const success = jest.fn()

// antd-style ships untranspiled ESM, which jest does not transform.
jest.mock('@Pimcore/modules/ant-design/styles/create-styles', () => ({
createStyles: () => () => ({ styles: {}, cx: () => '', theme: {} }),
css: () => '',
cx: () => '',
keyframes: () => ''
}))

jest.mock('@Pimcore/app/api/pimcore/route', () => ({ getPrefix: () => '/pimcore-studio/api' }))

jest.mock('@Pimcore/app/store', () => ({
useAppDispatch: () => dispatch,
injectSliceWithState: jest.fn()
}))

jest.mock('@Pimcore/modules/class-definition/class-definition-slice-enhanced', () => ({
api: { util: { invalidateTags: (tags: unknown) => ({ type: 'api/invalidateTags', payload: tags }) } }
}))

// The Editor contexts the shared module also reads; their providers drag the whole app in.
jest.mock('@Pimcore/modules/field-definitions/components/editor/settings-provider', () => ({
useSettings: () => ({})
}))

jest.mock('@Pimcore/modules/field-definitions/components/editor/items/provider', () => ({
useItems: () => ({})
}))

jest.mock('@Pimcore/modules/field-definitions/components/editor/items/detail/refresh-provider', () => ({
useRefresh: () => ({ refreshLayout: jest.fn() })
}))

jest.mock('@Pimcore/modules/app/utils/download', () => ({
downloadFile: jest.fn()
}))

// The real modal pulls antd's untranspiled ESM and an axios upload.
jest.mock('@Pimcore/components/import-modal/import-modal', () => ({
ImportModal: ({ action, onUploadSuccess, title }: any) => (
<button
data-action={ action }
data-testid="import-modal"
data-title={ title }
onClick={ () => { onUploadSuccess({}) } }
>
upload
</button>
)
}))

jest.mock('@sdk/components', () => ({
ButtonGroup: ({ items }: any) => <div>{items}</div>,
Dropdown: ({ children, menu }: any) => (
<div>
{children}
{menu.items.map(({ key, label, onClick }: any) => (
<button
key={ key }
onClick={ onClick }
>
{label}
</button>
))}
</div>
),
Icon: ({ value }: any) => <i>{value}</i>,
IconTextButton: ({ children, onClick }: any) => <button onClick={ onClick }>{children}</button>,
useMessage: () => ({ success })
}))

jest.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))

const { SelectOptionImportExportActions } = jest.requireActual('./select-option-import-export-actions')

const renderActions = (): { onImported: jest.Mock } => {
const onImported = jest.fn()

render(
<SelectOptionImportExportActions
id={ SELECT_OPTION_ID }
onImported={ onImported }
/>
)

return { onImported }
}

describe('SelectOptionImportExportActions', () => {
const originalFetch = globalThis.fetch

beforeEach(() => {
dispatch.mockClear()
success.mockClear()
globalThis.fetch = jest.fn(async () => new Response('{}', { status: 200 })) as unknown as typeof fetch
})

afterEach(() => {
globalThis.fetch = originalFetch
})

it('puts export and import behind the More menu, as the class definition editor does', () => {
renderActions()

expect(screen.getByText('toolbar.more')).toBeInTheDocument()
expect(screen.getByText(EXPORT)).toBeInTheDocument()
expect(screen.getByText(IMPORT)).toBeInTheDocument()
})

it('exports the open select option through its export endpoint', async () => {
renderActions()

fireEvent.click(screen.getByText(EXPORT))

await waitFor(() => { expect(globalThis.fetch).toHaveBeenCalledWith(`${SELECT_OPTION_PATH}/export`) })
})

it('uploads the import to the open select option under the select option title', () => {
renderActions()

expect(screen.getByTestId(IMPORT_MODAL)).toHaveAttribute('data-action', `${SELECT_OPTION_PATH}/import`)
expect(screen.getByTestId(IMPORT_MODAL)).toHaveAttribute('data-title', 'select-option.import.title')
})

it('refreshes the tree and the editor after an import', () => {
const { onImported } = renderActions()

fireEvent.click(screen.getByTestId(IMPORT_MODAL))

expect(success).toHaveBeenCalledWith('select-option.import.success')
expect(onImported).toHaveBeenCalledTimes(1)
expect(dispatch).toHaveBeenCalledWith({ type: 'api/invalidateTags', payload: ['SELECT_OPTION_COLLECTION'] })
})
})
Loading
Loading