Update structure code

This commit is contained in:
2023-11-05 20:42:03 +07:00
parent 0b9450a0ce
commit 61ec8e9f68
22 changed files with 149 additions and 174 deletions
@@ -4,7 +4,7 @@ import { MutableRefObject, ReactNode, forwardRef } from 'react';
import { StyledBody, StyledDialog, StyledTitle } from './styled'; import { StyledBody, StyledDialog, StyledTitle } from './styled';
// Type // Type
import { Nullable } from '../../globals/types'; import { Nullable } from '../../types/common';
export interface IDialogProps { export interface IDialogProps {
title?: string; title?: string;
@@ -13,7 +13,7 @@ import { StyledMenu, StyledButton, StyledList, StyledToggle } from './styled';
import MenusContext from '../../contexts/MenuContext'; import MenusContext from '../../contexts/MenuContext';
// Types // Types
import { Nullable } from '../../globals/types'; import { Nullable } from '../../types/common';
interface IButton { interface IButton {
children?: string; children?: string;
@@ -2,6 +2,7 @@ const STATUS_CODE = {
OK: 200, OK: 200,
CREATE: 201, CREATE: 201,
NOT_FOUND: 404, NOT_FOUND: 404,
INTERNAL_SERVER_ERROR: 500,
}; };
const RESPONSE_MESSAGE = { const RESPONSE_MESSAGE = {
-31
View File
@@ -1,31 +0,0 @@
type TUser = {
id: number;
name: string;
identifiedCode: string;
phone: string;
roomId: number;
};
type TRoom = {
id: number;
name: string;
price: number;
discount: number;
finalPrice: number;
status: boolean;
};
type TResponse<T> = {
statusCode: number;
msg: string;
data?: T;
};
type Nullable<T> = T | null;
export type {
TUser,
TRoom,
TResponse,
Nullable,
};
+1 -1
View File
@@ -2,7 +2,7 @@
import { BASE_URL } from '../constants/path'; import { BASE_URL } from '../constants/path';
// Types // Types
import { TResponse } from '../globals/types'; import { TResponse } from '../types/types';
type TMethodRequest = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; type TMethodRequest = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
+1 -1
View File
@@ -8,7 +8,7 @@ import { DEFAULT_ORDER_BY, DEFAULT_SORT_BY } from '../constants/config';
import { searchQuery } from '../helpers/utils'; import { searchQuery } from '../helpers/utils';
// Types // Types
import { Nullable } from '../globals/types'; import { Nullable } from '../types/common';
/** /**
* The function use to fetch data on server API. * The function use to fetch data on server API.
+1 -1
View File
@@ -1,7 +1,7 @@
import { ForwardedRef, useEffect, useRef } from 'react'; import { ForwardedRef, useEffect, useRef } from 'react';
// Types // Types
import { Nullable } from '../globals/types'; import { Nullable } from '../types/common';
const useForwardRef = <T>( const useForwardRef = <T>(
ref: ForwardedRef<T>, ref: ForwardedRef<T>,
@@ -1,7 +1,7 @@
import { MutableRefObject, useEffect, useRef } from 'react'; import { MutableRefObject, useEffect, useRef } from 'react';
// Types // Types
import { Nullable } from '../globals/types'; import { Nullable } from '../types/common';
/** /**
* Custom hook to call handler when click outside element * Custom hook to call handler when click outside element
+2 -1
View File
@@ -11,7 +11,8 @@ import Dialog from '../../components/Dialog';
import RoomForm from './Form'; import RoomForm from './Form';
// Types // Types
import { Nullable, TRoom } from '../../globals/types'; import { Nullable } from '../../types/common';
import { TRoom } from '../../types/rooms';
// Hooks // Hooks
import { useForwardRef } from '../../hooks/useForwardRef'; import { useForwardRef } from '../../hooks/useForwardRef';
+23 -6
View File
@@ -10,12 +10,16 @@ import Button from '../../commons/styles/Button.ts';
import Input from '../../commons/styles/Input.ts'; import Input from '../../commons/styles/Input.ts';
// Types // Types
import { Nullable, TRoom } from '../../globals/types.ts'; import { Nullable } from '../../types/common';
import { TRoom } from '../../types/rooms.ts';
// Constants // Constants
import { ROOM_PATH } from '../../constants/path.ts';
import { STATUS_CODE } from '../../constants/responseStatus.ts';
import { import {
ADD_SUCCESS, ADD_SUCCESS,
EDIT_SUCCESS, EDIT_SUCCESS,
errorMsg,
} from '../../constants/messages.ts'; } from '../../constants/messages.ts';
import { import {
INVALID_DISCOUNT, INVALID_DISCOUNT,
@@ -24,6 +28,7 @@ import {
} from '../../constants/formValidateMessage.ts'; } from '../../constants/formValidateMessage.ts';
// Helpers // Helpers
import { sendRequest } from '../../helpers/sendRequest.ts';
import { import {
isValidDiscount, isValidDiscount,
isValidNumber, isValidNumber,
@@ -33,7 +38,6 @@ import {
// Components // Components
import FormRow from '../../components/LabelControl/index.tsx'; import FormRow from '../../components/LabelControl/index.tsx';
import Form from '../../components/Form/index.tsx'; import Form from '../../components/Form/index.tsx';
import { addRoom, updateRoom } from '../../services/roomServices.ts';
const FormBtn = styled(Button)` const FormBtn = styled(Button)`
width: 100%; width: 100%;
@@ -83,17 +87,30 @@ const RoomForm = ({
try { try {
if (isAdd) { if (isAdd) {
// Add request // Add request
const response = await addRoom(room);
if(response) { const response = await sendRequest(
ROOM_PATH,
'POST',
JSON.stringify(room)
);
if (response.statusCode === STATUS_CODE.CREATE) {
toast.success(ADD_SUCCESS); toast.success(ADD_SUCCESS);
} else {
throw new Error(errorMsg(response.statusCode, response.msg));
} }
} else { } else {
// Edit request // Edit request
const response = await updateRoom(room); const response = await sendRequest(
ROOM_PATH + `/${room!.id}`,
'PUT',
JSON.stringify(room)
);
if (response) { if (response.statusCode == STATUS_CODE.OK) {
toast.success(EDIT_SUCCESS); toast.success(EDIT_SUCCESS);
} else {
throw new Error(errorMsg(response.statusCode, response.msg));
} }
} }
// Reload table data // Reload table data
+2 -1
View File
@@ -15,7 +15,8 @@ import SortBy from '../../components/SortBy';
import OrderBy from '../../components/OrderBy'; import OrderBy from '../../components/OrderBy';
// Types // Types
import { Nullable, TRoom } from '../../globals/types'; import { Nullable } from '../../types/common';
import { TRoom } from '../../types/rooms';
// Constants // Constants
import { useFetch } from '../../hooks/useFetch'; import { useFetch } from '../../hooks/useFetch';
+2 -1
View File
@@ -10,7 +10,8 @@ import Button from '../../commons/styles/Button';
import RoomDialog from './Dialog'; import RoomDialog from './Dialog';
// Types // Types
import { Nullable, TRoom } from '../../globals/types'; import { Nullable } from '../../types/common';
import { TRoom } from '../../types/rooms';
const Room = () => { const Room = () => {
const dialogRef = useRef<HTMLDialogElement>(null); const dialogRef = useRef<HTMLDialogElement>(null);
+2 -1
View File
@@ -11,7 +11,8 @@ import Dialog from '../../components/Dialog';
import UserForm from './Form'; import UserForm from './Form';
// Types // Types
import { Nullable, TUser } from '../../globals/types'; import { Nullable } from '../../types/common';
import { TUser } from '../../types/user';
// Hooks // Hooks
import { useForwardRef } from '../../hooks/useForwardRef'; import { useForwardRef } from '../../hooks/useForwardRef';
+29 -14
View File
@@ -19,6 +19,7 @@ import FormRow from '../../components/LabelControl/index.tsx';
import Select, { ISelectOptions } from '../../components/Select'; import Select, { ISelectOptions } from '../../components/Select';
// Helpers // Helpers
import { sendRequest } from '../../helpers/sendRequest.ts';
import { import {
isEmptyObj, isEmptyObj,
isValidName, isValidName,
@@ -27,10 +28,13 @@ import {
} from '../../helpers/validators.ts'; } from '../../helpers/validators.ts';
// Constants // Constants
import { STATUS_CODE } from '../../constants/responseStatus.ts';
import { import {
ADD_SUCCESS, ADD_SUCCESS,
EDIT_SUCCESS, EDIT_SUCCESS,
errorMsg,
} from '../../constants/messages.ts'; } from '../../constants/messages.ts';
import { USER_PATH } from '../../constants/path.ts';
import { import {
INVALID_FIELD, INVALID_FIELD,
INVALID_PHONE, INVALID_PHONE,
@@ -45,8 +49,9 @@ import { FormBtn } from './styled.ts';
import { getAllRoom, updateRoomStatus } from '../../services/roomServices.ts'; import { getAllRoom, updateRoomStatus } from '../../services/roomServices.ts';
// Types // Types
import { Nullable, TRoom, TUser } from '../../globals/types.ts'; import { Nullable } from '../../types/common';
import { createUser, updateUser } from '../../services/userServices.ts'; import { TUser } from '../../types/user.ts';
import { TRoom } from '../../types/rooms.ts';
interface IUserFormProp { interface IUserFormProp {
onClose: () => void; onClose: () => void;
@@ -82,12 +87,6 @@ const UserForm = ({
// Load and set default options room // Load and set default options room
if (rooms.length > 0) { if (rooms.length > 0) {
// Init first options
options.push({
label: '---Select---',
value: '0'
})
rooms.forEach((item) => { rooms.forEach((item) => {
if (!item.status || tempUser?.roomId === item.id) if (!item.status || tempUser?.roomId === item.id)
options.push({ options.push({
@@ -99,11 +98,16 @@ const UserForm = ({
if (options.length > 0) { if (options.length > 0) {
setOptions(options); setOptions(options);
reset({ roomId: +options[0].value });
} }
if (!isEmptyObj(tempUser)) { if (!isEmptyObj(tempUser)) {
// Init value // Init value
// Set default value when user not have room yet.
if (!tempUser.roomId) {
tempUser.roomId = +options[0].value;
}
reset(tempUser); reset(tempUser);
} else { } else {
reset(INIT_VALUE_USER_FORM); reset(INIT_VALUE_USER_FORM);
@@ -119,20 +123,32 @@ const UserForm = ({
try { try {
if (isAdd) { if (isAdd) {
// Add request // Add request
const response = await createUser(newUser); const response = await sendRequest(
USER_PATH,
'POST',
JSON.stringify(newUser)
);
if (response) { if (response.statusCode === STATUS_CODE.CREATE) {
toast.success(ADD_SUCCESS); toast.success(ADD_SUCCESS);
} else {
throw new Error(errorMsg(response.statusCode, response.msg));
} }
// Update room status // Update room status
updateRoomStatus(newUser.roomId, true); updateRoomStatus(newUser.roomId, true);
} else { } else {
// Edit request // Edit request
const response = await updateUser(newUser); const response = await sendRequest(
USER_PATH + `/${newUser.id}`,
'PUT',
JSON.stringify(newUser)
);
if (response) { if (response.statusCode == STATUS_CODE.OK) {
toast.success(EDIT_SUCCESS); toast.success(EDIT_SUCCESS);
} else {
throw new Error(errorMsg(response.statusCode, response.msg));
} }
// Update room status // Update room status
@@ -224,7 +240,6 @@ const UserForm = ({
optionsConfigForm={{ optionsConfigForm={{
valueAsNumber: true, valueAsNumber: true,
onChange: () => trigger('roomId'), onChange: () => trigger('roomId'),
validate: (v) => v !== 0
}} }}
/> />
) : ( ) : (
+2 -1
View File
@@ -14,7 +14,8 @@ import SortBy from '../../components/SortBy';
import OrderBy from '../../components/OrderBy'; import OrderBy from '../../components/OrderBy';
// Types // Types
import { Nullable, TUser } from '../../globals/types'; import { Nullable } from '../../types/common';
import { TUser } from '../../types/user';
// Hooks // Hooks
import { useFetch } from '../../hooks/useFetch'; import { useFetch } from '../../hooks/useFetch';
+2 -1
View File
@@ -10,7 +10,8 @@ import { StyledUser, Title } from './styled';
import UserDialog from './Dialog'; import UserDialog from './Dialog';
// Types // Types
import { Nullable, TUser } from '../../globals/types'; import { Nullable } from '../../types/common';
import { TUser } from '../../types/user';
const User = () => { const User = () => {
const dialogRef = useRef<HTMLDialogElement>(null); const dialogRef = useRef<HTMLDialogElement>(null);
+16 -43
View File
@@ -1,7 +1,9 @@
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
// Types // Types
import { Nullable, TResponse, TRoom } from '../globals/types'; import { Nullable } from '../types/common';
import { TRoom } from '../types/rooms';
import { TResponse } from '../types/response';
// Helpers // Helpers
import { sendRequest } from '../helpers/sendRequest'; import { sendRequest } from '../helpers/sendRequest';
@@ -44,13 +46,13 @@ const getRoom = async (roomId: number): Promise<Nullable<TRoom>> => {
try { try {
const response = await sendRequest<TRoom>(ROOM_PATH + '/' + roomId); const response = await sendRequest<TRoom>(ROOM_PATH + '/' + roomId);
if (response.statusCode !== STATUS_CODE.OK) { if (response.statusCode === STATUS_CODE.OK) {
throw new Error(errorMsg(response.statusCode, response.msg));
}
const rooms = response.data!; const rooms = response.data!;
return rooms; return rooms;
} else {
throw new Error(errorMsg(response.statusCode, response.msg));
}
} catch (error) { } catch (error) {
if (error instanceof Error) { if (error instanceof Error) {
toast.error(error.message); toast.error(error.message);
@@ -73,6 +75,10 @@ const updateRoom = async (room: TRoom): Promise<Nullable<TResponse<TRoom>>> => {
JSON.stringify(room) JSON.stringify(room)
); );
if (response.statusCode !== STATUS_CODE.OK) {
throw new Error(errorMsg(response.statusCode, response.msg));
}
return response; return response;
} catch (error: unknown) { } catch (error: unknown) {
if (error instanceof Error) { if (error instanceof Error) {
@@ -95,7 +101,6 @@ const updateRoomStatus = async (
status: boolean, status: boolean,
roomIdNew?: number roomIdNew?: number
): Promise<Nullable<TResponse<TRoom>>> => { ): Promise<Nullable<TResponse<TRoom>>> => {
try {
if (!roomIdNew) { if (!roomIdNew) {
const response = await sendRequest<TRoom>( const response = await sendRequest<TRoom>(
ROOM_PATH + '/' + roomId, ROOM_PATH + '/' + roomId,
@@ -129,43 +134,11 @@ const updateRoomStatus = async (
msg: RESPONSE_MESSAGE.UPDATE_SUCCESS, msg: RESPONSE_MESSAGE.UPDATE_SUCCESS,
}; };
} }
} catch (error) {
if (error instanceof Error) {
toast.error(error.message);
}
}
return null; return {
statusCode: STATUS_CODE.INTERNAL_SERVER_ERROR,
msg: 'Something went wrong!',
};
}; };
/** export { getRoom, updateRoom, updateRoomStatus, getAllRoom };
* Add room to server
* @param room The room object need to be add
* @returns The response object if complete or null
*/
const addRoom = async (room: TRoom): Promise<Nullable<TResponse<TRoom>>> => {
try {
// Set default status room
room.status = false;
const response = await sendRequest<TRoom>(
ROOM_PATH,
'POST',
JSON.stringify(room)
);
if (response.statusCode !== STATUS_CODE.CREATE) {
throw new Error(errorMsg(response.statusCode, response.msg));
}
return response;
} catch (error: unknown) {
if (error instanceof Error) {
toast.error(error.message);
}
}
return null;
};
export { getRoom, updateRoom, updateRoomStatus, getAllRoom, addRoom };
+4 -39
View File
@@ -6,43 +6,13 @@ import { USER_PATH } from '../constants/path';
import { STATUS_CODE } from '../constants/responseStatus'; import { STATUS_CODE } from '../constants/responseStatus';
// Types // Types
import { Nullable, TResponse, TUser } from '../globals/types'; import { Nullable } from '../types/common';
import { TUser } from '../types/user';
import { TResponse } from '../types/response';
// Helpers // Helpers
import { sendRequest } from '../helpers/sendRequest'; import { sendRequest } from '../helpers/sendRequest';
/**
* Create user to the server
* @param user The user object need to be created
* @returns The TResponse object if success or null
*/
const createUser = async (user: TUser): Promise<Nullable<TResponse<TUser>>> => {
try {
const response = await sendRequest<TUser>(
USER_PATH,
'POST',
JSON.stringify(user)
);
if (response.statusCode !== STATUS_CODE.CREATE) {
throw new Error(errorMsg(response.statusCode, response.msg));
}
return response;
} catch (error: unknown) {
if (error instanceof Error) {
toast.error(error.message);
}
}
return null;
}
/**
* Update the user to the server
* @param user The user object need to be updated
* @returns The TResponse object if update success or null
*/
const updateUser = async (user: TUser): Promise<Nullable<TResponse<TUser>>> => { const updateUser = async (user: TUser): Promise<Nullable<TResponse<TUser>>> => {
try { try {
const response = await sendRequest<TUser>( const response = await sendRequest<TUser>(
@@ -65,11 +35,6 @@ const updateUser = async (user: TUser): Promise<Nullable<TResponse<TUser>>> => {
return null; return null;
}; };
/**
* Checkout user
* @param user The user need to be checkout
* @returns The TResponse object if checkout success or not
*/
const checkOutUser = async (user: TUser): Promise<Nullable<TResponse<TUser>>> => { const checkOutUser = async (user: TUser): Promise<Nullable<TResponse<TUser>>> => {
const tempUser = user; const tempUser = user;
@@ -83,4 +48,4 @@ const checkOutUser = async (user: TUser): Promise<Nullable<TResponse<TUser>>> =>
return null; return null;
}; };
export { updateUser, checkOutUser, createUser }; export { updateUser, checkOutUser };
+3
View File
@@ -0,0 +1,3 @@
type Nullable<T> = T | null;
export type { Nullable };
+7
View File
@@ -0,0 +1,7 @@
type TResponse<T> = {
statusCode: number;
msg: string;
data?: T;
};
export type { TResponse };
+10
View File
@@ -0,0 +1,10 @@
type TRoom = {
id: number;
name: string;
price: number;
discount: number;
finalPrice: number;
status: boolean;
};
export type { TRoom };
+9
View File
@@ -0,0 +1,9 @@
type TUser = {
id: number;
name: string;
identifiedCode: string;
phone: string;
roomId: number;
};
export type { TUser };