Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(models): gen models tables selector #179

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
13 changes: 11 additions & 2 deletions src/components/ApiSetup/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ const ApiSetup: FC<ApiSetupProps> = ({
password = initialValue?.password,
database = initialValue?.db,
}) => {
const [hostname, port] = host.split(":");
const [hostname, port] = host ? host?.split?.(":") : [];

const portOption = port ? `-P ${port}` : "";
const psqlPortOption = port ? `--port=${port}` : "";
Expand Down Expand Up @@ -239,7 +239,16 @@ const ApiSetup: FC<ApiSetupProps> = ({
<div className={cn(styles.textareaWrapper, styles.label)}>
<Input
control={control}
defaultValue={createConnectionString({})}
defaultValue={
initialValue
? createConnectionString({
user: initialValue?.db_username,
password: initialValue?.password,
host: connectionUrls[CONNECTION_DEFAULT],
connection: initialValue?.connection,
})
: ""
}
name="connection_string"
fieldType="textarea"
label={`${getLabel("connect_using")} ${
Expand Down
16 changes: 16 additions & 0 deletions src/components/DataModelGeneration/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import cn from "classnames";
import { useResponsive } from "ahooks";
import { useForm } from "react-hook-form";
import { init } from "i18next";

import Input from "@/components/Input";
import type {
Expand Down Expand Up @@ -57,6 +58,7 @@ const DataModelGeneration: FC<DataModelGenerationProps> = ({
}) => {
const { t } = useTranslation(["dataModelGeneration", "common"]);

console.log(initialValue);
const { control, handleSubmit, watch, reset } = useForm<DynamicForm>({
values: initialValue,
});
Expand All @@ -74,7 +76,21 @@ const DataModelGeneration: FC<DataModelGenerationProps> = ({
}
};

console.log("loading", loading);

const onFormSubmit = (data: DynamicForm, type: string) => {
Object.keys(data).forEach((scope) => {
if (typeof data?.[scope] === "object") {
data[scope] = Object.keys(data[scope]).reduce(
(res: any, table: any) => ({
...res,
[table.replace(`${scope}.`, "")]: data[scope][table],
}),
{}
);
}
});
console.log("formsubmit", data);
onSubmit(data, type);
if (resetOnSubmit) reset();
};
Expand Down
1 change: 0 additions & 1 deletion src/components/DataSourceForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ const DataSourceForm: FC<DataSourceFormProps> = ({
}) => {
const { t } = useTranslation(["dataSourceStepForm"]);
const { step } = DataSourceStore();

return (
<Card
style={{
Expand Down
1 change: 1 addition & 0 deletions src/components/DataSourceFormBody/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ const DataSourceFormBody: FC<DataSourceFormBodyProps> = ({
);
case 3:
const initialValue = formState?.step3 || formData?.step3;

return (
<ApiSetup
isOnboarding={isOnboarding}
Expand Down
14 changes: 8 additions & 6 deletions src/components/TableSelection/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,21 @@ const TableSelection: FC<TableSelectionProps> = ({
defaultValue: initialValue,
});

console.log(value);

const isAllSelected = () =>
Object.keys(schema[path]).every((tb) => value[tb] === true);
Object.keys(schema[path]).every((tb) => value[`${path}.${tb}`] === true);

const onClear = () => {
const newVal: DynamicForm = {};
Object.keys(value).forEach((k) => (newVal[k] = false));
Object.keys(value).forEach((k) => (newVal[`${path}.${k}`] = false));
onChange(newVal);
};

const onSelectAll = (e: CheckboxChangeEvent) => {
if (!e.target.checked) return onClear();
const newVal: DynamicForm = {};
Object.keys(schema[path]).forEach((tb) => (newVal[tb] = true));
Object.keys(schema[path]).forEach((tb) => (newVal[`${path}.${tb}`] = true));
onChange(newVal);
};

Expand All @@ -66,12 +68,12 @@ const TableSelection: FC<TableSelectionProps> = ({
</Button>
</div>
{Object.keys(schema[path]).map((tb) => (
<div key={tb}>
<div key={`${path}.${tb}`}>
<div className={cn(styles.field)}>
<Checkbox
checked={value?.[tb]}
checked={value?.[`${path}.${tb}`]}
onChange={(e) => {
onChange({ ...value, [tb]: e.target.checked });
onChange({ ...value, [`${path}.${tb}`]: e.target.checked });
}}
>
<span
Expand Down
120 changes: 70 additions & 50 deletions src/hooks/useOnboarding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,11 @@ export default ({ editId }: Props) => {
clean,
setSchema,
setFormStateData,
formState,
} = DataSourceStore();

const [fetchTablesQuery, execFetchTables] = useFetchTablesQuery({
variables: { id: dataSourceSetup?.id },
variables: { id: editId },
pause: true,
});

Expand Down Expand Up @@ -91,9 +92,11 @@ export default ({ editId }: Props) => {
() => teamData?.dataSources || [],
[teamData]
) as DataSourceInfo[];

const curDataSource = useMemo(
() =>
dataSources.find((d) => d.id === editId || d.id === dataSourceSetup?.id),
dataSources.find((d) => d.id === editId) ||
dataSources.find((d) => d.id === dataSourceSetup?.id),
[editId, dataSourceSetup?.id, dataSources]
);

Expand Down Expand Up @@ -130,56 +133,70 @@ export default ({ editId }: Props) => {
}
};

const prepareSqlApiData = (
dataSourceName?: string,
dataSourceId?: string
): { apiConfig: ApiSetupForm; credentialParams: CredentialParams } => {
const apiConfig: ApiSetupForm = prepareInitValues(
dataSourceId,
currentUser.id,
dataSourceName
);
const credentialParams: CredentialParams = {
user_id: currentUser.id,
username: apiConfig.db_username,
password: apiConfig.password,
};

if (dataSourceId) {
credentialParams.datasource_id = dataSourceId;
}
const prepareSqlApiData = useCallback(
(
dataSourceName?: string,
dataSourceId?: string
): { apiConfig: ApiSetupForm; credentialParams: CredentialParams } => {
const apiConfig: ApiSetupForm = prepareInitValues(
dataSourceId,
currentUser.id,
dataSourceName
);
const credentialParams: CredentialParams = {
user_id: currentUser.id,
username: apiConfig.db_username,
password: apiConfig.password,
};

return { apiConfig, credentialParams };
};
if (dataSourceId) {
credentialParams.datasource_id = dataSourceId;
}

const tryInsertSqlCredentials = async (
dataSourceId?: string,
dataSourceName?: string,
attemptsLeft: number = 5
): Promise<ApiSetupForm | any> => {
if (attemptsLeft === 0) {
return false;
}
return { apiConfig, credentialParams };
},
[currentUser.id]
);

const { apiConfig, credentialParams } = prepareSqlApiData(
dataSourceName,
dataSourceId
);
const res = await execInsertSqlCredentialsMutation({
object: credentialParams,
});
const tryInsertSqlCredentials = useCallback(
async (
dataSourceId?: string,
dataSourceName?: string,
attemptsLeft: number = 5
): Promise<ApiSetupForm | any> => {
if (attemptsLeft === 0) {
return false;
}

const newCredentials = res.data?.insert_sql_credentials_one;
if (res.error || !newCredentials) {
return await tryInsertSqlCredentials(
dataSourceId,
const { apiConfig, credentialParams } = prepareSqlApiData(
dataSourceName,
attemptsLeft - 1
dataSourceId
);
}
const res = await execInsertSqlCredentialsMutation({
object: credentialParams,
});

return apiConfig;
};
const newCredentials = res.data?.insert_sql_credentials_one;
if (res.error || !newCredentials) {
return await tryInsertSqlCredentials(
dataSourceId,
dataSourceName,
attemptsLeft - 1
);
}

DataSourceStore.setState((prev) => ({
...prev,
formState: {
...prev.formState,
step3: { ...apiConfig },
},
}));

return apiConfig;
},
[execInsertSqlCredentialsMutation, prepareSqlApiData]
);

const createOrUpdateDataSource = async (data: DataSourceSetupForm) => {
let dataSourceId;
Expand Down Expand Up @@ -321,10 +338,10 @@ export default ({ editId }: Props) => {
}, [curDataSource, dataSourceSetup?.id, dataSources, editId]);

useEffect(() => {
if (step === 2 && dataSourceSetup?.id && !schema) {
if (step === 2 && curDataSource?.id && !schema) {
execFetchTables();
}
}, [dataSourceSetup?.id, schema, step, execFetchTables]);
}, [curDataSource?.id, schema, step, execFetchTables]);

useEffect(() => {
if (fetchTablesQuery.data) {
Expand All @@ -333,10 +350,13 @@ export default ({ editId }: Props) => {
}, [fetchTablesQuery.data, setSchema]);

useEffect(() => {
if (step === 0) {
clean();
if (step === 3) {
tryInsertSqlCredentials(
curDataSource?.id as string | undefined,
curDataSource?.name as string | undefined
);
}
}, [clean, step]);
}, [curDataSource?.id, curDataSource?.name, step, tryInsertSqlCredentials]);

const loading =
createMutation.fetching ||
Expand Down
7 changes: 0 additions & 7 deletions src/pages/DataSources/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,6 @@ const DataSourcesWrapper = () => {
isGenerate,
setIsGenerate,
setStep,
setIsOnboarding,
clean,
nextStep,
setFormStateData,
Expand Down Expand Up @@ -332,12 +331,6 @@ const DataSourcesWrapper = () => {
await onDataSourceSetupSubmit(data, true, nextStep);
};

useEffect(() => {
if (connect) {
setIsOnboarding(true);
}
}, [connect, setIsOnboarding]);

useEffect(() => {
if (!connect && editId && !generate) {
setStep(1);
Expand Down
7 changes: 5 additions & 2 deletions src/pages/Onboarding/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const Onboarding: React.FC<OnboardingProps> = ({
onDataModelGenerationSubmit = () => {},
}) => {
const responsive = useResponsive();
const { currentUser } = CurrentUserStore();
const { currentUser, teamData } = CurrentUserStore();

const header = (
<Navbar
Expand Down Expand Up @@ -79,6 +79,7 @@ const OnboardingWrapper = () => {
const [, setLocation] = useLocation();
const basePath = ONBOARDING;

const { teamData } = CurrentUserStore();
const step = useMemo(() => parseInt(pageStep || "0", 10) - 1, [pageStep]);

const {
Expand All @@ -91,7 +92,9 @@ const OnboardingWrapper = () => {
} = DataSourceStore();

const { loading, onDataSourceSetupSubmit, onDataModelGenerationSubmit } =
useOnboarding({});
useOnboarding({
editId: teamData?.dataSources?.[0]?.id as string | undefined,
});

const onFinish = () => {
clean();
Expand Down
5 changes: 4 additions & 1 deletion src/stores/DataSourceStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export interface DataSourceState extends DataSourceData {
setIsGenerate: (value: boolean) => void;
setIsOnboarding: (value: boolean) => void;
clean: () => void;
reset: (set: (newValue: DataSourceState) => void) => void;
}

export const defaultFormState = {
Expand Down Expand Up @@ -81,7 +82,9 @@ const dataSourceStore = create<DataSourceState>((set) => ({
...prev,
isOnboarding: value,
})),
clean: () => set({ ...defaultState }),
clean: () =>
set((prev) => ({ ...defaultState, isOnboarding: prev.isOnboarding })),
reset: set as any,
}));

export default dataSourceStore;
Loading