Provisioning: Add Connections page (#116060)
* Provisioning: Add connections page * Provisioning: Add connections form * Provisioning: Add connections form * Update fields * Fix generated name * Update connection name * Add edit page * error handling * Form validation * Add Connections button * Cleanup * Extract ConnectionFormData type * Add list test and separate empty states * Add form test * Update tests * i18n * Cleanup * Use SecretTextArea from grafana-ui * Fix breadcrumbs * tweaks * Add missing URL * Switch to ShowConfirmModalEvent * i18n * redirect to list on success * add timeout * Fix tags invalidation
This commit is contained in:
@@ -14,6 +14,8 @@ export type Props = React.ComponentProps<typeof TextArea> & {
|
||||
isConfigured: boolean;
|
||||
/** Called when the user clicks on the "Reset" button in order to clear the secret */
|
||||
onReset: () => void;
|
||||
/** If true, the text area will grow to fill available width. */
|
||||
grow?: boolean;
|
||||
};
|
||||
|
||||
export const CONFIGURED_TEXT = 'configured';
|
||||
@@ -35,11 +37,11 @@ const getStyles = (theme: GrafanaTheme2) => {
|
||||
*
|
||||
* https://developers.grafana.com/ui/latest/index.html?path=/docs/inputs-secrettextarea--docs
|
||||
*/
|
||||
export const SecretTextArea = ({ isConfigured, onReset, ...props }: Props) => {
|
||||
export const SecretTextArea = ({ isConfigured, onReset, grow, ...props }: Props) => {
|
||||
const styles = useStyles2(getStyles);
|
||||
return (
|
||||
<Stack>
|
||||
<Box>
|
||||
<Box grow={grow ? 1 : undefined}>
|
||||
{!isConfigured && <TextArea {...props} />}
|
||||
{isConfigured && (
|
||||
<TextArea
|
||||
|
||||
@@ -11,6 +11,7 @@ import { t } from '@grafana/i18n';
|
||||
import { isFetchError } from '@grafana/runtime';
|
||||
import { clearFolders } from 'app/features/browse-dashboards/state/slice';
|
||||
import { getState } from 'app/store/store';
|
||||
import { ThunkDispatch } from 'app/types/store';
|
||||
|
||||
import { createSuccessNotification, createErrorNotification } from '../../../../core/copy/appNotification';
|
||||
import { notifyApp } from '../../../../core/reducers/appNotification';
|
||||
@@ -19,6 +20,26 @@ import { refetchChildren } from '../../../../features/browse-dashboards/state/ac
|
||||
import { handleError } from '../../../utils';
|
||||
import { createOnCacheEntryAdded } from '../utils/createOnCacheEntryAdded';
|
||||
|
||||
const handleProvisioningFormError = (e: unknown, dispatch: ThunkDispatch, title: string) => {
|
||||
if (typeof e === 'object' && e && 'error' in e && isFetchError(e.error)) {
|
||||
if (e.error.data.kind === 'Status' && e.error.data.status === 'Failure') {
|
||||
const statusError: Status = e.error.data;
|
||||
dispatch(notifyApp(createErrorNotification(title, new Error(statusError.message || 'Unknown error'))));
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(e.error.data.errors) && e.error.data.errors.length) {
|
||||
const nonFieldErrors = e.error.data.errors.filter((err: ErrorDetails) => !err.field);
|
||||
if (nonFieldErrors.length > 0) {
|
||||
dispatch(notifyApp(createErrorNotification(title)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
handleError(e, dispatch, title);
|
||||
};
|
||||
|
||||
export const provisioningAPIv0alpha1 = generatedAPI.enhanceEndpoints({
|
||||
endpoints: {
|
||||
listJob: {
|
||||
@@ -37,6 +58,17 @@ export const provisioningAPIv0alpha1 = generatedAPI.enhanceEndpoints({
|
||||
}),
|
||||
onCacheEntryAdded: createOnCacheEntryAdded<RepositorySpec, RepositoryStatus>('repositories'),
|
||||
},
|
||||
listConnection: {
|
||||
providesTags: (result) =>
|
||||
result
|
||||
? [
|
||||
{ type: 'Connection', id: 'LIST' },
|
||||
...result.items
|
||||
.map((connection) => ({ type: 'Connection' as const, id: connection.metadata?.name }))
|
||||
.filter(Boolean),
|
||||
]
|
||||
: [{ type: 'Connection', id: 'LIST' }],
|
||||
},
|
||||
deleteRepository: {
|
||||
onQueryStarted: async (_, { queryFulfilled, dispatch }) => {
|
||||
try {
|
||||
@@ -104,34 +136,7 @@ export const provisioningAPIv0alpha1 = generatedAPI.enhanceEndpoints({
|
||||
try {
|
||||
await queryFulfilled;
|
||||
} catch (e) {
|
||||
// Handle special cases first
|
||||
if (typeof e === 'object' && e && 'error' in e && isFetchError(e.error)) {
|
||||
// Handle Status error responses (Kubernetes style)
|
||||
if (e.error.data.kind === 'Status' && e.error.data.status === 'Failure') {
|
||||
const statusError: Status = e.error.data;
|
||||
dispatch(
|
||||
notifyApp(
|
||||
createErrorNotification(
|
||||
'Error validating repository',
|
||||
new Error(statusError.message || 'Unknown error')
|
||||
)
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Handle TestResults error responses with field errors
|
||||
if (Array.isArray(e.error.data.errors) && e.error.data.errors.length) {
|
||||
const nonFieldErrors = e.error.data.errors.filter((err: ErrorDetails) => !err.field);
|
||||
// Only show notification if there are errors that don't have a field, field errors are handled by the form
|
||||
if (nonFieldErrors.length > 0) {
|
||||
dispatch(notifyApp(createErrorNotification('Error validating repository')));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// For all other cases, use handleError
|
||||
handleError(e, dispatch, 'Error validating repository');
|
||||
handleProvisioningFormError(e, dispatch, 'Error validating repository');
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -240,6 +245,70 @@ export const provisioningAPIv0alpha1 = generatedAPI.enhanceEndpoints({
|
||||
}
|
||||
},
|
||||
},
|
||||
createConnection: {
|
||||
onQueryStarted: async (_, { queryFulfilled, dispatch }) => {
|
||||
try {
|
||||
await queryFulfilled;
|
||||
dispatch(
|
||||
notifyApp(
|
||||
createSuccessNotification(t('provisioning.connection-form.alert-connection-saved', 'Connection saved'))
|
||||
)
|
||||
);
|
||||
} catch (e) {
|
||||
handleProvisioningFormError(
|
||||
e,
|
||||
dispatch,
|
||||
t('provisioning.connection-form.error-save-connection', 'Failed to save connection')
|
||||
);
|
||||
}
|
||||
},
|
||||
},
|
||||
replaceConnection: {
|
||||
onQueryStarted: async (_, { queryFulfilled, dispatch }) => {
|
||||
try {
|
||||
await queryFulfilled;
|
||||
dispatch(
|
||||
notifyApp(
|
||||
createSuccessNotification(
|
||||
t('provisioning.connection-form.alert-connection-updated', 'Connection updated')
|
||||
)
|
||||
)
|
||||
);
|
||||
} catch (e) {
|
||||
handleProvisioningFormError(
|
||||
e,
|
||||
dispatch,
|
||||
t('provisioning.connection-form.error-save-connection', 'Failed to save connection')
|
||||
);
|
||||
}
|
||||
},
|
||||
},
|
||||
deleteConnection: {
|
||||
invalidatesTags: (result, error) => (error ? [] : [{ type: 'Connection', id: 'LIST' }]),
|
||||
onQueryStarted: async (_, { queryFulfilled, dispatch }) => {
|
||||
try {
|
||||
await queryFulfilled;
|
||||
dispatch(
|
||||
notifyApp(
|
||||
createSuccessNotification(
|
||||
t('provisioning.connection-form.alert-connection-deleted', 'Connection deleted')
|
||||
)
|
||||
)
|
||||
);
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
dispatch(
|
||||
notifyApp(
|
||||
createErrorNotification(
|
||||
t('provisioning.connection-form.error-delete-connection', 'Failed to delete connection'),
|
||||
e
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ export function ConfigForm({ data }: ConfigFormProps) {
|
||||
const repositoryName = data?.metadata?.name;
|
||||
const settings = useGetFrontendSettingsQuery();
|
||||
const [submitData, request] = useCreateOrUpdateRepository(repositoryName);
|
||||
const navigate = useNavigate();
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
@@ -77,7 +78,6 @@ export function ConfigForm({ data }: ConfigFormProps) {
|
||||
const isEdit = Boolean(repositoryName);
|
||||
const [tokenConfigured, setTokenConfigured] = useState(isEdit);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const [type, readOnly] = watch(['type', 'readOnly']);
|
||||
const targetOptions = useMemo(() => getTargetOptions(settings.data?.allowedTargets || ['folder']), [settings.data]);
|
||||
const isGitBased = isGitProvider(type);
|
||||
@@ -104,17 +104,6 @@ export function ConfigForm({ data }: ConfigFormProps) {
|
||||
const localFields = type === 'local' ? getLocalProviderFields(type) : null;
|
||||
const hasTokenInstructions = getHasTokenInstructions(type);
|
||||
|
||||
// TODO: this should be removed after 12.2 is released
|
||||
useEffect(() => {
|
||||
if (isGitBased && !data?.secure?.token) {
|
||||
setTokenConfigured(false);
|
||||
setError('token', {
|
||||
type: 'manual',
|
||||
message: `Enter your ${gitFields?.tokenConfig.label ?? 'access token'}`,
|
||||
});
|
||||
}
|
||||
}, [data, gitFields, setTokenConfigured, setError, isGitBased]);
|
||||
|
||||
useEffect(() => {
|
||||
if (request.isSuccess) {
|
||||
const formData = getValues();
|
||||
@@ -126,11 +115,9 @@ export function ConfigForm({ data }: ConfigFormProps) {
|
||||
});
|
||||
|
||||
reset(formData);
|
||||
setTimeout(() => {
|
||||
navigate('/admin/provisioning');
|
||||
}, 300);
|
||||
setTimeout(() => navigate(PROVISIONING_URL), 300);
|
||||
}
|
||||
}, [request.isSuccess, reset, getValues, navigate, repositoryName]);
|
||||
}, [request.isSuccess, reset, getValues, repositoryName, navigate]);
|
||||
|
||||
const onSubmit = async (form: RepositoryFormData) => {
|
||||
setIsLoading(true);
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
import { QueryStatus } from '@reduxjs/toolkit/query';
|
||||
import { render, screen, waitFor } from 'test/test-utils';
|
||||
|
||||
import { Connection } from 'app/api/clients/provisioning/v0alpha1';
|
||||
|
||||
import { useCreateOrUpdateConnection } from '../hooks/useCreateOrUpdateConnection';
|
||||
|
||||
import { ConnectionForm } from './ConnectionForm';
|
||||
|
||||
jest.mock('../hooks/useCreateOrUpdateConnection', () => ({
|
||||
useCreateOrUpdateConnection: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock('@grafana/runtime', () => ({
|
||||
...jest.requireActual('@grafana/runtime'),
|
||||
reportInteraction: jest.fn(),
|
||||
}));
|
||||
|
||||
const mockSubmitData = jest.fn();
|
||||
const mockUseCreateOrUpdateConnection = useCreateOrUpdateConnection as jest.MockedFunction<
|
||||
typeof useCreateOrUpdateConnection
|
||||
>;
|
||||
|
||||
type MockRequestState = {
|
||||
status: QueryStatus;
|
||||
isLoading: boolean;
|
||||
isSuccess: boolean;
|
||||
isError: boolean;
|
||||
error?: unknown;
|
||||
reset: jest.Mock;
|
||||
};
|
||||
|
||||
const createMockRequestState = (overrides: Partial<MockRequestState> = {}): MockRequestState => ({
|
||||
status: QueryStatus.uninitialized,
|
||||
isLoading: false,
|
||||
isSuccess: false,
|
||||
isError: false,
|
||||
reset: jest.fn(),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const createMockConnection = (overrides: Partial<Connection> = {}): Connection => ({
|
||||
metadata: { name: 'test-connection' },
|
||||
spec: {
|
||||
type: 'github',
|
||||
url: 'https://github.com/settings/installations/12345678',
|
||||
github: {
|
||||
appID: '123456',
|
||||
installationID: '12345678',
|
||||
},
|
||||
},
|
||||
secure: {
|
||||
privateKey: { name: 'configured' },
|
||||
},
|
||||
status: {
|
||||
state: 'connected',
|
||||
health: { healthy: true },
|
||||
observedGeneration: 1,
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
interface SetupOptions {
|
||||
data?: Connection;
|
||||
requestState?: Partial<MockRequestState>;
|
||||
}
|
||||
|
||||
function setup(options: SetupOptions = {}) {
|
||||
const { data, requestState = {} } = options;
|
||||
|
||||
mockUseCreateOrUpdateConnection.mockReturnValue([
|
||||
mockSubmitData,
|
||||
createMockRequestState(requestState) as unknown as ReturnType<typeof useCreateOrUpdateConnection>[1],
|
||||
]);
|
||||
|
||||
return {
|
||||
mockSubmitData,
|
||||
...render(<ConnectionForm data={data} />),
|
||||
};
|
||||
}
|
||||
|
||||
describe('ConnectionForm', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockSubmitData.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe('Rendering - Create Mode', () => {
|
||||
it('should render all form fields', () => {
|
||||
setup();
|
||||
|
||||
expect(screen.getByLabelText(/^Provider/)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/^GitHub App ID/)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/^GitHub Installation ID/)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/^Private Key \(PEM\)/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render Save button', () => {
|
||||
setup();
|
||||
|
||||
expect(screen.getByRole('button', { name: /^save$/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should not render Delete button in create mode', () => {
|
||||
setup();
|
||||
|
||||
expect(screen.queryByRole('button', { name: /delete/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should have Provider field disabled', () => {
|
||||
setup();
|
||||
|
||||
expect(screen.getByLabelText(/^Provider/)).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Rendering - Edit Mode', () => {
|
||||
it('should populate form fields with existing connection data', () => {
|
||||
setup({ data: createMockConnection() });
|
||||
|
||||
expect(screen.getByLabelText(/^GitHub App ID/)).toHaveValue('123456');
|
||||
expect(screen.getByLabelText(/^GitHub Installation ID/)).toHaveValue('12345678');
|
||||
});
|
||||
|
||||
it('should render Delete button in edit mode', () => {
|
||||
setup({ data: createMockConnection() });
|
||||
|
||||
expect(screen.getByRole('button', { name: /delete/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show configured state for private key', () => {
|
||||
setup({ data: createMockConnection() });
|
||||
|
||||
expect(screen.getByLabelText(/^Private Key \(PEM\)/)).toHaveValue('configured');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Form Validation', () => {
|
||||
it('should show required error and not submit when fields are empty', async () => {
|
||||
const { user, mockSubmitData } = setup();
|
||||
|
||||
const saveButton = screen.getByRole('button', { name: /^save$/i });
|
||||
await user.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByText('This field is required')).toHaveLength(3);
|
||||
});
|
||||
|
||||
expect(mockSubmitData).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Form Submission - Create', () => {
|
||||
it('should call submitData with correct data on valid submission', async () => {
|
||||
const { user, mockSubmitData } = setup();
|
||||
|
||||
await user.type(screen.getByLabelText(/^GitHub App ID/), '123456');
|
||||
await user.type(screen.getByLabelText(/^GitHub Installation ID/), '12345678');
|
||||
await user.type(screen.getByLabelText(/^Private Key \(PEM\)/), '-----BEGIN RSA PRIVATE KEY-----');
|
||||
|
||||
const saveButton = screen.getByRole('button', { name: /^save$/i });
|
||||
await user.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSubmitData).toHaveBeenCalledWith(
|
||||
{
|
||||
type: 'github',
|
||||
github: {
|
||||
appID: '123456',
|
||||
installationID: '12345678',
|
||||
},
|
||||
},
|
||||
'-----BEGIN RSA PRIVATE KEY-----'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Form Submission - Edit', () => {
|
||||
it('should allow submission without changing private key', async () => {
|
||||
const { user, mockSubmitData } = setup({ data: createMockConnection() });
|
||||
|
||||
const saveButton = screen.getByRole('button', { name: /^save$/i });
|
||||
await user.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSubmitData).toHaveBeenCalledWith(
|
||||
{
|
||||
type: 'github',
|
||||
github: {
|
||||
appID: '123456',
|
||||
installationID: '12345678',
|
||||
},
|
||||
},
|
||||
'configured'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Loading State', () => {
|
||||
it('should disable Save button while loading', () => {
|
||||
setup({ requestState: { isLoading: true } });
|
||||
|
||||
const saveButton = screen.getByRole('button', { name: /saving/i });
|
||||
expect(saveButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should show "Saving..." text while loading', () => {
|
||||
setup({ requestState: { isLoading: true } });
|
||||
|
||||
expect(screen.getByText('Saving...')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('should map API error for appID to form field', async () => {
|
||||
const { user, mockSubmitData } = setup();
|
||||
|
||||
mockSubmitData.mockRejectedValue({
|
||||
status: 400,
|
||||
data: { errors: [{ field: 'appID', detail: 'Invalid App ID' }] },
|
||||
});
|
||||
|
||||
await user.type(screen.getByLabelText(/^GitHub App ID/), '123456');
|
||||
await user.type(screen.getByLabelText(/^GitHub Installation ID/), '12345678');
|
||||
await user.type(screen.getByLabelText(/^Private Key \(PEM\)/), '-----BEGIN RSA PRIVATE KEY-----');
|
||||
|
||||
const saveButton = screen.getByRole('button', { name: /^save$/i });
|
||||
await user.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Invalid App ID')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should map API error for installationID to form field', async () => {
|
||||
const { user, mockSubmitData } = setup();
|
||||
|
||||
mockSubmitData.mockRejectedValue({
|
||||
status: 400,
|
||||
data: { errors: [{ field: 'installationID', detail: 'Invalid Installation ID' }] },
|
||||
});
|
||||
|
||||
await user.type(screen.getByLabelText(/^GitHub App ID/), '123456');
|
||||
await user.type(screen.getByLabelText(/^GitHub Installation ID/), '12345678');
|
||||
await user.type(screen.getByLabelText(/^Private Key \(PEM\)/), '-----BEGIN RSA PRIVATE KEY-----');
|
||||
|
||||
const saveButton = screen.getByRole('button', { name: /^save$/i });
|
||||
await user.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Invalid Installation ID')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should map API error for privateKey to form field', async () => {
|
||||
const { user, mockSubmitData } = setup();
|
||||
|
||||
mockSubmitData.mockRejectedValue({
|
||||
status: 400,
|
||||
data: { errors: [{ field: 'secure.privateKey', detail: 'Invalid Private Key format' }] },
|
||||
});
|
||||
|
||||
await user.type(screen.getByLabelText(/^GitHub App ID/), '123456');
|
||||
await user.type(screen.getByLabelText(/^GitHub Installation ID/), '12345678');
|
||||
await user.type(screen.getByLabelText(/^Private Key \(PEM\)/), 'invalid-key');
|
||||
|
||||
const saveButton = screen.getByRole('button', { name: /^save$/i });
|
||||
await user.click(saveButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Invalid Private Key format')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { useNavigate } from 'react-router-dom-v5-compat';
|
||||
|
||||
import { t } from '@grafana/i18n';
|
||||
import { isFetchError, reportInteraction } from '@grafana/runtime';
|
||||
import { Button, Combobox, Field, Input, SecretTextArea, Stack } from '@grafana/ui';
|
||||
import { Connection } from 'app/api/clients/provisioning/v0alpha1';
|
||||
import { FormPrompt } from 'app/core/components/FormPrompt/FormPrompt';
|
||||
|
||||
import { CONNECTIONS_URL } from '../constants';
|
||||
import { useCreateOrUpdateConnection } from '../hooks/useCreateOrUpdateConnection';
|
||||
import { ConnectionFormData } from '../types';
|
||||
import { getConnectionFormErrors } from '../utils/getFormErrors';
|
||||
|
||||
import { DeleteConnectionButton } from './DeleteConnectionButton';
|
||||
|
||||
interface ConnectionFormProps {
|
||||
data?: Connection;
|
||||
}
|
||||
|
||||
const providerOptions = [{ value: 'github', label: 'GitHub' }];
|
||||
|
||||
export function ConnectionForm({ data }: ConnectionFormProps) {
|
||||
const connectionName = data?.metadata?.name;
|
||||
const isEdit = Boolean(connectionName);
|
||||
const privateKey = data?.secure?.privateKey;
|
||||
const [privateKeyConfigured, setPrivateKeyConfigured] = useState(Boolean(privateKey));
|
||||
const [submitData, request] = useCreateOrUpdateConnection(connectionName);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
control,
|
||||
formState: { errors, isDirty },
|
||||
setValue,
|
||||
getValues,
|
||||
setError,
|
||||
} = useForm<ConnectionFormData>({
|
||||
defaultValues: {
|
||||
type: data?.spec?.type || 'github',
|
||||
appID: data?.spec?.github?.appID || '',
|
||||
installationID: data?.spec?.github?.installationID || '',
|
||||
privateKey: privateKey?.name || '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (request.isSuccess) {
|
||||
const formData = getValues();
|
||||
|
||||
reportInteraction('grafana_provisioning_connection_saved', {
|
||||
connectionName: connectionName ?? 'unknown',
|
||||
connectionType: formData.type,
|
||||
});
|
||||
|
||||
reset(formData);
|
||||
// use timeout to ensure the form resets before navigating
|
||||
setTimeout(() => navigate(CONNECTIONS_URL), 300);
|
||||
}
|
||||
}, [request.isSuccess, reset, getValues, connectionName, navigate]);
|
||||
|
||||
const onSubmit = async (form: ConnectionFormData) => {
|
||||
try {
|
||||
const spec = {
|
||||
type: form.type,
|
||||
github: {
|
||||
appID: form.appID,
|
||||
installationID: form.installationID,
|
||||
},
|
||||
};
|
||||
|
||||
await submitData(spec, form.privateKey);
|
||||
} catch (err) {
|
||||
if (isFetchError(err)) {
|
||||
const [field, errorMessage] = getConnectionFormErrors(err.data?.errors);
|
||||
|
||||
if (field && errorMessage) {
|
||||
setError(field, errorMessage);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)} style={{ maxWidth: 700 }}>
|
||||
<FormPrompt onDiscard={reset} confirmRedirect={isDirty} />
|
||||
<Stack direction="column" gap={2}>
|
||||
<Field
|
||||
noMargin
|
||||
htmlFor="type"
|
||||
label={t('provisioning.connection-form.label-provider', 'Provider')}
|
||||
description={t('provisioning.connection-form.description-provider', 'Select the provider type')}
|
||||
>
|
||||
<Controller
|
||||
name="type"
|
||||
control={control}
|
||||
render={({ field: { ref, onChange, ...field } }) => (
|
||||
<Combobox
|
||||
id="type"
|
||||
disabled // TODO enable when other providers are supported
|
||||
options={providerOptions}
|
||||
onChange={(option) => onChange(option?.value)}
|
||||
{...field}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
noMargin
|
||||
label={t('provisioning.connection-form.label-app-id', 'GitHub App ID')}
|
||||
description={t('provisioning.connection-form.description-app-id', 'The ID of your GitHub App')}
|
||||
invalid={!!errors.appID}
|
||||
error={errors?.appID?.message}
|
||||
required
|
||||
>
|
||||
<Input
|
||||
id="appID"
|
||||
{...register('appID', {
|
||||
required: t('provisioning.connection-form.error-required', 'This field is required'),
|
||||
})}
|
||||
placeholder={t('provisioning.connection-form.placeholder-app-id', '123456')}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
noMargin
|
||||
label={t('provisioning.connection-form.label-installation-id', 'GitHub Installation ID')}
|
||||
description={t(
|
||||
'provisioning.connection-form.description-installation-id',
|
||||
'The installation ID of your GitHub App'
|
||||
)}
|
||||
invalid={!!errors.installationID}
|
||||
error={errors?.installationID?.message}
|
||||
required
|
||||
>
|
||||
<Input
|
||||
id="installationID"
|
||||
{...register('installationID', {
|
||||
required: t('provisioning.connection-form.error-required', 'This field is required'),
|
||||
})}
|
||||
placeholder={t('provisioning.connection-form.placeholder-installation-id', '12345678')}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field
|
||||
noMargin
|
||||
htmlFor="privateKey"
|
||||
label={t('provisioning.connection-form.label-private-key', 'Private Key (PEM)')}
|
||||
description={t(
|
||||
'provisioning.connection-form.description-private-key',
|
||||
'The private key for your GitHub App in PEM format'
|
||||
)}
|
||||
invalid={!!errors.privateKey}
|
||||
error={errors?.privateKey?.message}
|
||||
required={!isEdit}
|
||||
>
|
||||
<Controller
|
||||
name="privateKey"
|
||||
control={control}
|
||||
rules={{
|
||||
required: isEdit ? false : t('provisioning.connection-form.error-required', 'This field is required'),
|
||||
}}
|
||||
render={({ field: { ref, ...field } }) => (
|
||||
<SecretTextArea
|
||||
{...field}
|
||||
id="privateKey"
|
||||
placeholder={t(
|
||||
'provisioning.connection-form.placeholder-private-key',
|
||||
'-----BEGIN RSA PRIVATE KEY-----...'
|
||||
)}
|
||||
isConfigured={privateKeyConfigured}
|
||||
onReset={() => {
|
||||
setValue('privateKey', '');
|
||||
setPrivateKeyConfigured(false);
|
||||
}}
|
||||
rows={8}
|
||||
grow
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Stack gap={2}>
|
||||
<Button type="submit" disabled={request.isLoading}>
|
||||
{request.isLoading
|
||||
? t('provisioning.connection-form.button-saving', 'Saving...')
|
||||
: t('provisioning.connection-form.button-save', 'Save')}
|
||||
</Button>
|
||||
{connectionName && data && <DeleteConnectionButton name={connectionName} connection={data} />}
|
||||
</Stack>
|
||||
</Stack>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { skipToken } from '@reduxjs/toolkit/query/react';
|
||||
import { useParams } from 'react-router-dom-v5-compat';
|
||||
|
||||
import { Trans, t } from '@grafana/i18n';
|
||||
import { EmptyState, Text, TextLink } from '@grafana/ui';
|
||||
import { useGetConnectionQuery } from 'app/api/clients/provisioning/v0alpha1';
|
||||
import { Page } from 'app/core/components/Page/Page';
|
||||
|
||||
import { CONNECTIONS_URL } from '../constants';
|
||||
|
||||
import { ConnectionForm } from './ConnectionForm';
|
||||
|
||||
export default function ConnectionFormPage() {
|
||||
const { name = '' } = useParams();
|
||||
const isCreate = !name;
|
||||
|
||||
const query = useGetConnectionQuery(isCreate ? skipToken : { name });
|
||||
|
||||
//@ts-expect-error TODO add error types
|
||||
const notFound = !isCreate && query.isError && query.error?.status === 404;
|
||||
|
||||
const pageTitle = isCreate
|
||||
? t('provisioning.connection-form.page-title-create', 'Create connection')
|
||||
: t('provisioning.connection-form.page-title-edit', 'Edit connection');
|
||||
|
||||
return (
|
||||
<Page
|
||||
navId="provisioning"
|
||||
pageNav={{
|
||||
text: pageTitle,
|
||||
subTitle: t(
|
||||
'provisioning.connection-form.page-subtitle',
|
||||
'Configure a connection to authenticate with external providers'
|
||||
),
|
||||
parentItem: {
|
||||
text: t('provisioning.connections.page-title', 'Connections'),
|
||||
url: CONNECTIONS_URL,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Page.Contents isLoading={!isCreate && query.isLoading}>
|
||||
{notFound ? (
|
||||
<EmptyState message={t('provisioning.connection-form.not-found', 'Connection not found')} variant="not-found">
|
||||
<Text element="p">
|
||||
<Trans i18nKey="provisioning.connection-form.not-found-description">
|
||||
The connection you are looking for does not exist.
|
||||
</Trans>
|
||||
</Text>
|
||||
<TextLink href={CONNECTIONS_URL}>
|
||||
<Trans i18nKey="provisioning.connection-form.back-to-connections">Back to connections</Trans>
|
||||
</TextLink>
|
||||
</EmptyState>
|
||||
) : (
|
||||
<ConnectionForm data={isCreate ? undefined : query.data} />
|
||||
)}
|
||||
</Page.Contents>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import { render, screen } from 'test/test-utils';
|
||||
|
||||
import { Connection } from 'app/api/clients/provisioning/v0alpha1';
|
||||
|
||||
import { ConnectionList } from './ConnectionList';
|
||||
|
||||
const createMockConnection = (overrides: Partial<Connection> = {}): Connection => ({
|
||||
metadata: { name: 'test-connection' },
|
||||
spec: {
|
||||
type: 'github',
|
||||
url: 'https://github.com/settings/installations/12345678',
|
||||
github: {
|
||||
appID: '123456',
|
||||
installationID: '12345678',
|
||||
},
|
||||
},
|
||||
status: {
|
||||
state: 'connected',
|
||||
health: { healthy: true },
|
||||
observedGeneration: 1,
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const mockConnections: Connection[] = [
|
||||
createMockConnection({
|
||||
metadata: { name: 'github-conn-1' },
|
||||
spec: {
|
||||
type: 'github',
|
||||
url: 'https://github.com/settings/installations/103343308',
|
||||
github: {
|
||||
appID: '123456',
|
||||
installationID: '103343308',
|
||||
},
|
||||
},
|
||||
}),
|
||||
createMockConnection({
|
||||
metadata: { name: 'gitlab-conn-2' },
|
||||
spec: { type: 'gitlab', url: 'https://gitlab.com/org2/repo2' },
|
||||
}),
|
||||
createMockConnection({
|
||||
metadata: { name: 'another-github' },
|
||||
spec: {
|
||||
type: 'github',
|
||||
url: 'https://github.com/settings/installations/987654321',
|
||||
github: {
|
||||
appID: '654321',
|
||||
installationID: '987654321',
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
function setup(items: Connection[] = mockConnections) {
|
||||
return render(<ConnectionList items={items} />, { renderWithRouter: true });
|
||||
}
|
||||
|
||||
describe('ConnectionList', () => {
|
||||
describe('Rendering', () => {
|
||||
it('should render search input with correct placeholder', () => {
|
||||
setup();
|
||||
|
||||
expect(screen.getByPlaceholderText('Search connections')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render all connection items when no filter is applied', () => {
|
||||
setup();
|
||||
|
||||
// Verify all 3 connections are displayed by checking for their URL links
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'https://github.com/settings/installations/103343308' })
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'https://gitlab.com/org2/repo2' })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'https://github.com/settings/installations/987654321' })
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render EmptyState when items array is empty', () => {
|
||||
setup([]);
|
||||
|
||||
expect(screen.getByText('No connections configured')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Filtering', () => {
|
||||
it('should filter connections by name', async () => {
|
||||
const { user } = setup();
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search connections');
|
||||
await user.type(searchInput, 'gitlab');
|
||||
|
||||
// Should show only gitlab connection
|
||||
expect(screen.getByRole('link', { name: 'https://gitlab.com/org2/repo2' })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('link', { name: 'https://github.com/settings/installations/103343308' })
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('link', { name: 'https://github.com/settings/installations/987654321' })
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should filter connections by provider type', async () => {
|
||||
const { user } = setup();
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search connections');
|
||||
await user.type(searchInput, 'github');
|
||||
|
||||
// Should show only github connections
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'https://github.com/settings/installations/103343308' })
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByRole('link', { name: 'https://gitlab.com/org2/repo2' })).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'https://github.com/settings/installations/987654321' })
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should be case-insensitive', async () => {
|
||||
const { user } = setup();
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search connections');
|
||||
await user.type(searchInput, 'GITLAB');
|
||||
|
||||
expect(screen.getByRole('link', { name: 'https://gitlab.com/org2/repo2' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show EmptyState when filter matches nothing', async () => {
|
||||
const { user } = setup();
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search connections');
|
||||
await user.type(searchInput, 'nonexistent');
|
||||
|
||||
expect(screen.getByText('No results matching your query')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('link', { name: 'https://github.com/settings/installations/103343308' })
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should clear filter and show all items', async () => {
|
||||
const { user } = setup();
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search connections');
|
||||
await user.type(searchInput, 'gitlab');
|
||||
|
||||
// Filter applied
|
||||
expect(screen.getByRole('link', { name: 'https://gitlab.com/org2/repo2' })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('link', { name: 'https://github.com/settings/installations/103343308' })
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
// Clear the filter
|
||||
await user.clear(searchInput);
|
||||
|
||||
// All items should be visible again
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'https://github.com/settings/installations/103343308' })
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'https://gitlab.com/org2/repo2' })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'https://github.com/settings/installations/987654321' })
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import { t } from '@grafana/i18n';
|
||||
import { EmptyState, FilterInput, Stack } from '@grafana/ui';
|
||||
import { Connection } from 'app/api/clients/provisioning/v0alpha1';
|
||||
|
||||
import { ConnectionListItem } from './ConnectionListItem';
|
||||
|
||||
interface Props {
|
||||
items: Connection[];
|
||||
}
|
||||
|
||||
export function ConnectionList({ items }: Props) {
|
||||
const [query, setQuery] = useState('');
|
||||
|
||||
const filteredItems = items.filter((item) => {
|
||||
if (!query) {
|
||||
return true;
|
||||
}
|
||||
const lowerQuery = query.toLowerCase();
|
||||
const name = item.metadata?.name?.toLowerCase() ?? '';
|
||||
const providerType = item.spec?.type?.toLowerCase() ?? '';
|
||||
return name.includes(lowerQuery) || providerType.includes(lowerQuery);
|
||||
});
|
||||
|
||||
const isEmpty = items.length === 0;
|
||||
|
||||
return (
|
||||
<Stack direction={'column'} gap={3}>
|
||||
<FilterInput
|
||||
placeholder={t('provisioning.connections.search-placeholder', 'Search connections')}
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
/>
|
||||
<Stack direction={'column'} gap={2}>
|
||||
{filteredItems.length ? (
|
||||
filteredItems.map((item) => <ConnectionListItem key={item.metadata?.name} connection={item} />)
|
||||
) : (
|
||||
<EmptyState
|
||||
variant={isEmpty ? 'completed' : 'not-found'}
|
||||
message={
|
||||
isEmpty
|
||||
? t('provisioning.connections.no-connections', 'No connections configured')
|
||||
: t('provisioning.connections.no-results', 'No results matching your query')
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Trans } from '@grafana/i18n';
|
||||
import { Card, LinkButton, Stack, Text, TextLink } from '@grafana/ui';
|
||||
import { Connection } from 'app/api/clients/provisioning/v0alpha1';
|
||||
|
||||
import { RepoIcon } from '../Shared/RepoIcon';
|
||||
import { RepoType } from '../Wizard/types';
|
||||
import { CONNECTIONS_URL } from '../constants';
|
||||
import { getRepositoryTypeConfigs } from '../utils/repositoryTypes';
|
||||
|
||||
import { ConnectionStatusBadge } from './ConnectionStatusBadge';
|
||||
|
||||
interface Props {
|
||||
connection: Connection;
|
||||
}
|
||||
|
||||
export function ConnectionListItem({ connection }: Props) {
|
||||
const { metadata, spec, status } = connection;
|
||||
const name = metadata?.name ?? '';
|
||||
const url = spec?.url;
|
||||
const providerType: RepoType = spec?.type ?? 'github';
|
||||
const repoConfig = getRepositoryTypeConfigs().find((config) => config.type === providerType);
|
||||
return (
|
||||
<Card noMargin key={name}>
|
||||
<Card.Figure>
|
||||
<RepoIcon type={providerType} />
|
||||
</Card.Figure>
|
||||
<Card.Heading>
|
||||
<Stack gap={2} direction="row" alignItems="center">
|
||||
{repoConfig && <Text variant="h3">{`${repoConfig.label} app connection`}</Text>}
|
||||
{status?.state && <ConnectionStatusBadge status={status} />}
|
||||
</Stack>
|
||||
</Card.Heading>
|
||||
|
||||
{url && (
|
||||
<Card.Meta>
|
||||
<TextLink external href={url}>
|
||||
{url}
|
||||
</TextLink>
|
||||
</Card.Meta>
|
||||
)}
|
||||
|
||||
<Card.Actions>
|
||||
<LinkButton icon="eye" href={`${CONNECTIONS_URL}/${name}/edit`} variant="primary" size="md">
|
||||
<Trans i18nKey="provisioning.connections.view">View</Trans>
|
||||
</LinkButton>
|
||||
</Card.Actions>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { t } from '@grafana/i18n';
|
||||
import { Badge, IconName } from '@grafana/ui';
|
||||
import { ConnectionStatus } from 'app/api/clients/provisioning/v0alpha1';
|
||||
|
||||
interface Props {
|
||||
status: ConnectionStatus;
|
||||
}
|
||||
|
||||
interface BadgeConfig {
|
||||
color: 'green' | 'red' | 'darkgrey';
|
||||
text: string;
|
||||
icon: IconName;
|
||||
}
|
||||
|
||||
function getBadgeConfig(status: ConnectionStatus): BadgeConfig {
|
||||
switch (status.state) {
|
||||
case 'connected':
|
||||
return {
|
||||
color: 'green',
|
||||
text: t('provisioning.connections.status-connected', 'Connected'),
|
||||
icon: 'check',
|
||||
};
|
||||
case 'disconnected':
|
||||
return {
|
||||
color: 'red',
|
||||
text: t('provisioning.connections.status-disconnected', 'Disconnected'),
|
||||
icon: 'times-circle',
|
||||
};
|
||||
default:
|
||||
return {
|
||||
color: 'darkgrey',
|
||||
text: t('provisioning.connections.status-unknown', 'Unknown'),
|
||||
icon: 'question-circle',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function ConnectionStatusBadge({ status }: Props) {
|
||||
const config = getBadgeConfig(status);
|
||||
|
||||
return <Badge color={config.color} text={config.text} icon={config.icon} />;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { t, Trans } from '@grafana/i18n';
|
||||
import { Alert, EmptyState, LinkButton, Stack, Text } from '@grafana/ui';
|
||||
import { Page } from 'app/core/components/Page/Page';
|
||||
|
||||
import { CONNECTIONS_URL } from '../constants';
|
||||
import { useConnectionList } from '../hooks/useConnectionList';
|
||||
import { getErrorMessage } from '../utils/httpUtils';
|
||||
|
||||
import { ConnectionList } from './ConnectionList';
|
||||
|
||||
export default function ConnectionsPage() {
|
||||
const [items, isLoading, error] = useConnectionList();
|
||||
const hasNoConnections = !isLoading && !error && items?.length === 0;
|
||||
|
||||
return (
|
||||
<Page
|
||||
navId="provisioning"
|
||||
pageNav={{
|
||||
text: t('provisioning.connections.page-title', 'Connections'),
|
||||
subTitle: t('provisioning.connections.page-subtitle', 'View and manage your app connections'),
|
||||
}}
|
||||
actions={
|
||||
<LinkButton variant="primary" href={`${CONNECTIONS_URL}/new`}>
|
||||
<Trans i18nKey="provisioning.connections.add-connection">Add connection</Trans>
|
||||
</LinkButton>
|
||||
}
|
||||
>
|
||||
<Page.Contents isLoading={isLoading}>
|
||||
<Stack direction={'column'} gap={3}>
|
||||
{!!error && (
|
||||
<Alert severity="error" title={t('provisioning.connections.error-loading', 'Failed to load connections')}>
|
||||
{getErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{hasNoConnections && (
|
||||
<EmptyState
|
||||
variant="call-to-action"
|
||||
message={t('provisioning.connections.no-connections', 'No connections configured')}
|
||||
>
|
||||
<Text element="p">
|
||||
{t(
|
||||
'provisioning.connections.no-connections-message',
|
||||
'Add a connection to authenticate with external providers'
|
||||
)}
|
||||
</Text>
|
||||
</EmptyState>
|
||||
)}
|
||||
|
||||
{!!items?.length && <ConnectionList items={items} />}
|
||||
</Stack>
|
||||
</Page.Contents>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom-v5-compat';
|
||||
|
||||
import { t, Trans } from '@grafana/i18n';
|
||||
import { reportInteraction } from '@grafana/runtime';
|
||||
import { Button } from '@grafana/ui';
|
||||
import { Connection, useDeleteConnectionMutation } from 'app/api/clients/provisioning/v0alpha1';
|
||||
import { appEvents } from 'app/core/app_events';
|
||||
import { ShowConfirmModalEvent } from 'app/types/events';
|
||||
|
||||
import { CONNECTIONS_URL } from '../constants';
|
||||
|
||||
interface Props {
|
||||
name: string;
|
||||
connection: Connection;
|
||||
}
|
||||
|
||||
export function DeleteConnectionButton({ name, connection }: Props) {
|
||||
const navigate = useNavigate();
|
||||
const [deleteConnection, deleteRequest] = useDeleteConnectionMutation();
|
||||
|
||||
const onDelete = useCallback(async () => {
|
||||
reportInteraction('grafana_provisioning_connection_deleted', {
|
||||
connectionName: name,
|
||||
connectionType: connection?.spec?.type ?? 'unknown',
|
||||
});
|
||||
|
||||
await deleteConnection({ name });
|
||||
navigate(CONNECTIONS_URL);
|
||||
}, [deleteConnection, name, connection, navigate]);
|
||||
|
||||
const showDeleteModal = useCallback(() => {
|
||||
appEvents.publish(
|
||||
new ShowConfirmModalEvent({
|
||||
title: t('provisioning.connections.delete-title', 'Delete connection'),
|
||||
text: t(
|
||||
'provisioning.connections.delete-confirm',
|
||||
'Are you sure you want to delete this connection? This action cannot be undone.'
|
||||
),
|
||||
yesText: t('provisioning.connections.delete', 'Delete'),
|
||||
noText: t('provisioning.connections.cancel', 'Cancel'),
|
||||
yesButtonVariant: 'destructive',
|
||||
onConfirm: onDelete,
|
||||
})
|
||||
);
|
||||
}, [onDelete]);
|
||||
|
||||
return (
|
||||
<Button variant="destructive" size="md" disabled={deleteRequest.isLoading} onClick={showDeleteModal}>
|
||||
<Trans i18nKey="provisioning.connections.delete">Delete</Trans>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom-v5-compat';
|
||||
|
||||
import { t, Trans } from '@grafana/i18n';
|
||||
import { reportInteraction } from '@grafana/runtime';
|
||||
import { Button, ConfirmModal, Dropdown, Icon, Menu, Stack } from '@grafana/ui';
|
||||
import { Button, Dropdown, Icon, Menu, Stack } from '@grafana/ui';
|
||||
import {
|
||||
Repository,
|
||||
useDeleteRepositoryMutation,
|
||||
useReplaceRepositoryMutation,
|
||||
} from 'app/api/clients/provisioning/v0alpha1';
|
||||
import { appEvents } from 'app/core/app_events';
|
||||
import { ShowConfirmModalEvent } from 'app/types/events';
|
||||
|
||||
type DeleteAction = 'remove-resources' | 'keep-resources';
|
||||
|
||||
@@ -21,110 +23,102 @@ interface Props {
|
||||
export function DeleteRepositoryButton({ name, repository, redirectTo }: Props) {
|
||||
const [deleteRepository, deleteRequest] = useDeleteRepositoryMutation();
|
||||
const [replaceRepository, replaceRequest] = useReplaceRepositoryMutation();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [selectedAction, setSelectedAction] = useState<DeleteAction>('remove-resources');
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if (deleteRequest.isSuccess) {
|
||||
setShowModal(false);
|
||||
const performDelete = useCallback(
|
||||
async (deleteAction: DeleteAction) => {
|
||||
if (deleteAction === 'keep-resources' && repository) {
|
||||
const updatedRepository = {
|
||||
...repository,
|
||||
metadata: {
|
||||
...repository.metadata,
|
||||
finalizers: ['cleanup', 'release-orphan-resources'],
|
||||
},
|
||||
};
|
||||
await replaceRepository({ name, repository: updatedRepository });
|
||||
}
|
||||
|
||||
reportInteraction('grafana_provisioning_repository_deleted', {
|
||||
repositoryName: name,
|
||||
repositoryType: repository?.spec?.type ?? 'unknown',
|
||||
deleteAction,
|
||||
target: repository?.spec?.sync?.target ?? 'unknown',
|
||||
workflows: repository?.spec?.workflows ?? [],
|
||||
});
|
||||
|
||||
await deleteRepository({ name });
|
||||
|
||||
if (redirectTo) {
|
||||
navigate(redirectTo);
|
||||
}
|
||||
}
|
||||
}, [deleteRequest.isSuccess, redirectTo, navigate]);
|
||||
},
|
||||
[deleteRepository, replaceRepository, name, repository, redirectTo, navigate]
|
||||
);
|
||||
|
||||
const onConfirm = useCallback(async () => {
|
||||
if (selectedAction === 'keep-resources' && repository) {
|
||||
const updatedRepository = {
|
||||
...repository,
|
||||
metadata: {
|
||||
...repository.metadata,
|
||||
finalizers: ['cleanup', 'release-orphan-resources'],
|
||||
},
|
||||
};
|
||||
await replaceRepository({ name, repository: updatedRepository });
|
||||
}
|
||||
|
||||
reportInteraction('grafana_provisioning_repository_deleted', {
|
||||
repositoryName: name,
|
||||
repositoryType: repository?.spec?.type ?? 'unknown',
|
||||
deleteAction: selectedAction,
|
||||
target: repository?.spec?.sync?.target ?? 'unknown',
|
||||
workflows: repository?.spec?.workflows ?? [],
|
||||
});
|
||||
|
||||
deleteRepository({ name });
|
||||
}, [deleteRepository, replaceRepository, name, selectedAction, repository]);
|
||||
|
||||
const getConfirmationMessage = () => {
|
||||
if (selectedAction === 'remove-resources') {
|
||||
return t(
|
||||
'provisioning.delete-repository-button.confirm-delete-with-resources',
|
||||
'Are you sure you want to delete the repository configuration and all its resources?'
|
||||
);
|
||||
}
|
||||
return t(
|
||||
'provisioning.delete-repository-button.confirm-delete-keep-resources',
|
||||
'Are you sure you want to delete the repository configuration but keep its resources?'
|
||||
const showDeleteWithResourcesModal = useCallback(() => {
|
||||
appEvents.publish(
|
||||
new ShowConfirmModalEvent({
|
||||
title: t(
|
||||
'provisioning.delete-repository-button.title-delete-repository-and-resources',
|
||||
'Delete repository configuration and resources'
|
||||
),
|
||||
text: t(
|
||||
'provisioning.delete-repository-button.confirm-delete-with-resources',
|
||||
'Are you sure you want to delete the repository configuration and all its resources?'
|
||||
),
|
||||
yesText: t('provisioning.delete-repository-button.button-delete', 'Delete'),
|
||||
noText: t('provisioning.delete-repository-button.button-cancel', 'Cancel'),
|
||||
yesButtonVariant: 'destructive',
|
||||
onConfirm: () => performDelete('remove-resources'),
|
||||
})
|
||||
);
|
||||
};
|
||||
}, [performDelete]);
|
||||
|
||||
const getModalTitle = () => {
|
||||
if (selectedAction === 'remove-resources') {
|
||||
return t(
|
||||
'provisioning.delete-repository-button.title-delete-repository-and-resources',
|
||||
'Delete repository configuration and resources'
|
||||
);
|
||||
}
|
||||
return t(
|
||||
'provisioning.delete-repository-button.title-delete-repository-only',
|
||||
'Delete repository configuration only'
|
||||
const showDeleteKeepResourcesModal = useCallback(() => {
|
||||
appEvents.publish(
|
||||
new ShowConfirmModalEvent({
|
||||
title: t(
|
||||
'provisioning.delete-repository-button.title-delete-repository-only',
|
||||
'Delete repository configuration only'
|
||||
),
|
||||
text: t(
|
||||
'provisioning.delete-repository-button.confirm-delete-keep-resources',
|
||||
'Are you sure you want to delete the repository configuration but keep its resources?'
|
||||
),
|
||||
yesText: t('provisioning.delete-repository-button.button-delete', 'Delete'),
|
||||
noText: t('provisioning.delete-repository-button.button-cancel', 'Cancel'),
|
||||
yesButtonVariant: 'destructive',
|
||||
onConfirm: () => performDelete('keep-resources'),
|
||||
})
|
||||
);
|
||||
};
|
||||
}, [performDelete]);
|
||||
|
||||
const isLoading = deleteRequest.isLoading || replaceRequest.isLoading;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dropdown
|
||||
overlay={
|
||||
<Menu>
|
||||
<Menu.Item
|
||||
label={t(
|
||||
'provisioning.delete-repository-button.delete-and-remove-resources',
|
||||
'Delete and remove resources (default)'
|
||||
)}
|
||||
onClick={() => {
|
||||
setSelectedAction('remove-resources');
|
||||
setShowModal(true);
|
||||
}}
|
||||
/>
|
||||
<Menu.Item
|
||||
label={t('provisioning.delete-repository-button.delete-and-keep-resources', 'Delete and keep resources')}
|
||||
onClick={() => {
|
||||
setSelectedAction('keep-resources');
|
||||
setShowModal(true);
|
||||
}}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
>
|
||||
<Button variant="destructive" disabled={isLoading}>
|
||||
<Stack alignItems="center">
|
||||
<Trans i18nKey="provisioning.delete-repository-button.delete">Delete</Trans>
|
||||
<Icon name={'angle-down'} />
|
||||
</Stack>
|
||||
</Button>
|
||||
</Dropdown>
|
||||
<ConfirmModal
|
||||
isOpen={showModal}
|
||||
title={getModalTitle()}
|
||||
body={getConfirmationMessage()}
|
||||
confirmText={t('provisioning.delete-repository-button.button-delete', 'Delete')}
|
||||
onConfirm={onConfirm}
|
||||
onDismiss={() => setShowModal(false)}
|
||||
/>
|
||||
</>
|
||||
<Dropdown
|
||||
overlay={
|
||||
<Menu>
|
||||
<Menu.Item
|
||||
label={t(
|
||||
'provisioning.delete-repository-button.delete-and-remove-resources',
|
||||
'Delete and remove resources (default)'
|
||||
)}
|
||||
onClick={showDeleteWithResourcesModal}
|
||||
/>
|
||||
<Menu.Item
|
||||
label={t('provisioning.delete-repository-button.delete-and-keep-resources', 'Delete and keep resources')}
|
||||
onClick={showDeleteKeepResourcesModal}
|
||||
/>
|
||||
</Menu>
|
||||
}
|
||||
>
|
||||
<Button variant="destructive" disabled={isLoading}>
|
||||
<Stack alignItems="center">
|
||||
<Trans i18nKey="provisioning.delete-repository-button.delete">Delete</Trans>
|
||||
<Icon name={'angle-down'} />
|
||||
</Stack>
|
||||
</Button>
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Badge, Button, LinkButton, Stack } from '@grafana/ui';
|
||||
import { Repository } from 'app/api/clients/provisioning/v0alpha1';
|
||||
|
||||
import { StatusBadge } from '../Shared/StatusBadge';
|
||||
import { PROVISIONING_URL } from '../constants';
|
||||
import { CONNECTIONS_URL, PROVISIONING_URL } from '../constants';
|
||||
import { getRepoHrefForProvider } from '../utils/git';
|
||||
import { getIsReadOnlyWorkflows } from '../utils/repository';
|
||||
import { getRepositoryTypeConfig } from '../utils/repositoryTypes';
|
||||
@@ -34,6 +34,9 @@ export function RepositoryActions({ repository }: RepositoryActionsProps) {
|
||||
</Button>
|
||||
)}
|
||||
<SyncRepository repository={repository} />
|
||||
<LinkButton variant="secondary" icon="link" href={CONNECTIONS_URL}>
|
||||
<Trans i18nKey="provisioning.repository-actions.connections">Connections</Trans>
|
||||
</LinkButton>
|
||||
<LinkButton
|
||||
variant="secondary"
|
||||
icon="cog"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export const PROVISIONING_URL = '/admin/provisioning';
|
||||
export const CONNECTIONS_URL = `${PROVISIONING_URL}/connections`;
|
||||
export const CONNECT_URL = `${PROVISIONING_URL}/connect`;
|
||||
export const GETTING_STARTED_URL = `${PROVISIONING_URL}/getting-started`;
|
||||
export const UPGRADE_URL = 'https://grafana.com/profile/org/subscription';
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { skipToken } from '@reduxjs/toolkit/query';
|
||||
|
||||
import { ListConnectionApiArg, useListConnectionQuery } from 'app/api/clients/provisioning/v0alpha1';
|
||||
|
||||
// Sort connections alphabetically by name
|
||||
export function useConnectionList(options: ListConnectionApiArg | typeof skipToken = {}) {
|
||||
const query = useListConnectionQuery(options);
|
||||
const collator = new Intl.Collator(undefined, { numeric: true });
|
||||
|
||||
const sortedItems = query.data?.items?.slice().sort((a, b) => {
|
||||
const nameA = a.metadata?.name ?? '';
|
||||
const nameB = b.metadata?.name ?? '';
|
||||
return collator.compare(nameA, nameB);
|
||||
});
|
||||
|
||||
return [sortedItems, query.isLoading, query.error] as const;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useCallback } from 'react';
|
||||
|
||||
import {
|
||||
Connection,
|
||||
ConnectionSpec,
|
||||
ConnectionSecure,
|
||||
useCreateConnectionMutation,
|
||||
useReplaceConnectionMutation,
|
||||
} from 'app/api/clients/provisioning/v0alpha1';
|
||||
|
||||
export function useCreateOrUpdateConnection(name?: string) {
|
||||
const [create, createRequest] = useCreateConnectionMutation();
|
||||
const [update, updateRequest] = useReplaceConnectionMutation();
|
||||
|
||||
const updateOrCreate = useCallback(
|
||||
async (data: ConnectionSpec, privateKey?: string) => {
|
||||
const secure: ConnectionSecure | undefined = privateKey?.length
|
||||
? { privateKey: { create: privateKey } }
|
||||
: undefined;
|
||||
|
||||
const connection: Connection = {
|
||||
metadata: name ? { name } : { generateName: 'c' },
|
||||
spec: data,
|
||||
secure,
|
||||
};
|
||||
|
||||
if (name) {
|
||||
return update({
|
||||
name,
|
||||
connection,
|
||||
});
|
||||
}
|
||||
|
||||
return create({ connection });
|
||||
},
|
||||
[create, name, update]
|
||||
);
|
||||
|
||||
return [updateOrCreate, name ? updateRequest : createRequest] as const;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { SelectableValue } from '@grafana/data';
|
||||
|
||||
import {
|
||||
BitbucketRepositoryConfig,
|
||||
ConnectionSpec,
|
||||
GitHubRepositoryConfig,
|
||||
GitLabRepositoryConfig,
|
||||
GitRepositoryConfig,
|
||||
@@ -51,6 +52,16 @@ export type RepositoryFormData = Omit<RepositorySpec, 'workflows' | RepositorySp
|
||||
|
||||
export type RepositorySettingsField = Path<RepositoryFormData>;
|
||||
|
||||
// Connection type definition - extracted from API client
|
||||
export type ConnectionType = ConnectionSpec['type'];
|
||||
|
||||
export type ConnectionFormData = {
|
||||
type: ConnectionSpec['type'];
|
||||
appID: string;
|
||||
installationID: string;
|
||||
privateKey?: string;
|
||||
};
|
||||
|
||||
// Section configuration
|
||||
export interface RepositorySection {
|
||||
name: string;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Path } from 'react-hook-form';
|
||||
import { ErrorDetails } from 'app/api/clients/provisioning/v0alpha1';
|
||||
|
||||
import { WizardFormData } from '../Wizard/types';
|
||||
import { RepositoryFormData } from '../types';
|
||||
import { ConnectionFormData, RepositoryFormData } from '../types';
|
||||
|
||||
export type RepositoryField = keyof WizardFormData['repository'];
|
||||
export type RepositoryFormPath = `repository.${RepositoryField}` | 'repository.sync.intervalSeconds';
|
||||
@@ -89,3 +89,20 @@ export const getConfigFormErrors = (errors?: ErrorDetails[]): ConfigFormErrorTup
|
||||
|
||||
return mapErrorsToField(errors, fieldMap, { allowPartial: true });
|
||||
};
|
||||
|
||||
// Connection form errors
|
||||
export type ConnectionFormPath = Path<ConnectionFormData>;
|
||||
export type ConnectionFormErrorTuple = GenericFormErrorTuple<ConnectionFormPath>;
|
||||
|
||||
export const getConnectionFormErrors = (errors?: ErrorDetails[]): ConnectionFormErrorTuple => {
|
||||
const fieldMap: Record<string, ConnectionFormPath> = {
|
||||
appID: 'appID',
|
||||
installationID: 'installationID',
|
||||
'github.appID': 'appID',
|
||||
'github.installationID': 'installationID',
|
||||
'secure.privateKey': 'privateKey',
|
||||
privateKey: 'privateKey',
|
||||
};
|
||||
|
||||
return mapErrorsToField(errors, fieldMap, { allowPartial: true });
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@ import { RouteDescriptor } from 'app/core/navigation/types';
|
||||
import { DashboardRoutes } from 'app/types/dashboard';
|
||||
|
||||
import { checkRequiredFeatures } from '../GettingStarted/features';
|
||||
import { PROVISIONING_URL, CONNECT_URL, GETTING_STARTED_URL } from '../constants';
|
||||
import { CONNECTIONS_URL, CONNECT_URL, GETTING_STARTED_URL, PROVISIONING_URL } from '../constants';
|
||||
|
||||
export function getProvisioningRoutes(): RouteDescriptor[] {
|
||||
if (!checkRequiredFeatures()) {
|
||||
@@ -36,6 +36,26 @@ export function getProvisioningRoutes(): RouteDescriptor[] {
|
||||
)
|
||||
),
|
||||
},
|
||||
{
|
||||
path: CONNECTIONS_URL,
|
||||
component: SafeDynamicImport(
|
||||
() => import(/* webpackChunkName: "ConnectionsPage"*/ 'app/features/provisioning/Connection/ConnectionsPage')
|
||||
),
|
||||
},
|
||||
{
|
||||
path: `${CONNECTIONS_URL}/:name/edit`,
|
||||
component: SafeDynamicImport(
|
||||
() =>
|
||||
import(/* webpackChunkName: "ConnectionFormPage"*/ 'app/features/provisioning/Connection/ConnectionFormPage')
|
||||
),
|
||||
},
|
||||
{
|
||||
path: `${CONNECTIONS_URL}/new`,
|
||||
component: SafeDynamicImport(
|
||||
() =>
|
||||
import(/* webpackChunkName: "ConnectionFormPage"*/ 'app/features/provisioning/Connection/ConnectionFormPage')
|
||||
),
|
||||
},
|
||||
{
|
||||
path: `${CONNECT_URL}/:type`,
|
||||
component: SafeDynamicImport(
|
||||
|
||||
@@ -11806,7 +11806,53 @@
|
||||
"free-tier-limit-tooltip": "Free-tier accounts are restricted to one connection",
|
||||
"instance-fully-managed-tooltip": "Configuration is disabled because this instance is fully managed"
|
||||
},
|
||||
"connection-form": {
|
||||
"alert-connection-deleted": "Connection deleted",
|
||||
"alert-connection-saved": "Connection saved",
|
||||
"alert-connection-updated": "Connection updated",
|
||||
"back-to-connections": "Back to connections",
|
||||
"button-save": "Save",
|
||||
"button-saving": "Saving...",
|
||||
"description-app-id": "The ID of your GitHub App",
|
||||
"description-installation-id": "The installation ID of your GitHub App",
|
||||
"description-private-key": "The private key for your GitHub App in PEM format",
|
||||
"description-provider": "Select the provider type",
|
||||
"error-delete-connection": "Failed to delete connection",
|
||||
"error-required": "This field is required",
|
||||
"error-save-connection": "Failed to save connection",
|
||||
"label-app-id": "GitHub App ID",
|
||||
"label-installation-id": "GitHub Installation ID",
|
||||
"label-private-key": "Private Key (PEM)",
|
||||
"label-provider": "Provider",
|
||||
"not-found": "Connection not found",
|
||||
"not-found-description": "The connection you are looking for does not exist.",
|
||||
"page-subtitle": "Configure a connection to authenticate with external providers",
|
||||
"page-title-create": "Create connection",
|
||||
"page-title-edit": "Edit connection",
|
||||
"placeholder-app-id": "123456",
|
||||
"placeholder-installation-id": "12345678",
|
||||
"placeholder-private-key": "-----BEGIN RSA PRIVATE KEY-----..."
|
||||
},
|
||||
"connections": {
|
||||
"add-connection": "Add connection",
|
||||
"cancel": "Cancel",
|
||||
"delete": "Delete",
|
||||
"delete-confirm": "Are you sure you want to delete this connection? This action cannot be undone.",
|
||||
"delete-title": "Delete connection",
|
||||
"error-loading": "Failed to load connections",
|
||||
"no-connections": "No connections configured",
|
||||
"no-connections-message": "Add a connection to authenticate with external providers",
|
||||
"no-results": "No results matching your query",
|
||||
"page-subtitle": "View and manage your app connections",
|
||||
"page-title": "Connections",
|
||||
"search-placeholder": "Search connections",
|
||||
"status-connected": "Connected",
|
||||
"status-disconnected": "Disconnected",
|
||||
"status-unknown": "Unknown",
|
||||
"view": "View"
|
||||
},
|
||||
"delete-repository-button": {
|
||||
"button-cancel": "Cancel",
|
||||
"button-delete": "Delete",
|
||||
"confirm-delete-keep-resources": "Are you sure you want to delete the repository configuration but keep its resources?",
|
||||
"confirm-delete-with-resources": "Are you sure you want to delete the repository configuration and all its resources?",
|
||||
@@ -12070,6 +12116,7 @@
|
||||
"jobs": "Jobs"
|
||||
},
|
||||
"repository-actions": {
|
||||
"connections": "Connections",
|
||||
"settings": "Settings",
|
||||
"source-code": "Source code"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user