Skip to content

Commit

Permalink
fix: changes
Browse files Browse the repository at this point in the history
- remove hovers on the login form.
- add roles
- failed to update credential
- catalog instructions text
  • Loading branch information
S-Nagendra committed Jul 3, 2024
1 parent f7306c2 commit b0aada6
Show file tree
Hide file tree
Showing 12 changed files with 116 additions and 98 deletions.
4 changes: 2 additions & 2 deletions pages/api/proxyApiRequest.ts → pages/api/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { NextApiRequest, NextApiResponse } from 'next/types';
import { sendErrorToBugsnag } from '@/lib/bugsnag';
import { handleAxiosError } from '@/components/Error/ErrorUtils';

const proxyApiRequestHandler = async (req: NextApiRequest, res: NextApiResponse) => {
const createOrUpdateConnectionHandler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
// Process a POST request
let { url, data } = req.body;
Expand Down Expand Up @@ -38,4 +38,4 @@ const proxyApiRequestHandler = async (req: NextApiRequest, res: NextApiResponse)
}
};

export default proxyApiRequestHandler;
export default createOrUpdateConnectionHandler;
3 changes: 1 addition & 2 deletions src/components/FormInput/FormFieldText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ const FormFieldText = (props: FormFieldTextProps) => {
onChange
} = props;

const inputProps =
type === 'number' ? { inputMode: 'numeric', pattern: '[0-9]*' } : {};
const inputProps = type === 'number' ? { inputMode: 'numeric', pattern: '[0-9]*' } : {};

return (
<Tooltip title={description ? description : ''} placement="top-start">
Expand Down
2 changes: 1 addition & 1 deletion src/components/FormInput/FormOneOfControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ const MaterialOneOfEnumControl = (props: CombinatorRendererProps) => {
handleOnConfigureButtonClick={handleOnConfigureButtonClick}
oAuthProvider={getOAuthProviderName(selectedConnector)}
oauth_error={oauth_error}
hasOAuthAuthorized={isIntegrationAuthorized(oauth_params, false)}
hasOAuthAuthorized={isIntegrationAuthorized(oauth_params, isEditableFlow)}
sx={{ mt: 2 }}
/>
);
Expand Down
64 changes: 31 additions & 33 deletions src/components/FormInput/FormSelectControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import { ControlProps } from '@jsonforms/core';
import { withJsonFormsControlProps } from '@jsonforms/react';
import { Card, FormControl, Hidden, MenuItem, TextField, Tooltip, Typography } from '@mui/material';
import { Card, FormControl, Hidden, MenuItem, TextField, Typography } from '@mui/material';
import { merge } from 'lodash';
import { useDebouncedChange, useFocus } from '@jsonforms/material-renderers';

Expand Down Expand Up @@ -41,40 +41,38 @@ export const FormSelectControl = (props: ControlProps) => {
<Hidden xsUp={!visible}>
<Card sx={{ py: 2 }}>
{visible && (
<Tooltip title={description ? description : ''} placement="top-start">
<FormControl
fullWidth={!appliedUiSchemaOptions.trim}
onFocus={onFocus}
onBlur={onBlur}
id={id}
variant={'standard'}
<FormControl
fullWidth={!appliedUiSchemaOptions.trim}
onFocus={onFocus}
onBlur={onBlur}
id={id}
variant={'standard'}
>
<TextField
size="small"
label={label}
select={true}
required={required}
disabled={!enabled}
value={inputText}
onChange={onChange}
InputLabelProps={{
shrink: true
}}
>
<TextField
size="small"
label={label}
select={true}
required={required}
disabled={!enabled}
value={inputText}
onChange={onChange}
InputLabelProps={{
shrink: true
}}
>
{schema.enum?.map((item: string) => {
return (
<MenuItem key={item} value={item}>
{item}
</MenuItem>
);
})}
</TextField>
{schema.enum?.map((item: string) => {
return (
<MenuItem key={item} value={item}>
{item}
</MenuItem>
);
})}
</TextField>

<Typography color={!isValid ? 'error.main' : 'primary.main'} variant="body2">
{formErrorHelperText?.toLowerCase() ?? ''}
</Typography>
</FormControl>
</Tooltip>
<Typography color={!isValid ? 'error.main' : 'primary.main'} variant="body2">
{formErrorHelperText?.toLowerCase() ?? ''}
</Typography>
</FormControl>
)}
</Card>
</Hidden>
Expand Down
10 changes: 2 additions & 8 deletions src/components/Instructions/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
/*
* Copyright (c) 2024 valmi.io <https://github.com/valmi-io>
* Created Date: Thursday, May 25th 2023, 6:11:37 pm
* Author: Nagendra S @ valmi.io
*/

import { Box, Link, Typography, styled } from '@mui/material';

const InstructionsBox = styled(Box)(({}) => ({
Expand Down Expand Up @@ -34,11 +28,11 @@ const Instructions = (props: InstructionsProps) => {
</Typography>

<InstructionsText variant="body1">
Refer to step-by-step instructions to setup a{' '}
Follow the step-by-step instructions to connect to{' '}
<Link color="secondary" href={documentationUrl} target="_blank" rel="noreferrer" underline="always">
{linkText}
</Link>
{type && type === 'credential' && <> {'credential.'}</>}
{/* {type && type === 'credential' && <> {'credential.'}</>} */}
</InstructionsText>
</InstructionsBox>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,13 +260,15 @@ const ConnectionLoginButton = (props: any) => {
/>

<Tooltip title={getTooltipTitle({ requireConfiguration, isConfigured })}>
<LoginContainer
onClick={onClick}
isConfigured={isConfigured}
formData={formData}
oAuthProvider={oAuthProvider}
requireConfiguration={requireConfiguration}
/>
<>
<LoginContainer
onClick={onClick}
isConfigured={isConfigured}
formData={formData}
oAuthProvider={oAuthProvider}
requireConfiguration={requireConfiguration}
/>
</>
</Tooltip>

<ErrorStatusText sx={{ ml: 1 }} variant="body1">
Expand Down
51 changes: 24 additions & 27 deletions src/content/ConnectionFlow/ConnectionConfig/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ import {
getExtrasObjKey,
filterStreamsBasedOnScope,
initializeConnectionFlowState,
generateConfigFromSpec,
generateFormStateFromSpec,
generateCredentialPayload
} from '@/utils/connectionFlowUtils';
import { isObjectEmpty } from '@/utils/lib';
import { flattenObject, isObjectEmpty } from '@/utils/lib';
import { generateStreamObj } from '@/content/ConnectionFlow/ConnectionDiscover/streamsReducer';
import { useRouter } from 'next/router';
import {
Expand Down Expand Up @@ -57,17 +57,11 @@ const ConnectionConfig = ({ params, isEditableFlow = false }: TConnectionUpsertP

const selectedConnector = connectionDataFlow.entities[getSelectedConnectorKey()] ?? {};

const {
type = '',
display_name: displayName = '',
oauth_keys: oauthKeys = '',
mode = '',
oauth_params: oAuthParams = {}
} = selectedConnector;
const { type = '', display_name: displayName = '', mode = '', oauth_params: oAuthParams = {} } = selectedConnector;

const { config = {}, account = {} } = connectionDataFlow.entities[getCredentialObjKey(type)] ?? {};

const { id: credentialId = '' } = config ?? {};
const { id: credentialId = '', name: credentialName = '' } = config ?? {};

// Getting credential selectors for editing case specifically - not useful for create case
const { selectCredentialById } = getCredentialsSelectors(wid as string);
Expand Down Expand Up @@ -119,27 +113,27 @@ const ConnectionConfig = ({ params, isEditableFlow = false }: TConnectionUpsertP

useEffect(() => {
if (oAuthParams && !isObjectEmpty(oAuthParams)) {
oAuthConfiguredState().run();
const currentFormState = connectionDataFlow.entities[getSelectedConnectorKey()]?.formValues || {};
storeOAuthState(currentFormState, oAuthParams);
}
}, [oAuthParams]);

const oAuthConfiguredState = () => {
return {
run: () => {
const { spec = null } = connectionDataFlow.entities[getCredentialObjKey(type)];
const formDataFromStore = connectionDataFlow.entities[getSelectedConnectorKey()]?.formValues || {};
let combinedValues = {
...formDataFromStore,
...getOAuthParams(oAuthParams)
};
/**
* Stores state consisting of current form state and OAuth response in connectionForm context.
* @param currentFormState The current state of the form.
* @param oauthResponse The response received from OAuth.
*/
const storeOAuthState = (currentFormState: any, oauthResponse: any) => {
const formAndOAuthState = flattenObject({
...currentFormState,
...getOAuthParams(oauthResponse)
});

let config = generateConfigFromSpec(spec, combinedValues);
const { spec = null } = connectionDataFlow.entities[getCredentialObjKey(type)];

setFormState(config);
const updatedFormState = generateFormStateFromSpec(spec, formAndOAuthState, type);

return;
}
};
setFormState(updatedFormState);
};

// STATE: Trigger to get into Checking Credential State - BEGIN
Expand Down Expand Up @@ -172,8 +166,11 @@ const ConnectionConfig = ({ params, isEditableFlow = false }: TConnectionUpsertP
} else {
if (isEditableFlow) {
const userAccount = { ...user, id: account.id };

const updatedFormState = { ...formState, id: credentialId, name: credentialName };

const payload = generateCredentialPayload({
credentialConfig: formState,
credentialConfig: updatedFormState,
type,
user: userAccount,
isEditableFlow: isEditableFlow
Expand Down Expand Up @@ -206,7 +203,7 @@ const ConnectionConfig = ({ params, isEditableFlow = false }: TConnectionUpsertP
const handleCredentialUpdate = async (workspaceId: string, payload: any) => {
const credentialUpdateURL = `/workspaces/${workspaceId}/credentials/update`;
await httpPostRequestHandler({
route: apiRoutes['proxyURL'],
route: apiRoutes['connectionURL'],
url: credentialUpdateURL,
payload,
errorCb: handleCredentialUpdateError,
Expand Down
1 change: 1 addition & 0 deletions src/contexts/OAuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ function OAuthContextProvider({ children }: Props) {
}
}
};

dispatch(setEntities(entities));

router.push(`${oAuthRoute}?state=${state}`);
Expand Down
44 changes: 29 additions & 15 deletions src/utils/connectionFlowUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -432,35 +432,39 @@ export const isIntegrationAuthorized = (oAuthParams: any, isEditableFlow: boolea
return !!((oAuthParams && !isObjectEmpty(oAuthParams)) || isEditableFlow);
};

export const generateConfigFromSpec = (spec: any, values: any) => {
export const generateFormStateFromSpec = (spec: any, values: any, type: string) => {
return createJsonObject(
spec.spec.connectionSpecification.required,
spec.spec.connectionSpecification.properties,
values
values,
type
);
};

const createJsonObject = (required: any, properties_def: any, values: any) => {
const createJsonObject = (required: any, properties_def: any, values: any, type: string) => {
let obj: any = {};

if (required) {
for (const field of required) {
if (properties_def[field].oneOf) {
// Determine which oneOf schema to use based on the auth_method value
const method = values?.credentials?.auth_method ?? '';

const authMethodKey = getOAuthMethodKeyFromType(type);

const authMethodValue = values?.[authMethodKey] ?? '';

const selectedSchema = properties_def[field].oneOf.find(
(schema: any) => schema.properties.auth_method.const === method
(schema: any) => schema?.properties?.[authMethodKey]?.const === authMethodValue
);

// Merge nested credentials from top-level values
const nestedValues = { ...values.credentials, ...extractNestedCredentials(values) };
obj[field] = createJsonObject(selectedSchema?.required, selectedSchema?.properties, nestedValues);
obj[field] = createJsonObject(selectedSchema?.required, selectedSchema?.properties, values, type);
} else if (properties_def[field].type === 'object') {
if (properties_def[field].required) {
obj[field] = createJsonObject(
properties_def[field].required,
properties_def[field].properties,
values[field]
values[field],
type
);
} else {
obj[field] = values[field];
Expand All @@ -474,10 +478,20 @@ const createJsonObject = (required: any, properties_def: any, values: any) => {
return obj;
};

const extractNestedCredentials = (values: any) => {
return {
client_id: values.client_id,
client_secret: values.client_secret,
access_token: values.access_token
};
export const getOAuthMethodKeyFromType = (type: string): string => {
switch (type) {
case getShopifyIntegrationType():
return 'auth_method';
default:
return '';
}
};

export const getOAuthMethodDefaultValueFromType = (type: string): string => {
switch (type) {
case getShopifyIntegrationType():
return 'api_password';
default:
return '';
}
};
12 changes: 12 additions & 0 deletions src/utils/lib.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,15 @@ export function deepFlattenToObject(obj, prefix = '') {
return acc;
}, {});
}

// Function to flatten nested objects
export function flattenObject(obj: any, parentKey = '') {
return Object.keys(obj).reduce((acc, key) => {
if (typeof obj[key] === 'object' && obj[key] !== null) {
Object.assign(acc, flattenObject(obj[key], key));
} else {
acc[key] = obj[key];
}
return acc;
}, {});
}
5 changes: 3 additions & 2 deletions src/utils/login-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@ export const loginFormSchema = {
type: 'boolean',
title: 'Check to receive latest product updates over email',
const: true,
description: 'Select this checkbox to receive emails about new product features and announcements'
// description: 'Select this checkbox to receive emails about new product features and announcements'
description: ''
},
role: {
type: 'string',
title: 'You are part of',
enum: ['Engineering', 'Marketing', 'Other'],
enum: ['Engineering', 'Marketing', 'Finance', 'Sales', 'Operations', 'Other'],
description: "Select your role from the dropdown menu. If your role isn't listed, choose 'Other'"
}
},
Expand Down
2 changes: 1 addition & 1 deletion src/utils/router-utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const apiRoutes = {
checkURL: `/api/checkConnection`,
defaultURL: `/`,
fbTokenURL: '/api/getFbLongLivedToken',
proxyURL: `/api/proxyApiRequest`
connectionURL: `/api/connection`
};

export const redirectToHomePage = (wid: string, router: NextRouter) => {
Expand Down

0 comments on commit b0aada6

Please sign in to comment.