Skip to content

Commit

Permalink
Merge pull request #42 from suvarnakale/release-1.0.0
Browse files Browse the repository at this point in the history
Issue #PS-1254 feat:add learner to system
  • Loading branch information
itsvick authored Jul 24, 2024
2 parents 234364c + 10258cb commit 7eccea4
Show file tree
Hide file tree
Showing 8 changed files with 209 additions and 52 deletions.
3 changes: 2 additions & 1 deletion public/locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@
"YOU_DONT_HAVE_PERMISSION_TO_ACCESS_THIS_PAGE": "You don't have access to this page",
"NEW_LEARNER": "New Learner",
"NEW_FACILITATOR": "New Facilitator",
"SUBMIT": "Submit"
"SUBMIT": "Submit",
"LEARNER_CREATED_SUCCESSFULLY": "Leaner has been Successfully Created!"
},
"LOGIN_PAGE": {
"USERNAME": "Username",
Expand Down
99 changes: 87 additions & 12 deletions src/components/AddLeanerModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import { FormContext, FormContextType } from '@/utils/app.constant';
import SimpleModal from '@/components/SimpleModal';
import { useTranslation } from 'react-i18next';
import { generateUsernameAndPassword } from '@/utils/Helper';
import { RoleId } from '@/utils/app.constant';
import { showToastMessage } from './Toastify';

interface AddLearnerModalProps {
open: boolean;
Expand All @@ -24,17 +26,14 @@ interface AddLearnerModalProps {
const AddLearnerModal: React.FC<AddLearnerModalProps> = ({ open, onClose }) => {
const [schema, setSchema] = React.useState<any>();
const [uiSchema, setUiSchema] = React.useState<any>();
const [credentials, setCredentials] = React.useState({ username: '', password: '' });
const [credentials, setCredentials] = React.useState({
username: '',
password: '',
});
// const [learnerFormData, setLearnerFormData] = React.useState<any>();
const { t } = useTranslation();
const theme = useTheme<any>();

const handleGenerateCredentials = () => {
const stateCode = 'MH';
const newCredentials = generateUsernameAndPassword(stateCode);
setCredentials(newCredentials);
};

useEffect(() => {
const getAddLearnerFormData = async () => {
try {
Expand All @@ -56,7 +55,7 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({ open, onClose }) => {
getAddLearnerFormData();
}, []);

const handleSubmit = (
const handleSubmit = async (
data: IChangeEvent<any, RJSFSchema, any>,
event: React.FormEvent<any>
) => {
Expand All @@ -77,6 +76,80 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({ open, onClose }) => {
}
}
console.log('Form data submitted:', data.formData);

const formData = data.formData;
console.log('Form data submitted:', formData);
const schemaProperties = schema.properties;
let cohortId;
if (typeof window !== 'undefined' && window.localStorage) {
var teacherData = JSON.parse(localStorage.getItem('teacherApp') || '');
cohortId =
localStorage.getItem('cohortId') || localStorage.getItem('classId');
}
const { username, password } = generateUsernameAndPassword(
teacherData?.state?.stateCode,
''
);

let apiBody: any = {
username: username,
password: password,
tenantCohortRoleMapping: [
{
tenantId: 'ef99949b-7f3a-4a5f-806a-e67e683e38f3',
roleId: RoleId.STUDENT,
cohortId: [cohortId],
},
],
customFields: [],
};

Object.entries(formData).forEach(([fieldKey, fieldValue]) => {
const fieldSchema = schemaProperties[fieldKey];
const fieldId = fieldSchema?.fieldId;
console.log(
`FieldID: ${fieldId}, FieldValue: ${fieldValue}, type: ${typeof fieldValue}`
);

if (fieldId === null || fieldId === 'null') {
if (typeof fieldValue !== 'object') {
apiBody[fieldKey] = fieldValue;
}
} else {
if (
fieldSchema?.hasOwnProperty('isDropdown') ||
fieldSchema.hasOwnProperty('isCheckbox')
) {
apiBody.customFields.push({
fieldId: fieldId,
value: [String(fieldValue)],
});
} else {
apiBody.customFields.push({
fieldId: fieldId,
value: String(fieldValue),
});
}
}
});

apiBody.customFields.push({
fieldId: teacherData?.state?.blockId,
value: [teacherData?.state?.blockCode],
});
apiBody.customFields.push({
fieldId: teacherData?.state?.stateId,
value: [teacherData?.state?.stateCode],
});
apiBody.customFields.push({
fieldId: teacherData?.state?.districtId,
value: [teacherData?.state?.districtCode],
});
console.log(apiBody);

const response = await createUser(apiBody);
onClose();
showToastMessage(t('COMMON.LEARNER_CREATED_SUCCESSFULLY'), 'success');
};

const handleChange = (event: IChangeEvent<any>) => {
Expand All @@ -91,7 +164,9 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({ open, onClose }) => {
console.log('Form errors:', errors);
};

const CustomSubmitButton: React.FC<{ onClose: () => void }> = ({ onClose }) => (
const CustomSubmitButton: React.FC<{ onClose: () => void }> = ({
onClose,
}) => (
<div
style={{
marginTop: '16px',
Expand Down Expand Up @@ -145,7 +220,7 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({ open, onClose }) => {
const secondaryActionHandler = async (e: React.FormEvent) => {
// console.log('Secondary action handler clicked');
e.preventDefault();
handleGenerateCredentials();
// handleGenerateCredentials();
// try {
// const response = await createUser(learnerFormData);
// console.log('User created successfully', response);
Expand Down Expand Up @@ -173,8 +248,8 @@ const AddLearnerModal: React.FC<AddLearnerModalProps> = ({ open, onClose }) => {
showErrorList={true}
customFields={customFields}
>
<CustomSubmitButton onClose={primaryActionHandler}/>
</DynamicForm>
{/* <CustomSubmitButton onClose={primaryActionHandler} /> */}
</DynamicForm>
)}
</SimpleModal>
</>
Expand Down
8 changes: 3 additions & 5 deletions src/components/DynamicForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ interface DynamicFormProps {
onSubmit: (
data: IChangeEvent<any, RJSFSchema, any>,
event: React.FormEvent<any>
) => void | undefined;
) => void | Promise<void>;
onChange: (event: IChangeEvent<any>) => void;
onError: (errors: any) => void;
showErrorList: boolean;
Expand All @@ -29,7 +29,7 @@ interface DynamicFormProps {
customFields: {
[key: string]: React.FC<RegistryFieldsType<any, RJSFSchema, any>>;
};
children?: ReactNode
children?: ReactNode;
}
const DynamicForm: React.FC<DynamicFormProps> = ({
schema,
Expand All @@ -39,15 +39,14 @@ const DynamicForm: React.FC<DynamicFormProps> = ({
onChange,
onError,
customFields,
children
children,
}) => {
const widgets = {
MultiSelectCheckboxes: MultiSelectCheckboxes,
CustomRadioWidget: CustomRadioWidget,
};
const { t } = useTranslation();


// console.log('CustomErrorList', CustomErrorList);

const handleError = (errors: any) => {
Expand Down Expand Up @@ -129,7 +128,6 @@ const DynamicForm: React.FC<DynamicFormProps> = ({
onChange(event);
}


return (
<div>
<FormWithMaterialUI
Expand Down
62 changes: 48 additions & 14 deletions src/components/GeneratedSchemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export const GenerateSchemaAndUiSchema = (

const fieldSchema: any = {
title: t(`FORM.${label}`),
fieldId: field.fieldId ?? field.fieldId,
};

const fieldUiSchema: any = {};
Expand All @@ -67,17 +68,19 @@ export const GenerateSchemaAndUiSchema = (
break;
case 'drop_down':
fieldSchema.type = 'string';
fieldSchema.oneOf = options.map((opt: FieldOption) => ({
const: opt.value,
title:
t(`FORM.${opt.label}`) === `FORM.${opt.label}`
? opt.label
: t(`FORM.${opt.label}`),
}));
fieldSchema.isDropdown = true;
// fieldSchema.oneOf = options.map((opt: FieldOption) => ({
// const: opt.value,
// title:
// t(`FORM.${opt.label}`) === `FORM.${opt.label}`
// ? opt.label
// : t(`FORM.${opt.label}`),
// }));
fieldUiSchema['ui:widget'] = 'select';
break;
case 'checkbox':
fieldSchema.type = 'array';
fieldSchema.checkbox = true;
fieldSchema.items = {
type: 'string',
oneOf: options.map((opt: FieldOption) => ({
Expand Down Expand Up @@ -114,19 +117,50 @@ export const GenerateSchemaAndUiSchema = (
// Handle dependencies logic if needed
}

// if (isMultiSelect && type === 'drop_down') {
// fieldSchema.type = 'array';
// fieldSchema.items = {
// type: 'string',
// oneOf: options.map((opt: FieldOption) => ({
// const: opt.value,
// title:
// t(`FORM.${opt.label}`) === `FORM.${opt.label}`
// ? opt.label
// : t(`FORM.${opt.label}`),
// })),
// };
// fieldSchema.uniqueItems = true;
// fieldUiSchema['ui:widget'] = 'select';
// }

if (isMultiSelect && type === 'drop_down') {
fieldSchema.type = 'array';
fieldSchema.items = {
type: 'string',
oneOf: options.map((opt: FieldOption) => ({
const: opt.value,
title:
t(`FORM.${opt.label}`) === `FORM.${opt.label}`
? opt.label
: t(`FORM.${opt.label}`),
})),
enum: options.map((opt: FieldOption) => opt.value),
};
fieldSchema.uniqueItems = true;
fieldSchema.enumNames = options.map((opt: FieldOption) =>
t(`FORM.${opt.label}`) === `FORM.${opt.label}`
? opt.label
: t(`FORM.${opt.label}`)
);
if (maxSelections) {
fieldSchema.maxItems = maxSelections;
}
fieldUiSchema['ui:widget'] = 'select';
}

if (!isMultiSelect && type === 'drop_down') {
fieldSchema.type = 'string';
fieldSchema.isDropdown = true;
fieldSchema.oneOf = options.map((opt: FieldOption) => ({
const: opt.value,
title:
t(`FORM.${opt.label}`) === `FORM.${opt.label}`
? opt.label
: t(`FORM.${opt.label}`),
}));
fieldUiSchema['ui:widget'] = 'select';
}

Expand Down
35 changes: 35 additions & 0 deletions src/pages/centers/[cohortId].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useRouter } from 'next/router';
import { useTheme } from '@mui/material/styles';
import { useTranslation } from 'next-i18next';
import manageUserStore from '@/store/manageUserStore';

const TeachingCenterDetails = () => {
const [value, setValue] = React.useState(1);
Expand All @@ -50,6 +51,26 @@ const TeachingCenterDetails = () => {
const router = useRouter();
const { cohortId }: any = router.query;
const { t } = useTranslation();
const store = manageUserStore();
const setDistrictCode = manageUserStore(
(state: { setDistrictCode: any }) => state.setDistrictCode
);
const setDistrictId = manageUserStore(
(state: { setDistrictId: any }) => state.setDistrictId
);
const setStateCode = manageUserStore(
(state: { setStateCode: any }) => state.setStateCode
);
const setStateId = manageUserStore(
(state: { setStateId: any }) => state.setStateId
);
const setBlockCode = manageUserStore(
(state: { setBlockCode: any }) => state.setBlockCode
);
const setBlockId = manageUserStore(
(state: { setBlockId: any }) => state.setBlockId
);

const [open, setOpen] = React.useState(false);
const theme = useTheme<any>();
const [selectedDate, setSelectedDate] =
Expand Down Expand Up @@ -102,9 +123,23 @@ const TeachingCenterDetails = () => {
const district = cohortData.customField.find(
(item: CustomField) => item.label === 'District'
);
const districtCode = district?.code || '';
setDistrictCode(districtCode);
const districtId = district?.fieldId || '';
// setDistrictId(districtId);
const state = cohortData.customField.find(
(item: CustomField) => item.label === 'State'
);
const stateCode = state?.code || '';
setStateCode(stateCode);
const stateId = state?.fieldId || '';
// setStateId(stateId);

const blockField = cohortData?.customField.find(
(field: any) => field.label === 'Block'
);
setBlockCode(blockField.code);
// setBlockId(blockField.fieldId);

cohortData.address =
`${toPascalCase(district?.value)}, ${toPascalCase(state?.value)}` ||
Expand Down
Loading

0 comments on commit 7eccea4

Please sign in to comment.