CFE-3 Merging
This commit is contained in:
@@ -1,7 +1,5 @@
|
||||
{
|
||||
"extends": [
|
||||
"next/core-web-vitals",
|
||||
"plugin:testing-library/react",
|
||||
"plugin:jest-dom/recommended"
|
||||
"next/core-web-vitals"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import {
|
||||
CREATE_EXPERT_MANAGEMENT,
|
||||
GET_PERMISSIONS_LIST,
|
||||
GET_ROLE_MANAGEMENT,
|
||||
GET_SIDEBAR_NOTIFICATION,
|
||||
GET_USER_ROUTE,
|
||||
SET_USER_PASSWORD,
|
||||
EXPERT_MANAGEMENT,
|
||||
GET_PROVINCE_LIST,
|
||||
GET_ROLE_LIST,
|
||||
GET_USER_ROUTE
|
||||
} from "@/core/data/apiRoutes";
|
||||
import {rest} from "msw";
|
||||
|
||||
@@ -11,10 +14,90 @@ export const handler = [
|
||||
rest.get(GET_USER_ROUTE, (req, res, ctx) => {
|
||||
return res(ctx.json({
|
||||
data: {
|
||||
id: 10
|
||||
id: 10,
|
||||
permissions: [
|
||||
"manage_users"
|
||||
],
|
||||
}
|
||||
}))
|
||||
}),
|
||||
rest.get(GET_SIDEBAR_NOTIFICATION, (req, res, ctx) => {
|
||||
return res(ctx.json({
|
||||
data: []
|
||||
}))
|
||||
}),
|
||||
rest.post(SET_USER_PASSWORD, (req, res, ctx) => {
|
||||
return res(
|
||||
ctx.status(200),
|
||||
);
|
||||
}),
|
||||
rest.get(GET_PERMISSIONS_LIST, (req, res, ctx) => {
|
||||
return res(ctx.json(
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: 1,
|
||||
name: "manage_passenger_office_navgan",
|
||||
name_fa: "مدیریت کارتابل رییس اداره مسافری استان"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "manage_province_working_group_navgan",
|
||||
name_fa: "مدیریت کارتابل کارگروه استانی"
|
||||
}
|
||||
]
|
||||
}
|
||||
))
|
||||
}),
|
||||
rest.get(GET_ROLE_MANAGEMENT, (req, res, ctx) => {
|
||||
return res(
|
||||
ctx.json(
|
||||
{
|
||||
data: [
|
||||
{
|
||||
created_at: "2023-10-01T07:20:07.000000Z",
|
||||
guard_name: "api",
|
||||
id: 1,
|
||||
name: "admin",
|
||||
name_fa: "ادمین",
|
||||
permissions: [
|
||||
{
|
||||
id: 1,
|
||||
name: "manage_users",
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "manage_roles",
|
||||
},
|
||||
],
|
||||
updated_at: "2023-10-10T07:38:12.000000Z"
|
||||
},
|
||||
{
|
||||
created_at: "2023-10-01T07:20:07.000000Z",
|
||||
guard_name: "api",
|
||||
id: 2,
|
||||
name: "manager",
|
||||
name_fa: "مدیر",
|
||||
permissions: [
|
||||
{
|
||||
id: 1,
|
||||
name: "manage_users",
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "manage_roles",
|
||||
},
|
||||
],
|
||||
updated_at: "2023-10-10T07:38:12.000000Z"
|
||||
}
|
||||
],
|
||||
meta: {
|
||||
totalRowCount: 2
|
||||
}
|
||||
}
|
||||
),
|
||||
);
|
||||
}),
|
||||
rest.get(GET_PROVINCE_LIST, (req, res, ctx) => {
|
||||
return res(ctx.json({
|
||||
data: [
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
"jest": "^29.7.0",
|
||||
"jest-environment-jsdom": "^29.7.0",
|
||||
"msw": "^1.3.1",
|
||||
"next-router-mock": "^0.9.9",
|
||||
"next-router-mock": "^0.9.10",
|
||||
"run-script-os": "^1.1.6"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
"between": "میان",
|
||||
"online_message": "شما به اینترنت وصل هستید",
|
||||
"offline_message": "اتصال شما به اینترنت قطع شده است",
|
||||
"socket_is_connect_message": "شما به سوکت وصل هستید",
|
||||
"socket_is_not_connect_message": "اتصال شما به سوکت قطع شده است",
|
||||
"header": {
|
||||
"open_profile": "پروفایل",
|
||||
"edit_profile": " پروفایل",
|
||||
@@ -32,6 +34,7 @@
|
||||
"dashboard": "داشبورد",
|
||||
"change-password": "تغییر رمز عبور",
|
||||
"edit-profile": "ویرایش پروفایل",
|
||||
"role-management": "مدیریت نقش ها",
|
||||
"admin": "مدیریت",
|
||||
"expert-management": "مدیریت کارشناسان"
|
||||
},
|
||||
@@ -41,7 +44,7 @@
|
||||
"typography_your_login_is_valid_and_you_do_not_need_to_login_again": "شما دسترسی لازم به این صفحه را دارید نیاز به ورود مجدد نیست.",
|
||||
"typography_your_access_to_this_page_has_expired_Please_login_again": "دسترسی شما منقضی شده است لطفا دوباره ورود نمایید.",
|
||||
"typography_redirect_to": "درحال رفتن به صفحه",
|
||||
"typography_routing_previuos_page": "صفحه قبل...",
|
||||
"typography_routing_previuos_page": " قبل...",
|
||||
"typography_routing_dashbaord_page": "داشبورد..."
|
||||
},
|
||||
"Permission": {
|
||||
@@ -72,7 +75,8 @@
|
||||
"dashboard_page": "داشبورد",
|
||||
"change_password": "تغییر رمز عبور",
|
||||
"edit_profile": "ویرایش پروفایل",
|
||||
"expert_management": "داشبورد"
|
||||
"role_management_page": "مدیریت نقش ها",
|
||||
"expert_management": "مدیریت کارشناسان"
|
||||
},
|
||||
"MuiDatePicker": {
|
||||
"date_picker_birthday": "تاریخ"
|
||||
@@ -82,7 +86,9 @@
|
||||
"label_current_password": "رمز عبور فعلی",
|
||||
"label_new_password": "رمز عبور جدید",
|
||||
"label_confirm_password": "تکرار رمز عبور جدید",
|
||||
"error_message_required": "اجباری !",
|
||||
"error_message_current_password_required": "وارد کردن رمز عبور فعلی الزامیست!",
|
||||
"error_message_new_password_required": "وارد کردن رمز عبور جدید الزامیست!",
|
||||
"error_message_confirm_password_required": "وارد کردن تکرار رمز عبور جدید الزامیست!",
|
||||
"error_message_password_length": "رمز عبور باید حداقل 8 کاراکتر باشد.",
|
||||
"error_message_password_match": "پسورد ها یکسان هستند",
|
||||
"error_message_password_not_match": "پسورد و تکرار رمز عبور باید یکسان باشد"
|
||||
@@ -121,6 +127,70 @@
|
||||
"delete": "پاک کردن",
|
||||
"uploadfile_error": "حجم فایل بیشتر از 2 مگابایت می باشد"
|
||||
},
|
||||
"RoleManagement": {
|
||||
"id": "کد یکتا",
|
||||
"name_fa": "نام فارسی ",
|
||||
"name": "نام انگلیسی",
|
||||
"created_at": "تاریخ درخواست",
|
||||
"updated_at": "تاریخ بروزرسانی"
|
||||
},
|
||||
"AddDialog": {
|
||||
"add": "افزودن",
|
||||
"name_en": "نام انگلیسی",
|
||||
"name_en_error": "وارد کردن نام انگلیسی الزامیست",
|
||||
"name_fa": "نام فارسی",
|
||||
"name_fa_error": "وارد کردن نام فارسی الزامیست",
|
||||
"permission": "دسترسی",
|
||||
"permission_min_error": "حداقل باید یک دسترسی انتخاب شود",
|
||||
"phone_number": "شماره تلفن",
|
||||
"phone_number_positive": "شماره تلفن باید مثبت باشد",
|
||||
"phone_number_error": "وارد کردن شماره تلفن الزامیست",
|
||||
"phone_number_number": "شماره تلفن باید شامل اعداد باشد",
|
||||
"phone_number_max": "شماره تلفن باید شامل 11 رقم باشد",
|
||||
"national_id_positive": "کد ملی باید مثبت باشد",
|
||||
"national_id_number": "کد ملی باید شامل اعداد باشد",
|
||||
"national_id_max": "کد ملی باید شامل 10 رقم باشد",
|
||||
"national_id": "کد ملی",
|
||||
"national_id_error": "وارد کردن کد ملی الزامیست",
|
||||
"type_id_error": "وارد کردن نوع کاربر الزامیست",
|
||||
"navgan_id_error": "وارد کردن کد ناوگان الزامیست",
|
||||
"refahi": "رفاهی",
|
||||
"navgan": "ناوگان",
|
||||
"type_id": "نوع کاربر",
|
||||
"navgan_id": "کد ناوگان",
|
||||
"button-cancel": "انصراف",
|
||||
"loading_permissions_list": "درحال دریافت لیست دسترسی ها",
|
||||
"button-add": "ثبت"
|
||||
},
|
||||
"UpdateDialog": {
|
||||
"update": "ویرایش",
|
||||
"description": "توضیحات خود را وارد نمائید",
|
||||
"description_error": "وارد کردن توضیحات الزامی است!",
|
||||
"next-state-id": "وضعیت",
|
||||
"next-state-id-error": "وارد کردن وضعیت الزامیست",
|
||||
"update-tooltip": "ویرایش",
|
||||
"button-cancel": "بستن",
|
||||
"refahi": "رفاهی",
|
||||
"navgan": "ناوگان",
|
||||
"phone_number": "شماره تلفن",
|
||||
"national_id": "کد ملی",
|
||||
"name_en": "نام انگلیسی",
|
||||
"name_en_error": "وارد کردن نام انگلیسی الزامیست",
|
||||
"name_fa": "نام فارسی",
|
||||
"name_fa_error": "وارد کردن نام فارسی الزامیست",
|
||||
"permission": "دسترسی",
|
||||
"permission_min_error": "حداقل باید یک دسترسی انتخاب شود",
|
||||
"type_id": "نوع کاربر",
|
||||
"navgan_id": "کد ناوگان",
|
||||
"loading_permissions_list": "درحال دریافت لیست دسترسی ها",
|
||||
"button-update": "ثبت"
|
||||
},
|
||||
"DeleteDialog": {
|
||||
"delete": "حذف",
|
||||
"button-cancel": "انصراف",
|
||||
"typography": "آیا از حدف این مورد اطمینان دارید ؟",
|
||||
"button-delete": "حذف کردن"
|
||||
},
|
||||
"ExpertMangement": {
|
||||
"id": "کد یکتا",
|
||||
"name": "نام کامل",
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
import { render, screen, waitFor, fireEvent , act } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import MockAppWithProviders from "../../../../../../mocks/AppWithProvider";
|
||||
import ChangePasswordForm from "@/components/dashboard/change-password/change-password-form";
|
||||
import {SET_USER_PASSWORD} from "@/core/data/apiRoutes";
|
||||
import {server} from "../../../../../../mocks/server";
|
||||
import {rest} from "msw";
|
||||
|
||||
describe('Change Password Form Component From Change Password Page', () => {
|
||||
describe('Rendering', () => {
|
||||
it('Should see change password heading',() => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
const changePasswordElement = screen.getByRole('heading', { level: 4 });
|
||||
expect(changePasswordElement).toHaveTextContent('تغییر رمز عبور');
|
||||
});
|
||||
it('Should see the label for current password field', () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
const currentPasswordLabel = screen.queryByLabelText('رمز عبور فعلی');
|
||||
expect(currentPasswordLabel).toBeInTheDocument();
|
||||
});
|
||||
it('Should see the label for new password field', () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
const newPasswordLabel = screen.queryByLabelText('رمز عبور جدید');
|
||||
expect(newPasswordLabel).toBeInTheDocument();
|
||||
});
|
||||
it('Should see the label for confirm password field', () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
const confirmPasswordLabel = screen.queryByLabelText('تکرار رمز عبور جدید');
|
||||
expect(confirmPasswordLabel).toBeInTheDocument();
|
||||
});
|
||||
it('Should see the submit button with the submit label and should be disable', () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
const submitButton = screen.getByRole('button', { name: 'ثبت' });
|
||||
expect(submitButton).toBeInTheDocument();
|
||||
expect(submitButton).toBeDisabled();
|
||||
});
|
||||
it('Should have empty input fields and not see any validation error for current password, new password, and confirm password', () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
const currentPasswordInput = screen.queryByLabelText('رمز عبور فعلی');
|
||||
const newPasswordInput = screen.queryByLabelText('رمز عبور جدید');
|
||||
const confirmPasswordInput = screen.queryByLabelText('تکرار رمز عبور جدید');
|
||||
|
||||
expect(currentPasswordInput).toHaveValue('');
|
||||
expect(newPasswordInput).toHaveValue('');
|
||||
expect(confirmPasswordInput).toHaveValue('');
|
||||
|
||||
expect(screen.queryByText("وارد کردن رمز عبور فعلی الزامیست!")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("وارد کردن رمز عبور جدید الزامیست!")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("وارد کردن تکرار رمز عبور جدید الزامیست!")).not.toBeInTheDocument();
|
||||
|
||||
});
|
||||
});
|
||||
describe("Behavior", ()=>{
|
||||
it('Should fill the current password field and not see any error while its not empty', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
const currentPasswordInput = screen.queryByLabelText('رمز عبور فعلی');
|
||||
|
||||
// Simulate typing something in the current password input
|
||||
fireEvent.change(currentPasswordInput, { target: { value: 'witel@fani0' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("وارد کردن رمز عبور فعلی الزامیست!")).not.toBeInTheDocument();
|
||||
expect(currentPasswordInput).toHaveValue('witel@fani0');
|
||||
});
|
||||
});
|
||||
it('Should fill the new password field and not see any error while its not empty', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
const newPasswordInput = screen.queryByLabelText('رمز عبور جدید');
|
||||
|
||||
// Simulate typing something in the new password input
|
||||
fireEvent.change(newPasswordInput, { target: { value: 'witel@fani1' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("وارد کردن رمز عبور جدید الزامیست!")).not.toBeInTheDocument();
|
||||
expect(newPasswordInput).toHaveValue('witel@fani1');
|
||||
});
|
||||
});
|
||||
it('Should fill the confirm new password field and not see any error while its not empty', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
const confirmPasswordInput = screen.queryByLabelText('تکرار رمز عبور جدید');
|
||||
|
||||
// Simulate typing something in the confirmation new password input
|
||||
fireEvent.change(confirmPasswordInput, { target: { value: 'witel@fani1' } });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("وارد کردن تکرار رمز عبور جدید الزامیست!")).not.toBeInTheDocument();
|
||||
expect(confirmPasswordInput).toHaveValue('witel@fani1');
|
||||
});
|
||||
});
|
||||
});
|
||||
describe("Validation", ()=>{
|
||||
it('Should see error while current password is empty on blur event', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
// Simulate blur event on the current password input
|
||||
const currentPasswordInput = screen.queryByLabelText('رمز عبور فعلی');
|
||||
|
||||
// Clear the input field
|
||||
fireEvent.change(currentPasswordInput, { target: { value: '' } });
|
||||
|
||||
fireEvent.blur(currentPasswordInput);
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن رمز عبور فعلی الزامیست!")).toBeInTheDocument()
|
||||
});
|
||||
});
|
||||
it('Should see error while new password is empty on blur event', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
// Simulate blur event on the new password input
|
||||
const newPasswordInput = screen.queryByLabelText('رمز عبور جدید');
|
||||
|
||||
// Clear the input field
|
||||
fireEvent.change(newPasswordInput, { target: { value: '' } });
|
||||
|
||||
fireEvent.blur(newPasswordInput);
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن رمز عبور جدید الزامیست!")).toBeInTheDocument()
|
||||
});
|
||||
});
|
||||
it('Should see error while confirm new password is empty on blur event', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
// Simulate blur event on the new password input
|
||||
const confirmPasswordInput = screen.queryByLabelText('تکرار رمز عبور جدید');
|
||||
|
||||
// Clear the input field
|
||||
fireEvent.change(confirmPasswordInput, { target: { value: '' } });
|
||||
|
||||
fireEvent.blur(confirmPasswordInput);
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن تکرار رمز عبور جدید الزامیست!")).toBeInTheDocument()
|
||||
});
|
||||
});
|
||||
it('Should see error when new password is less than 8 characters', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
const newPasswordInput = screen.queryByLabelText('رمز عبور جدید');
|
||||
const submitButton = screen.getByRole('button', { name: 'ثبت' });
|
||||
|
||||
// Simulate entering a short new password
|
||||
fireEvent.change(newPasswordInput, { target: { value: 'test' } });
|
||||
fireEvent.blur(newPasswordInput);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("رمز عبور باید حداقل 8 کاراکتر باشد.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Simulate clicking the submit button
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("رمز عبور باید حداقل 8 کاراکتر باشد.")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
it('Should not see error when new password are 8 or more characters', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
const newPasswordInput = screen.queryByLabelText('رمز عبور جدید');
|
||||
const submitButton = screen.getByRole('button', { name: 'ثبت' });
|
||||
|
||||
// Simulate entering a valid new password
|
||||
fireEvent.change(newPasswordInput, { target: { value: 'Witel@fani1' } });
|
||||
fireEvent.blur(newPasswordInput);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("رمز عبور باید حداقل 8 کاراکتر باشد.")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Simulate clicking the submit button
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("رمز عبور باید حداقل 8 کاراکتر باشد.")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
it('Should see error when new password and confirm password do not match on blur event and submit click', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
const newPasswordInput = screen.queryByLabelText('رمز عبور جدید');
|
||||
const confirmPasswordInput = screen.queryByLabelText('تکرار رمز عبور جدید');
|
||||
const submitButton = screen.getByRole('button', { name: 'ثبت' });
|
||||
|
||||
// Simulate entering a valid new password
|
||||
fireEvent.change(newPasswordInput, { target: { value: 'Witel@fani1' } });
|
||||
fireEvent.blur(newPasswordInput);
|
||||
|
||||
// Simulate entering a different value in the confirm password field
|
||||
fireEvent.change(confirmPasswordInput, { target: { value: 'MismatchedPassword' } });
|
||||
fireEvent.blur(confirmPasswordInput);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("پسورد و تکرار رمز عبور باید یکسان باشد")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Simulate clicking the submit button
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("پسورد و تکرار رمز عبور باید یکسان باشد")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
it('Should not see error when new password and confirm password match on blur event and submit click', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
const newPasswordInput = screen.queryByLabelText('رمز عبور جدید');
|
||||
const confirmPasswordInput = screen.queryByLabelText('تکرار رمز عبور جدید');
|
||||
const submitButton = screen.getByRole('button', { name: 'ثبت' });
|
||||
|
||||
// Simulate entering a valid new password
|
||||
fireEvent.change(newPasswordInput, { target: { value: 'Witel@fani1' } });
|
||||
fireEvent.blur(newPasswordInput);
|
||||
|
||||
// Simulate entering the same value in the confirmation password field
|
||||
fireEvent.change(confirmPasswordInput, { target: { value: 'Witel@fani1' } });
|
||||
fireEvent.blur(confirmPasswordInput);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("پسورد و تکرار رمز عبور باید یکسان باشد")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Simulate clicking the submit button
|
||||
fireEvent.click(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("پسورد و تکرار رمز عبور باید یکسان باشد")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
describe("Form Submission", () => {
|
||||
it('Should enable the submit button when the inputs are valid', async () => {
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
const submitButton = screen.getByRole('button', { name: 'ثبت' });
|
||||
|
||||
// Simulate entering valid values in the form fields
|
||||
const currentPasswordInput = screen.queryByLabelText('رمز عبور فعلی');
|
||||
const newPasswordInput = screen.queryByLabelText('رمز عبور جدید');
|
||||
const confirmPasswordInput = screen.queryByLabelText('تکرار رمز عبور جدید');
|
||||
|
||||
fireEvent.change(currentPasswordInput, { target: { value: 'Witel@fani0' } });
|
||||
fireEvent.change(newPasswordInput, { target: { value: 'Witel@fani1' } });
|
||||
fireEvent.change(confirmPasswordInput, { target: { value: 'Witel@fani1' } });
|
||||
|
||||
// Check if the submit button is enabled
|
||||
await waitFor(() => {
|
||||
expect(submitButton).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
it('Should request to api and resetform in success response', async () => {
|
||||
// Render the component
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
|
||||
// Fill in the form fields
|
||||
const currentPasswordInput = screen.queryByLabelText('رمز عبور فعلی');
|
||||
const newPasswordInput = screen.queryByLabelText('رمز عبور جدید');
|
||||
const confirmPasswordInput = screen.queryByLabelText('تکرار رمز عبور جدید');
|
||||
|
||||
fireEvent.change(currentPasswordInput, { target: { value: 'Witel@fani0' } });
|
||||
fireEvent.change(newPasswordInput, { target: { value: 'Witel@fani1' } });
|
||||
fireEvent.change(confirmPasswordInput, { target: { value: 'Witel@fani1' } });
|
||||
|
||||
// Submit the form
|
||||
const submitButton = screen.getByRole('button', { name: 'ثبت' });
|
||||
await userEvent.click(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(currentPasswordInput).toHaveValue('');
|
||||
expect(newPasswordInput).toHaveValue('');
|
||||
expect(confirmPasswordInput).toHaveValue('');
|
||||
});
|
||||
});
|
||||
it('Should request to api and not resetform in error response', async () => {
|
||||
// Render the component
|
||||
render(<MockAppWithProviders><ChangePasswordForm /></MockAppWithProviders>);
|
||||
server.use([rest.get(SET_USER_PASSWORD, (req, res, ctx) => {
|
||||
return res(ctx.status(422))
|
||||
})])
|
||||
|
||||
// Fill in the form fields wrong
|
||||
const currentPasswordInput = screen.queryByLabelText('رمز عبور فعلی');
|
||||
const newPasswordInput = screen.queryByLabelText('رمز عبور جدید');
|
||||
const confirmPasswordInput = screen.queryByLabelText('تکرار رمز عبور جدید');
|
||||
|
||||
fireEvent.change(currentPasswordInput, { target: { value: 'incorrect' } });
|
||||
fireEvent.change(newPasswordInput, { target: { value: 'Witel@fani1' } });
|
||||
fireEvent.change(confirmPasswordInput, { target: { value: 'Witel@fani1' } });
|
||||
|
||||
// Submit the form
|
||||
const submitButton = screen.getByRole('button', { name: 'ثبت' });
|
||||
await userEvent.click(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(currentPasswordInput.value).toBe('incorrect');
|
||||
expect(newPasswordInput.value).toBe('Witel@fani1');
|
||||
expect(confirmPasswordInput.value).toBe('Witel@fani1');
|
||||
});
|
||||
});
|
||||
});
|
||||
})
|
||||
@@ -0,0 +1,137 @@
|
||||
import {Formik, Form} from "formik";
|
||||
import * as Yup from "yup";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {Button, Paper, Stack, Typography} from "@mui/material";
|
||||
import PasswordField from "@/core/components/PasswordField";
|
||||
import StyledForm from "@/core/components/StyledForm";
|
||||
import useRequest from "@/lib/app/hooks/useRequest";
|
||||
import {SET_USER_PASSWORD} from "@/core/data/apiRoutes";
|
||||
|
||||
const ChangePasswordForm = ({onSubmit}) => {
|
||||
const t = useTranslations();
|
||||
const requestServer = useRequest({auth: true})
|
||||
|
||||
const handleSubmit = (values, {setSubmitting, resetForm}) => {
|
||||
requestServer(SET_USER_PASSWORD, 'post', {
|
||||
data: {
|
||||
current_password: values.current_password,
|
||||
new_password: values.new_password,
|
||||
new_password_confirmation: values.new_password_confirmation,
|
||||
},
|
||||
}).then((response) => {
|
||||
resetForm();
|
||||
}).catch(() => {
|
||||
}).finally(() => {
|
||||
setSubmitting(false);
|
||||
});
|
||||
};
|
||||
const initialValues = {
|
||||
current_password: "",
|
||||
new_password: "",
|
||||
new_password_confirmation: "",
|
||||
};
|
||||
const validationSchema = Yup.object().shape({
|
||||
current_password: Yup.string().required(
|
||||
t("ChangePassword.error_message_current_password_required")
|
||||
),
|
||||
new_password: Yup.string()
|
||||
.min(8, t("ChangePassword.error_message_password_length"))
|
||||
.required(t("ChangePassword.error_message_new_password_required")),
|
||||
new_password_confirmation: Yup.string()
|
||||
.required(t("ChangePassword.error_message_confirm_password_required"))
|
||||
.test(
|
||||
t("ChangePassword.error_message_password_match"),
|
||||
t("ChangePassword.error_message_password_not_match"), // Use the correct error message here
|
||||
function (value) {
|
||||
return this.parent.new_password === value;
|
||||
}
|
||||
),
|
||||
});
|
||||
|
||||
return (
|
||||
<Formik
|
||||
initialValues={initialValues}
|
||||
onSubmit={handleSubmit}
|
||||
validationSchema={validationSchema}
|
||||
>
|
||||
{(props) => (
|
||||
<StyledForm
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
props.handleSubmit();
|
||||
}}
|
||||
>
|
||||
<Paper elevation={0}>
|
||||
<Stack spacing={3} sx={{p: 5}} component="div">
|
||||
<Typography margin={2} variant="h4" textAlign="center">
|
||||
{t("ChangePassword.typography_change_password")}
|
||||
</Typography>
|
||||
<Stack spacing={1} component="div">
|
||||
<PasswordField
|
||||
name="current_password"
|
||||
label={t("ChangePassword.label_current_password")}
|
||||
error={
|
||||
props.touched.current_password &&
|
||||
props.errors.current_password
|
||||
? true
|
||||
: false
|
||||
}
|
||||
helperText={
|
||||
props.touched.current_password
|
||||
? props.errors.current_password
|
||||
: null
|
||||
}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack spacing={1} component="div">
|
||||
<PasswordField
|
||||
name="new_password"
|
||||
label={t("ChangePassword.label_new_password")}
|
||||
error={
|
||||
props.touched.new_password && props.errors.new_password
|
||||
? true
|
||||
: false
|
||||
}
|
||||
helperText={
|
||||
props.touched.new_password ? props.errors.new_password : null
|
||||
}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack spacing={1} component="div">
|
||||
<PasswordField
|
||||
name="new_password_confirmation"
|
||||
label={t("ChangePassword.label_confirm_password")}
|
||||
error={
|
||||
props.touched.new_password_confirmation &&
|
||||
props.errors.new_password_confirmation
|
||||
? true
|
||||
: false
|
||||
}
|
||||
helperText={
|
||||
props.touched.new_password_confirmation
|
||||
? props.errors.new_password_confirmation
|
||||
: null
|
||||
}
|
||||
/>
|
||||
</Stack>
|
||||
<Button
|
||||
type="submit"
|
||||
fullWidth
|
||||
variant="contained"
|
||||
color="primary"
|
||||
size="large"
|
||||
disabled={props.isSubmitting || !(props.values.current_password && props.values.new_password && props.values.new_password_confirmation)}
|
||||
>
|
||||
{props.isSubmitting
|
||||
? t("SubmitButton.button_while_submit")
|
||||
: t("SubmitButton.button_submit")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</StyledForm>
|
||||
)}
|
||||
</Formik>
|
||||
);
|
||||
};
|
||||
|
||||
export default ChangePasswordForm;
|
||||
@@ -1,149 +1,18 @@
|
||||
import CenterLayout from "@/layouts/CenterLayout";
|
||||
import DashboardLayouts from "@/layouts/DashboardLayout";
|
||||
import {Button, Container, Paper, Stack, Typography,} from "@mui/material";
|
||||
import {Formik} from "formik";
|
||||
import * as Yup from "yup";
|
||||
import {useTranslations} from "next-intl";
|
||||
import PasswordField from "@/core/components/PasswordField";
|
||||
import StyledForm from "@/core/components/StyledForm";
|
||||
import {SET_USER_PASSWORD} from "@/core/data/apiRoutes";
|
||||
import SvgChangePassword from "@/core/components/svgs/SvgChangePassword";
|
||||
import useRequest from "@/lib/app/hooks/useRequest";
|
||||
import DashboardLayout from "@/layouts/DashboardLayout";
|
||||
import {Container} from "@mui/material";
|
||||
import ChangePasswordForm from "@/components/dashboard/change-password/change-password-form";
|
||||
|
||||
const DashboardChangePasswordComponent = () => {
|
||||
const t = useTranslations();
|
||||
const requestServer = useRequest({auth: true})
|
||||
|
||||
const handleSubmit = (values, {setSubmitting, resetForm}) => {
|
||||
requestServer(SET_USER_PASSWORD, 'post', {
|
||||
data: {
|
||||
current_password: values.current_password,
|
||||
new_password: values.new_password,
|
||||
new_password_confirmation: values.new_password_confirmation,
|
||||
},
|
||||
}).then((response) => {
|
||||
resetForm();
|
||||
}).catch(() => {
|
||||
}).finally(() => {
|
||||
setSubmitting(false);
|
||||
});
|
||||
};
|
||||
const initialValues = {
|
||||
current_password: "",
|
||||
new_password: "",
|
||||
new_password_confirmation: "",
|
||||
};
|
||||
const validationSchema = Yup.object().shape({
|
||||
current_password: Yup.string().required(
|
||||
t("ChangePassword.error_message_required")
|
||||
),
|
||||
new_password: Yup.string()
|
||||
.min(8, t("ChangePassword.error_message_password_length"))
|
||||
.required(t("ChangePassword.error_message_required")),
|
||||
new_password_confirmation: Yup.string()
|
||||
.required(t("ChangePassword.error_message_required"))
|
||||
.test(
|
||||
t("ChangePassword.error_message_password_match"),
|
||||
t("ChangePassword.error_message_password_not_match"),
|
||||
function (value) {
|
||||
return this.parent.new_password === value;
|
||||
}
|
||||
),
|
||||
});
|
||||
|
||||
return (
|
||||
<DashboardLayouts>
|
||||
<DashboardLayout>
|
||||
<CenterLayout>
|
||||
<Container maxWidth="sm">
|
||||
<Formik
|
||||
initialValues={initialValues}
|
||||
onSubmit={handleSubmit}
|
||||
validationSchema={validationSchema}
|
||||
>
|
||||
{(props) => (
|
||||
<StyledForm
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
props.handleSubmit();
|
||||
}}
|
||||
>
|
||||
<Paper elevation={0}>
|
||||
<Stack spacing={3} sx={{p: 5}} component="div">
|
||||
<SvgChangePassword width={300} height={200}/>
|
||||
<Typography margin={2} variant="h4" textAlign="center">
|
||||
{t("ChangePassword.typography_change_password")}
|
||||
</Typography>
|
||||
<Stack spacing={1} component="div">
|
||||
<PasswordField
|
||||
name="current_password"
|
||||
label={t("ChangePassword.label_current_password")}
|
||||
error={
|
||||
props.touched.current_password &&
|
||||
props.errors.current_password
|
||||
? true
|
||||
: false
|
||||
}
|
||||
helperText={
|
||||
props.touched.current_password
|
||||
? props.errors.current_password
|
||||
: null
|
||||
}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack spacing={1} component="div">
|
||||
<PasswordField
|
||||
name="new_password"
|
||||
label={t("ChangePassword.label_new_password")}
|
||||
error={
|
||||
props.touched.new_password &&
|
||||
props.errors.new_password
|
||||
? true
|
||||
: false
|
||||
}
|
||||
helperText={
|
||||
props.touched.new_password
|
||||
? props.errors.new_password
|
||||
: null
|
||||
}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack spacing={1} component="div">
|
||||
<PasswordField
|
||||
name="new_password_confirmation"
|
||||
label={t("ChangePassword.label_confirm_password")}
|
||||
error={
|
||||
props.touched.new_password_confirmation &&
|
||||
props.errors.new_password_confirmation
|
||||
? true
|
||||
: false
|
||||
}
|
||||
helperText={
|
||||
props.touched.new_password_confirmation
|
||||
? props.errors.new_password_confirmation
|
||||
: null
|
||||
}
|
||||
/>
|
||||
</Stack>
|
||||
<Button
|
||||
type="submit"
|
||||
fullWidth
|
||||
variant="contained"
|
||||
color="primary"
|
||||
size="large"
|
||||
disabled={props.isSubmitting}
|
||||
>
|
||||
{props.isSubmitting
|
||||
? t("SubmitButton.button_while_submit")
|
||||
: t("SubmitButton.button_submit")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</StyledForm>
|
||||
)}
|
||||
</Formik>
|
||||
<ChangePasswordForm />
|
||||
</Container>
|
||||
</CenterLayout>
|
||||
</DashboardLayouts>
|
||||
</DashboardLayout>
|
||||
);
|
||||
};
|
||||
export default DashboardChangePasswordComponent;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import StyledForm from "@/core/components/StyledForm";
|
||||
import CenterLayout from "@/layouts/CenterLayout";
|
||||
import DashboardLayouts from "@/layouts/DashboardLayout";
|
||||
import DashboardLayout from "@/layouts/DashboardLayout";
|
||||
import useUser from "@/lib/app/hooks/useUser";
|
||||
import {Box, Container, Grid, Paper, Stack, TextField, Typography,} from "@mui/material";
|
||||
import * as Yup from "yup";
|
||||
@@ -54,7 +54,7 @@ const DashboardEditProfile = () => {
|
||||
const validationSchema = Yup.object().shape({});
|
||||
|
||||
return (
|
||||
<DashboardLayouts>
|
||||
<DashboardLayout>
|
||||
<CenterLayout>
|
||||
<Container maxWidth="sm">
|
||||
<Formik
|
||||
@@ -216,7 +216,7 @@ const DashboardEditProfile = () => {
|
||||
</Formik>
|
||||
</Container>
|
||||
</CenterLayout>
|
||||
</DashboardLayouts>
|
||||
</DashboardLayout>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import DashboardLayouts from "@/layouts/DashboardLayout";
|
||||
import DashboardLayout from "@/layouts/DashboardLayout";
|
||||
|
||||
const DashboardFirstComponent = () => {
|
||||
return <DashboardLayouts></DashboardLayouts>;
|
||||
return <DashboardLayout></DashboardLayout>;
|
||||
};
|
||||
|
||||
export default DashboardFirstComponent;
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import {
|
||||
Button,
|
||||
Checkbox, CircularProgress,
|
||||
DialogActions,
|
||||
DialogContent, DialogTitle,
|
||||
FormControl,
|
||||
FormControlLabel,
|
||||
FormHelperText,
|
||||
FormLabel,
|
||||
Grid,
|
||||
Stack,
|
||||
TextField, Typography
|
||||
} from "@mui/material";
|
||||
import {useTranslations} from "next-intl";
|
||||
import useRequest from "@/lib/app/hooks/useRequest";
|
||||
import * as Yup from "yup";
|
||||
import {useFormik} from "formik";
|
||||
import {ADD_ROLE_MANAGEMENT} from "@/core/data/apiRoutes";
|
||||
import usePermissions from "@/lib/app/hooks/usePermissions";
|
||||
|
||||
const CreateContent = ({mutate, fetchUrl, setOpenConfirmDialog}) => {
|
||||
const t = useTranslations();
|
||||
const requestServer = useRequest({auth: true})
|
||||
const {permissions_list, isLoading} = usePermissions()
|
||||
const validationSchema = Yup.object().shape({
|
||||
name_en: Yup.string().required(t("AddDialog.name_en_error")),
|
||||
name_fa: Yup.string().required(t("AddDialog.name_fa_error")),
|
||||
permissions: Yup.array().min(1, t("AddDialog.permission_min_error")).required(t("AddDialog.permission")),
|
||||
});
|
||||
const formik = useFormik({
|
||||
initialValues: {
|
||||
name_en: "",
|
||||
name_fa: "",
|
||||
permissions: [],
|
||||
}, validationSchema, onSubmit: (values, {setSubmitting}) => {
|
||||
const formData = new FormData();
|
||||
formData.append("name", values.name_en);
|
||||
formData.append("name_fa", values.name_fa);
|
||||
for (let i = 0; i < values.permissions.length; i++) {
|
||||
formData.append(`permissions[${i}]`, values.permissions[i]);
|
||||
}
|
||||
|
||||
requestServer(ADD_ROLE_MANAGEMENT, 'post', {
|
||||
data: formData,
|
||||
}).then(() => {
|
||||
setOpenConfirmDialog(false)
|
||||
mutate(fetchUrl)
|
||||
update_notification()
|
||||
}).catch(() => {
|
||||
}).finally(() => {
|
||||
setSubmitting(false);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogTitle>{t("AddDialog.add")}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack sx={{mt: 2}} spacing={2}>
|
||||
<Stack direction="row" spacing={2}>
|
||||
<TextField
|
||||
name="name_en"
|
||||
label={t("AddDialog.name_en")}
|
||||
type="text"
|
||||
value={formik.values.name}
|
||||
onChange={formik.handleChange}
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
onBlur={formik.handleBlur("name_en")}
|
||||
error={formik.touched.name_en && Boolean(formik.errors.name_en)}
|
||||
helperText={formik.touched.name_en && formik.errors.name_en}
|
||||
|
||||
/>
|
||||
<TextField
|
||||
name="name_fa"
|
||||
label={t("AddDialog.name_fa")}
|
||||
value={formik.values.name_fa}
|
||||
onChange={formik.handleChange}
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
onBlur={formik.handleBlur("name_fa")}
|
||||
error={formik.touched.name_fa && Boolean(formik.errors.name_fa)}
|
||||
helperText={formik.touched.name_fa && formik.errors.name_fa}
|
||||
|
||||
/>
|
||||
</Stack>
|
||||
<Stack>
|
||||
<FormLabel>{t("AddDialog.permission")}<br/>
|
||||
<FormControl
|
||||
name="permissions"
|
||||
error={formik.touched.permissions && Boolean(formik.errors.permissions)}
|
||||
onBlur={formik.handleBlur("permissions")}
|
||||
sx={{mt: 2}}
|
||||
fullWidth
|
||||
>
|
||||
<FormHelperText>{formik.touched.permissions && formik.errors.permissions}</FormHelperText>
|
||||
{isLoading ?
|
||||
<Stack direction={'row'} alignItems={'center'} spacing={2} justifyContent={'center'}>
|
||||
<CircularProgress size={20}/>
|
||||
<Typography variant={'caption'}>{t("AddDialog.loading_permissions_list")}</Typography>
|
||||
</Stack>
|
||||
:(
|
||||
<Grid container spacing={2}>
|
||||
<>
|
||||
{permissions_list.map((permission) => (
|
||||
<Grid key={permission.id} item xs={6}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
data-testid="PermissionList-checkbox"
|
||||
checked={formik.values.permissions.includes(permission.id)}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
formik.setFieldValue("permissions", [...formik.values.permissions, permission.id])
|
||||
} else {
|
||||
formik.setFieldValue("permissions", formik.values.permissions.filter((id) => id !== permission.id))
|
||||
}
|
||||
}}
|
||||
/>
|
||||
}
|
||||
label={permission.name_fa}
|
||||
/>
|
||||
</Grid>
|
||||
))}
|
||||
</>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
</FormControl>
|
||||
</FormLabel>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setOpenConfirmDialog(false)} variant="outlined" color="secondary"
|
||||
disabled={formik.isSubmitting} autoFocus>
|
||||
{t("AddDialog.button-cancel")}
|
||||
</Button>
|
||||
<Button onClick={formik.handleSubmit} variant="contained" color="primary"
|
||||
disabled={formik.isSubmitting}>
|
||||
{t("AddDialog.button-add")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default CreateContent
|
||||
@@ -0,0 +1,167 @@
|
||||
import {act, fireEvent, render, screen, waitFor} from "@testing-library/react";
|
||||
import MockAppWithProviders from "../../../../../../../mocks/AppWithProvider";
|
||||
import CreateContent from "@/components/dashboard/role-management/Form/CreateForm/CreateContent";
|
||||
|
||||
describe("Create Content component from Create Form Component in Role Management Component",()=>{
|
||||
describe("Rendering", ()=>{
|
||||
it('should see AddDialog text in the top ', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.queryByText("افزودن")
|
||||
await waitFor(()=>{
|
||||
expect(textElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see name_en text', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.queryByLabelText("نام انگلیسی")
|
||||
await waitFor(()=>{
|
||||
expect(textElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see name_fa text', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.queryByLabelText("نام فارسی")
|
||||
await waitFor(()=>{
|
||||
expect(textElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see name_fa text', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.queryByLabelText("نام فارسی")
|
||||
await waitFor(()=>{
|
||||
expect(textElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
})
|
||||
describe("Behavior",()=>{
|
||||
it('should see what fill in the name_en input', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const nameEnglishInput = screen.getByLabelText('نام انگلیسی');
|
||||
|
||||
fireEvent.change(nameEnglishInput, {target: {value: 'testuser'}});
|
||||
await act(()=>{
|
||||
// Simulate user input
|
||||
expect(nameEnglishInput).toHaveValue('testuser');
|
||||
})
|
||||
});
|
||||
it('should see what fill in the name_fa input', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const nameFarsiInput = screen.getByLabelText('نام فارسی');
|
||||
|
||||
fireEvent.change(nameFarsiInput, {target: {value: 'testuser'}});
|
||||
await act(()=>{
|
||||
// Simulate user input
|
||||
expect(nameFarsiInput).toHaveValue('testuser');
|
||||
})
|
||||
});
|
||||
it('should return permissions_list', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const checkboxElement = await screen.findAllByTestId("PermissionList-checkbox")
|
||||
expect(checkboxElement).toHaveLength(2)
|
||||
});
|
||||
it('should get checked if permission list item get clicked', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const checkboxElement = screen.getByLabelText("مدیریت کارتابل رییس اداره مسافری استان")
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(checkboxElement).not.toBeChecked();
|
||||
})
|
||||
|
||||
fireEvent.click(checkboxElement);
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(checkboxElement).toBeChecked();
|
||||
})
|
||||
});
|
||||
})
|
||||
describe("Validation",()=>{
|
||||
it('should see error text when name_fa input is empty', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const name_faInput = screen.getByLabelText("نام فارسی")
|
||||
expect(screen.queryByText("وارد کردن نام فارسی الزامیست")).not.toBeInTheDocument()
|
||||
fireEvent.blur(name_faInput);
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن نام فارسی الزامیست")).toBeInTheDocument()
|
||||
})
|
||||
fireEvent.change(name_faInput, {target : {value : "نام فارسی"}})
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن نام فارسی الزامیست")).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
it('should see error text when name_en input is empty', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const name_enInput = screen.getByLabelText("نام انگلیسی")
|
||||
expect(screen.queryByText("وارد کردن نام انگلیسی الزامیست")).not.toBeInTheDocument()
|
||||
fireEvent.blur(name_enInput);
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن نام انگلیسی الزامیست")).toBeInTheDocument()
|
||||
})
|
||||
fireEvent.change(name_enInput, {target : {value : "english name"}})
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن نام انگلیسی الزامیست")).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
it('should see errors when click on submit button and field not completed', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateContent/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const submitButtonElement = screen.queryByText("ثبت")
|
||||
fireEvent.click(submitButtonElement)
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن نام انگلیسی الزامیست")).toBeInTheDocument()
|
||||
})
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن نام فارسی الزامیست")).toBeInTheDocument()
|
||||
})
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("حداقل باید یک دسترسی انتخاب شود")).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import {fireEvent, queryByText, render, screen, waitFor} from "@testing-library/react";
|
||||
import CreateForm from "@/components/dashboard/role-management/Form/CreateForm";
|
||||
import MockAppWithProviders from "../../../../../../../mocks/AppWithProvider";
|
||||
|
||||
describe("Create Form Component from Role Management Component",()=>{
|
||||
describe("Rendering",()=>{
|
||||
|
||||
it('should see Dialog text', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateForm />
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.queryByText("افزودن")
|
||||
await waitFor(()=>{
|
||||
expect(textElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
|
||||
it('should see Tooltip text when mouse over', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<CreateForm />
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const buttonElement = screen.getByText("افزودن");
|
||||
fireEvent.mouseOver(buttonElement);
|
||||
const tooltipTextElement = screen.getByText("افزودن");
|
||||
await waitFor(()=>{
|
||||
expect(tooltipTextElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import {Button, Dialog, DialogTitle, Stack, Tooltip} from "@mui/material";
|
||||
import DataSaverOnIcon from "@mui/icons-material/DataSaverOn";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {useState} from "react";
|
||||
import CreateContent from "./CreateContent";
|
||||
|
||||
const CreateForm = ({mutate, fetchUrl}) => {
|
||||
const t = useTranslations();
|
||||
const [openConfirmDialog, setOpenConfirmDialog] = useState(false);
|
||||
|
||||
return (
|
||||
<Stack direction={"row"} spacing={2}>
|
||||
<Tooltip title={t("AddDialog.add")} arrow placement="right">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="contained"
|
||||
size="small"
|
||||
sx={{textTransform: "unset", alignSelf: "center"}}
|
||||
startIcon={<DataSaverOnIcon/>}
|
||||
onClick={() => {
|
||||
setOpenConfirmDialog(true)
|
||||
}}
|
||||
>
|
||||
{t("AddDialog.add")}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Dialog maxWidth={"lg"} open={openConfirmDialog}
|
||||
PaperProps={{sx: {boxShadow: 'rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px'}}}>
|
||||
<CreateContent mutate={mutate} fetchUrl={fetchUrl} setOpenConfirmDialog={setOpenConfirmDialog}/>
|
||||
</Dialog>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
export default CreateForm
|
||||
@@ -0,0 +1,42 @@
|
||||
import {Button, DialogActions, DialogContent, DialogTitle, Typography} from "@mui/material";
|
||||
import {DELETE_ROLE_MANAGEMENT} from "@/core/data/apiRoutes";
|
||||
import {useState} from "react";
|
||||
import useRequest from "@/lib/app/hooks/useRequest";
|
||||
import useNotification from "@/lib/app/hooks/useNotification";
|
||||
import {useTranslations} from "next-intl";
|
||||
|
||||
const DeleteContent = ({rowId, fetchUrl, mutate, setOpenConfirmDialog}) => {
|
||||
const t = useTranslations();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const requestServer = useRequest({auth: true})
|
||||
const {update_notification} = useNotification()
|
||||
const handleSubmit = () => {
|
||||
setIsSubmitting(true)
|
||||
requestServer(`${DELETE_ROLE_MANAGEMENT}/${rowId}`, 'delete').then((response) => {
|
||||
mutate(fetchUrl)
|
||||
update_notification()
|
||||
}).catch(() => {
|
||||
}).finally(() => {
|
||||
setIsSubmitting(false)
|
||||
});
|
||||
}
|
||||
return(
|
||||
<>
|
||||
<DialogTitle>{t("DeleteDialog.delete")}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography>{t("DeleteDialog.typography")}</Typography>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setOpenConfirmDialog(false)} variant="outlined" color="secondary"
|
||||
disabled={isSubmitting} autoFocus>
|
||||
{t("DeleteDialog.button-cancel")}
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} variant="contained" color="primary"
|
||||
disabled={isSubmitting}>
|
||||
{t("DeleteDialog.button-delete")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default DeleteContent
|
||||
@@ -0,0 +1,53 @@
|
||||
import {act, render, screen} from "@testing-library/react";
|
||||
import MockAppWithProviders from "../../../../../../../mocks/AppWithProvider";
|
||||
import DeleteContent from "@/components/dashboard/role-management/Form/DeleteForm/DeleteContent";
|
||||
import UpdateContent from "@/components/dashboard/role-management/Form/UpdateForm/UpdateContent";
|
||||
|
||||
describe("Create Content component from Create Form Component in Role Management Component",()=> {
|
||||
describe("Rendering", () => {
|
||||
it('should see DeleteDialog text in the top ', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<DeleteContent rowId={1}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.queryByText("حذف")
|
||||
act(()=>{
|
||||
expect(textElement).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
it('should see DeleteDialog text content ', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<DeleteContent rowId={1}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.queryByText("آیا از حدف این مورد اطمینان دارید ؟")
|
||||
act(()=>{
|
||||
expect(textElement).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
it('should see delete text in the delete button ', () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<DeleteContent rowId={1}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const buttonElement = screen.queryByText("حذف کردن")
|
||||
act(()=>{
|
||||
expect(buttonElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see cancel text in the cancel button ', () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<DeleteContent rowId={1}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const buttonElement = screen.queryByText("انصراف")
|
||||
act(()=>{
|
||||
expect(buttonElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
import {fireEvent, render, screen, waitFor} from "@testing-library/react";
|
||||
import MockAppWithProviders from "../../../../../../../mocks/AppWithProvider";
|
||||
import DeleteForm from "@/components/dashboard/role-management/Form/DeleteForm";
|
||||
import UpdateForm from "@/components/dashboard/role-management/Form/UpdateForm";
|
||||
|
||||
describe("Create Form Component from Role Management Component",()=> {
|
||||
describe("Rendering", () => {
|
||||
it('should see Dialog text when mouse is over', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<DeleteForm />
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.getByTestId("dialog_tooltip")
|
||||
fireEvent.mouseOver(textElement)
|
||||
await waitFor(()=>{
|
||||
expect(screen.getByText("حذف")).toBeInTheDocument();
|
||||
})
|
||||
});
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import {useTranslations} from "next-intl";
|
||||
import {useState} from "react";
|
||||
import {
|
||||
Dialog, IconButton,
|
||||
Tooltip,
|
||||
} from "@mui/material";
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
import DeleteContent from "@/components/dashboard/role-management/Form/DeleteForm/DeleteContent";
|
||||
|
||||
const DeleteForm = ({rowId, fetchUrl, mutate}) => {
|
||||
const t = useTranslations();
|
||||
const [openConfirmDialog, setOpenConfirmDialog] = useState(false);
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<Tooltip title={t("DeleteDialog.delete")}>
|
||||
<IconButton
|
||||
data-testid="dialog_tooltip"
|
||||
color="primary"
|
||||
onClick={() => {
|
||||
setOpenConfirmDialog(true)
|
||||
}}
|
||||
>
|
||||
<DeleteIcon/>
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Dialog maxWidth="sm" open={openConfirmDialog}
|
||||
PaperProps={{sx: {boxShadow: 'rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px'}}}>
|
||||
<DeleteContent rowId={rowId} fetchUrl={fetchUrl} mutate={mutate} setOpenConfirmDialog={setOpenConfirmDialog} />
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
export default DeleteForm;
|
||||
@@ -0,0 +1,147 @@
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Checkbox, CircularProgress, DialogActions,
|
||||
DialogContent, DialogTitle,
|
||||
FormControl,
|
||||
FormControlLabel,
|
||||
FormHelperText,
|
||||
FormLabel,
|
||||
Grid,
|
||||
Stack,
|
||||
TextField, Typography
|
||||
} from "@mui/material";
|
||||
import {useFormik} from "formik";
|
||||
import {UPDATE_ROLE_MANAGEMENT} from "@/core/data/apiRoutes";
|
||||
import * as Yup from "yup";
|
||||
import usePermissions from "@/lib/app/hooks/usePermissions";
|
||||
import useNotification from "@/lib/app/hooks/useNotification";
|
||||
import useRequest from "@/lib/app/hooks/useRequest";
|
||||
import {useTranslations} from "next-intl";
|
||||
|
||||
const UpdateContent = ({mutate, row, fetchUrl, setOpenConfirmDialog}) => {
|
||||
const t = useTranslations();
|
||||
const requestServer = useRequest({auth: true})
|
||||
const {update_notification} = useNotification()
|
||||
const {permissions_list, isLoading} = usePermissions()
|
||||
|
||||
const validationSchema = Yup.object().shape({
|
||||
name_en: Yup.string().required(t("UpdateDialog.name_en_error")),
|
||||
name_fa: Yup.string().required(t("UpdateDialog.name_fa_error")),
|
||||
permissions: Yup.array().min(1, t("UpdateDialog.permission_min_error")).required(t("UpdateDialog.permission")),
|
||||
});
|
||||
|
||||
const formik = useFormik({
|
||||
initialValues: {
|
||||
name_en: row.getValue("name"),
|
||||
name_fa: row.getValue("name_fa"),
|
||||
permissions: row.original.permissions.map((obj) => obj.id),
|
||||
}, validationSchema, onSubmit: (values, {setSubmitting}) => {
|
||||
const formData = new FormData();
|
||||
formData.append("name", values.name_en);
|
||||
formData.append("name_fa", values.name_fa);
|
||||
for (let i = 0; i < values.permissions.length; i++) {
|
||||
formData.append(`permissions[${i}]`, values.permissions[i]);
|
||||
}
|
||||
|
||||
requestServer(`${UPDATE_ROLE_MANAGEMENT}/${row.getValue("id")}`, 'post', {
|
||||
data: formData,
|
||||
}).then((response) => {
|
||||
mutate(fetchUrl)
|
||||
update_notification()
|
||||
}).catch(() => {
|
||||
}).finally(() => {
|
||||
setSubmitting(false);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return(
|
||||
<>
|
||||
<DialogTitle>{t("UpdateDialog.update")}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack sx={{mt: 2}} spacing={2}>
|
||||
<Stack direction="row" spacing={2} sx={{mt: 1}}>
|
||||
<TextField
|
||||
name="name_en"
|
||||
label={t("UpdateDialog.name_en")}
|
||||
value={formik.values.name_en}
|
||||
onChange={formik.handleChange}
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
onBlur={formik.handleBlur("name_en")}
|
||||
error={formik.touched.name_en && Boolean(formik.errors.name_en)}
|
||||
helperText={formik.touched.name_en && formik.errors.name_en}
|
||||
/>
|
||||
<TextField
|
||||
name="name_fa"
|
||||
label={t("UpdateDialog.name_fa")}
|
||||
value={formik.values.name_fa}
|
||||
onChange={formik.handleChange}
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
onBlur={formik.handleBlur("name_fa")}
|
||||
error={formik.touched.name_fa && Boolean(formik.errors.name_fa)}
|
||||
helperText={formik.touched.name_fa && formik.errors.name_fa}
|
||||
/>
|
||||
</Stack>
|
||||
<Stack>
|
||||
<FormLabel>{t("UpdateDialog.permission")}<br/>
|
||||
<FormControl
|
||||
name="permissions"
|
||||
error={formik.touched.permissions && Boolean(formik.errors.permissions)}
|
||||
onBlur={formik.handleBlur("permissions")}
|
||||
sx={{mt: 2}}
|
||||
fullWidth
|
||||
>
|
||||
<FormHelperText>{formik.touched.permissions && formik.errors.permissions}</FormHelperText>
|
||||
{isLoading ?
|
||||
<Stack direction={'row'} alignItems={'center'} spacing={2} justifyContent={'center'}>
|
||||
<CircularProgress size={20}/>
|
||||
<Typography variant={'caption'}>{t("UpdateDialog.loading_permissions_list")}</Typography>
|
||||
</Stack>
|
||||
:(
|
||||
<Grid container spacing={2}>
|
||||
<>
|
||||
{permissions_list.map((permission) => (
|
||||
<Grid key={permission.id} item xs={6}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
data-testid="PermissionList-checkbox"
|
||||
checked={formik.values.permissions.includes(permission.id)}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
formik.setFieldValue("permissions", [...formik.values.permissions, permission.id])
|
||||
} else {
|
||||
formik.setFieldValue("permissions", formik.values.permissions.filter((id) => id !== permission.id))
|
||||
}
|
||||
}}
|
||||
/>
|
||||
}
|
||||
label={permission.name_fa}
|
||||
/>
|
||||
</Grid>
|
||||
))}
|
||||
</>
|
||||
</Grid>
|
||||
)}
|
||||
</FormControl>
|
||||
</FormLabel>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setOpenConfirmDialog(false)} variant="outlined" color="secondary"
|
||||
disabled={formik.isSubmitting} autoFocus>
|
||||
{t("UpdateDialog.button-cancel")}
|
||||
</Button>
|
||||
<Button onClick={formik.handleSubmit} variant="contained" color="primary"
|
||||
disabled={formik.isSubmitting}>
|
||||
{t("UpdateDialog.button-update")}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default UpdateContent
|
||||
@@ -0,0 +1,209 @@
|
||||
import {act, fireEvent, render, screen, waitFor} from "@testing-library/react";
|
||||
import MockAppWithProviders from "../../../../../../../mocks/AppWithProvider";
|
||||
import UpdateContent from "@/components/dashboard/role-management/Form/UpdateForm/UpdateContent";
|
||||
const row = {
|
||||
id : 0,
|
||||
getValue : name => {
|
||||
if (name === "name") {
|
||||
return "manage_passenger_office_navgan";
|
||||
}
|
||||
else if (name === "name_fa") {
|
||||
return "مدیریت کارتابل رییس اداره مسافری استان";
|
||||
}
|
||||
},
|
||||
original : {
|
||||
permissions : [
|
||||
{
|
||||
id: 1,
|
||||
name: "manage_passenger_office_navgan",
|
||||
name_fa: "مدیریت کارتابل رییس اداره مسافری استان"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "manage_passenger_office_navgan",
|
||||
name_fa: "مدیریت کارتابل رییس اداره مسافری استان"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
describe("Create Content component from Create Form Component in Role Management Component",()=>{
|
||||
describe("Rendering", ()=>{
|
||||
it('should see AddDialog text in the top ', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.queryByText("ویرایش")
|
||||
await waitFor(()=>{
|
||||
expect(textElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see name_en text', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.queryByLabelText("نام انگلیسی")
|
||||
await waitFor(()=>{
|
||||
expect(textElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see name_fa text', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const textElement = screen.queryByLabelText("نام فارسی")
|
||||
await waitFor(()=>{
|
||||
expect(textElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see update text in the submit button ', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const buttonElement = screen.queryByText("ثبت")
|
||||
await waitFor(()=>{
|
||||
expect(buttonElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see cancel text in the cancel button ', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const buttonElement = screen.queryByText("بستن")
|
||||
await waitFor(()=>{
|
||||
expect(buttonElement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
})
|
||||
|
||||
describe("Behavior", ()=>{
|
||||
it('should see what fill in the name_en input', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const nameEnglishInput = screen.getByLabelText('نام انگلیسی');
|
||||
|
||||
fireEvent.change(nameEnglishInput, {target: {value: 'testuser'}});
|
||||
await waitFor(()=>{
|
||||
// Simulate user input
|
||||
expect(nameEnglishInput).toHaveValue('testuser');
|
||||
})
|
||||
});
|
||||
it('should see what fill in the name_fa input', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const nameFarsiInput = screen.getByLabelText('نام فارسی');
|
||||
|
||||
fireEvent.change(nameFarsiInput, {target: {value: 'testuser'}});
|
||||
await waitFor(()=>{
|
||||
// Simulate user input
|
||||
expect(nameFarsiInput).toHaveValue('testuser');
|
||||
})
|
||||
});
|
||||
it('should return permissions_list', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const checkboxElement = await screen.findAllByTestId("PermissionList-checkbox")
|
||||
await waitFor(()=>{
|
||||
expect(checkboxElement).toHaveLength(2)
|
||||
})
|
||||
});
|
||||
it('should see the value of the name_en that pass to input value', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const name_enElement = screen.getByLabelText("نام انگلیسی")
|
||||
await waitFor(()=>{
|
||||
expect(name_enElement).toHaveValue("manage_passenger_office_navgan")
|
||||
})
|
||||
});
|
||||
it('should see the value of the name_fa that pass to input value', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const name_enElement = screen.getByLabelText("نام فارسی")
|
||||
await waitFor(()=>{
|
||||
expect(name_enElement).toHaveValue("مدیریت کارتابل رییس اداره مسافری استان")
|
||||
})
|
||||
});
|
||||
it('should get checked if the id exists in permission lists', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const checkboxElement = screen.getByLabelText("مدیریت کارتابل رییس اداره مسافری استان")
|
||||
await waitFor(()=>{
|
||||
expect(checkboxElement).toBeChecked();
|
||||
})
|
||||
|
||||
});
|
||||
})
|
||||
describe("Validation", ()=>{
|
||||
it('should see error text when name_fa input is empty', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const name_faInput = screen.getByLabelText("نام فارسی")
|
||||
expect(screen.queryByText("وارد کردن نام فارسی الزامیست")).not.toBeInTheDocument()
|
||||
fireEvent.change(name_faInput, {target : {value : ''}});
|
||||
|
||||
fireEvent.blur(name_faInput)
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن نام فارسی الزامیست")).toBeInTheDocument()
|
||||
})
|
||||
fireEvent.change(name_faInput, {target : {value : "نام فارسی"}})
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن نام فارسی الزامیست")).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
it('should see error text when name_en input is empty', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateContent row={row}/>
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const name_enInput = screen.getByLabelText("نام انگلیسی")
|
||||
expect(screen.queryByText("وارد کردن نام انگلیسی الزامیست")).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.change(name_enInput, {target : {value : null}});
|
||||
fireEvent.blur(name_enInput)
|
||||
|
||||
await waitFor(()=>{
|
||||
|
||||
expect(screen.queryByText("وارد کردن نام انگلیسی الزامیست")).toBeInTheDocument()
|
||||
})
|
||||
fireEvent.change(name_enInput, {target : {value : "english name"}})
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("وارد کردن نام انگلیسی الزامیست")).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import {fireEvent, render, screen, waitFor} from "@testing-library/react";
|
||||
import MockAppWithProviders from "../../../../../../../mocks/AppWithProvider";
|
||||
import UpdateContent from "@/components/dashboard/role-management/Form/UpdateForm/UpdateContent";
|
||||
import UpdateForm from "@/components/dashboard/role-management/Form/UpdateForm";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
|
||||
describe("Create Form Component from Role Management Component",()=>{
|
||||
describe("Rendering",()=>{
|
||||
it('should see Tooltip text when mouse over', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<UpdateForm />
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const buttonElement = screen.getByTestId("dialog_tooltip");
|
||||
fireEvent.mouseOver(buttonElement);
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText("ویرایش")).toBeVisible();
|
||||
})
|
||||
});
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import {Dialog, IconButton, Stack, Tooltip} from "@mui/material";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {useState} from "react";
|
||||
import UpdateContent from "@/components/dashboard/role-management/Form/UpdateForm/UpdateContent";
|
||||
import EditIcon from "@mui/icons-material/Edit";
|
||||
|
||||
const UpdateForm = ({mutate, fetchUrl, row}) => {
|
||||
const t = useTranslations();
|
||||
const [openConfirmDialog, setOpenConfirmDialog] = useState(false);
|
||||
|
||||
return (
|
||||
<Stack direction={"row"} spacing={2}>
|
||||
<Tooltip title={t("UpdateDialog.update")} arrow placement="right">
|
||||
<IconButton
|
||||
data-testid="dialog_tooltip"
|
||||
color="primary"
|
||||
onClick={() => {
|
||||
setOpenConfirmDialog(true);
|
||||
}}
|
||||
>
|
||||
<EditIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Dialog maxWidth={"md"} open={openConfirmDialog}
|
||||
PaperProps={{sx: {boxShadow: 'rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px'}}}>
|
||||
<UpdateContent mutate={mutate} row={row} fetchUrl={fetchUrl} setOpenConfirmDialog={setOpenConfirmDialog}/>
|
||||
</Dialog>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
export default UpdateForm
|
||||
@@ -0,0 +1,94 @@
|
||||
import DataTable from "@/core/components/DataTable";
|
||||
import {GET_ROLE_MANAGEMENT} from "@/core/data/apiRoutes";
|
||||
import TableRowActions from "@/components/dashboard/role-management/TableRowActions";
|
||||
import {Box, Typography} from "@mui/material";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {useMemo} from "react";
|
||||
import moment from "jalali-moment";
|
||||
import MuiDatePicker from "@/core/components/MuiDatePicker";
|
||||
import TableToolbar from "@/components/dashboard/role-management/TableToolbar";
|
||||
|
||||
const RoleManagementComponent = () => {
|
||||
const t = useTranslations();
|
||||
|
||||
const columns = useMemo(() => [{
|
||||
accessorFn: (row) => row.id,
|
||||
id: "id",
|
||||
sortDescFirst: true,
|
||||
header: t("RoleManagement.id"),
|
||||
enableColumnFilter: true,
|
||||
datatype: "numeric",
|
||||
filterFn: "equals",
|
||||
columnFilterModeOptions: ["equals", "notEquals", "contains", "lessThan", "greaterThan", "between",],
|
||||
Cell: ({renderedCellValue}) => (<Typography variant="body2">{renderedCellValue}</Typography>),
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.name_fa,
|
||||
id: "name_fa",
|
||||
header: t("RoleManagement.name_fa"),
|
||||
enableColumnFilter: true,
|
||||
datatype: "text",
|
||||
filterFn: "contains",
|
||||
columnFilterModeOptions: ["contains", "equals", "notEquals"],
|
||||
Cell: ({renderedCellValue}) => (<Typography variant="body2">{renderedCellValue}</Typography>),
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => row.name,
|
||||
id: "name",
|
||||
header: t("RoleManagement.name"),
|
||||
enableColumnFilter: true,
|
||||
datatype: "text",
|
||||
filterFn: "contains",
|
||||
columnFilterModeOptions: ["contains"],
|
||||
Cell: ({renderedCellValue}) => (<Typography variant="body2">{renderedCellValue}</Typography>),
|
||||
},
|
||||
{
|
||||
accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"),
|
||||
id: "created_at",
|
||||
header: t("RoleManagement.created_at"),
|
||||
enableColumnFilter: true,
|
||||
datatype: "date",
|
||||
filterFn: "lessThan",
|
||||
columnFilterModeOptions: ["lessThan", "greaterThan"],
|
||||
Cell: ({renderedCellValue}) => {
|
||||
return <Typography variant="body2">{renderedCellValue}</Typography>;
|
||||
},
|
||||
Header: ({column}) => <>{column.columnDef.header}</>,
|
||||
Filter: ({column}) => {
|
||||
return (<MuiDatePicker column={column}/>);
|
||||
},
|
||||
}, {
|
||||
accessorFn: (row) => moment(row.updated_at).locale("fa").format("HH:mm | yyyy/MM/DD"),
|
||||
id: "updated_at",
|
||||
header: t("RoleManagement.updated_at"),
|
||||
enableColumnFilter: false,
|
||||
datatype: "numeric",
|
||||
Cell: ({renderedCellValue}) => (<Typography variant="body2">{renderedCellValue}</Typography>),
|
||||
}], []);
|
||||
return(
|
||||
<Box sx={{px: 3}}>
|
||||
<DataTable
|
||||
tableUrl={GET_ROLE_MANAGEMENT}
|
||||
columns={columns}
|
||||
selectableRow={false}
|
||||
enableCustomToolbar={true}
|
||||
CustomToolbar={TableToolbar}
|
||||
enableLastUpdate={true}
|
||||
enablePinning={true}
|
||||
enableDensityToggle={false}
|
||||
sorting={[{
|
||||
id: 'id', desc: true
|
||||
}]}
|
||||
initialState={{density: 'compact'}} //compact (small) //comfortable (medium) //spacious (large)
|
||||
enableColumnFilters={true}
|
||||
enableHiding={true}
|
||||
enableFullScreenToggle={false}
|
||||
enableGlobalFilter={false}
|
||||
enableColumnResizing={false} // if you want true this you should change renderRowActions props ** see https://www.material-react-table.com/docs/guides/row-actions
|
||||
enableRowActions={true}
|
||||
TableRowAction={TableRowActions}
|
||||
/>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
export default RoleManagementComponent
|
||||
24
src/components/dashboard/role-management/TableRowActions.jsx
Normal file
24
src/components/dashboard/role-management/TableRowActions.jsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import {Box} from "@mui/material";
|
||||
import UpdateForm from "@/components/dashboard/role-management/Form/UpdateForm";
|
||||
import DeleteForm from "@/components/dashboard/role-management/Form/DeleteForm";
|
||||
|
||||
|
||||
const TableRowActions = ({row, mutate, fetchUrl}) => {
|
||||
|
||||
return (
|
||||
<Box sx={{display: "flex", flexWrap: "nowrap", gap: "8px"}}>
|
||||
<UpdateForm
|
||||
row={row}
|
||||
mutate={mutate}
|
||||
fetchUrl={fetchUrl}
|
||||
/>
|
||||
<DeleteForm
|
||||
rowId={row.getValue("id")}
|
||||
fetchUrl={fetchUrl}
|
||||
mutate={mutate}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default TableRowActions;
|
||||
11
src/components/dashboard/role-management/TableToolbar.jsx
Normal file
11
src/components/dashboard/role-management/TableToolbar.jsx
Normal file
@@ -0,0 +1,11 @@
|
||||
import {useTranslations} from "next-intl";
|
||||
import CreateForm from "@/components/dashboard/role-management/Form/CreateForm";
|
||||
|
||||
function TableToolbar({mutate, fetchUrl}) {
|
||||
const t = useTranslations();
|
||||
|
||||
return <CreateForm mutate={mutate} fetchUrl={fetchUrl}/>
|
||||
|
||||
}
|
||||
|
||||
export default TableToolbar;
|
||||
@@ -0,0 +1,63 @@
|
||||
import {render, screen, waitFor} from "@testing-library/react";
|
||||
import MockAppWithProviders from "../../../../../mocks/AppWithProvider";
|
||||
import RoleManagementComponent from "@/components/dashboard/role-management/RoleManagementComponent";
|
||||
|
||||
describe("Role Management", ()=>{
|
||||
describe("Rendering", ()=>{
|
||||
it('should see id title of data table', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<RoleManagementComponent />
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const idEelement = screen.queryByText("کد یکتا")
|
||||
await waitFor(()=>{
|
||||
expect(idEelement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see name title of data table', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<RoleManagementComponent />
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const nameEelement = screen.queryByText("نام انگلیسی")
|
||||
await waitFor(()=>{
|
||||
expect(nameEelement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see name_fa title of data table', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<RoleManagementComponent />
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const name_faEelement = screen.queryByText("نام فارسی")
|
||||
await waitFor(()=>{
|
||||
expect(name_faEelement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see created at title of data table', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<RoleManagementComponent />
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const createdEelement = screen.queryByText("تاریخ درخواست")
|
||||
await waitFor(()=>{
|
||||
expect(createdEelement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
it('should see updated at title of data table', async () => {
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<RoleManagementComponent />
|
||||
</MockAppWithProviders>
|
||||
)
|
||||
const updateEelement = screen.queryByText("تاریخ بروزرسانی")
|
||||
await waitFor(()=>{
|
||||
expect(updateEelement).toBeInTheDocument()
|
||||
})
|
||||
});
|
||||
})
|
||||
})
|
||||
13
src/components/dashboard/role-management/index.jsx
Normal file
13
src/components/dashboard/role-management/index.jsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import RoleManagementComponent from "@/components/dashboard/role-management/RoleManagementComponent";
|
||||
import DashboardLayout from "@/layouts/DashboardLayout";
|
||||
|
||||
function DashboardRoleManagementComponent() {
|
||||
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<RoleManagementComponent />
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
|
||||
export default DashboardRoleManagementComponent;
|
||||
@@ -1,13 +0,0 @@
|
||||
import PermPhoneMsgIcon from '@mui/icons-material/PermPhoneMsg';
|
||||
import StyledFab from "@/core/components/StyledFab";
|
||||
|
||||
const CallWidgetButton = ({setOpen}) => {
|
||||
return (
|
||||
<StyledFab color="primary" aria-label="open-dialog"
|
||||
onClick={() => setOpen(true)}>
|
||||
<PermPhoneMsgIcon/>
|
||||
</StyledFab>
|
||||
)
|
||||
}
|
||||
|
||||
export default CallWidgetButton
|
||||
@@ -0,0 +1,7 @@
|
||||
const CallActions = ({tab}) => {
|
||||
return (
|
||||
<>CallActions - {tab.id}</>
|
||||
)
|
||||
}
|
||||
|
||||
export default CallActions
|
||||
@@ -0,0 +1,7 @@
|
||||
const CallHistory = ({tab}) => {
|
||||
return (
|
||||
<>CallHistory - {tab.id}</>
|
||||
)
|
||||
}
|
||||
|
||||
export default CallHistory
|
||||
@@ -0,0 +1,19 @@
|
||||
import {Grid} from "@mui/material";
|
||||
import CallActions from "@/components/layouts/Dashboard/CallWidget/CallWidgetDialog/CallTabs/CallTabPanel/CallActions";
|
||||
import CallHistory from "@/components/layouts/Dashboard/CallWidget/CallWidgetDialog/CallTabs/CallTabPanel/CallHistory";
|
||||
|
||||
const CallTabPanel = ({tab}) => {
|
||||
return (
|
||||
<Grid container columns={{xs: 3}} sx={{display: !tab.active && 'none'}} role="tabpanel"
|
||||
id={`answer-tabpanel-${tab.id}`} aria-labelledby={`answer-tab-${tab.id}`}>
|
||||
<Grid item xs={2}>
|
||||
<CallActions tab={tab}/>
|
||||
</Grid>
|
||||
<Grid item xs={1}>
|
||||
<CallHistory tab={tab}/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
)
|
||||
}
|
||||
|
||||
export default CallTabPanel
|
||||
@@ -0,0 +1,23 @@
|
||||
import {IconButton, Stack, Typography, Zoom} from "@mui/material";
|
||||
import CloseIcon from '@mui/icons-material/Close';
|
||||
import useAnswers from "@/lib/callWidget/hooks/useAnswers";
|
||||
|
||||
const CallTabLabel = ({tab}) => {
|
||||
const {closeAnswerTab} = useAnswers()
|
||||
const handleCloseClick = (id) => {
|
||||
closeAnswerTab(id)
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack sx={{width: '100%'}} direction={'row'} alignItems={'center'} justifyContent={'space-between'}>
|
||||
<Typography>{tab.phone_number} - {tab.id}</Typography>
|
||||
<Zoom in={tab.active}>
|
||||
<IconButton onClick={() => handleCloseClick(tab.id)}>
|
||||
<CloseIcon/>
|
||||
</IconButton>
|
||||
</Zoom>
|
||||
</Stack>
|
||||
)
|
||||
}
|
||||
|
||||
export default CallTabLabel
|
||||
@@ -0,0 +1,27 @@
|
||||
import {Box, Tab, Tabs} from "@mui/material";
|
||||
import CallTabLabel
|
||||
from "@/components/layouts/Dashboard/CallWidget/CallWidgetDialog/CallTabs/CallTabsList/CallTabLabel";
|
||||
import useAnswers from "@/lib/callWidget/hooks/useAnswers";
|
||||
|
||||
const CallTabsList = () => {
|
||||
const {answersList, changeActiveTabAnswers, activeTab} = useAnswers()
|
||||
const handleChange = (event, newValue) => {
|
||||
changeActiveTabAnswers(newValue)
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{borderBottom: 1, borderColor: 'divider'}}>
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onChange={handleChange}
|
||||
variant={'fullWidth'}
|
||||
>
|
||||
{answersList.map((answer) => (
|
||||
<Tab component={'div'} sx={{py: 0.5, pr: 0}} label={<CallTabLabel tab={answer}/>} key={answer.id}/>
|
||||
))}
|
||||
</Tabs>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
export default CallTabsList
|
||||
@@ -0,0 +1,17 @@
|
||||
import CallTabPanel from "@/components/layouts/Dashboard/CallWidget/CallWidgetDialog/CallTabs/CallTabPanel";
|
||||
import useAnswers from "@/lib/callWidget/hooks/useAnswers";
|
||||
import CallTabsList from "src/components/layouts/Dashboard/CallWidget/CallWidgetDialog/CallTabs/CallTabsList";
|
||||
|
||||
const CallTabs = () => {
|
||||
const {answersList} = useAnswers()
|
||||
|
||||
return (
|
||||
<>
|
||||
<CallTabsList/>
|
||||
{answersList.map((answer) => (
|
||||
<CallTabPanel key={answer.id} tab={answer}/>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default CallTabs
|
||||
@@ -1,23 +1,48 @@
|
||||
import {Dialog} from "@mui/material";
|
||||
import {DialogTransition} from "@/core/components/DialogTransition";
|
||||
import {useEffect} from "react";
|
||||
import useCallDialog from "@/lib/callWidget/hooks/useCallDialog";
|
||||
import useAnswers from "@/lib/callWidget/hooks/useAnswers";
|
||||
import useSocket from "@/lib/app/hooks/useSocket";
|
||||
import CallTabs from "@/components/layouts/Dashboard/CallWidget/CallWidgetDialog/CallTabs";
|
||||
|
||||
const CallWidgetDialog = ({open, setOpen}) => {
|
||||
const CallWidgetDialog = () => {
|
||||
const {openCallDialog, setOpenCallDialog} = useCallDialog()
|
||||
const {answersList, newAnswerTab} = useAnswers()
|
||||
const socket = useSocket()
|
||||
|
||||
const handleClose = () => {
|
||||
setOpen(false);
|
||||
};
|
||||
useEffect(() => {
|
||||
const answerCall = (_data, act) => {
|
||||
const data = JSON.parse(_data)
|
||||
newAnswerTab({
|
||||
id: data.call_id,
|
||||
phone_number: data.phone_number
|
||||
})
|
||||
act()
|
||||
}
|
||||
socket.on('answer', answerCall)
|
||||
|
||||
return () => {
|
||||
socket.off('answer', answerCall)
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (answersList.length === 0) {
|
||||
setOpenCallDialog(false)
|
||||
return
|
||||
}
|
||||
setOpenCallDialog(true)
|
||||
}, [answersList.length]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog
|
||||
fullScreen
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
TransitionComponent={DialogTransition}
|
||||
>
|
||||
|
||||
</Dialog>
|
||||
</>
|
||||
<Dialog
|
||||
fullScreen
|
||||
open={openCallDialog}
|
||||
TransitionComponent={DialogTransition}
|
||||
>
|
||||
<CallTabs/>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,25 @@
|
||||
import CallWidgetButton from "@/components/layouts/Dashboard/CallWidget/CallWidgetButton";
|
||||
import CallWidgetDialog from "@/components/layouts/Dashboard/CallWidget/CallWidgetDialog";
|
||||
import {useState} from "react";
|
||||
import {AnswersProvider} from "@/lib/callWidget/contexts/answers";
|
||||
import useSocket from "@/lib/app/hooks/useSocket";
|
||||
import {useEffect} from "react";
|
||||
|
||||
const CallWidget = () => {
|
||||
const [open, setOpen] = useState(false)
|
||||
const socket = useSocket()
|
||||
|
||||
useEffect(() => {
|
||||
if (socket.connected) return
|
||||
|
||||
socket.connect()
|
||||
|
||||
return () => {
|
||||
socket.disconnect()
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<CallWidgetButton setOpen={setOpen}/>
|
||||
<CallWidgetDialog open={open} setOpen={setOpen}/>
|
||||
</>
|
||||
<AnswersProvider>
|
||||
<CallWidgetDialog/>
|
||||
</AnswersProvider>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import MenuIcon from "@mui/icons-material/Menu";
|
||||
import {AppBar, Box, Container, CssBaseline, IconButton, Stack, Toolbar, useTheme} from "@mui/material";
|
||||
import ProfileMenu from "./ProfileMenu";
|
||||
import {useTheme} from "@mui/material/styles";
|
||||
import CssBaseline from "@mui/material/CssBaseline";
|
||||
import {AppBar, Box, Container, IconButton, Stack, Toolbar} from "@mui/material";
|
||||
|
||||
function Header({drawerWidth, handleDrawerToggle}) {
|
||||
const theme = useTheme();
|
||||
|
||||
@@ -124,6 +124,7 @@ describe('Login expert component from login page', () => {
|
||||
})
|
||||
describe("validation", ()=>{
|
||||
it("Disabled submit button until fields completed", async ()=> {
|
||||
|
||||
render(
|
||||
<MockAppWithProviders>
|
||||
<LoginExpertComponent/>
|
||||
|
||||
@@ -9,54 +9,45 @@ import useRequest from "@/lib/app/hooks/useRequest";
|
||||
|
||||
function DataTable(props) {
|
||||
const requestServer = useRequest({auth: true})
|
||||
const fetcher = (...args) => {
|
||||
return requestServer(args, 'get', {
|
||||
pending: false,
|
||||
success: {notification: {show: false}}
|
||||
}).then((response) => {
|
||||
setRowCount(response.data.meta.totalRowCount);
|
||||
return response.data.data;
|
||||
}).catch(() => {
|
||||
})
|
||||
};
|
||||
const t = useTranslations();
|
||||
const {languageApp, languageList} = useLanguage();
|
||||
const [columnFilters, setColumnFilters] = useState([]);
|
||||
const [sorting, setSorting] = useState([]);
|
||||
const [pagination, setPagination] = useState({pageIndex: 0, pageSize: 10});
|
||||
const [rowCount, setRowCount] = useState(0);
|
||||
const [columnFilterFns, setColumnFilterFns] = useState(() => {
|
||||
let output = {};
|
||||
const list = props.columns.map((item) =>
|
||||
item.enableColumnFilter ? {[item.id]: item.filterFn} : {[item.id]: ""}
|
||||
);
|
||||
for (var key in list) {
|
||||
var nestedObj = list[key];
|
||||
for (var nestedKey in nestedObj) {
|
||||
for (const key in list) {
|
||||
const nestedObj = list[key];
|
||||
for (const nestedKey in nestedObj) {
|
||||
output[nestedKey] = nestedObj[nestedKey];
|
||||
}
|
||||
}
|
||||
return output;
|
||||
});
|
||||
|
||||
const [updateTime, setupdateTime] = useState(
|
||||
const [updateTime, setUpdateTime] = useState(
|
||||
moment().format("HH:mm | jYYYY/jM/jD")
|
||||
);
|
||||
|
||||
const tableLocalization = useMemo(
|
||||
() =>
|
||||
languageList.find((item) => item.key == languageApp).tableLocalization,
|
||||
languageList.find((item) => item.key === languageApp).tableLocalization,
|
||||
[languageApp, languageList]
|
||||
);
|
||||
|
||||
const fetchUrl = useMemo(() => {
|
||||
const url = new URL(props.tableUrl);
|
||||
url.searchParams.set(
|
||||
const params = new URLSearchParams();
|
||||
params.set(
|
||||
"start",
|
||||
`${pagination.pageIndex * pagination.pageSize}`
|
||||
);
|
||||
const filters = columnFilters.map((filter) => {
|
||||
let datatype;
|
||||
for (const i in props.columns) {
|
||||
if (props.columns[i].id == filter.id) {
|
||||
if (props.columns[i].id === filter.id) {
|
||||
datatype = props.columns[i].datatype;
|
||||
}
|
||||
}
|
||||
@@ -66,32 +57,40 @@ function DataTable(props) {
|
||||
datatype: datatype,
|
||||
};
|
||||
});
|
||||
url.searchParams.set("size", pagination.pageSize);
|
||||
url.searchParams.set("filters", JSON.stringify(filters ?? []));
|
||||
url.searchParams.set("sorting", JSON.stringify(sorting ?? []));
|
||||
return url;
|
||||
params.set("size", pagination.pageSize);
|
||||
params.set("filters", JSON.stringify(filters ?? []));
|
||||
params.set("sorting", JSON.stringify(sorting ?? []));
|
||||
return `${props.tableUrl}?${params}`;
|
||||
}, [
|
||||
props.tableUrl,
|
||||
columnFilters,
|
||||
columnFilterFns,
|
||||
pagination,
|
||||
sorting,
|
||||
props.columns,
|
||||
]);
|
||||
|
||||
const {data, isValidating, mutate} = useSWR(fetchUrl, fetcher, {
|
||||
revalidateIfStale: false,
|
||||
revalidateOnFocus: false,
|
||||
revalidateOnReconnect: false
|
||||
});
|
||||
const {data, isValidating, mutate} = useSWR(fetchUrl, (...args) =>
|
||||
requestServer(args, 'get', {
|
||||
pending: false,
|
||||
success: {notification: {show: false}}
|
||||
}).then((response) => response.data).catch(() => {
|
||||
})
|
||||
, {
|
||||
revalidateIfStale: false,
|
||||
revalidateOnFocus: false,
|
||||
revalidateOnReconnect: true,
|
||||
keepPreviousData: true
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setupdateTime(moment().format("HH:mm | jYYYY/jM/jD"));
|
||||
setUpdateTime(moment().format("HH:mm | jYYYY/jM/jD"));
|
||||
}, [isValidating, languageApp]);
|
||||
|
||||
|
||||
return (
|
||||
<MaterialReactTable
|
||||
localization={tableLocalization}
|
||||
data={data ?? []}
|
||||
data={data?.data ?? []}
|
||||
manualFiltering
|
||||
manualPagination
|
||||
manualSorting
|
||||
@@ -122,7 +121,7 @@ function DataTable(props) {
|
||||
}}
|
||||
enableColumnFilterModes
|
||||
muiTablePaperProps={{elevation: 0}}
|
||||
rowCount={rowCount}
|
||||
rowCount={data?.meta.totalRowCount}
|
||||
onColumnFilterFnsChange={setColumnFilterFns}
|
||||
onColumnFiltersChange={setColumnFilters}
|
||||
onPaginationChange={setPagination}
|
||||
@@ -131,8 +130,8 @@ function DataTable(props) {
|
||||
renderTopToolbarCustomActions={({table}) => (
|
||||
<>
|
||||
{props.enableCustomToolbar /* send condition */
|
||||
? (<props.CustomToolbar fetchUrl={fetchUrl} mutate={mutate}/>) /* send component */
|
||||
: <span></span>}
|
||||
? <props.CustomToolbar fetchUrl={fetchUrl} mutate={mutate}/> /* send component */
|
||||
: "<span></span>"}
|
||||
</>
|
||||
)}
|
||||
renderBottomToolbarCustomActions={({table}) => (
|
||||
@@ -156,6 +155,7 @@ function DataTable(props) {
|
||||
</>
|
||||
)}
|
||||
state={{
|
||||
showProgressBars: isValidating,
|
||||
columnFilters,
|
||||
columnFilterFns,
|
||||
pagination,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {Backdrop, Box, styled} from "@mui/material";
|
||||
import SvgLoading from "@/core/components/svgs/SvgLoading";
|
||||
import {Backdrop, Box} from "@mui/material";
|
||||
import {styled} from "@mui/material/styles";
|
||||
|
||||
const LoadingImage = styled(Box)({
|
||||
"@keyframes load": {
|
||||
@@ -23,7 +24,7 @@ const LoadingHardPage = ({children, loading}) => {
|
||||
return (
|
||||
<>
|
||||
<Backdrop
|
||||
sx={{bgcolor: "#fff", zIndex: (theme) => theme.zIndex.drawer + 1}}
|
||||
sx={{bgcolor: "#fff", zIndex: (theme) => theme.zIndex.modal + 1}}
|
||||
open={loading}
|
||||
>
|
||||
<LoadingImage
|
||||
|
||||
33
src/core/components/Middleware/RolePermissionComponent.jsx
Normal file
33
src/core/components/Middleware/RolePermissionComponent.jsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Button, Typography } from "@mui/material";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { NextLinkComposed } from "@/core/components/LinkRouting";
|
||||
import Message from "@/core/components/Messages";
|
||||
|
||||
const RolePermissionComponent = () => {
|
||||
const t = useTranslations();
|
||||
|
||||
return (
|
||||
<Message
|
||||
text={
|
||||
<Typography sx={{ textAlign: "center" }}>
|
||||
{t("Permission.typography_you_dont_have_access")}
|
||||
</Typography>
|
||||
}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
variant="contained"
|
||||
component={NextLinkComposed}
|
||||
to={{
|
||||
pathname: "/dashboard",
|
||||
}}
|
||||
>
|
||||
{t("Permission.button_back_dashboard")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default RolePermissionComponent;
|
||||
36
src/core/components/Middleware/WithAuthComponent.jsx
Normal file
36
src/core/components/Middleware/WithAuthComponent.jsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Button, Typography } from "@mui/material";
|
||||
import { useRouter } from "next/router";
|
||||
import Message from "@/core/components/Messages";
|
||||
import { NextLinkComposed } from "@/core/components/LinkRouting";
|
||||
import {useTranslations} from "next-intl";
|
||||
|
||||
const WithAuthComponent = () => {
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
|
||||
return (
|
||||
<Message
|
||||
text={
|
||||
<Typography sx={{ textAlign: "center" }}>
|
||||
{t("Authorization.typography_your_access_to_this_page_has_expired_Please_login_again")}
|
||||
</Typography>
|
||||
}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
variant="contained"
|
||||
component={NextLinkComposed}
|
||||
to={{
|
||||
pathname: "/login-expert",
|
||||
query: {back_url: encodeURIComponent(router.asPath)},
|
||||
}}
|
||||
>
|
||||
{t("login")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default WithAuthComponent;
|
||||
25
src/core/components/Middleware/WithoutAuthComponent.jsx
Normal file
25
src/core/components/Middleware/WithoutAuthComponent.jsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import {Button, Stack, Typography} from "@mui/material";
|
||||
import Message from "@/core/components/Messages";
|
||||
import {useTranslations} from "next-intl";
|
||||
const WithoutAuthComponent = ({ backUrlDecodedPath }) => {
|
||||
const t = useTranslations();
|
||||
|
||||
return (
|
||||
<Message
|
||||
text={
|
||||
<Stack alignItems="center" spacing={2}>
|
||||
<Typography sx={{ textAlign: "center" }}>
|
||||
{t("Authorization.typography_your_login_is_valid_and_you_do_not_need_to_login_again")}
|
||||
</Typography>
|
||||
<Typography>
|
||||
{t("Authorization.typography_redirect_to")}{" "}
|
||||
{backUrlDecodedPath
|
||||
? t("Authorization.typography_routing_previuos_page")
|
||||
: t("Authorization.typography_routing_dashbaord_page")}
|
||||
</Typography>
|
||||
</Stack>
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
export default WithoutAuthComponent;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import MockAppWithProviders from "../../../../../mocks/AppWithProvider";
|
||||
import RolePermissionComponent from "@/core/components/Middleware/RolePermissionComponent";
|
||||
|
||||
describe('RolePermissionComponent From RolePermissionComponent page', () => {
|
||||
describe('Rendering', () => {
|
||||
it('should render the error message when user dont have permission', () => {
|
||||
render(<MockAppWithProviders><RolePermissionComponent /></MockAppWithProviders>);
|
||||
|
||||
expect(screen.queryByText('شما دسترسی لازم برای مشاهده این صفحه را ندارید!')).toBeInTheDocument();
|
||||
|
||||
});
|
||||
|
||||
it('should render the back dashboard button when user dont have permission', () => {
|
||||
render(<MockAppWithProviders><RolePermissionComponent /></MockAppWithProviders>);
|
||||
|
||||
const backButton = screen.queryByText('بازگشت به صفحه اصلی');
|
||||
|
||||
expect(backButton).toBeInTheDocument();
|
||||
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import MockAppWithProviders from "../../../../../mocks/AppWithProvider";
|
||||
import WithAuthComponent from "@/core/components/Middleware/WithAuthComponent";
|
||||
import mockRouter from 'next-router-mock';
|
||||
|
||||
describe('WithAuthComponent From WithAuthMiddleware', () => {
|
||||
describe('Rendering', () => {
|
||||
it('should see expired text in render component', () => {
|
||||
render(<MockAppWithProviders><WithAuthComponent /></MockAppWithProviders>);
|
||||
|
||||
const authText = screen.queryByText('دسترسی شما منقضی شده است لطفا دوباره ورود نمایید.');
|
||||
|
||||
expect(authText).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should see login button in render component', () => {
|
||||
render(<MockAppWithProviders><WithAuthComponent /></MockAppWithProviders>);
|
||||
|
||||
const loginButton = screen.queryByText('ورود');
|
||||
|
||||
expect(loginButton).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
describe('behavior', () => {
|
||||
it('should see if router updated in login button', () => {
|
||||
|
||||
mockRouter.query.back_url = 'back_url'
|
||||
render(<MockAppWithProviders><WithAuthComponent /></MockAppWithProviders>);
|
||||
|
||||
const loginButton = screen.queryByText('ورود');
|
||||
|
||||
fireEvent.click(loginButton);
|
||||
|
||||
expect(mockRouter).toMatchObject({
|
||||
query: { back_url: "back_url" },
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import {render, screen, waitFor} from '@testing-library/react';
|
||||
import WithoutAuthComponent from "@/core/components/Middleware/WithoutAuthComponent";
|
||||
import MockAppWithProviders from "../../../../../mocks/AppWithProvider";
|
||||
import WithoutAuthMiddleware from "@/middlewares/WithoutAuth";
|
||||
|
||||
describe('WithoutAuthComponent From WithoutAuthMiddleware', () => {
|
||||
describe('Rendering', () => {
|
||||
it('should render the message with correct text when backUrlDecodedPath is not provided', async () => {
|
||||
|
||||
localStorage.setItem("_token", 'token');
|
||||
|
||||
render(<MockAppWithProviders><WithoutAuthMiddleware /></MockAppWithProviders>);
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText('شما دسترسی لازم به این صفحه را دارید نیاز به ورود مجدد نیست.')).toBeInTheDocument();
|
||||
|
||||
expect(screen.queryByText('درحال رفتن به صفحه داشبورد...')).toBeInTheDocument();
|
||||
})
|
||||
|
||||
});
|
||||
|
||||
it('should render the message with a different text when backUrlDecodedPath is provided', async() => {
|
||||
render(<MockAppWithProviders><WithoutAuthComponent backUrlDecodedPath="/dashboard/change-password" /></MockAppWithProviders>);
|
||||
|
||||
localStorage.setItem("_token", 'token');
|
||||
|
||||
render(<MockAppWithProviders><WithoutAuthMiddleware /></MockAppWithProviders>);
|
||||
|
||||
await waitFor(()=>{
|
||||
|
||||
expect(screen.queryByText('درحال رفتن به صفحه قبل...')).toBeInTheDocument();
|
||||
})
|
||||
|
||||
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -6,13 +6,13 @@ import WifiOffIcon from '@mui/icons-material/WifiOff';
|
||||
import {useTranslations} from "next-intl";
|
||||
|
||||
const NetworkComponent = () => {
|
||||
const toastId = useRef(null);
|
||||
const networkToastId = useRef(null);
|
||||
const network = useNetwork()
|
||||
const t = useTranslations()
|
||||
|
||||
useEffect(() => {
|
||||
if (network.online) {
|
||||
toast.update(toastId.current, {
|
||||
toast.update(networkToastId.current, {
|
||||
type: toast.TYPE.SUCCESS,
|
||||
render: t('online_message'),
|
||||
autoClose: 2000,
|
||||
@@ -22,8 +22,7 @@ const NetworkComponent = () => {
|
||||
});
|
||||
return
|
||||
}
|
||||
toast.dismiss()
|
||||
toastId.current = toast.warn(t('offline_message'), {
|
||||
networkToastId.current = toast.warn(t('offline_message'), {
|
||||
autoClose: false, closeButton: false, closeOnClick: false, icon: <WifiOffIcon/>
|
||||
})
|
||||
}, [network.online]);
|
||||
|
||||
@@ -5,7 +5,6 @@ const StyledFab = styled(Fab)`
|
||||
bottom: 16px;
|
||||
/* @noflip */
|
||||
left: 16px;
|
||||
z-index: 1500;
|
||||
`;
|
||||
|
||||
export default StyledFab;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {styled} from "@mui/material";
|
||||
import {Form} from "formik";
|
||||
import {styled} from "@mui/material/styles";
|
||||
|
||||
const StyledForm = styled(Form)``;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {useTheme} from "@mui/material";
|
||||
import {useTheme} from "@mui/material/styles";
|
||||
|
||||
const Svg403 = ({width, height}) => {
|
||||
const theme = useTheme()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {useTheme} from "@mui/material";
|
||||
import {useTheme} from "@mui/material/styles";
|
||||
|
||||
const Svg404 = ({width, height}) => {
|
||||
const theme = useTheme()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {useTheme} from "@mui/material";
|
||||
import {useTheme} from "@mui/material/styles";
|
||||
|
||||
const SvgChangePassword = ({width, height}) => {
|
||||
const theme = useTheme()
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {useTheme} from "@mui/material";
|
||||
import {useTheme} from "@mui/material/styles";
|
||||
|
||||
const SvgDashboard = ({width, height}) => {
|
||||
const theme = useTheme()
|
||||
const fillColor = theme.palette.primary.main
|
||||
|
||||
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" width={width} height={height}
|
||||
viewBox="0 0 1029.56255 548.69495">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {useTheme} from "@mui/material";
|
||||
import {useTheme} from "@mui/material/styles";
|
||||
|
||||
const SvgLoading = ({width, height}) => {
|
||||
const theme = useTheme()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {useTheme} from "@mui/material";
|
||||
import {useTheme} from "@mui/material/styles";
|
||||
|
||||
const SvgLogin = ({width, height}) => {
|
||||
const theme = useTheme()
|
||||
|
||||
@@ -4,6 +4,10 @@ const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
|
||||
export const GET_USER_TOKEN = BASE_URL + "/api/auth/login";
|
||||
//end login
|
||||
|
||||
//edit profile
|
||||
export const UPDATE_AVATAR = BASE_URL + "";
|
||||
//end edit profile
|
||||
|
||||
// role list
|
||||
export const GET_ROLE_LIST = BASE_URL + "/api/roles/list";
|
||||
// role list
|
||||
@@ -13,13 +17,32 @@ export const GET_PROVINCE_LIST = BASE_URL + "/api/provinces";
|
||||
// province list
|
||||
|
||||
//change password
|
||||
export const SET_USER_PASSWORD = BASE_URL + "/dashboard/profile/change_password";
|
||||
export const SET_USER_PASSWORD = BASE_URL + "/api/profile/change_password";
|
||||
//end change password
|
||||
|
||||
//user data
|
||||
export const GET_USER_ROUTE = BASE_URL + "/api/profile/info";
|
||||
//user data
|
||||
|
||||
//sidebar notification
|
||||
export const GET_SIDEBAR_NOTIFICATION = BASE_URL + "/dashboard/notification"
|
||||
//sidebar notification
|
||||
|
||||
|
||||
// role management
|
||||
export const GET_ROLE_MANAGEMENT =
|
||||
BASE_URL + "/api/roles"
|
||||
export const ADD_ROLE_MANAGEMENT =
|
||||
BASE_URL + "/api/roles"
|
||||
export const UPDATE_ROLE_MANAGEMENT =
|
||||
BASE_URL + "/api/roles"
|
||||
export const DELETE_ROLE_MANAGEMENT =
|
||||
BASE_URL + "/api/roles"
|
||||
|
||||
export const GET_PERMISSIONS_LIST =
|
||||
BASE_URL + "/api/permissions/list"
|
||||
//role management
|
||||
|
||||
//expert management
|
||||
export const EXPERT_MANAGEMENT = BASE_URL + "/api/users";
|
||||
//expert management
|
||||
@@ -1,4 +1,5 @@
|
||||
import SpaceDashboardIcon from "@mui/icons-material/SpaceDashboard";
|
||||
import AccessibilityIcon from '@mui/icons-material/Accessibility';
|
||||
import ManageAccountsIcon from '@mui/icons-material/ManageAccounts';
|
||||
|
||||
const sidebarMenu = [
|
||||
@@ -7,7 +8,7 @@ const sidebarMenu = [
|
||||
key: "sidebar.dashboard",
|
||||
type: "page",
|
||||
route: "/dashboard",
|
||||
icon: <SpaceDashboardIcon/>,
|
||||
icon: <SpaceDashboardIcon />,
|
||||
selected: false,
|
||||
permission: "all",
|
||||
},
|
||||
@@ -20,6 +21,15 @@ const sidebarMenu = [
|
||||
selected: false,
|
||||
permission: "all",
|
||||
},
|
||||
{
|
||||
key: "sidebar.role-management",
|
||||
name : "role_management",
|
||||
type: "page",
|
||||
route: "/dashboard/role-management",
|
||||
icon: <AccessibilityIcon />,
|
||||
selected: false,
|
||||
permission: "manage_roles",
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import CallWidget from "src/components/layouts/Dashboard/CallWidget";
|
||||
import Dashboard from "src/components/layouts/Dashboard";
|
||||
|
||||
const DashboardLayouts = (props) => {
|
||||
const DashboardLayout = (props) => {
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -11,4 +11,4 @@ const DashboardLayouts = (props) => {
|
||||
);
|
||||
};
|
||||
|
||||
export default DashboardLayouts;
|
||||
export default DashboardLayout;
|
||||
|
||||
@@ -22,26 +22,23 @@ const MuiLayout = ({children, isBot}) => {
|
||||
<ThemeProvider theme={theme}>
|
||||
<GlobalStyles
|
||||
styles={{
|
||||
"*:not(.MuiTableContainer-root)::-webkit-scrollbar": {
|
||||
display: "none",
|
||||
},
|
||||
"*::-webkit-scrollbar": {
|
||||
height: "8px",
|
||||
},
|
||||
"*:not(.MuiTableContainer-root)::-webkit-scrollbar": {
|
||||
display: "none",
|
||||
},
|
||||
"*::-webkit-scrollbar-thumb": {
|
||||
background: `${theme.palette.primary.light}80`,
|
||||
borderRadius: "3px",
|
||||
},
|
||||
"*:not(.MuiTableContainer-root)": {
|
||||
scrollbarWidth: "thin",
|
||||
scrollbarColor: "transparent transparent",
|
||||
},
|
||||
|
||||
"*": {
|
||||
scrollbarWidth: "thin",
|
||||
scrollbarColor: `${theme.palette.primary.light}80 transparent`,
|
||||
},
|
||||
|
||||
"*:not(.MuiTableContainer-root)": {
|
||||
scrollbarWidth: "none",
|
||||
},
|
||||
"*::-moz-scrollbar-thumb": {
|
||||
backgroundColor: `${theme.palette.primary.light}80`,
|
||||
},
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import {createContext, useMemo} from "react";
|
||||
import {createContext, useEffect, useMemo, useRef, useState} from "react";
|
||||
import {io} from "socket.io-client";
|
||||
import useUser from "@/lib/app/hooks/useUser";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {toast} from "react-toastify";
|
||||
import PowerIcon from "@mui/icons-material/Power";
|
||||
import PowerOffIcon from "@mui/icons-material/PowerOff";
|
||||
|
||||
export const SocketContext = createContext()
|
||||
|
||||
export const SocketProvider = ({children}) => {
|
||||
const {user, isAuth} = useUser()
|
||||
const [connectionError, setConnectionError] = useState(false)
|
||||
const socketToastId = useRef(null);
|
||||
const t = useTranslations()
|
||||
const socket = useMemo(() => io(process.env.NEXT_PUBLIC_SERVER_SOCKET_URL, {
|
||||
autoConnect: false,
|
||||
auth: {
|
||||
@@ -11,5 +20,48 @@ export const SocketProvider = ({children}) => {
|
||||
}
|
||||
}), [])
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuth) {
|
||||
socket.auth.token = user.telephone_id
|
||||
return
|
||||
}
|
||||
socket.auth.token = ''
|
||||
}, [isAuth]);
|
||||
|
||||
useEffect(() => {
|
||||
const connectErrorHandler = () => {
|
||||
setConnectionError(true)
|
||||
}
|
||||
const connectHandler = () => {
|
||||
setConnectionError(false)
|
||||
}
|
||||
socket.on("connect_error", connectErrorHandler);
|
||||
socket.on("connect", connectHandler);
|
||||
|
||||
return () => {
|
||||
socket.off("connect_error", connectErrorHandler);
|
||||
socket.off("connect", connectHandler);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!connectionError) {
|
||||
toast.update(socketToastId.current, {
|
||||
type: toast.TYPE.SUCCESS,
|
||||
render: t('socket_is_connect_message'),
|
||||
autoClose: 2000,
|
||||
closeButton: true,
|
||||
closeOnClick: true,
|
||||
icon: <PowerIcon/>
|
||||
});
|
||||
return
|
||||
}
|
||||
socketToastId.current = toast.warn(t('socket_is_not_connect_message'), {
|
||||
draggable: false,
|
||||
autoClose: false, closeButton: false, closeOnClick: false, icon: <PowerOffIcon/>
|
||||
})
|
||||
|
||||
}, [connectionError]);
|
||||
|
||||
return <SocketContext.Provider value={{socket}}>{children}</SocketContext.Provider>
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import {GET_USER_ROUTE} from "@/core/data/apiRoutes";
|
||||
import axios from "axios";
|
||||
import {createContext, useCallback, useEffect, useReducer} from "react";
|
||||
import {errorRequest, errorResponse, errorSetting} from "@/core/utils/errorHandler";
|
||||
import useSocket from "@/lib/app/hooks/useSocket";
|
||||
|
||||
const initialUser = {
|
||||
isAuth: false,
|
||||
@@ -40,7 +39,6 @@ const reducer = (state, action) => {
|
||||
export const UserContext = createContext();
|
||||
|
||||
export const UserProvider = ({children}) => {
|
||||
const socket = useSocket()
|
||||
const [state, dispatch] = useReducer(reducer, initialUser);
|
||||
|
||||
const clearUser = useCallback(() => {
|
||||
@@ -102,16 +100,12 @@ export const UserProvider = ({children}) => {
|
||||
clearUser();
|
||||
changeAuthState(false);
|
||||
changeLanguageState(false);
|
||||
|
||||
socket.auth.token = ""
|
||||
return;
|
||||
}
|
||||
getUser((data) => {
|
||||
changeUser(data);
|
||||
changeAuthState(true);
|
||||
changeLanguageState(true);
|
||||
|
||||
socket.auth.token = data.telephone_id
|
||||
});
|
||||
}, [state.token]);
|
||||
|
||||
|
||||
@@ -1,29 +1,5 @@
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
function getNetworkConnection() {
|
||||
return (
|
||||
navigator.connection ||
|
||||
navigator.mozConnection ||
|
||||
navigator.webkitConnection ||
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
function getNetworkConnectionInfo() {
|
||||
const connection = getNetworkConnection();
|
||||
if (!connection) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
rtt: connection.rtt,
|
||||
type: connection.type,
|
||||
saveData: connection.saveData,
|
||||
downLink: connection.downLink,
|
||||
downLinkMax: connection.downLinkMax,
|
||||
effectiveType: connection.effectiveType,
|
||||
};
|
||||
}
|
||||
|
||||
function useNetwork() {
|
||||
const [state, setState] = useState(() => {
|
||||
return {
|
||||
@@ -51,7 +27,7 @@ function useNetwork() {
|
||||
window.removeEventListener("offline", handleOffline);
|
||||
};
|
||||
}, []);
|
||||
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
|
||||
26
src/lib/app/hooks/usePermissions.jsx
Normal file
26
src/lib/app/hooks/usePermissions.jsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import useRequest from "@/lib/app/hooks/useRequest";
|
||||
import useSWR from "swr";
|
||||
import {GET_PERMISSIONS_LIST} from "@/core/data/apiRoutes";
|
||||
|
||||
const usePermissions = () => {
|
||||
const requestServer = useRequest({auth: true, notification: false})
|
||||
const fetcher = (...args) => {
|
||||
return requestServer(args, 'get').then((response) => {
|
||||
return response.data.data;
|
||||
}).catch(() => {
|
||||
})
|
||||
};
|
||||
|
||||
const {data, isLoading} = useSWR(GET_PERMISSIONS_LIST, fetcher, {
|
||||
revalidateIfStale: false,
|
||||
revalidateOnFocus: false,
|
||||
revalidateOnReconnect: false,
|
||||
keepPreviousData : true
|
||||
})
|
||||
const permissions_list = data
|
||||
//swr config
|
||||
|
||||
// render data
|
||||
return {permissions_list, isLoading}
|
||||
}
|
||||
export default usePermissions;
|
||||
31
src/lib/callWidget/contexts/answers.jsx
Normal file
31
src/lib/callWidget/contexts/answers.jsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import {createContext, useReducer, useState} from "react";
|
||||
|
||||
const reducer = (state, action) => {
|
||||
switch (action.type) {
|
||||
case "CHANGE_ACTIVE_TAB":
|
||||
return state.map((answer, index) => action.newValue === index ? {...answer, active: true} : {
|
||||
...answer,
|
||||
active: false
|
||||
});
|
||||
case "CHANGE_LIST":
|
||||
return [...action.newList]
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
export const AnswersContext = createContext()
|
||||
export const AnswersProvider = ({children}) => {
|
||||
const [openCallDialog, setOpenCallDialog] = useState(false)
|
||||
const [activeTab, setActiveTab] = useState(0)
|
||||
const [state, dispatch] = useReducer(reducer, []);
|
||||
|
||||
return <AnswersContext.Provider
|
||||
value={{
|
||||
openCallDialog,
|
||||
setOpenCallDialog,
|
||||
state,
|
||||
dispatch,
|
||||
activeTab,
|
||||
setActiveTab
|
||||
}}>{children}</AnswersContext.Provider>
|
||||
}
|
||||
37
src/lib/callWidget/hooks/useAnswers.jsx
Normal file
37
src/lib/callWidget/hooks/useAnswers.jsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import {useContext} from "react";
|
||||
import {AnswersContext} from "@/lib/callWidget/contexts/answers";
|
||||
|
||||
const useAnswers = () => {
|
||||
const {state, dispatch, activeTab, setActiveTab} = useContext(AnswersContext)
|
||||
|
||||
const changeActiveTabAnswers = (newValue) => {
|
||||
dispatch({type: 'CHANGE_ACTIVE_TAB', newValue})
|
||||
setActiveTab(newValue)
|
||||
}
|
||||
const newAnswerTab = (data) => {
|
||||
const newAnswer = {
|
||||
id: data.id,
|
||||
phone_number: data.phone_number,
|
||||
active: true
|
||||
}
|
||||
const newList = [...state, newAnswer]
|
||||
dispatch({type: 'CHANGE_LIST', newList})
|
||||
changeActiveTabAnswers(newList.length - 1)
|
||||
}
|
||||
|
||||
const closeAnswerTab = (id) => {
|
||||
const index = state.findIndex(answer => answer.id === id)
|
||||
const newIndex = index === 0 ? 0 : index - 1
|
||||
const newList = [...state]
|
||||
newList.splice(index, 1);
|
||||
if (newList.length !== 0) {
|
||||
newList[newIndex].active = true
|
||||
setActiveTab(newIndex)
|
||||
}
|
||||
dispatch({type: 'CHANGE_LIST', newList})
|
||||
}
|
||||
|
||||
return {answersList: state, activeTab, setActiveTab, changeActiveTabAnswers, closeAnswerTab, newAnswerTab}
|
||||
}
|
||||
|
||||
export default useAnswers
|
||||
10
src/lib/callWidget/hooks/useCallDialog.jsx
Normal file
10
src/lib/callWidget/hooks/useCallDialog.jsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import {useContext} from "react";
|
||||
import {AnswersContext} from "@/lib/callWidget/contexts/answers";
|
||||
|
||||
const useCallDialog = () => {
|
||||
const {openCallDialog, setOpenCallDialog} = useContext(AnswersContext)
|
||||
|
||||
return {openCallDialog, setOpenCallDialog}
|
||||
}
|
||||
|
||||
export default useCallDialog
|
||||
@@ -1,43 +1,14 @@
|
||||
import {NextLinkComposed} from "@/core/components/LinkRouting";
|
||||
import Message from "@/core/components/Messages";
|
||||
import useUser from "@/lib/app/hooks/useUser";
|
||||
import {Button, Typography} from "@mui/material";
|
||||
import {useTranslations} from "next-intl";
|
||||
import RolePermissionComponent from "@/core/components/Middleware/RolePermissionComponent";
|
||||
|
||||
const RolePermissionMiddleware = ({children, requiredPermissions}) => {
|
||||
const {user} = useUser();
|
||||
const t = useTranslations();
|
||||
|
||||
const hasPermission = requiredPermissions.some((permission) =>
|
||||
user?.permissions?.includes(permission)
|
||||
);
|
||||
|
||||
if (!hasPermission) {
|
||||
return (
|
||||
<Message
|
||||
text={
|
||||
<Typography sx={{textAlign: "center"}}>
|
||||
{t("Permission.typography_you_dont_have_access")}
|
||||
</Typography>
|
||||
}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
variant="contained"
|
||||
component={NextLinkComposed}
|
||||
to={{
|
||||
pathname: "/dashboard",
|
||||
}}
|
||||
>
|
||||
{t("Permission.button_back_dashboard")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
return !hasPermission ? <RolePermissionComponent /> : <>{children}</>;
|
||||
};
|
||||
|
||||
export default RolePermissionMiddleware;
|
||||
|
||||
@@ -1,42 +1,11 @@
|
||||
import {NextLinkComposed} from "@/core/components/LinkRouting";
|
||||
import Message from "@/core/components/Messages";
|
||||
import useUser from "@/lib/app/hooks/useUser";
|
||||
import {Button, Typography} from "@mui/material";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {useRouter} from "next/router";
|
||||
import WithAuthComponent from "@/core/components/Middleware/WithAuthComponent";
|
||||
|
||||
|
||||
const WithAuthMiddleware = ({children}) => {
|
||||
const {isAuth} = useUser();
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
|
||||
if (!isAuth)
|
||||
return (
|
||||
<Message
|
||||
text={
|
||||
<Typography sx={{textAlign: "center"}}>
|
||||
{t(
|
||||
"Authorization.typography_your_access_to_this_page_has_expired_Please_login_again"
|
||||
)}
|
||||
</Typography>
|
||||
}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
variant="contained"
|
||||
component={NextLinkComposed}
|
||||
to={{
|
||||
pathname: "/login-expert",
|
||||
query: {back_url: encodeURIComponent(router.asPath)},
|
||||
}}
|
||||
>
|
||||
{t("login")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
return <>{children}</>;
|
||||
return isAuth ? <>{children}</> : <WithAuthComponent />;
|
||||
};
|
||||
|
||||
export default WithAuthMiddleware;
|
||||
|
||||
@@ -1,19 +1,13 @@
|
||||
import Message from "@/core/components/Messages";
|
||||
import useUser from "@/lib/app/hooks/useUser";
|
||||
import {Stack, Typography} from "@mui/material";
|
||||
import {useTranslations} from "next-intl";
|
||||
import {useSearchParams} from "next/navigation";
|
||||
import {useRouter} from "next/router";
|
||||
import {useEffect} from "react";
|
||||
import WithoutAuthComponent from "@/core/components/Middleware/WithoutAuthComponent";
|
||||
|
||||
const WithoutAuthMiddleware = ({children}) => {
|
||||
const {isAuth} = useUser();
|
||||
const t = useTranslations();
|
||||
const router = useRouter();
|
||||
|
||||
// gettin url query
|
||||
const searchParams = useSearchParams();
|
||||
const backUrlDecodedPath = searchParams.get("back_url");
|
||||
const backUrlDecodedPath = router.query?.back_url;
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuth) return;
|
||||
@@ -30,27 +24,11 @@ const WithoutAuthMiddleware = ({children}) => {
|
||||
};
|
||||
}, [isAuth]);
|
||||
|
||||
if (isAuth)
|
||||
return (
|
||||
<Message
|
||||
text={
|
||||
<Stack alignItems="center" spacing={2}>
|
||||
<Typography sx={{textAlign: "center"}}>
|
||||
{t(
|
||||
"Authorization.typography_your_login_is_valid_and_you_do_not_need_to_login_again"
|
||||
)}
|
||||
</Typography>
|
||||
<Typography>
|
||||
{t("Authorization.typography_redirect_to")}{" "}
|
||||
{backUrlDecodedPath
|
||||
? t("Authorization.typography_routing_previuos_page")
|
||||
: t("Authorization.typography_routing_dashbaord_page")}
|
||||
</Typography>
|
||||
</Stack>
|
||||
}
|
||||
/>
|
||||
);
|
||||
return <>{children}</>;
|
||||
return isAuth ? (
|
||||
<WithoutAuthComponent backUrlDecodedPath={backUrlDecodedPath} />
|
||||
) : (
|
||||
<>{children}</>
|
||||
);
|
||||
};
|
||||
|
||||
export default WithoutAuthMiddleware;
|
||||
|
||||
34
src/middlewares/__test__/RolePermission.test.js
Normal file
34
src/middlewares/__test__/RolePermission.test.js
Normal file
@@ -0,0 +1,34 @@
|
||||
import {render, screen, waitFor} from '@testing-library/react';
|
||||
import MockAppWithProviders from "../../../mocks/AppWithProvider";
|
||||
import RolePermissionMiddleware from "@/middlewares/RolePermission";
|
||||
|
||||
|
||||
describe('RolePermissionMiddleware From RolePermissionMiddleware', () => {
|
||||
describe('Behavior', () => {
|
||||
it('show related child if permission exist', async () => {
|
||||
|
||||
const requiredPermissions = ["manage_users"];
|
||||
render(<MockAppWithProviders><RolePermissionMiddleware requiredPermissions={requiredPermissions}/>{'children'}</MockAppWithProviders>);
|
||||
|
||||
await waitFor(()=>{
|
||||
expect(screen.queryByText('children')).toBeInTheDocument();
|
||||
|
||||
})
|
||||
|
||||
});
|
||||
it('show related error if permission not exist', async () => {
|
||||
|
||||
const requiredPermissions = ["other-permission"];
|
||||
|
||||
render(<MockAppWithProviders><RolePermissionMiddleware requiredPermissions={requiredPermissions}/></MockAppWithProviders>);
|
||||
|
||||
await waitFor(()=>{
|
||||
|
||||
expect(screen.queryByText('شما دسترسی لازم برای مشاهده این صفحه را ندارید!')).toBeInTheDocument();
|
||||
|
||||
})
|
||||
|
||||
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -12,22 +12,22 @@ import {SocketProvider} from "@/lib/app/contexts/socket";
|
||||
const App = ({Component, pageProps}) => {
|
||||
|
||||
return (<>
|
||||
<SocketProvider>
|
||||
<UserProvider>
|
||||
<LanguageProvider>
|
||||
<NextIntlProvider locale={pageProps.locale} messages={pageProps.messages || {}}>
|
||||
<MuiLayout isBot={pageProps.isBot}>
|
||||
{pageProps.messages ? <TitlePage text={pageProps.title}/> : ''}
|
||||
<LoadingProvider>
|
||||
<AppLayout isBot={pageProps.isBot}>
|
||||
<UserProvider>
|
||||
<LanguageProvider>
|
||||
<NextIntlProvider locale={pageProps.locale} messages={pageProps.messages || {}}>
|
||||
<MuiLayout isBot={pageProps.isBot}>
|
||||
{pageProps.messages ? <TitlePage text={pageProps.title}/> : ''}
|
||||
<LoadingProvider>
|
||||
<AppLayout isBot={pageProps.isBot}>
|
||||
<SocketProvider>
|
||||
<Component {...pageProps} />
|
||||
</AppLayout>
|
||||
</LoadingProvider>
|
||||
</MuiLayout>
|
||||
</NextIntlProvider>
|
||||
</LanguageProvider>
|
||||
</UserProvider>
|
||||
</SocketProvider>
|
||||
</SocketProvider>
|
||||
</AppLayout>
|
||||
</LoadingProvider>
|
||||
</MuiLayout>
|
||||
</NextIntlProvider>
|
||||
</LanguageProvider>
|
||||
</UserProvider>
|
||||
</>)
|
||||
};
|
||||
|
||||
|
||||
26
src/pages/dashboard/role-management/index.jsx
Normal file
26
src/pages/dashboard/role-management/index.jsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import RolePermissionMiddleware from "@/middlewares/RolePermission";
|
||||
import WithAuthMiddleware from "@/middlewares/WithAuth";
|
||||
import {parse} from "next-useragent";
|
||||
import DashboardRoleManagementComponent from "@/components/dashboard/role-management";
|
||||
|
||||
const requiredPermissions = ["manage_roles"];
|
||||
export default function RoleManagement() {
|
||||
return (
|
||||
<WithAuthMiddleware>
|
||||
<RolePermissionMiddleware requiredPermissions={requiredPermissions}>
|
||||
<DashboardRoleManagementComponent/>
|
||||
</RolePermissionMiddleware>
|
||||
</WithAuthMiddleware>
|
||||
);
|
||||
}
|
||||
|
||||
export async function getServerSideProps({req, locale}) {
|
||||
const {isBot} = parse(req.headers["user-agent"]);
|
||||
return {
|
||||
props: {
|
||||
messages: (await import(`&/locales/${locale}/app.json`)).default,
|
||||
title: "Dashboard.role_management_page",
|
||||
isBot,
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user