From 774f3eae7dd861d4f391e7fe91b78e45e0a4a8e1 Mon Sep 17 00:00:00 2001 From: vivek kasture Date: Sun, 4 Aug 2024 01:06:56 +0530 Subject: [PATCH] Issue #PS-000 fix: Run prettier --- __tests__/ActionCell.test.tsx | 107 +-- __tests__/CardItem.test.tsx | 6 +- __tests__/Helper.test.ts | 776 ++++++++++---------- __tests__/UserNameCell.test.tsx | 4 +- app.config.ts | 2 +- jest.config.ts | 10 +- jest.setup.ts | 2 +- src/components/ActionCell.tsx | 2 +- src/components/ActionIcon.tsx | 4 +- src/components/AddBlockModal.tsx | 2 +- src/components/AddDistrictBlockModal.tsx | 4 +- src/components/AddNewCenters.tsx | 96 ++- src/components/AddStateModal.tsx | 2 +- src/components/AreaSelection.tsx | 10 +- src/components/CommonUserModal.tsx | 241 +++--- src/components/CustomModal.tsx | 3 +- src/components/CustomRadioWidget.tsx | 12 +- src/components/DynamicForm.tsx | 95 ++- src/components/FormControl.tsx | 14 +- src/components/GeneratedSchemas.ts | 4 +- src/components/HeaderComponent.tsx | 12 +- src/components/KaTableComponent.tsx | 26 +- src/components/MultiSelectCheckboxes.tsx | 14 +- src/components/SendCredentialModal.tsx | 72 +- src/components/UserTable.tsx | 143 ++-- src/components/form/NumberInputField.tsx | 38 +- src/components/layouts/header/Profile.tsx | 5 +- src/components/layouts/header/SearchBar.tsx | 2 +- src/components/layouts/sidebar/Sidebar.tsx | 2 +- src/data/tableColumns.ts | 285 ++++--- src/pages/block.tsx | 18 +- src/pages/centers.tsx | 25 +- src/pages/course-planner/foundation.tsx | 14 +- src/pages/csvDetails.tsx | 2 +- src/pages/district.tsx | 10 +- src/pages/faciliator.tsx | 42 +- src/pages/importCsv.tsx | 2 +- src/pages/learners.tsx | 44 +- src/pages/login.tsx | 4 +- src/pages/state.tsx | 6 +- src/pages/stateDetails.tsx | 2 +- src/pages/teamLeader.tsx | 45 +- src/services/CohortService/cohortService.ts | 8 +- src/services/CreateUserService.ts | 54 +- src/services/MasterDataService.ts | 4 +- src/services/RestClient.ts | 2 +- src/services/UserList.ts | 9 +- src/store/manageUserStore.js | 28 +- src/store/store.js | 14 +- src/utils/Helper.ts | 12 +- src/utils/Interfaces.ts | 4 +- src/utils/useLocationState.tsx | 65 +- 52 files changed, 1229 insertions(+), 1180 deletions(-) diff --git a/__tests__/ActionCell.test.tsx b/__tests__/ActionCell.test.tsx index cbe4e451..471fd129 100644 --- a/__tests__/ActionCell.test.tsx +++ b/__tests__/ActionCell.test.tsx @@ -1,28 +1,31 @@ -import ActionCell from '@/components/ActionCell'; -import { Edit as EditIcon, MoreVert as MoreVertIcon } from '@mui/icons-material'; -import { fireEvent, render, screen } from '@testing-library/react'; +import ActionCell from "@/components/ActionCell"; +import { + Edit as EditIcon, + MoreVert as MoreVertIcon, +} from "@mui/icons-material"; +import { fireEvent, render, screen } from "@testing-library/react"; // Mock the translation hook -jest.mock('next-i18next', () => ({ +jest.mock("next-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key, }), })); -describe('ActionCell Component', () => { - const mockRowData = { id: 1, name: 'Sample Row' }; +describe("ActionCell Component", () => { + const mockRowData = { id: 1, name: "Sample Row" }; const mockOnEdit = jest.fn(); const mockOnDelete = jest.fn(); const mockExtraAction = jest.fn(); const extraActions = [ { - name: 'edit', + name: "edit", onClick: mockExtraAction, icon: EditIcon, }, { - name: 'delete', + name: "delete", onClick: mockOnDelete, icon: MoreVertIcon, }, @@ -36,45 +39,45 @@ describe('ActionCell Component', () => { showIcons: true, }; - it('should render without crashing', () => { + it("should render without crashing", () => { render(); - const iconButton = screen.getByRole('button'); + const iconButton = screen.getByRole("button"); expect(iconButton).toBeInTheDocument(); }); - it('should display MoreVertIcon button', () => { + it("should display MoreVertIcon button", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); expect(moreVertIcon).toBeInTheDocument(); }); - it('should open the menu on MoreVertIcon click', () => { + it("should open the menu on MoreVertIcon click", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Open the menu fireEvent.click(moreVertIcon); - const menuItem = screen.getAllByRole('menuitem'); + const menuItem = screen.getAllByRole("menuitem"); expect(menuItem.length).toBe(extraActions.length); }); - it('should display the correct number of actions in the menu', () => { + it("should display the correct number of actions in the menu", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Open the menu fireEvent.click(moreVertIcon); - const menuItems = screen.getAllByRole('menuitem'); + const menuItems = screen.getAllByRole("menuitem"); expect(menuItems).toHaveLength(extraActions.length); }); - it('should call the correct action when a menu item is clicked', () => { + it("should call the correct action when a menu item is clicked", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Open the menu fireEvent.click(moreVertIcon); - const menuItems = screen.getAllByRole('menuitem'); + const menuItems = screen.getAllByRole("menuitem"); // Click the first action fireEvent.click(menuItems[0]); @@ -88,85 +91,85 @@ describe('ActionCell Component', () => { expect(mockOnDelete).toHaveBeenCalledWith(mockRowData); }); - it('should close the menu after an action is clicked', () => { + it("should close the menu after an action is clicked", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Open the menu fireEvent.click(moreVertIcon); - const menuItems = screen.getAllByRole('menuitem'); + const menuItems = screen.getAllByRole("menuitem"); // Click the first action fireEvent.click(menuItems[0]); expect(mockExtraAction).toHaveBeenCalledWith(mockRowData); // Menu should be closed - expect(screen.queryByRole('menuitem')).not.toBeInTheDocument(); + expect(screen.queryByRole("menuitem")).not.toBeInTheDocument(); }); - xit('should not display menu items if extraActions are empty', () => { + xit("should not display menu items if extraActions are empty", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Try to open the menu fireEvent.click(moreVertIcon); - expect(screen.queryByRole('menuitem')).not.toBeInTheDocument(); + expect(screen.queryByRole("menuitem")).not.toBeInTheDocument(); }); - it('should not show icons when showIcons is false', () => { + it("should not show icons when showIcons is false", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Open the menu fireEvent.click(moreVertIcon); - const listItemIcons = screen.queryAllByRole('icon'); + const listItemIcons = screen.queryAllByRole("icon"); expect(listItemIcons).toHaveLength(0); // Icons should not be displayed }); - it('should display translated action names using useTranslation hook', () => { + it("should display translated action names using useTranslation hook", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Open the menu fireEvent.click(moreVertIcon); - const menuItems = screen.getAllByRole('menuitem'); + const menuItems = screen.getAllByRole("menuitem"); // Check the translated action names - expect(menuItems[0]).toHaveTextContent('edit'); - expect(menuItems[1]).toHaveTextContent('delete'); + expect(menuItems[0]).toHaveTextContent("edit"); + expect(menuItems[1]).toHaveTextContent("delete"); }); - xit('should handle no actions gracefully', () => { + xit("should handle no actions gracefully", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); expect(moreVertIcon).toBeInTheDocument(); // Try to open the menu fireEvent.click(moreVertIcon); - expect(screen.queryByRole('menuitem')).not.toBeInTheDocument(); + expect(screen.queryByRole("menuitem")).not.toBeInTheDocument(); }); - it('should display actions without icons when showIcons is false', () => { + it("should display actions without icons when showIcons is false", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Open the menu fireEvent.click(moreVertIcon); - const menuItems = screen.getAllByRole('menuitem'); + const menuItems = screen.getAllByRole("menuitem"); expect(menuItems.length).toBe(extraActions.length); - const icons = screen.queryAllByRole('icon'); + const icons = screen.queryAllByRole("icon"); expect(icons).toHaveLength(0); }); - it('should correctly handle onEdit and onDelete props', () => { + it("should correctly handle onEdit and onDelete props", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Open the menu fireEvent.click(moreVertIcon); - const menuItems = screen.getAllByRole('menuitem'); + const menuItems = screen.getAllByRole("menuitem"); // Click the first action (edit) fireEvent.click(menuItems[0]); @@ -180,27 +183,27 @@ describe('ActionCell Component', () => { expect(mockOnDelete).toHaveBeenCalledWith(mockRowData); }); - it('should display all extra actions', () => { + it("should display all extra actions", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Open the menu fireEvent.click(moreVertIcon); - const menuItems = screen.getAllByRole('menuitem'); + const menuItems = screen.getAllByRole("menuitem"); expect(menuItems).toHaveLength(extraActions.length); }); - xit('should render the correct icon for each action', () => { + xit("should render the correct icon for each action", () => { render(); - const moreVertIcon = screen.getByRole('button'); + const moreVertIcon = screen.getByRole("button"); // Open the menu fireEvent.click(moreVertIcon); // Check for each action icon extraActions.forEach((action) => { - const iconElement = screen.getByTestId(action.name + '-icon'); + const iconElement = screen.getByTestId(action.name + "-icon"); expect(iconElement).toBeInTheDocument(); }); }); diff --git a/__tests__/CardItem.test.tsx b/__tests__/CardItem.test.tsx index 9208b838..4b9f9deb 100644 --- a/__tests__/CardItem.test.tsx +++ b/__tests__/CardItem.test.tsx @@ -54,7 +54,7 @@ describe("CardItem Component", () => { it("should display the correct progress", () => { render(); const progressText = screen.getByText( - `${defaultProps.card.boardsUploaded} / ${defaultProps.card.totalBoards} COURSE_PLANNER.BOARDS_FULLY_UPLOADED` + `${defaultProps.card.boardsUploaded} / ${defaultProps.card.totalBoards} COURSE_PLANNER.BOARDS_FULLY_UPLOADED`, ); expect(progressText).toBeInTheDocument(); }); @@ -62,7 +62,9 @@ describe("CardItem Component", () => { it("should render CustomStepper with the correct completed steps", () => { render(); const stepper = screen.getByTestId("custom-stepper"); - expect(stepper).toHaveTextContent(`Stepper: ${defaultProps.card.boardsUploaded}`); + expect(stepper).toHaveTextContent( + `Stepper: ${defaultProps.card.boardsUploaded}`, + ); }); xit("should call onClick handler when the card is clicked", () => { diff --git a/__tests__/Helper.test.ts b/__tests__/Helper.test.ts index de45edd1..01199baa 100644 --- a/__tests__/Helper.test.ts +++ b/__tests__/Helper.test.ts @@ -1,19 +1,26 @@ -import { capitalizeFirstLetterOfEachWordInArray, fieldTextValidation, firstLetterInUpperCase, generateUsernameAndPassword, transformArray, transformLabel } from '@/utils/Helper'; -import { State } from '@/utils/Interfaces'; -import { Role } from '@/utils/app.constant'; -import '@testing-library/jest-dom'; +import { + capitalizeFirstLetterOfEachWordInArray, + fieldTextValidation, + firstLetterInUpperCase, + generateUsernameAndPassword, + transformArray, + transformLabel, +} from "@/utils/Helper"; +import { State } from "@/utils/Interfaces"; +import { Role } from "@/utils/app.constant"; +import "@testing-library/jest-dom"; -describe('generateUsernameAndPassword', () => { +describe("generateUsernameAndPassword", () => { // Mock Date to control current year const mockDate = new Date(2024, 7, 3); - jest.spyOn(global, 'Date').mockImplementation(() => mockDate); + jest.spyOn(global, "Date").mockImplementation(() => mockDate); afterEach(() => { jest.clearAllMocks(); }); - it('should generate username and password for a valid role and state code', () => { - const stateCode = 'CA'; + it("should generate username and password for a valid role and state code", () => { + const stateCode = "CA"; const role = Role.TEACHER; const result = generateUsernameAndPassword(stateCode, role); @@ -22,10 +29,10 @@ describe('generateUsernameAndPassword', () => { expect(result?.password).toMatch(/^\d{5}$/); // Match 5 random digits }); - it('should return null and log a warning for an invalid role', () => { - const stateCode = 'NY'; - const role = 'INVALID_ROLE'; - const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(); + it("should return null and log a warning for an invalid role", () => { + const stateCode = "NY"; + const role = "INVALID_ROLE"; + const consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(); const result = generateUsernameAndPassword(stateCode, role); @@ -33,32 +40,32 @@ describe('generateUsernameAndPassword', () => { expect(consoleWarnSpy).toHaveBeenCalledWith(`Unknown role: ${role}`); }); - it('should generate a 5-digit random password', () => { - const stateCode = 'TX'; + it("should generate a 5-digit random password", () => { + const stateCode = "TX"; const role = Role.STUDENT; const result = generateUsernameAndPassword(stateCode, role); expect(result?.password).toMatch(/^\d{5}$/); }); - it('should generate username with correct prefix for TEACHER role', () => { - const stateCode = 'FL'; + it("should generate username with correct prefix for TEACHER role", () => { + const stateCode = "FL"; const role = Role.TEACHER; const result = generateUsernameAndPassword(stateCode, role); expect(result?.username).toMatch(/^FSCFL24\d{5}$/); // Match FSC, FL, 24 (year), and 5 random digits }); - it('should generate username with correct prefix for STUDENT role', () => { - const stateCode = 'NV'; + it("should generate username with correct prefix for STUDENT role", () => { + const stateCode = "NV"; const role = Role.STUDENT; const result = generateUsernameAndPassword(stateCode, role); expect(result?.username).toMatch(/^SCNV24\d{5}$/); // Match SC, NV, 24 (year), and 5 random digits }); - it('should generate username with correct prefix for TEAM_LEADER role', () => { - const stateCode = 'OH'; + it("should generate username with correct prefix for TEAM_LEADER role", () => { + const stateCode = "OH"; const role = Role.TEAM_LEADER; const result = generateUsernameAndPassword(stateCode, role); @@ -66,356 +73,381 @@ describe('generateUsernameAndPassword', () => { }); }); +describe("fieldTextValidation", () => { + it("should return true for a valid text containing only alphabets and spaces", () => { + expect(fieldTextValidation("Hello World")).toBe(true); + expect(fieldTextValidation("This is a Test")).toBe(true); + expect(fieldTextValidation("OpenAI ChatGPT")).toBe(true); + }); + + it("should return false for text containing numbers", () => { + expect(fieldTextValidation("Hello123")).toBe(false); + expect(fieldTextValidation("2024")).toBe(false); + expect(fieldTextValidation("Text with 123 numbers")).toBe(false); + }); + + it("should return false for text containing special characters", () => { + expect(fieldTextValidation("Hello@World")).toBe(false); + expect(fieldTextValidation("Test!")).toBe(false); + expect(fieldTextValidation("Hello#")).toBe(false); + }); + + it("should return true for text with mixed case alphabets", () => { + expect(fieldTextValidation("Hello")).toBe(true); + expect(fieldTextValidation("hello")).toBe(true); + expect(fieldTextValidation("HELLO")).toBe(true); + }); + + it("should return true for text with leading and trailing spaces", () => { + expect(fieldTextValidation(" Leading")).toBe(true); + expect(fieldTextValidation("Trailing ")).toBe(true); + expect(fieldTextValidation(" Both ")).toBe(true); + }); + + it("should return false for empty string", () => { + expect(fieldTextValidation("")).toBe(false); + }); + + it("should return true for single space", () => { + expect(fieldTextValidation(" ")).toBe(true); + }); + + it("should return true for multiple spaces", () => { + expect(fieldTextValidation(" ")).toBe(true); + }); + + it("should return true for strings with only alphabetic characters", () => { + expect(fieldTextValidation("abc")).toBe(true); + expect(fieldTextValidation("ABC")).toBe(true); + expect(fieldTextValidation("AbC")).toBe(true); + }); + + it("should return false for strings with underscores or hyphens", () => { + expect(fieldTextValidation("Hello_World")).toBe(false); + expect(fieldTextValidation("Hello-World")).toBe(false); + }); +}); + +describe("capitalizeFirstLetterOfEachWordInArray", () => { + it("should capitalize the first letter of each word in every string of the array", () => { + const input = ["hello world", "this is a test", "openai chatgpt"]; + const expectedOutput = ["Hello World", "This Is A Test", "Openai Chatgpt"]; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); + + it("should handle single word strings", () => { + const input = ["hello", "world"]; + const expectedOutput = ["Hello", "World"]; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); + + it("should handle empty strings within the array", () => { + const input = ["", "hello world", ""]; + const expectedOutput = ["", "Hello World", ""]; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); + + it("should handle arrays with single character words", () => { + const input = ["a b c", "d e f"]; + const expectedOutput = ["A B C", "D E F"]; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); + + it("should handle strings with multiple spaces between words", () => { + const input = ["hello world", "this is a test"]; + const expectedOutput = ["Hello World", "This Is A Test"]; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); + + it("should not affect already capitalized words", () => { + const input = ["Hello World", "Already Capitalized"]; + const expectedOutput = ["Hello World", "Already Capitalized"]; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); + + it("should handle strings with special characters", () => { + const input = ["hello-world", "openai@chatgpt"]; + const expectedOutput = ["Hello-World", "Openai@Chatgpt"]; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); + + it("should handle mixed case words", () => { + const input = ["hElLo WoRlD", "OpEnAi ChAtGpT"]; + const expectedOutput = ["HElLo WoRlD", "OpEnAi ChAtGpT"]; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); + + it("should handle an empty array", () => { + const input: string[] = []; + const expectedOutput: string[] = []; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); + + it("should handle an array with empty strings only", () => { + const input = ["", "", ""]; + const expectedOutput = ["", "", ""]; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); + + it("should handle arrays with non-alphabetic characters", () => { + const input = ["123 abc", "$%^ abc", "123"]; + const expectedOutput = ["123 Abc", "$%^ Abc", "123"]; + expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual( + expectedOutput, + ); + }); +}); + +describe("firstLetterInUpperCase", () => { + it("should capitalize the first letter of each word in a single-word string", () => { + expect(firstLetterInUpperCase("hello")).toBe("Hello"); + expect(firstLetterInUpperCase("world")).toBe("World"); + }); + + it("should capitalize the first letter of each word in a multi-word string", () => { + expect(firstLetterInUpperCase("hello world")).toBe("Hello World"); + expect(firstLetterInUpperCase("this is a test")).toBe("This Is A Test"); + expect(firstLetterInUpperCase("openai chatgpt")).toBe("Openai Chatgpt"); + }); + + it("should return null for an empty string", () => { + expect(firstLetterInUpperCase("")).toBeNull(); + }); + + it("should handle strings with leading and trailing spaces", () => { + expect(firstLetterInUpperCase(" leading")).toBe(" Leading"); + expect(firstLetterInUpperCase("trailing ")).toBe("Trailing "); + expect(firstLetterInUpperCase(" both ")).toBe(" Both "); + }); + + it("should handle strings with multiple spaces between words", () => { + expect(firstLetterInUpperCase("hello world")).toBe("Hello World"); + expect(firstLetterInUpperCase("this is a test")).toBe( + "This Is A Test", + ); + }); + + it("should not affect already capitalized words", () => { + expect(firstLetterInUpperCase("Hello World")).toBe("Hello World"); + expect(firstLetterInUpperCase("Already Capitalized")).toBe( + "Already Capitalized", + ); + }); + + it("should handle mixed case words", () => { + expect(firstLetterInUpperCase("hElLo WoRlD")).toBe("HElLo WoRlD"); + expect(firstLetterInUpperCase("OpEnAi ChAtGpT")).toBe("OpEnAi ChAtGpT"); + }); + + it("should handle single-character words", () => { + expect(firstLetterInUpperCase("a b c")).toBe("A B C"); + expect(firstLetterInUpperCase("x y z")).toBe("X Y Z"); + }); + + it("should return null for a null input", () => { + expect(firstLetterInUpperCase(null as unknown as string)).toBeNull(); + }); -describe('fieldTextValidation', () => { - it('should return true for a valid text containing only alphabets and spaces', () => { - expect(fieldTextValidation('Hello World')).toBe(true); - expect(fieldTextValidation('This is a Test')).toBe(true); - expect(fieldTextValidation('OpenAI ChatGPT')).toBe(true); - }); - - it('should return false for text containing numbers', () => { - expect(fieldTextValidation('Hello123')).toBe(false); - expect(fieldTextValidation('2024')).toBe(false); - expect(fieldTextValidation('Text with 123 numbers')).toBe(false); - }); - - it('should return false for text containing special characters', () => { - expect(fieldTextValidation('Hello@World')).toBe(false); - expect(fieldTextValidation('Test!')).toBe(false); - expect(fieldTextValidation('Hello#')).toBe(false); - }); - - it('should return true for text with mixed case alphabets', () => { - expect(fieldTextValidation('Hello')).toBe(true); - expect(fieldTextValidation('hello')).toBe(true); - expect(fieldTextValidation('HELLO')).toBe(true); - }); - - it('should return true for text with leading and trailing spaces', () => { - expect(fieldTextValidation(' Leading')).toBe(true); - expect(fieldTextValidation('Trailing ')).toBe(true); - expect(fieldTextValidation(' Both ')).toBe(true); - }); - - it('should return false for empty string', () => { - expect(fieldTextValidation('')).toBe(false); - }); - - it('should return true for single space', () => { - expect(fieldTextValidation(' ')).toBe(true); - }); - - it('should return true for multiple spaces', () => { - expect(fieldTextValidation(' ')).toBe(true); - }); - - it('should return true for strings with only alphabetic characters', () => { - expect(fieldTextValidation('abc')).toBe(true); - expect(fieldTextValidation('ABC')).toBe(true); - expect(fieldTextValidation('AbC')).toBe(true); - }); - - it('should return false for strings with underscores or hyphens', () => { - expect(fieldTextValidation('Hello_World')).toBe(false); - expect(fieldTextValidation('Hello-World')).toBe(false); - }); - }); - - describe('capitalizeFirstLetterOfEachWordInArray', () => { - it('should capitalize the first letter of each word in every string of the array', () => { - const input = ['hello world', 'this is a test', 'openai chatgpt']; - const expectedOutput = ['Hello World', 'This Is A Test', 'Openai Chatgpt']; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - - it('should handle single word strings', () => { - const input = ['hello', 'world']; - const expectedOutput = ['Hello', 'World']; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - - it('should handle empty strings within the array', () => { - const input = ['', 'hello world', '']; - const expectedOutput = ['', 'Hello World', '']; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - - it('should handle arrays with single character words', () => { - const input = ['a b c', 'd e f']; - const expectedOutput = ['A B C', 'D E F']; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - - it('should handle strings with multiple spaces between words', () => { - const input = ['hello world', 'this is a test']; - const expectedOutput = ['Hello World', 'This Is A Test']; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - - it('should not affect already capitalized words', () => { - const input = ['Hello World', 'Already Capitalized']; - const expectedOutput = ['Hello World', 'Already Capitalized']; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - - it('should handle strings with special characters', () => { - const input = ['hello-world', 'openai@chatgpt']; - const expectedOutput = ['Hello-World', 'Openai@Chatgpt']; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - - it('should handle mixed case words', () => { - const input = ['hElLo WoRlD', 'OpEnAi ChAtGpT']; - const expectedOutput = ['HElLo WoRlD', 'OpEnAi ChAtGpT']; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - - it('should handle an empty array', () => { - const input: string[] = []; - const expectedOutput: string[] = []; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - - it('should handle an array with empty strings only', () => { - const input = ['', '', '']; - const expectedOutput = ['', '', '']; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - - it('should handle arrays with non-alphabetic characters', () => { - const input = ['123 abc', '$%^ abc', '123']; - const expectedOutput = ['123 Abc', '$%^ Abc', '123']; - expect(capitalizeFirstLetterOfEachWordInArray(input)).toEqual(expectedOutput); - }); - }); - - describe('firstLetterInUpperCase', () => { - it('should capitalize the first letter of each word in a single-word string', () => { - expect(firstLetterInUpperCase('hello')).toBe('Hello'); - expect(firstLetterInUpperCase('world')).toBe('World'); - }); - - it('should capitalize the first letter of each word in a multi-word string', () => { - expect(firstLetterInUpperCase('hello world')).toBe('Hello World'); - expect(firstLetterInUpperCase('this is a test')).toBe('This Is A Test'); - expect(firstLetterInUpperCase('openai chatgpt')).toBe('Openai Chatgpt'); - }); - - it('should return null for an empty string', () => { - expect(firstLetterInUpperCase('')).toBeNull(); - }); - - it('should handle strings with leading and trailing spaces', () => { - expect(firstLetterInUpperCase(' leading')).toBe(' Leading'); - expect(firstLetterInUpperCase('trailing ')).toBe('Trailing '); - expect(firstLetterInUpperCase(' both ')).toBe(' Both '); - }); - - it('should handle strings with multiple spaces between words', () => { - expect(firstLetterInUpperCase('hello world')).toBe('Hello World'); - expect(firstLetterInUpperCase('this is a test')).toBe('This Is A Test'); - }); - - it('should not affect already capitalized words', () => { - expect(firstLetterInUpperCase('Hello World')).toBe('Hello World'); - expect(firstLetterInUpperCase('Already Capitalized')).toBe('Already Capitalized'); - }); - - it('should handle mixed case words', () => { - expect(firstLetterInUpperCase('hElLo WoRlD')).toBe('HElLo WoRlD'); - expect(firstLetterInUpperCase('OpEnAi ChAtGpT')).toBe('OpEnAi ChAtGpT'); - }); - - it('should handle single-character words', () => { - expect(firstLetterInUpperCase('a b c')).toBe('A B C'); - expect(firstLetterInUpperCase('x y z')).toBe('X Y Z'); - }); - - it('should return null for a null input', () => { - expect(firstLetterInUpperCase(null as unknown as string)).toBeNull(); - }); - - it('should handle strings with numbers', () => { - expect(firstLetterInUpperCase('hello 123 world')).toBe('Hello 123 World'); - expect(firstLetterInUpperCase('2024 is a year')).toBe('2024 Is A Year'); - }); - - it('should handle an empty word array', () => { - expect(firstLetterInUpperCase(' ')).toBe(' '); - }); - - it('should handle strings with non-alphabetic characters', () => { - expect(firstLetterInUpperCase('123 abc')).toBe('123 Abc'); - expect(firstLetterInUpperCase('$%^ abc')).toBe('$%^ Abc'); - expect(firstLetterInUpperCase('123')).toBe('123'); - }); - }); - - describe('transformLabel', () => { - it('should transform a label with underscores to capitalized words', () => { - expect(transformLabel('hello_world')).toBe('Hello World'); - expect(transformLabel('this_is_a_test')).toBe('This Is A Test'); - expect(transformLabel('openai_chatgpt')).toBe('Openai Chatgpt'); - }); - - it('should transform a label with mixed casing', () => { - expect(transformLabel('hELLo_wOrLD')).toBe('Hello World'); - expect(transformLabel('tHiS_iS_A_tEsT')).toBe('This Is A Test'); - }); - - it('should handle labels with spaces instead of underscores', () => { - expect(transformLabel('hello world')).toBe('Hello World'); - expect(transformLabel('this is a test')).toBe('This Is A Test'); - }); - - it('should transform a single word label', () => { - expect(transformLabel('hello')).toBe('Hello'); - expect(transformLabel('WORLD')).toBe('World'); - }); - - it('should return an empty string if the label is empty', () => { - expect(transformLabel('')).toBe(''); - }); - - it('should handle labels with numbers', () => { - expect(transformLabel('hello_123_world')).toBe('Hello 123 World'); - expect(transformLabel('2024_is_a_year')).toBe('2024 Is A Year'); - }); - - it('should handle labels with multiple underscores', () => { - expect(transformLabel('hello___world')).toBe('Hello World'); - expect(transformLabel('this__is___a_test')).toBe('This Is A Test'); - }); - - it('should handle labels with leading and trailing underscores', () => { - expect(transformLabel('_hello_world_')).toBe(' Hello World '); - expect(transformLabel('__this_is_a_test__')).toBe(' This Is A Test '); - }); - - it('should handle labels with leading and trailing spaces', () => { - expect(transformLabel(' hello world ')).toBe(' Hello World '); - }); - }); - - describe('transformArray', () => { - it('should transform an array of State objects', () => { - const input: State[] = [ - { value: '1', label: 'hello_world' }, - { value: '2', label: 'this_is_a_test' }, - { value: '3', label: 'openai_chatgpt' }, - ]; - - const expectedOutput: State[] = [ - { value: '1', label: 'Hello World' }, - { value: '2', label: 'This Is A Test' }, - { value: '3', label: 'Openai Chatgpt' }, - ]; - - expect(transformArray(input)).toEqual(expectedOutput); - }); - - it('should handle an empty array', () => { - const input: State[] = []; - const expectedOutput: State[] = []; - - expect(transformArray(input)).toEqual(expectedOutput); - }); - - it('should handle an array with a single State object', () => { - const input: State[] = [{ value: '1', label: 'single_word' }]; - const expectedOutput: State[] = [{ value: '1', label: 'Single Word' }]; - - expect(transformArray(input)).toEqual(expectedOutput); - }); - - it('should handle an array with mixed casing in labels', () => { - const input: State[] = [ - { value: '1', label: 'hELLo_wOrLD' }, - { value: '2', label: 'tHiS_iS_A_tEsT' }, - ]; - - const expectedOutput: State[] = [ - { value: '1', label: 'Hello World' }, - { value: '2', label: 'This Is A Test' }, - ]; - - expect(transformArray(input)).toEqual(expectedOutput); - }); - - it('should handle an array with numbers in labels', () => { - const input: State[] = [ - { value: '1', label: 'hello_123_world' }, - { value: '2', label: '2024_is_a_year' }, - ]; - - const expectedOutput: State[] = [ - { value: '1', label: 'Hello 123 World' }, - { value: '2', label: '2024 Is A Year' }, - ]; - - expect(transformArray(input)).toEqual(expectedOutput); - }); - - it('should handle an array with leading and trailing underscores in labels', () => { - const input: State[] = [ - { value: '1', label: '_hello_world_' }, - { value: '2', label: '__this_is_a_test__' }, - ]; - - const expectedOutput: State[] = [ - { value: '1', label: ' Hello World ' }, - { value: '2', label: ' This Is A Test ' }, - ]; - - expect(transformArray(input)).toEqual(expectedOutput); - }); - - it('should handle an array with leading and trailing spaces in labels', () => { - const input: State[] = [ - { value: '1', label: ' hello world ' }, - { value: '2', label: ' this is a test ' }, - ]; - - const expectedOutput: State[] = [ - { value: '1', label: ' Hello World ' }, - { value: '2', label: ' This Is A Test ' }, - ]; - - expect(transformArray(input)).toEqual(expectedOutput); - }); - - it('should handle arrays with labels containing multiple underscores', () => { - const input: State[] = [ - { value: '1', label: 'hello___world' }, - { value: '2', label: 'this__is___a_test' }, - ]; - - const expectedOutput: State[] = [ - { value: '1', label: 'Hello World' }, - { value: '2', label: 'This Is A Test' }, - ]; - - expect(transformArray(input)).toEqual(expectedOutput); - }); - - it('should return a new array without modifying the original array', () => { - const input: State[] = [ - { value: '1', label: 'hello_world' }, - { value: '2', label: 'this_is_a_test' }, - ]; - - const expectedOutput: State[] = [ - { value: '1', label: 'Hello World' }, - { value: '2', label: 'This Is A Test' }, - ]; - - const result = transformArray(input); - - expect(result).toEqual(expectedOutput); - expect(input).toEqual([ - { value: '1', label: 'hello_world' }, - { value: '2', label: 'this_is_a_test' }, - ]); // Ensure original array is unchanged - }); - }); \ No newline at end of file + it("should handle strings with numbers", () => { + expect(firstLetterInUpperCase("hello 123 world")).toBe("Hello 123 World"); + expect(firstLetterInUpperCase("2024 is a year")).toBe("2024 Is A Year"); + }); + + it("should handle an empty word array", () => { + expect(firstLetterInUpperCase(" ")).toBe(" "); + }); + + it("should handle strings with non-alphabetic characters", () => { + expect(firstLetterInUpperCase("123 abc")).toBe("123 Abc"); + expect(firstLetterInUpperCase("$%^ abc")).toBe("$%^ Abc"); + expect(firstLetterInUpperCase("123")).toBe("123"); + }); +}); + +describe("transformLabel", () => { + it("should transform a label with underscores to capitalized words", () => { + expect(transformLabel("hello_world")).toBe("Hello World"); + expect(transformLabel("this_is_a_test")).toBe("This Is A Test"); + expect(transformLabel("openai_chatgpt")).toBe("Openai Chatgpt"); + }); + + it("should transform a label with mixed casing", () => { + expect(transformLabel("hELLo_wOrLD")).toBe("Hello World"); + expect(transformLabel("tHiS_iS_A_tEsT")).toBe("This Is A Test"); + }); + + it("should handle labels with spaces instead of underscores", () => { + expect(transformLabel("hello world")).toBe("Hello World"); + expect(transformLabel("this is a test")).toBe("This Is A Test"); + }); + + it("should transform a single word label", () => { + expect(transformLabel("hello")).toBe("Hello"); + expect(transformLabel("WORLD")).toBe("World"); + }); + + it("should return an empty string if the label is empty", () => { + expect(transformLabel("")).toBe(""); + }); + + it("should handle labels with numbers", () => { + expect(transformLabel("hello_123_world")).toBe("Hello 123 World"); + expect(transformLabel("2024_is_a_year")).toBe("2024 Is A Year"); + }); + + it("should handle labels with multiple underscores", () => { + expect(transformLabel("hello___world")).toBe("Hello World"); + expect(transformLabel("this__is___a_test")).toBe("This Is A Test"); + }); + + it("should handle labels with leading and trailing underscores", () => { + expect(transformLabel("_hello_world_")).toBe(" Hello World "); + expect(transformLabel("__this_is_a_test__")).toBe(" This Is A Test "); + }); + + it("should handle labels with leading and trailing spaces", () => { + expect(transformLabel(" hello world ")).toBe(" Hello World "); + }); +}); + +describe("transformArray", () => { + it("should transform an array of State objects", () => { + const input: State[] = [ + { value: "1", label: "hello_world" }, + { value: "2", label: "this_is_a_test" }, + { value: "3", label: "openai_chatgpt" }, + ]; + + const expectedOutput: State[] = [ + { value: "1", label: "Hello World" }, + { value: "2", label: "This Is A Test" }, + { value: "3", label: "Openai Chatgpt" }, + ]; + + expect(transformArray(input)).toEqual(expectedOutput); + }); + + it("should handle an empty array", () => { + const input: State[] = []; + const expectedOutput: State[] = []; + + expect(transformArray(input)).toEqual(expectedOutput); + }); + + it("should handle an array with a single State object", () => { + const input: State[] = [{ value: "1", label: "single_word" }]; + const expectedOutput: State[] = [{ value: "1", label: "Single Word" }]; + + expect(transformArray(input)).toEqual(expectedOutput); + }); + + it("should handle an array with mixed casing in labels", () => { + const input: State[] = [ + { value: "1", label: "hELLo_wOrLD" }, + { value: "2", label: "tHiS_iS_A_tEsT" }, + ]; + + const expectedOutput: State[] = [ + { value: "1", label: "Hello World" }, + { value: "2", label: "This Is A Test" }, + ]; + + expect(transformArray(input)).toEqual(expectedOutput); + }); + + it("should handle an array with numbers in labels", () => { + const input: State[] = [ + { value: "1", label: "hello_123_world" }, + { value: "2", label: "2024_is_a_year" }, + ]; + + const expectedOutput: State[] = [ + { value: "1", label: "Hello 123 World" }, + { value: "2", label: "2024 Is A Year" }, + ]; + + expect(transformArray(input)).toEqual(expectedOutput); + }); + + it("should handle an array with leading and trailing underscores in labels", () => { + const input: State[] = [ + { value: "1", label: "_hello_world_" }, + { value: "2", label: "__this_is_a_test__" }, + ]; + + const expectedOutput: State[] = [ + { value: "1", label: " Hello World " }, + { value: "2", label: " This Is A Test " }, + ]; + + expect(transformArray(input)).toEqual(expectedOutput); + }); + + it("should handle an array with leading and trailing spaces in labels", () => { + const input: State[] = [ + { value: "1", label: " hello world " }, + { value: "2", label: " this is a test " }, + ]; + + const expectedOutput: State[] = [ + { value: "1", label: " Hello World " }, + { value: "2", label: " This Is A Test " }, + ]; + + expect(transformArray(input)).toEqual(expectedOutput); + }); + + it("should handle arrays with labels containing multiple underscores", () => { + const input: State[] = [ + { value: "1", label: "hello___world" }, + { value: "2", label: "this__is___a_test" }, + ]; + + const expectedOutput: State[] = [ + { value: "1", label: "Hello World" }, + { value: "2", label: "This Is A Test" }, + ]; + + expect(transformArray(input)).toEqual(expectedOutput); + }); + + it("should return a new array without modifying the original array", () => { + const input: State[] = [ + { value: "1", label: "hello_world" }, + { value: "2", label: "this_is_a_test" }, + ]; + + const expectedOutput: State[] = [ + { value: "1", label: "Hello World" }, + { value: "2", label: "This Is A Test" }, + ]; + + const result = transformArray(input); + + expect(result).toEqual(expectedOutput); + expect(input).toEqual([ + { value: "1", label: "hello_world" }, + { value: "2", label: "this_is_a_test" }, + ]); // Ensure original array is unchanged + }); +}); diff --git a/__tests__/UserNameCell.test.tsx b/__tests__/UserNameCell.test.tsx index c6aef1cd..ad6ca821 100644 --- a/__tests__/UserNameCell.test.tsx +++ b/__tests__/UserNameCell.test.tsx @@ -48,7 +48,7 @@ describe("UserNameCell Component", () => { name .split(" ") .map((word: string) => word.charAt(0).toUpperCase() + word.slice(1)) - .join(" ") + .join(" "), ); render(); @@ -62,7 +62,7 @@ describe("UserNameCell Component", () => { }); it("should display a dash if username is not available", async () => { - mockGetUserName.mockResolvedValueOnce(''); + mockGetUserName.mockResolvedValueOnce(""); render(); diff --git a/app.config.ts b/app.config.ts index b48fe0ee..4ef8bb3f 100644 --- a/app.config.ts +++ b/app.config.ts @@ -1 +1 @@ -export const tenantId = "ef99949b-7f3a-4a5f-806a-e67e683e38f3" \ No newline at end of file +export const tenantId = "ef99949b-7f3a-4a5f-806a-e67e683e38f3"; diff --git a/jest.config.ts b/jest.config.ts index 4b985bfc..2b0cc53c 100644 --- a/jest.config.ts +++ b/jest.config.ts @@ -3,12 +3,12 @@ * https://jestjs.io/docs/configuration */ -import type {Config} from 'jest'; -import nextJest from 'next/jest.js'; +import type { Config } from "jest"; +import nextJest from "next/jest.js"; const createJestConfig = nextJest({ // Provide the path to your Next.js app to load next.config.js and .env files in your test environment - dir: './', + dir: "./", }); const config: Config = { @@ -97,7 +97,7 @@ const config: Config = { // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module moduleNameMapper: { - '^@/(.*)$': '/src/$1', + "^@/(.*)$": "/src/$1", }, // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader @@ -145,7 +145,7 @@ const config: Config = { // setupFiles: [], // A list of paths to modules that run some code to configure or set up the testing framework before each test - setupFilesAfterEnv: ['/jest.setup.ts'], + setupFilesAfterEnv: ["/jest.setup.ts"], // The number of seconds after which a test is considered as slow and reported as such in the results. // slowTestThreshold: 5, diff --git a/jest.setup.ts b/jest.setup.ts index 7b0828bf..d0de870d 100644 --- a/jest.setup.ts +++ b/jest.setup.ts @@ -1 +1 @@ -import '@testing-library/jest-dom'; +import "@testing-library/jest-dom"; diff --git a/src/components/ActionCell.tsx b/src/components/ActionCell.tsx index 521686fd..7944318a 100644 --- a/src/components/ActionCell.tsx +++ b/src/components/ActionCell.tsx @@ -44,7 +44,7 @@ const ActionCell: React.FC = ({ {extraActions?.length > 0 ? ( - + = ({ : "rgb(244, 67, 54)", }} /> - {t("COMMON.DELETE")} + + {t("COMMON.DELETE")} + diff --git a/src/components/AddBlockModal.tsx b/src/components/AddBlockModal.tsx index 94c55caa..a52a0ea3 100644 --- a/src/components/AddBlockModal.tsx +++ b/src/components/AddBlockModal.tsx @@ -20,7 +20,7 @@ interface AddBlockModalProps { value: string, controllingField: string, fieldId: string, - districtId?: string + districtId?: string, ) => void; fieldId: string; initialValues?: { diff --git a/src/components/AddDistrictBlockModal.tsx b/src/components/AddDistrictBlockModal.tsx index f6547c48..941a7c2f 100644 --- a/src/components/AddDistrictBlockModal.tsx +++ b/src/components/AddDistrictBlockModal.tsx @@ -21,7 +21,7 @@ interface AddDistrictBlockModalProps { value: string, controllingField: string, fieldId: string, - districtId?: string + districtId?: string, ) => void; fieldId: string; initialValues?: { @@ -116,7 +116,7 @@ export const AddDistrictBlockModal: React.FC = ({ }; const handleControllingFieldChange = ( - e: React.ChangeEvent + e: React.ChangeEvent, ) => { const inputControllingField = e.target.value; if (fieldTextValidation(inputControllingField)) { diff --git a/src/components/AddNewCenters.tsx b/src/components/AddNewCenters.tsx index 9423c363..d30df335 100644 --- a/src/components/AddNewCenters.tsx +++ b/src/components/AddNewCenters.tsx @@ -4,9 +4,7 @@ import { customFields, } from "@/components/GeneratedSchemas"; import SimpleModal from "@/components/SimpleModal"; -import { - getFormRead, -} from "@/services/CreateUserService"; +import { getFormRead } from "@/services/CreateUserService"; import { CustomField } from "@/utils/Interfaces"; import { CohortTypes } from "@/utils/app.constant"; import { useLocationState } from "@/utils/useLocationState"; @@ -49,7 +47,6 @@ const AddNewCenters: React.FC = ({ const [openAddNewCohort, setOpenAddNewCohort] = React.useState(false); - const { t } = useTranslation(); const { states, @@ -92,7 +89,7 @@ const AddNewCenters: React.FC = ({ const handleSubmit = async ( data: IChangeEvent, - event: React.FormEvent + event: React.FormEvent, ) => { const formData = data?.formData; @@ -144,53 +141,52 @@ const AddNewCenters: React.FC = ({ }; return ( - - + - - - + + - {dynamicFormForBlock && schema && uiSchema && ( - - )} - + {dynamicFormForBlock && schema && uiSchema && ( + + )} + ); }; diff --git a/src/components/AddStateModal.tsx b/src/components/AddStateModal.tsx index f24b66f6..9f1cddbb 100644 --- a/src/components/AddStateModal.tsx +++ b/src/components/AddStateModal.tsx @@ -20,7 +20,7 @@ interface AddStateModalProps { name: string, value: string, fieldId: string, - stateId?: string + stateId?: string, ) => void; fieldId: string; initialValues?: { diff --git a/src/components/AreaSelection.tsx b/src/components/AreaSelection.tsx index bbf01d4c..f0163a10 100644 --- a/src/components/AreaSelection.tsx +++ b/src/components/AreaSelection.tsx @@ -32,19 +32,19 @@ interface DropdownBoxProps { selectedCenter?: any; handleStateChangeWrapper: ( selectedNames: string[], - selectedCodes: string[] + selectedCodes: string[], ) => Promise; handleDistrictChangeWrapper: ( selected: string[], - selectedCodes: string[] + selectedCodes: string[], ) => Promise; handleBlockChangeWrapper: ( selected: string[], - selectedCodes: string[] + selectedCodes: string[], ) => void; handleCenterChangeWrapper?: ( selected: string[], - selectedCodes: string[] + selectedCodes: string[], ) => void; isMobile: boolean; @@ -89,7 +89,7 @@ const AreaSelection: React.FC = ({ names={states?.map( (state) => state.label?.toLowerCase().charAt(0).toUpperCase() + - state.label?.toLowerCase().slice(1) + state.label?.toLowerCase().slice(1), )} codes={states?.map((state) => state.value)} tagName={t("FACILITATORS.STATE")} diff --git a/src/components/CommonUserModal.tsx b/src/components/CommonUserModal.tsx index 4764cc39..07f17597 100644 --- a/src/components/CommonUserModal.tsx +++ b/src/components/CommonUserModal.tsx @@ -2,7 +2,13 @@ import React, { useState, useEffect } from "react"; import { useTranslation } from "next-i18next"; import { IChangeEvent } from "@rjsf/core"; import { RJSFSchema } from "@rjsf/utils"; -import { Typography, useMediaQuery , Box, Button, useTheme} from "@mui/material"; +import { + Typography, + useMediaQuery, + Box, + Button, + useTheme, +} from "@mui/material"; import { GenerateSchemaAndUiSchema, customFields, @@ -18,17 +24,13 @@ import { } from "@/services/CreateUserService"; import { generateUsernameAndPassword } from "@/utils/Helper"; import { FormData } from "@/utils/Interfaces"; -import { RoleId ,Role} from "@/utils/app.constant"; +import { RoleId, Role } from "@/utils/app.constant"; import AreaSelection from "./AreaSelection"; import { showToastMessage } from "./Toastify"; import { transformArray } from "../utils/Helper"; import { useLocationState } from "@/utils/useLocationState"; import { tenantId } from "../../app.config"; - - - - interface UserModalProps { open: boolean; onClose: () => void; @@ -36,7 +38,7 @@ interface UserModalProps { isEditModal?: boolean; userId?: string; onSubmit: (submitValue: boolean) => void; - userType:string + userType: string; } const CommonUserModal: React.FC = ({ @@ -46,16 +48,26 @@ const CommonUserModal: React.FC = ({ isEditModal = false, userId, onSubmit, - userType + userType, }) => { - console.log(userType) + console.log(userType); const [schema, setSchema] = React.useState(); const [uiSchema, setUiSchema] = React.useState(); const { t } = useTranslation(); const [formValue, setFormValue] = useState(); - const modalTitle=!isEditModal? userType === FormContextType.STUDENT?t("LEARNERS.NEW_LEARNER"):userType === FormContextType.TEACHER?t("FACILITATORS.NEW_FACILITATOR"):t("TEAM_LEADERS.NEW_TEAM_LEADER"): userType === FormContextType.STUDENT?t("LEARNERS.EDIT_LEARNER"):userType === FormContextType.TEACHER?t("FACILITATORS.EDIT_FACILITATOR"):t("TEAM_LEADERS.EDIT_TEAM_LEADER") + const modalTitle = !isEditModal + ? userType === FormContextType.STUDENT + ? t("LEARNERS.NEW_LEARNER") + : userType === FormContextType.TEACHER + ? t("FACILITATORS.NEW_FACILITATOR") + : t("TEAM_LEADERS.NEW_TEAM_LEADER") + : userType === FormContextType.STUDENT + ? t("LEARNERS.EDIT_LEARNER") + : userType === FormContextType.TEACHER + ? t("FACILITATORS.EDIT_FACILITATOR") + : t("TEAM_LEADERS.EDIT_TEAM_LEADER"); const theme = useTheme(); - const { + const { states, districts, blocks, @@ -74,49 +86,56 @@ const CommonUserModal: React.FC = ({ handleDistrictChangeWrapper, handleBlockChangeWrapper, handleCenterChangeWrapper, - selectedCenterCode, selectedBlockCohortId, blockFieldId, distrctFieldId, stateFieldId, dynamicFormForBlock - + selectedCenterCode, + selectedBlockCohortId, + blockFieldId, + distrctFieldId, + stateFieldId, + dynamicFormForBlock, } = useLocationState(open, onClose); useEffect(() => { const getAddUserFormData = async () => { try { - const response: FormData = await getFormRead( FormContext.USERS, - userType ); - + userType, + ); + console.log("sortedFields", response); if (response) { - if(userType=== FormContextType.TEACHER ) - { - const newResponse={ + if (userType === FormContextType.TEACHER) { + const newResponse = { ...response, - fields: response.fields.filter(field => field.name !== 'no_of_clusters') - } - const { schema, uiSchema, formValues } = GenerateSchemaAndUiSchema(newResponse, t); - setFormValue(formValues) - setSchema(schema); - setUiSchema(uiSchema); - } - else if(userType=== FormContextType.TEAM_LEADER) - { - const { schema, uiSchema, formValues } = GenerateSchemaAndUiSchema(response, t); - setFormValue(formValues) + fields: response.fields.filter( + (field) => field.name !== "no_of_clusters", + ), + }; + const { schema, uiSchema, formValues } = GenerateSchemaAndUiSchema( + newResponse, + t, + ); + setFormValue(formValues); + setSchema(schema); + setUiSchema(uiSchema); + } else if (userType === FormContextType.TEAM_LEADER) { + const { schema, uiSchema, formValues } = GenerateSchemaAndUiSchema( + response, + t, + ); + setFormValue(formValues); + setSchema(schema); + console.log(schema); + setUiSchema(uiSchema); + } else { + console.log("true"); + const { schema, uiSchema } = GenerateSchemaAndUiSchema(response, t); setSchema(schema); console.log(schema); setUiSchema(uiSchema); - } - else { - console.log("true") - const { schema, uiSchema } = GenerateSchemaAndUiSchema(response, t); - setSchema(schema); - console.log(schema); - setUiSchema(uiSchema); } } - } catch (error) { console.error("Error fetching form data:", error); } @@ -126,11 +145,11 @@ const CommonUserModal: React.FC = ({ const handleSubmit = async ( data: IChangeEvent, - event: React.FormEvent + event: React.FormEvent, ) => { // setOpenModal(true); const target = event.target as HTMLFormElement; - // const elementsArray = Array.from(target.elements); + // const elementsArray = Array.from(target.elements); console.log("onsubmit", data); // for (const element of elementsArray) { @@ -150,10 +169,10 @@ const CommonUserModal: React.FC = ({ const formData = data.formData; console.log("Form data submitted:", formData); const schemaProperties = schema.properties; - + const { username, password } = generateUsernameAndPassword( selectedStateCode, - userType + userType, ); let apiBody: any = { @@ -162,8 +181,16 @@ const CommonUserModal: React.FC = ({ tenantCohortRoleMapping: [ { tenantId: tenantId, - roleId:userType===FormContextType.STUDENT? RoleId.STUDENT: userType===FormContextType.TEACHER?RoleId.TEACHER:RoleId.TEAM_LEADER, - cohortId:userType===FormContextType.TEAM_LEADER ?[selectedBlockCohortId] :[selectedCenterCode], + roleId: + userType === FormContextType.STUDENT + ? RoleId.STUDENT + : userType === FormContextType.TEACHER + ? RoleId.TEACHER + : RoleId.TEAM_LEADER, + cohortId: + userType === FormContextType.TEAM_LEADER + ? [selectedBlockCohortId] + : [selectedCenterCode], }, ], customFields: [], @@ -173,7 +200,7 @@ const CommonUserModal: React.FC = ({ const fieldSchema = schemaProperties[fieldKey]; const fieldId = fieldSchema?.fieldId; console.log( - `FieldID: ${fieldId}, FieldValue: ${fieldSchema}, type: ${typeof fieldValue}` + `FieldID: ${fieldId}, FieldValue: ${fieldSchema}, type: ${typeof fieldValue}`, ); if (fieldId === null || fieldId === "null") { @@ -181,7 +208,6 @@ const CommonUserModal: React.FC = ({ apiBody[fieldKey] = fieldValue; } } else { - if ( fieldSchema?.hasOwnProperty("isDropdown") || fieldSchema?.hasOwnProperty("isCheckbox") @@ -191,21 +217,17 @@ const CommonUserModal: React.FC = ({ value: [String(fieldValue)], }); } else { - if(fieldSchema.checkbox &&fieldSchema.type==="array") - { + if (fieldSchema.checkbox && fieldSchema.type === "array") { apiBody.customFields.push({ fieldId: fieldId, - value: String(fieldValue).split(',') + value: String(fieldValue).split(","), }); - } - - else{ apiBody.customFields.push({ - fieldId: fieldId, - value: String(fieldValue), - }); - } - - + } else { + apiBody.customFields.push({ + fieldId: fieldId, + value: String(fieldValue), + }); + } } } }); @@ -239,22 +261,24 @@ const CommonUserModal: React.FC = ({ customFields: customFields, }; const response = await updateUser(userId, object); - const messageKey = userType === FormContextType.STUDENT - ? "LEARNERS.LEARNER_UPDATED_SUCCESSFULLY" - : userType === FormContextType.TEACHER - ? "FACILITATORS.FACILITATOR_UPDATED_SUCCESSFULLY" - : "TEAM_LEADERS.TEAM_LEADER_UPDATED_SUCCESSFULLY"; - - showToastMessage(t(messageKey), "success"); + const messageKey = + userType === FormContextType.STUDENT + ? "LEARNERS.LEARNER_UPDATED_SUCCESSFULLY" + : userType === FormContextType.TEACHER + ? "FACILITATORS.FACILITATOR_UPDATED_SUCCESSFULLY" + : "TEAM_LEADERS.TEAM_LEADER_UPDATED_SUCCESSFULLY"; + + showToastMessage(t(messageKey), "success"); } else { const response = await createUser(apiBody); - const messageKey = userType === FormContextType.STUDENT - ? "LEARNERS.LEARNER_CREATED_SUCCESSFULLY" - : userType === FormContextType.TEACHER - ? "FACILITATORS.FACILITATOR_CREATED_SUCCESSFULLY" - : "TEAM_LEADERS.TEAM_LEADER_CREATED_SUCCESSFULLY"; + const messageKey = + userType === FormContextType.STUDENT + ? "LEARNERS.LEARNER_CREATED_SUCCESSFULLY" + : userType === FormContextType.TEACHER + ? "FACILITATORS.FACILITATOR_CREATED_SUCCESSFULLY" + : "TEAM_LEADERS.TEAM_LEADER_CREATED_SUCCESSFULLY"; -showToastMessage(t(messageKey), "success"); + showToastMessage(t(messageKey), "success"); } onSubmit(true); onClose(); @@ -376,7 +400,7 @@ showToastMessage(t(messageKey), "success"); handleBlockChangeWrapper={handleBlockChangeWrapper} isMobile={isMobile} isMediumScreen={isMediumScreen} - isCenterSelection={userType!=="TEAM LEADER"?true: false} + isCenterSelection={userType !== "TEAM LEADER" ? true : false} allCenters={allCenters} selectedCenter={selectedCenter} handleCenterChangeWrapper={handleCenterChangeWrapper} @@ -401,44 +425,41 @@ showToastMessage(t(messageKey), "success"); {/* */} ) - :userType==="TEAM LEADER"? - dynamicFormForBlock && - schema && - uiSchema && ( - - {/* */} - ) - - - : (dynamicForm && - schema && - uiSchema && ( - - {/* */} - - ))} + : userType === "TEAM LEADER" + ? dynamicFormForBlock && + schema && + uiSchema && ( + + {/* */} + + ) + : dynamicForm && + schema && + uiSchema && ( + + {/* */} + + )} ); diff --git a/src/components/CustomModal.tsx b/src/components/CustomModal.tsx index e827d730..bb554afa 100644 --- a/src/components/CustomModal.tsx +++ b/src/components/CustomModal.tsx @@ -41,7 +41,7 @@ const CustomModal: React.FC = ({ children, }) => { const isSmallScreen = useMediaQuery((theme: Theme) => - theme.breakpoints.down("sm") + theme.breakpoints.down("sm"), ); return ( @@ -87,7 +87,6 @@ const CustomModal: React.FC = ({ {children} - {secondaryBtnText && ( @@ -108,4 +108,4 @@ const SendCredentialModal: React.FC = ({ ); }; -export default SendCredentialModal; \ No newline at end of file +export default SendCredentialModal; diff --git a/src/components/UserTable.tsx b/src/components/UserTable.tsx index 2fb17bb3..0e8cfa29 100644 --- a/src/components/UserTable.tsx +++ b/src/components/UserTable.tsx @@ -23,9 +23,9 @@ import { Role } from "@/utils/app.constant"; import { getFormRead } from "@/services/CreateUserService"; import { showToastMessage } from "./Toastify"; import { capitalizeFirstLetterOfEachWordInArray } from "../utils/Helper"; -import { getUserTableColumns,getTLTableColumns } from "@/data/tableColumns"; -import { useMediaQuery } from '@mui/material'; -import { Theme } from '@mui/system'; +import { getUserTableColumns, getTLTableColumns } from "@/data/tableColumns"; +import { useMediaQuery } from "@mui/material"; +import { Theme } from "@mui/system"; import CommonUserModal from "./CommonUserModal"; type UserDetails = { userId: any; @@ -60,19 +60,17 @@ interface UserTableProps { userType: string; searchPlaceholder: string; handleAddUserClick: any; - parentState?:boolean + parentState?: boolean; } - - const UserTable: React.FC = ({ role, userType, searchPlaceholder, handleAddUserClick, - parentState + parentState, }) => { - console.log(userType) + console.log(userType); const [selectedState, setSelectedState] = React.useState([]); const [selectedStateCode, setSelectedStateCode] = useState(""); const [selectedDistrict, setSelectedDistrict] = React.useState([]); @@ -93,9 +91,10 @@ const UserTable: React.FC = ({ const [selectedUserId, setSelectedUserId] = useState(""); const [selectedReason, setSelectedReason] = useState(""); const [otherReason, setOtherReason] = useState(""); - const isMobile = useMediaQuery((theme: Theme) => theme.breakpoints.down('sm')); - // const isMobile = useMediaQuery("(max-width:600px)"); - + const isMobile = useMediaQuery((theme: Theme) => + theme.breakpoints.down("sm"), + ); + // const isMobile = useMediaQuery("(max-width:600px)"); const [confirmButtonDisable, setConfirmButtonDisable] = useState(false); const [pagination, setPagination] = useState(true); @@ -112,7 +111,6 @@ const UserTable: React.FC = ({ }; const handleModalSubmit = (value: boolean) => { setSubmitValue(true); - }; const handleCloseAddLearnerModal = () => { setOpenAddLearnerModal(false); @@ -130,19 +128,15 @@ const UserTable: React.FC = ({ setOpenAddFacilitatorModal(false); }; - - - const [openAddTeamLeaderModal, setOpenAddTeamLeaderModal] = - React.useState(false); -const handleOpenAddTeamLeaderModal = () => { - setOpenAddTeamLeaderModal(true); -}; - -const handleCloseAddTeamLeaderModal = () => { - setOpenAddTeamLeaderModal(false); -}; - + const [openAddTeamLeaderModal, setOpenAddTeamLeaderModal] = + React.useState(false); + const handleOpenAddTeamLeaderModal = () => { + setOpenAddTeamLeaderModal(true); + }; + const handleCloseAddTeamLeaderModal = () => { + setOpenAddTeamLeaderModal(false); + }; const [filters, setFilters] = useState({ role: role, @@ -155,7 +149,7 @@ const handleCloseAddTeamLeaderModal = () => { const handlePaginationChange = ( event: React.ChangeEvent, - value: number + value: number, ) => { setPageOffset(value - 1); }; @@ -189,7 +183,11 @@ const handleCloseAddTeamLeaderModal = () => { const stateCodes = code?.join(","); setSelectedStateCode(stateCodes); if (filters.status) - setFilters({ status: [filters.status], states: stateCodes, role: role }); + setFilters({ + status: [filters.status], + states: stateCodes, + role: role, + }); else setFilters({ states: stateCodes, role: role }); } @@ -313,11 +311,11 @@ const handleCloseAddTeamLeaderModal = () => { formFields.fields.forEach((item: any) => { const userData = response?.userData; const customFieldValue = userData?.customFields?.find( - (field: any) => field.fieldId === item.fieldId + (field: any) => field.fieldId === item.fieldId, ); const getValue = (data: any, field: any) => { - console.log(data, field) + console.log(data, field); if (item.default) { return item.default; } @@ -331,19 +329,15 @@ const handleCloseAddTeamLeaderModal = () => { } } else { if (item?.type === "numeric") { - return parseInt(String(field?.value)); } else if (item?.type === "text") { return String(field?.value); - } - - else { - if(field?.value ==='FEMALE' || field?.value ==='MALE') - { - console.log(true) + } else { + if (field?.value === "FEMALE" || field?.value === "MALE") { + console.log(true); return field?.value?.toLowerCase(); } - // console.log() + // console.log() return field?.value?.toLowerCase(); } } @@ -353,11 +347,9 @@ const handleCloseAddTeamLeaderModal = () => { if (item?.isMultiSelect) { if (userData[item.name] && item?.maxSelections > 1) { initialFormData[item.name] = [userData[item.name]]; - } - else if (item?.type === "checkbox") { - initialFormData[item.name]= String(userData[item.name]).split(","); - } - else { + } else if (item?.type === "checkbox") { + initialFormData[item.name] = String(userData[item.name]).split(","); + } else { initialFormData[item.name] = userData[item.name]; } } else if (item?.type === "numeric") { @@ -365,8 +357,7 @@ const handleCloseAddTeamLeaderModal = () => { initialFormData[item.name] = Number(userData[item.name]); } else if (item?.type === "text" && userData[item.name]) { initialFormData[item.name] = String(userData[item.name]); - } - else { + } else { console.log(item.name); if (userData[item.name]) { initialFormData[item.name] = userData[item.name]; @@ -402,12 +393,11 @@ const handleCloseAddTeamLeaderModal = () => { } else if (Role.TEACHER === role) { formFields = await getFormRead("USERS", "TEACHER"); setFormData(mapFields(formFields, response)); - // handleOpenAddFacilitatorModal(); - } - else if (Role.TEAM_LEADER === role) { + // handleOpenAddFacilitatorModal(); + } else if (Role.TEAM_LEADER === role) { formFields = await getFormRead("USERS", "TEAM LEADER"); setFormData(mapFields(formFields, response)); - // handleOpenAddTeamLeaderModal(); + // handleOpenAddTeamLeaderModal(); } handleOpenAddLearnerModal(); @@ -465,25 +455,25 @@ const handleCloseAddTeamLeaderModal = () => { console.log(result); const finalResult = result?.map((user: any) => { const ageField = user.customFields.find( - (field: any) => field.name === "age" + (field: any) => field.name === "age", ); const genderField = user.customFields.find( - (field: any) => field.name=== "gender" + (field: any) => field.name === "gender", ); const blockField = user.customFields.find( - (field: any) => field.name === "blocks" + (field: any) => field.name === "blocks", ); const districtField = user.customFields.find( - (field: any) => field.name === "districts" + (field: any) => field.name === "districts", ); const stateField = user.customFields.find( - (field: any) => field.name === "states" + (field: any) => field.name === "states", ); return { userId: user.userId, username: user.username, - status:user.status, + status: user.status, name: user.name.charAt(0).toUpperCase() + user.name.slice(1).toLowerCase(), @@ -494,7 +484,10 @@ const handleCloseAddTeamLeaderModal = () => { district: districtField ? districtField.value : null, state: stateField ? stateField.value : null, blocks: blockField ? blockField.value : null, - gender: genderField ? genderField.value?.charAt(0)?.toUpperCase() + genderField.value.slice(1).toLowerCase() : null, + gender: genderField + ? genderField.value?.charAt(0)?.toUpperCase() + + genderField.value.slice(1).toLowerCase() + : null, // centers: null, // Programs: null, }; @@ -514,7 +507,15 @@ const handleCloseAddTeamLeaderModal = () => { } }; fetchUserList(); - }, [pageOffset,submitValue, pageLimit, sortBy, filters, openAddFacilitatorModal, openAddTeamLeaderModal]); + }, [ + pageOffset, + submitValue, + pageLimit, + sortBy, + filters, + openAddFacilitatorModal, + openAddTeamLeaderModal, + ]); useEffect(() => { const fetchData = async () => { @@ -526,20 +527,19 @@ const handleCloseAddTeamLeaderModal = () => { data?.map(async (user) => { const response = await getCohortList(user.userId); const cohortNames = response?.result?.cohortData?.map( - (cohort: Cohort) => cohort.name + (cohort: Cohort) => cohort.name, ); let finalArray; - if(cohortNames?.length>=1) - { - finalArray=capitalizeFirstLetterOfEachWordInArray(cohortNames) + if (cohortNames?.length >= 1) { + finalArray = capitalizeFirstLetterOfEachWordInArray(cohortNames); } - // const finalArray=capitalizeFirstLetterOfEachWordInArray(cohortNames) + // const finalArray=capitalizeFirstLetterOfEachWordInArray(cohortNames) // console.log(finalArray) return { ...user, centers: finalArray?.join(" , "), }; - }) + }), ); setData(newData); setCohortsFetched(true); @@ -605,7 +605,11 @@ const handleCloseAddTeamLeaderModal = () => { ) : data.length !== 0 && loading === false ? ( { confirmButtonDisable={confirmButtonDisable} setConfirmButtonDisable={setConfirmButtonDisable} /> - - - ); }; - export default UserTable; diff --git a/src/components/form/NumberInputField.tsx b/src/components/form/NumberInputField.tsx index 59467dc0..f7053bfa 100644 --- a/src/components/form/NumberInputField.tsx +++ b/src/components/form/NumberInputField.tsx @@ -1,6 +1,5 @@ -import { TextField, useTheme } from '@mui/material'; -import React, { useState } from 'react'; - +import { TextField, useTheme } from "@mui/material"; +import React, { useState } from "react"; const NumberInputField = (props: any) => { const theme = useTheme(); @@ -8,14 +7,17 @@ const NumberInputField = (props: any) => { const [error, setError] = useState(""); - console.log('NumberInputField', props); + console.log("NumberInputField", props); const handleChange = (event: any) => { const value = event.target.value; - const regex = props?.schema?.maxLength ? new RegExp(`^\\d{0,${props.schema.maxLength}}$`) : /^\d*$/; + const regex = props?.schema?.maxLength + ? new RegExp(`^\\d{0,${props.schema.maxLength}}$`) + : /^\d*$/; - if (regex.test(value)) { // Allow only up to 10 digits - if (props?.schema?.maxLength ) { + if (regex.test(value)) { + // Allow only up to 10 digits + if (props?.schema?.maxLength) { if (value.length === props.schema.maxLength) { setError(""); // Clear any existing error onChange(Number(value)); @@ -34,18 +36,18 @@ const NumberInputField = (props: any) => { // onChange={handleChange} // /> <> - -

{error}

- +

{error}

+ ); }; diff --git a/src/components/layouts/header/Profile.tsx b/src/components/layouts/header/Profile.tsx index 443e3bbd..df93f138 100644 --- a/src/components/layouts/header/Profile.tsx +++ b/src/components/layouts/header/Profile.tsx @@ -82,7 +82,10 @@ const Profile = () => { whiteSpace: "nowrap", }} > - {userName ? userName.charAt(0).toUpperCase() +userName.slice(1).toLowerCase() : ""} + {userName + ? userName.charAt(0).toUpperCase() + + userName.slice(1).toLowerCase() + : ""} diff --git a/src/components/layouts/header/SearchBar.tsx b/src/components/layouts/header/SearchBar.tsx index 3109dc39..92228c0f 100644 --- a/src/components/layouts/header/SearchBar.tsx +++ b/src/components/layouts/header/SearchBar.tsx @@ -30,7 +30,7 @@ const SearchBar: React.FC = ({ onSearch, placeholder }) => { const [keyword, setKeyword] = useState(""); const { t } = useTranslation(); const isSmallScreen = useMediaQuery((theme: any) => - theme.breakpoints.down("sm") + theme.breakpoints.down("sm"), ); const handleInputChange = (event: React.ChangeEvent) => { diff --git a/src/components/layouts/sidebar/Sidebar.tsx b/src/components/layouts/sidebar/Sidebar.tsx index 5a7f122b..3c1ef003 100644 --- a/src/components/layouts/sidebar/Sidebar.tsx +++ b/src/components/layouts/sidebar/Sidebar.tsx @@ -112,7 +112,7 @@ const Sidebar = ({ selected={location === subItem.href} sx={{ pl: 8, - ml:2, + ml: 2, mb: 1, ...(location === subItem.href && { color: "black", diff --git a/src/data/tableColumns.ts b/src/data/tableColumns.ts index 4e5b88b5..e1c44e34 100644 --- a/src/data/tableColumns.ts +++ b/src/data/tableColumns.ts @@ -1,184 +1,176 @@ import { DataType, SortDirection } from "ka-table"; export const getUserTableColumns = (t: any, isMobile: any) => { + return [ + { + key: "name", + title: t("FORM.NAME"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + width: isMobile ? 160 : null, + }, + { + key: "status", + title: t("FORM.STATUS"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + width: isMobile ? 160 : null, + }, - return [ - { - key: "name", - title: t("FORM.NAME"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - width:isMobile?160:null, + { + key: "age", + title: t("FORM.AGE"), + dataType: DataType.String, + width: isMobile ? 160 : null, + }, + { + key: "gender", + title: t("FORM.GENDER"), + dataType: DataType.String, + width: isMobile ? 160 : null, + }, + { + key: "mobile", + title: t("FORM.MOBILE_NUMBER"), + dataType: DataType.String, + width: isMobile ? 160 : null, + }, + { + key: "state", + title: t("FORM.STATE"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + width: isMobile ? 160 : null, + }, + { + key: "district", + title: t("FORM.DISTRICT"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + width: isMobile ? 160 : null, + }, - }, - { - key: "status", - title: t("FORM.STATUS"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - width:isMobile?160:null, - }, - - - { - key: "age", - title: t("FORM.AGE"), - dataType: DataType.String, - width:isMobile?160:null, - }, - { - key: "gender", - title: t("FORM.GENDER"), - dataType: DataType.String, - width:isMobile?160:null, - }, - { - key: "mobile", - title: t("FORM.MOBILE_NUMBER"), - dataType: DataType.String, - width:isMobile?160:null, - }, - { - key: "state", - title: t("FORM.STATE"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - width:isMobile?160:null, - }, - { - key: "district", - title:t("FORM.DISTRICT"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - width: isMobile?160:null, - }, - - { - key: "blocks", - title: t("FORM.BLOCK"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - width:isMobile?160:null, - }, - { - key: "centers", - title: t("FORM.CENTER"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - width: isMobile?160:null, - }, - { - key: "actions", - title: t("FORM.ACTION"), - dataType: DataType.String, - width: isMobile?160:null, - }, - ]; -} + { + key: "blocks", + title: t("FORM.BLOCK"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + width: isMobile ? 160 : null, + }, + { + key: "centers", + title: t("FORM.CENTER"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + width: isMobile ? 160 : null, + }, + { + key: "actions", + title: t("FORM.ACTION"), + dataType: DataType.String, + width: isMobile ? 160 : null, + }, + ]; +}; +export const getTLTableColumns = (t: any, isMobile: any) => { + return [ + { + key: "name", + title: t("FORM.NAME"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + // width: isMobile?160:null, + }, + { + key: "status", + title: t("FORM.STATUS"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + // width: isMobile?160:null, + }, -export const getTLTableColumns = (t: any, isMobile:any) => { - return[ - - { - key: "name", - title: t("FORM.NAME"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - // width: isMobile?160:null, + { + key: "age", + title: t("FORM.AGE"), + dataType: DataType.String, + // width: isMobile?160:null, + }, + { + key: "gender", + title: t("FORM.GENDER"), + dataType: DataType.String, + // width: isMobile?160:null, + }, - }, - { - key: "status", - title: t("FORM.STATUS"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - // width: isMobile?160:null, - }, - - - { - key: "age", - title: t("FORM.AGE"), - dataType: DataType.String, - // width: isMobile?160:null, - }, - { - key: "gender", - title: t("FORM.GENDER"), - dataType: DataType.String, - // width: isMobile?160:null, - }, - - { - key: "state", - title: t("FORM.STATE"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - // width: isMobile?160:null, - }, - { - key: "district", - title:t("FORM.DISTRICT"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - // width: isMobile?160:null, - }, - - { - key: "blocks", - title: t("FORM.BLOCK"), - dataType: DataType.String, - sortDirection: SortDirection.Ascend, - // width: isMobile?160:null, - }, - - { - key: "actions", - title: t("FORM.ACTION"), - dataType: DataType.String, - // width: isMobile?160:null, - }, - ]; -} + { + key: "state", + title: t("FORM.STATE"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + // width: isMobile?160:null, + }, + { + key: "district", + title: t("FORM.DISTRICT"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + // width: isMobile?160:null, + }, + + { + key: "blocks", + title: t("FORM.BLOCK"), + dataType: DataType.String, + sortDirection: SortDirection.Ascend, + // width: isMobile?160:null, + }, + { + key: "actions", + title: t("FORM.ACTION"), + dataType: DataType.String, + // width: isMobile?160:null, + }, + ]; +}; -export const getCenterTableData = (t: any, isMobile:any)=>{ - return[ +export const getCenterTableData = (t: any, isMobile: any) => { + return [ { key: "name", title: t("TABLE_TITLE.NAME"), dataType: DataType.String, sortDirection: SortDirection.Ascend, - width: isMobile ? 95:"", + width: isMobile ? 95 : "", }, { key: "status", title: t("TABLE_TITLE.STATUS"), dataType: DataType.String, sortDirection: SortDirection.Ascend, - width: isMobile?95:"", + width: isMobile ? 95 : "", }, { key: "updatedBy", title: t("TABLE_TITLE.UPDATED_BY"), dataType: DataType.String, sortDirection: SortDirection.Ascend, - width: isMobile?95:"", + width: isMobile ? 95 : "", }, { key: "createdBy", title: t("TABLE_TITLE.CREATED_BY"), dataType: DataType.String, sortDirection: SortDirection.Ascend, - width: isMobile?95:"", + width: isMobile ? 95 : "", }, { key: "createdAt", title: t("TABLE_TITLE.CREATED_DATE"), dataType: DataType.String, sortDirection: SortDirection.Ascend, - width: isMobile?95:"", + width: isMobile ? 95 : "", }, { @@ -186,15 +178,14 @@ export const getCenterTableData = (t: any, isMobile:any)=>{ title: t("TABLE_TITLE.UPDATED_DATE"), dataType: DataType.String, sortDirection: SortDirection.Ascend, - width: isMobile?95:"", + width: isMobile ? 95 : "", }, - - + { key: "actions", title: t("TABLE_TITLE.ACTIONS"), dataType: DataType.String, - width: isMobile?125:"", + width: isMobile ? 125 : "", }, ]; -} \ No newline at end of file +}; diff --git a/src/pages/block.tsx b/src/pages/block.tsx index c755ef7c..4e9790ea 100644 --- a/src/pages/block.tsx +++ b/src/pages/block.tsx @@ -157,7 +157,7 @@ const Block: React.FC = () => { dataType: DataType.String, }, ], - [t] + [t], ); const handleStateChange = useCallback( @@ -176,14 +176,14 @@ const Block: React.FC = () => { console.error("Error fetching district data", error); } }, - [] + [], ); const handleDistrictChange = useCallback( (event: SelectChangeEvent) => { setSelectedDistrict(event.target.value); }, - [] + [], ); const handleEdit = useCallback((rowData: any) => { @@ -205,8 +205,8 @@ const Block: React.FC = () => { await deleteOption("blocks", selectedStateForDelete.value); setStateData((prevStateData) => prevStateData.filter( - (state) => state.value !== selectedStateForDelete.value - ) + (state) => state.value !== selectedStateForDelete.value, + ), ); showToastMessage(t("COMMON.STATE_DELETED_SUCCESS"), "success"); } catch (error) { @@ -219,7 +219,7 @@ const Block: React.FC = () => { const handlePaginationChange = ( event: React.ChangeEvent, - value: number + value: number, ) => { setPageOffset(value - 1); }; @@ -233,7 +233,7 @@ const Block: React.FC = () => { const sortedData = [...blockData]; const paginatedData = sortedData.slice( pageOffset * pageLimit, - (pageOffset + 1) * pageLimit + (pageOffset + 1) * pageLimit, ); setPageCount(Math.ceil(sortedData.length / pageLimit)); }; @@ -263,7 +263,7 @@ const Block: React.FC = () => { value: string, controllingField: string, fieldId: string, - DistrictId?: string + DistrictId?: string, ) => { const newDistrict = { options: [ @@ -280,7 +280,7 @@ const Block: React.FC = () => { const response = await createOrUpdateOption( fieldId, newDistrict, - DistrictId + DistrictId, ); console.log("submit response:", response); diff --git a/src/pages/centers.tsx b/src/pages/centers.tsx index 1c3b3354..7f33a6be 100644 --- a/src/pages/centers.tsx +++ b/src/pages/centers.tsx @@ -1,6 +1,6 @@ -import React, { ChangeEvent , useState, useEffect } from "react"; +import React, { ChangeEvent, useState, useEffect } from "react"; import KaTableComponent from "../components/KaTableComponent"; -import { DataType ,SortDirection} from "ka-table/enums"; +import { DataType, SortDirection } from "ka-table/enums"; import { serverSideTranslations } from "next-i18next/serverSideTranslations"; import HeaderComponent from "@/components/HeaderComponent"; import { useTranslation } from "next-i18next"; @@ -24,7 +24,7 @@ import { CustomField } from "@/utils/Interfaces"; import { showToastMessage } from "@/components/Toastify"; import AddNewCenters from "@/components/AddNewCenters"; import { getCenterTableData } from "@/data/tableColumns"; -import { Theme } from '@mui/system'; +import { Theme } from "@mui/system"; type cohortFilterDetails = { type?: string; @@ -82,7 +82,9 @@ const Center: React.FC = () => { const handleCloseAddLearnerModal = () => { setOpenAddNewCohort(false); }; - const isMobile = useMediaQuery((theme: Theme) => theme.breakpoints.down('sm')); + const isMobile = useMediaQuery((theme: Theme) => + theme.breakpoints.down("sm"), + ); // use api calls useEffect(() => { if (typeof window !== "undefined" && window.localStorage) { @@ -173,7 +175,7 @@ const Center: React.FC = () => { const handlePaginationChange = ( event: React.ChangeEvent, - value: number + value: number, ) => { setPageOffset(value - 1); }; @@ -228,7 +230,6 @@ const Center: React.FC = () => { setFilters({ status: filters.status, states: selectedStateCode, - }); } else { setFilters({ @@ -243,7 +244,6 @@ const Center: React.FC = () => { status: filters.status, states: selectedStateCode, districts: districts, - }); } else { setFilters({ @@ -262,7 +262,6 @@ const Center: React.FC = () => { status: filters.status, states: selectedStateCode, districts: selectedDistrictCode, - }); } else { setFilters({ @@ -305,7 +304,7 @@ const Center: React.FC = () => { if (resp?.responseCode === 200) { showToastMessage(t("CENTERS.CENTER_DELETE_SUCCESSFULLY"), "success"); const cohort = cohortData?.find( - (item: any) => item.cohortId == selectedCohortId + (item: any) => item.cohortId == selectedCohortId, ); if (cohort) { cohort.status = Status.ARCHIVED; @@ -439,13 +438,10 @@ const Center: React.FC = () => { } }; - - const handleAddUserClick = () => { setOpenAddNewCohort(true); }; - // props to send in header const userProps = { userType: t("SIDEBAR.CENTER"), @@ -500,12 +496,11 @@ const Center: React.FC = () => { modalOpen={confirmationModalOpen} /> - {loading ? ( - ) : cohortData?.length > 0 ? ( + ) : cohortData?.length > 0 ? ( { const [searchQuery, setSearchQuery] = useState(""); const [selectedOption, setSelectedOption] = useState(""); const [selectFilter, setSelectFilter] = useState(""); - const [loading, setLoading] = useState(true); + const [loading, setLoading] = useState(true); useEffect(() => { const fetchData = async () => { setTimeout(() => { @@ -75,7 +75,7 @@ const Foundation = () => { }, (err) => { console.error("Failed to copy link: ", err); - } + }, ); }; @@ -101,7 +101,7 @@ const Foundation = () => { ) : ( { {!selectedCardId ? ( cardData?.map((card) => ( { {card.state} { }, (err) => { console.error("Failed to copy link: ", err); - } + }, ); }; diff --git a/src/pages/district.tsx b/src/pages/district.tsx index 327dc837..8fe3da11 100644 --- a/src/pages/district.tsx +++ b/src/pages/district.tsx @@ -120,8 +120,8 @@ const District: React.FC = () => { await deleteOption("districts", selectedStateForDelete.value); setDistrictData((prev) => prev.filter( - (district) => district.value !== selectedStateForDelete.value - ) + (district) => district.value !== selectedStateForDelete.value, + ), ); showToastMessage(t("COMMON.STATE_DELETED_SUCCESS"), "success"); } catch (error) { @@ -136,7 +136,7 @@ const District: React.FC = () => { value: string, controllingField: string, fieldId: string, - DistrictId?: string + DistrictId?: string, ) => { const newDistrict = { options: [ @@ -152,7 +152,7 @@ const District: React.FC = () => { const response = await createOrUpdateOption( fieldId, newDistrict, - DistrictId + DistrictId, ); if (response) { @@ -179,7 +179,7 @@ const District: React.FC = () => { value, controllingField, districtFieldId, - selectedStateForEdit?.value + selectedStateForEdit?.value, ) } fieldId={districtFieldId} diff --git a/src/pages/faciliator.tsx b/src/pages/faciliator.tsx index c4e24197..36469950 100644 --- a/src/pages/faciliator.tsx +++ b/src/pages/faciliator.tsx @@ -6,34 +6,38 @@ import { Role, FormContextType } from "@/utils/app.constant"; import CommonUserModal from "@/components/CommonUserModal"; const Faciliator: React.FC = () => { const { t } = useTranslation(); - const [openAddFacilitatorModal, setOpenAddFacilitatorModal] = React.useState(false); + const [openAddFacilitatorModal, setOpenAddFacilitatorModal] = + React.useState(false); const [submitValue, setSubmitValue] = React.useState(false); - const handleOpenAddFacilitatorModal = () => { - setOpenAddFacilitatorModal(true); -}; -const handleModalSubmit = (value: boolean) => { - setSubmitValue(true); - -}; -const handleCloseAddFacilitatorModal = () => { - setOpenAddFacilitatorModal(false); -}; + const handleOpenAddFacilitatorModal = () => { + setOpenAddFacilitatorModal(true); + }; + const handleModalSubmit = (value: boolean) => { + setSubmitValue(true); + }; + const handleCloseAddFacilitatorModal = () => { + setOpenAddFacilitatorModal(false); + }; const handleAddFaciliatorClick = () => { handleOpenAddFacilitatorModal(); }; return ( <> - + + open={openAddFacilitatorModal} + onClose={handleCloseAddFacilitatorModal} + userType={FormContextType.TEACHER} + onSubmit={handleModalSubmit} + /> ); }; diff --git a/src/pages/importCsv.tsx b/src/pages/importCsv.tsx index 306a8223..d0e08e7b 100644 --- a/src/pages/importCsv.tsx +++ b/src/pages/importCsv.tsx @@ -93,7 +93,7 @@ const ImportCsv = () => { }, (err) => { console.error("Failed to copy link: ", err); - } + }, ); }; diff --git a/src/pages/learners.tsx b/src/pages/learners.tsx index ef251390..d035408b 100644 --- a/src/pages/learners.tsx +++ b/src/pages/learners.tsx @@ -6,38 +6,42 @@ import { Role, FormContextType } from "@/utils/app.constant"; import CommonUserModal from "@/components/CommonUserModal"; const Learners: React.FC = () => { const { t } = useTranslation(); - const [openAddLearnerModal, setOpenAddLearnerModal] = React.useState(false); - const [submitValue, setSubmitValue] = React.useState(false); + const [openAddLearnerModal, setOpenAddLearnerModal] = React.useState(false); + const [submitValue, setSubmitValue] = React.useState(false); - const handleOpenAddLearnerModal = () => { - setOpenAddLearnerModal(true); -}; -const handleModalSubmit = (value: boolean) => { - setSubmitValue(true); - -}; -const handleCloseAddLearnerModal = () => { - setOpenAddLearnerModal(false); -}; + const handleOpenAddLearnerModal = () => { + setOpenAddLearnerModal(true); + }; + const handleModalSubmit = (value: boolean) => { + setSubmitValue(true); + }; + const handleCloseAddLearnerModal = () => { + setOpenAddLearnerModal(false); + }; const handleAddLearnerClick = () => { handleOpenAddLearnerModal(); }; return ( <> - + {/* */} - - + ); }; diff --git a/src/pages/login.tsx b/src/pages/login.tsx index 6d58af25..44ea3f81 100644 --- a/src/pages/login.tsx +++ b/src/pages/login.tsx @@ -90,7 +90,7 @@ const LoginPage = () => { }; const handleMouseDownPassword = ( - event: React.MouseEvent + event: React.MouseEvent, ) => { event.preventDefault(); }; @@ -139,7 +139,7 @@ const LoginPage = () => { router.push("/dashboard"); } catch (error: any) { setLoading(false); - const errorMessage = t("LOGIN_PAGE.USERNAME_PASSWORD_NOT_CORRECT") + const errorMessage = t("LOGIN_PAGE.USERNAME_PASSWORD_NOT_CORRECT"); showToastMessage(errorMessage, "error"); } } diff --git a/src/pages/state.tsx b/src/pages/state.tsx index 6af336ea..d4e0ab39 100644 --- a/src/pages/state.tsx +++ b/src/pages/state.tsx @@ -83,8 +83,8 @@ const State: React.FC = () => { await deleteOption("states", selectedStateForDelete.value); setStateData((prevStateData) => prevStateData.filter( - (state) => state.value !== selectedStateForDelete.value - ) + (state) => state.value !== selectedStateForDelete.value, + ), ); showToastMessage(t("COMMON.STATE_DELETED_SUCCESS"), "success"); } catch (error) { @@ -108,7 +108,7 @@ const State: React.FC = () => { const handleAddStateSubmit = async ( name: string, value: string, - stateId?: string + stateId?: string, ) => { const newState = { options: [{ name, value }], diff --git a/src/pages/stateDetails.tsx b/src/pages/stateDetails.tsx index 24e01968..13b4b15f 100644 --- a/src/pages/stateDetails.tsx +++ b/src/pages/stateDetails.tsx @@ -82,7 +82,7 @@ const StateDetails = () => { }, (err) => { console.error("Failed to copy link: ", err); - } + }, ); }; diff --git a/src/pages/teamLeader.tsx b/src/pages/teamLeader.tsx index 3cccbf47..b7cf2c6e 100644 --- a/src/pages/teamLeader.tsx +++ b/src/pages/teamLeader.tsx @@ -8,32 +8,37 @@ const TeamLeader: React.FC = () => { const { t } = useTranslation(); const handleAddTeamLeaderClick = () => { handleOpenAddTeamLeaderModal(); - }; const [submitValue, setSubmitValue] = React.useState(false); - const [openAddTeamLeaderModal, setOpenAddTeamLeaderModal] = React.useState(false); - const handleOpenAddTeamLeaderModal = () => { - setOpenAddTeamLeaderModal(true); -}; -const handleModalSubmit = (value: boolean) => { - setSubmitValue(true); + const [openAddTeamLeaderModal, setOpenAddTeamLeaderModal] = + React.useState(false); + const handleOpenAddTeamLeaderModal = () => { + setOpenAddTeamLeaderModal(true); + }; + const handleModalSubmit = (value: boolean) => { + setSubmitValue(true); + }; + const handleCloseAddTeamLeaderModal = () => { + setOpenAddTeamLeaderModal(false); + }; -}; -const handleCloseAddTeamLeaderModal = () => { - setOpenAddTeamLeaderModal(false); -}; - return ( <> - - - + + + ); }; diff --git a/src/services/CohortService/cohortService.ts b/src/services/CohortService/cohortService.ts index 74f7cbb4..fc5cf4bb 100644 --- a/src/services/CohortService/cohortService.ts +++ b/src/services/CohortService/cohortService.ts @@ -11,7 +11,7 @@ export interface cohortListFilter { export interface cohortListData { limit?: Number; offset?: Number; - filter?:any + filter?: any; } export const getCohortList = async (data: cohortListData): Promise => { @@ -31,7 +31,7 @@ export const updateCohortUpdate = async ( cohortDetails: { name?: string; status?: string; - } + }, ): Promise => { const { name, status } = cohortDetails; let apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/cohort/update/${userId}`; @@ -47,14 +47,14 @@ export const updateCohortUpdate = async ( export const getFormRead = async ( context: string, - contextType: string + contextType: string, ): Promise => { const apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/form/read?context=${context}&contextType=${contextType}`; try { let response = await get(apiUrl); const sortedFields = response?.data?.result.fields?.sort( (a: { order: string }, b: { order: string }) => - parseInt(a.order) - parseInt(b.order) + parseInt(a.order) - parseInt(b.order), ); const formData = { formid: response?.data?.result?.formid, diff --git a/src/services/CreateUserService.ts b/src/services/CreateUserService.ts index 9bfff7cc..84a248ff 100644 --- a/src/services/CreateUserService.ts +++ b/src/services/CreateUserService.ts @@ -1,36 +1,37 @@ -import { get, post, patch } from './RestClient'; -import { createUserParam } from '../utils/Interfaces'; -import axios from 'axios'; +import { get, post, patch } from "./RestClient"; +import { createUserParam } from "../utils/Interfaces"; +import axios from "axios"; import { AxiosRequestConfig, AxiosResponse } from "axios"; export interface UserDetailParam { userData?: object; - + customFields?: any; - } export const getFormRead = async ( context: string, - contextType: string + contextType: string, ): Promise => { - try { - const response = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/form/read`, { - params: { - context, - contextType - }, - paramsSerializer: params => { - return Object.entries(params) - ?.map(([key, value]) => `${key}=${value}`) - .join('&'); - }, - headers: { tenantId:"ef99949b-7f3a-4a5f-806a-e67e683e38f3"} - - }); + try { + const response = await axios.get( + `${process.env.NEXT_PUBLIC_BASE_URL}/form/read`, + { + params: { + context, + contextType, + }, + paramsSerializer: (params) => { + return Object.entries(params) + ?.map(([key, value]) => `${key}=${value}`) + .join("&"); + }, + headers: { tenantId: "ef99949b-7f3a-4a5f-806a-e67e683e38f3" }, + }, + ); const sortedFields = response?.data?.result.fields?.sort( (a: { order: string }, b: { order: string }) => - parseInt(a.order) - parseInt(b.order) + parseInt(a.order) - parseInt(b.order), ); const formData = { formid: response?.data?.result?.formid, @@ -39,7 +40,7 @@ export const getFormRead = async ( }; return formData; } catch (error) { - console.error('error in getting cohort details', error); + console.error("error in getting cohort details", error); // throw error; } }; @@ -50,22 +51,21 @@ export const createUser = async (userData: any): Promise => { const response = await post(apiUrl, userData); return response?.data?.result; } catch (error) { - console.error('error in getting cohort list', error); + console.error("error in getting cohort list", error); // throw error; } }; export const updateUser = async ( userId: string, - {userData, - customFields}: UserDetailParam + { userData, customFields }: UserDetailParam, ): Promise => { const apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/update/${userId}`; try { - const response = await patch(apiUrl, {userData, customFields}); + const response = await patch(apiUrl, { userData, customFields }); return response; } catch (error) { console.error("error in fetching user details", error); return error; } -}; \ No newline at end of file +}; diff --git a/src/services/MasterDataService.ts b/src/services/MasterDataService.ts index 444856e9..5c964b44 100644 --- a/src/services/MasterDataService.ts +++ b/src/services/MasterDataService.ts @@ -118,7 +118,7 @@ export const getCenterList = async ({ export const deleteOption = async ( type: "states" | "districts" | "blocks", - option: string + option: string, ): Promise => { const apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/fields/options/delete/${type}?option=${option}`; const requestBody = {}; @@ -136,7 +136,7 @@ export const deleteOption = async ( export const createOrUpdateOption = async ( fieldId: string, fieldParams: { options: { name: string; value: string }[] }, - stateId?: string + stateId?: string, ): Promise => { const apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/fields/update/${fieldId}`; diff --git a/src/services/RestClient.ts b/src/services/RestClient.ts index 102a1f70..2a963aa7 100644 --- a/src/services/RestClient.ts +++ b/src/services/RestClient.ts @@ -6,7 +6,7 @@ export async function get( url: string, headers: AxiosRequestConfig["headers"] = {}, ): Promise { - console.log(url) + console.log(url); return axiosInstance.get(url, { headers }); } diff --git a/src/services/UserList.ts b/src/services/UserList.ts index fbcc1513..fabb3cc7 100644 --- a/src/services/UserList.ts +++ b/src/services/UserList.ts @@ -39,21 +39,16 @@ export const userList = async ({ } }; - export const getUserDetails = async ( userId?: string | string[], - fieldValue?: boolean + fieldValue?: boolean, ): Promise => { const apiUrl: string = `${process.env.NEXT_PUBLIC_BASE_URL}/read/${userId}?fieldvalue=${fieldValue}`; try { const response = await get(apiUrl); return response?.data?.result; } catch (error) { - console.error('error in fetching user details', error); + console.error("error in fetching user details", error); return error; } }; - - - - diff --git a/src/store/manageUserStore.js b/src/store/manageUserStore.js index 2d913a63..ee5d0873 100644 --- a/src/store/manageUserStore.js +++ b/src/store/manageUserStore.js @@ -1,17 +1,17 @@ -import { create } from 'zustand'; -import { persist } from 'zustand/middleware'; +import { create } from "zustand"; +import { persist } from "zustand/middleware"; const manageUserStore = create( persist( (set) => ({ - deleteId: '', - learnerDeleteId: '', - blockCode: '', - districtCode: '', - stateCode: '', - blockId: 'a717bb68-5c8a-45cb-b6dd-376caa605736', - districtId: 'aecb84c9-fe4c-4960-817f-3d228c0c7300', - stateId: '61b5909a-0b45-4282-8721-e614fd36d7bd', + deleteId: "", + learnerDeleteId: "", + blockCode: "", + districtCode: "", + stateCode: "", + blockId: "a717bb68-5c8a-45cb-b6dd-376caa605736", + districtId: "aecb84c9-fe4c-4960-817f-3d228c0c7300", + stateId: "61b5909a-0b45-4282-8721-e614fd36d7bd", setCohortDeleteId: (newCohortDeleteId) => set((state) => ({ deleteId: newCohortDeleteId })), setCohortLearnerDeleteId: (newCohortLearnerDeleteId) => @@ -26,10 +26,10 @@ const manageUserStore = create( setStateId: (newStateId) => set(() => ({ stateId: newStateId })), }), { - name: 'teacherApp', + name: "teacherApp", getStorage: () => localStorage, - } - ) + }, + ), ); -export default manageUserStore; \ No newline at end of file +export default manageUserStore; diff --git a/src/store/store.js b/src/store/store.js index d773d830..ae241a2c 100644 --- a/src/store/store.js +++ b/src/store/store.js @@ -1,22 +1,22 @@ -import { create } from 'zustand'; -import { persist } from 'zustand/middleware'; +import { create } from "zustand"; +import { persist } from "zustand/middleware"; const useStore = create( persist( (set) => ({ - value: '', + value: "", cohorts: [], - userRole: '', + userRole: "", pairs: [], setValue: (newValue) => set((state) => ({ value: newValue })), setUserRole: (newRole) => set((state) => ({ userRole: newRole })), setCohorts: (newCohorts) => set(() => ({ cohorts: newCohorts })), }), { - name: 'teacherApp', + name: "teacherApp", getStorage: () => localStorage, - } - ) + }, + ), ); export default useStore; diff --git a/src/utils/Helper.ts b/src/utils/Helper.ts index 49468c7e..d0be6159 100644 --- a/src/utils/Helper.ts +++ b/src/utils/Helper.ts @@ -47,15 +47,15 @@ export const getDeviceId = () => { export const generateUsernameAndPassword = ( stateCode: string, - role: string + role: string, ) => { const currentYear = new Date().getFullYear().toString().slice(-2); // Last two digits of the current year const randomNum = Math.floor(10000 + Math.random() * 90000).toString(); //NOSONAR const rolePrefixes: Record = { - [FormContextType.TEACHER]: 'FSC', - [FormContextType.STUDENT]: 'SC', - [FormContextType.TEAM_LEADER]: 'TL' + [FormContextType.TEACHER]: "FSC", + [FormContextType.STUDENT]: "SC", + [FormContextType.TEAM_LEADER]: "TL", }; if (!(role in rolePrefixes)) { @@ -100,14 +100,14 @@ export const firstLetterInUpperCase = (label: string): string | null => { ?.join(" "); }; export const capitalizeFirstLetterOfEachWordInArray = ( - arr: string[] + arr: string[], ): string[] => { if (!arr) { return arr; } console.log(arr); return arr.map((str) => - str.replace(/\b[a-z]/g, (char) => char.toUpperCase()) + str.replace(/\b[a-z]/g, (char) => char.toUpperCase()), ); }; export const fieldTextValidation = (text: string) => { diff --git a/src/utils/Interfaces.ts b/src/utils/Interfaces.ts index 554b925a..9dd4d27b 100644 --- a/src/utils/Interfaces.ts +++ b/src/utils/Interfaces.ts @@ -10,7 +10,7 @@ export interface FieldOption { export interface Field { name: string; - type: 'text' | 'numeric' | 'drop_down' | 'checkbox' | 'radio' | 'email'; + type: "text" | "numeric" | "drop_down" | "checkbox" | "radio" | "email"; label: string; order: string; coreField: number; @@ -53,5 +53,3 @@ export interface createUserParam { tenantCohortRoleMapping: TenantCohortRoleMapping[]; customFields: CustomField[]; } - - diff --git a/src/utils/useLocationState.tsx b/src/utils/useLocationState.tsx index 976d43e8..6982fa84 100644 --- a/src/utils/useLocationState.tsx +++ b/src/utils/useLocationState.tsx @@ -55,7 +55,7 @@ export const useLocationState = (open: boolean, onClose: () => void) => { } handleStateChange(selectedNames, selectedCodes); }, - [selectedStateCode] + [selectedStateCode], ); const handleDistrictChangeWrapper = useCallback( @@ -79,7 +79,7 @@ export const useLocationState = (open: boolean, onClose: () => void) => { } handleDistrictChange(selected, selectedCodes); }, - [selectedDistrictCode] + [selectedDistrictCode], ); const handleBlockChangeWrapper = useCallback( @@ -90,38 +90,35 @@ export const useLocationState = (open: boolean, onClose: () => void) => { try { console.log(selectedStateCode, selectedDistrictCode); const object = { - "limit":200, - "offset": 0, - "filters": { - // "type": "COHORT", - "status": [ - "active" - ], - // "states": selectedStateCode, - // "districts": selectedDistrictCode, - // "blocks": selectedCodes[0] - name:selected[0] - } + limit: 200, + offset: 0, + filters: { + // "type": "COHORT", + status: ["active"], + // "states": selectedStateCode, + // "districts": selectedDistrictCode, + // "blocks": selectedCodes[0] + name: selected[0], + }, }; const response2 = await getCenterList(object); - console.log(selected) - const getBlockIdObject={ - "limit": 200, - "offset": 0, "filters": { + console.log(selected); + const getBlockIdObject = { + limit: 200, + offset: 0, + filters: { // "type":"COHORT", - "status": [ - "active" - ], - "states": selectedStateCode, - "districts": selectedDistrictCode, - "blocks": selectedCodes[0] - // "name": selected[0] - }, - } + status: ["active"], + states: selectedStateCode, + districts: selectedDistrictCode, + blocks: selectedCodes[0], + // "name": selected[0] + }, + }; const response = await getCenterList(getBlockIdObject); setSelectedBlockCohortId( - response?.result?.results?.cohortDetails[0].cohortId + response?.result?.results?.cohortDetails[0].cohortId, ); console.log(response?.result?.results?.cohortDetails[0].cohortId); // const result = response?.result?.cohortDetails; @@ -140,14 +137,14 @@ export const useLocationState = (open: boolean, onClose: () => void) => { } handleBlockChange(selected, selectedCodes); }, - [selectedBlockCode, selectedDistrictCode, selectedStateCode] + [selectedBlockCode, selectedDistrictCode, selectedStateCode], ); const handleCenterChangeWrapper = useCallback( (selected: string[], selectedCodes: string[]) => { handleCenterChange(selected, selectedCodes); }, - [] + [], ); const handleStateChange = useCallback( @@ -160,7 +157,7 @@ export const useLocationState = (open: boolean, onClose: () => void) => { setSelectedStateCode(stateCodes); console.log("Selected categories:", typeof code[0]); }, - [] + [], ); const handleDistrictChange = useCallback( @@ -172,7 +169,7 @@ export const useLocationState = (open: boolean, onClose: () => void) => { setSelectedDistrictCode(districts); console.log("Selected categories:", districts); }, - [] + [], ); const handleBlockChange = useCallback( @@ -184,7 +181,7 @@ export const useLocationState = (open: boolean, onClose: () => void) => { setdynamicFormForBlock(true); console.log("Selected categories:", blocks); }, - [] + [], ); const handleCenterChange = useCallback( @@ -197,7 +194,7 @@ export const useLocationState = (open: boolean, onClose: () => void) => { console.log("Selected categories:", selected); }, - [] + [], ); useEffect(() => {