mirror of
https://github.com/Nezumi-2711/react-training.git
synced 2026-09-22 13:38:51 +00:00
Update method for user pages and format code
This commit is contained in:
@@ -1,9 +1,25 @@
|
||||
import styled, { css } from 'styled-components';
|
||||
import styled, { RuleSet, css } from 'styled-components';
|
||||
|
||||
type TButtonStyle = 'primary' | 'secondary';
|
||||
interface IVariations {
|
||||
[key: string]: RuleSet<object>;
|
||||
}
|
||||
|
||||
const variations: IVariations = {
|
||||
primary: css`
|
||||
background-color: var(--primary-color);
|
||||
color: var(--light-text);
|
||||
`,
|
||||
secondary: css`
|
||||
background-color: var(--secondary-btn-color);
|
||||
`,
|
||||
danger: css`
|
||||
background-color: var(--danger-btn-color);
|
||||
color: var(--light-text);
|
||||
`,
|
||||
};
|
||||
|
||||
interface IButtonStyle {
|
||||
styled?: TButtonStyle;
|
||||
variations?: keyof IVariations;
|
||||
}
|
||||
|
||||
const Button = styled.button<IButtonStyle>`
|
||||
@@ -16,22 +32,16 @@ const Button = styled.button<IButtonStyle>`
|
||||
|
||||
border-radius: var(--radius-md);
|
||||
|
||||
${(props) =>
|
||||
props.styled === 'primary' &&
|
||||
css`
|
||||
background-color: var(--primary-color);
|
||||
color: var(--light-text);
|
||||
`}
|
||||
${(props) => variations[props.variations!]}
|
||||
|
||||
${(props) =>
|
||||
props.styled === 'secondary' &&
|
||||
css`
|
||||
background-color: var(--secondary-btn-color);
|
||||
`}
|
||||
&:disabled,
|
||||
&[disabled] {
|
||||
cursor: no-drop;
|
||||
}
|
||||
`;
|
||||
|
||||
Button.defaultProps = {
|
||||
styled: 'primary',
|
||||
variations: 'primary',
|
||||
};
|
||||
|
||||
export default Button;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { memo } from 'react';
|
||||
|
||||
// Styled
|
||||
import { StyledConfirmDelete } from './styled';
|
||||
|
||||
// Component
|
||||
import Button from '@commonStyle/Button';
|
||||
|
||||
interface IConfirmMessage {
|
||||
message: string;
|
||||
disabled: boolean;
|
||||
onConfirm: () => void;
|
||||
onCloseModal?: () => void;
|
||||
}
|
||||
|
||||
const ConfirmMessage = memo(
|
||||
({ message, disabled, onConfirm, onCloseModal }: IConfirmMessage) => {
|
||||
|
||||
return (
|
||||
<StyledConfirmDelete>
|
||||
<p>{message}</p>
|
||||
|
||||
<div>
|
||||
<Button variations="danger" disabled={disabled} onClick={onConfirm}>
|
||||
Delete
|
||||
</Button>
|
||||
<Button
|
||||
variations="secondary"
|
||||
disabled={disabled}
|
||||
onClick={onCloseModal}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</StyledConfirmDelete>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
export default ConfirmMessage;
|
||||
@@ -0,0 +1,20 @@
|
||||
import styled from "styled-components";
|
||||
|
||||
const StyledConfirmDelete = styled.div`
|
||||
width: 450px;
|
||||
|
||||
& p {
|
||||
font-size: var(--fs-sm);
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
& div {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
|
||||
padding-inline: 50px;
|
||||
}
|
||||
`;
|
||||
|
||||
export { StyledConfirmDelete };
|
||||
@@ -5,19 +5,26 @@ import { StyledSearch } from './styled';
|
||||
|
||||
// Hooks
|
||||
import { useDebounce } from '@hook/useDebounce';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { Nullable } from '@type/common';
|
||||
|
||||
interface ISearch {
|
||||
setPlaceHolder: string;
|
||||
setValueSearch: (phone: string) => void;
|
||||
}
|
||||
|
||||
const Search = ({ setValueSearch, setPlaceHolder }: ISearch) => {
|
||||
const [query, setQuery] = useState('');
|
||||
const debounceValue = useDebounce<string>(query, 700);
|
||||
const Search = ({ setPlaceHolder }: ISearch) => {
|
||||
const field = 'search';
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [query, setQuery] = useState<Nullable<string>>(null);
|
||||
const debounceValue = useDebounce<Nullable<string>>(query, 700);
|
||||
|
||||
useEffect(() => {
|
||||
setValueSearch(debounceValue);
|
||||
}, [debounceValue, setValueSearch]);
|
||||
if (debounceValue !== null) {
|
||||
searchParams.set(field, debounceValue);
|
||||
|
||||
setSearchParams(searchParams);
|
||||
}
|
||||
}, [debounceValue, searchParams, setSearchParams]);
|
||||
|
||||
return (
|
||||
<StyledSearch
|
||||
|
||||
@@ -41,7 +41,7 @@ const Toast = ({
|
||||
Toast.defaultProps = {
|
||||
position: 'top-center',
|
||||
gutter: 12,
|
||||
containerStyle: { margin: '8px', zIndex: 1 },
|
||||
containerStyle: { margin: '8px', zIndex: 2000 },
|
||||
success: {
|
||||
duration: 3000,
|
||||
},
|
||||
|
||||
@@ -37,7 +37,7 @@ const ROOM_PAGE = {
|
||||
label: 'Sort by name',
|
||||
},
|
||||
{
|
||||
value: 'finalPrice',
|
||||
value: 'price',
|
||||
label: 'Sort by price',
|
||||
},
|
||||
],
|
||||
@@ -59,6 +59,7 @@ const INIT_VALUE_ROOM_FORM = {
|
||||
|
||||
const FORM = {
|
||||
EDIT: 'edit',
|
||||
DELETE: 'delete',
|
||||
USER: 'user-form',
|
||||
ROOM: 'room-form',
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const TIME_OUT_SEC = 1;
|
||||
const DEFAULT_SORT_BY = 'id';
|
||||
const DEFAULT_ORDER_BY = 'asc';
|
||||
const supabaseUrl = 'https://pjqujsjzzdrlrgqbxepe.supabase.co'
|
||||
const supabaseKey = import.meta.env.VITE_SUPABASE_KEY
|
||||
|
||||
export { TIME_OUT_SEC, DEFAULT_SORT_BY, DEFAULT_ORDER_BY };
|
||||
export { DEFAULT_SORT_BY, DEFAULT_ORDER_BY, supabaseKey, supabaseUrl };
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
const ADD_SUCCESS = 'Add success';
|
||||
const EDIT_SUCCESS = 'Edit success';
|
||||
const UPDATE_SUCCESS = 'Update success';
|
||||
const CONFIRM_MESSAGE = 'Do you want to checkout this user?';
|
||||
const CONFIRM_DELETE = 'Are you sure to delete it?'
|
||||
const DELETE_SUCCESS = 'Delete success';
|
||||
const CHECKOUT_SUCCESS = 'Check out success';
|
||||
const DENIED_ACTION = "Can't checkout user not in room!";
|
||||
|
||||
export {
|
||||
ADD_SUCCESS,
|
||||
EDIT_SUCCESS,
|
||||
UPDATE_SUCCESS,
|
||||
CONFIRM_MESSAGE,
|
||||
CONFIRM_DELETE,
|
||||
DELETE_SUCCESS,
|
||||
CHECKOUT_SUCCESS,
|
||||
DENIED_ACTION
|
||||
};
|
||||
|
||||
@@ -2,6 +2,5 @@ export const DASHBOARD = '/dashboard';
|
||||
export const USER = '/user';
|
||||
export const ROOM = '/room';
|
||||
export const OTHER_PATH = '*';
|
||||
export const BASE_URL = 'http://localhost:3000/';
|
||||
export const USER_PATH = 'users';
|
||||
export const ROOM_PATH = 'rooms';
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
const STATUS_CODE = {
|
||||
OK: 200,
|
||||
CREATE: 201,
|
||||
NOT_FOUND: 404,
|
||||
};
|
||||
|
||||
const RESPONSE_MESSAGE = {
|
||||
UPDATE_SUCCESS: 'Update success',
|
||||
};
|
||||
|
||||
export { STATUS_CODE, RESPONSE_MESSAGE };
|
||||
@@ -1,7 +0,0 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { Database } from '@type/supabase';
|
||||
const supabaseUrl = 'https://pjqujsjzzdrlrgqbxepe.supabase.co'
|
||||
const supabaseKey = import.meta.env.VITE_SUPABASE_KEY
|
||||
const supabase = createClient<Database>(supabaseUrl, supabaseKey!)
|
||||
|
||||
export default supabase;
|
||||
@@ -1,6 +1,3 @@
|
||||
// Constants
|
||||
import { REQUIRED_FIELD_ERROR } from '../constants/formValidateMessage';
|
||||
|
||||
/**
|
||||
* Convert value to currency format with value
|
||||
* @param value Value need to be converted
|
||||
@@ -13,14 +10,4 @@ const formatCurrency = (value: number): string => {
|
||||
}).format(value);
|
||||
};
|
||||
|
||||
/**
|
||||
* Create error string
|
||||
* @param errorCode Error code
|
||||
* @param msg Message error
|
||||
* @returns Return the full error string
|
||||
*/
|
||||
const errorMsg = (errorCode: number, msg: string) => {
|
||||
return `Error code: ${errorCode}. Message: ${msg}`;
|
||||
};
|
||||
|
||||
export { errorMsg, formatCurrency, REQUIRED_FIELD_ERROR };
|
||||
export { formatCurrency };
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
// Constants
|
||||
import { BASE_URL } from '@constant/path';
|
||||
|
||||
// Types
|
||||
import { IResponse } from '@type/responses';
|
||||
|
||||
type TMethodRequest = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
||||
|
||||
/**
|
||||
* The send request method to the server
|
||||
* @param path The path of URL
|
||||
* @param body The content will push on
|
||||
* @param method HTTP method
|
||||
* @returns The status code and message from server
|
||||
*/
|
||||
export const sendRequest = async <T>(
|
||||
path: string,
|
||||
method: TMethodRequest = 'GET',
|
||||
body?: BodyInit
|
||||
): Promise<IResponse<T>> => {
|
||||
const response = await fetch(BASE_URL + path, {
|
||||
method,
|
||||
body,
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
const data = (await response.json()) as T;
|
||||
|
||||
return {
|
||||
statusCode: response.status,
|
||||
msg: response.statusText,
|
||||
data,
|
||||
};
|
||||
};
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
const isValidRegex = (regex: RegExp, value: string): boolean => {
|
||||
return regex.test(value);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Check value is valid discount or not
|
||||
@@ -17,7 +17,6 @@ const isValidDiscount = (value: number): boolean => {
|
||||
return value >= 0 && value <= 100;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Check value is valid string or not
|
||||
* @param value Value need to be checked
|
||||
@@ -27,18 +26,4 @@ const isValidString = (value: string): boolean => {
|
||||
return value.trim().length >= 5;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check object is empty or not
|
||||
* @param obj Object need to be check
|
||||
* @returns A boolean indicating whether or not the argument has valid
|
||||
*/
|
||||
const isEmptyObj = (obj: object) => {
|
||||
return Object.keys(obj).length === 0;
|
||||
};
|
||||
|
||||
export {
|
||||
isValidRegex,
|
||||
isValidString,
|
||||
isValidDiscount,
|
||||
isEmptyObj,
|
||||
};
|
||||
export { isValidRegex, isValidString, isValidDiscount };
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
// Services
|
||||
import { createRoom as createRoomFn } from '@service/roomServices';
|
||||
|
||||
// Constants
|
||||
import { ADD_SUCCESS } from '@constant/messages';
|
||||
|
||||
/**
|
||||
* Create room on database
|
||||
* @returns The boolean of isCreating and create room function
|
||||
*/
|
||||
const useCreateRoom = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { mutate: createRoom, isPending: isCreating } = useMutation({
|
||||
mutationFn: createRoomFn,
|
||||
onSuccess: () => {
|
||||
toast.success(ADD_SUCCESS);
|
||||
queryClient.invalidateQueries({ queryKey: ['rooms'] });
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
});
|
||||
|
||||
return { isCreating, createRoom };
|
||||
};
|
||||
|
||||
export { useCreateRoom };
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
// Services
|
||||
import { deleteRoom as deleteRoomFn } from '@service/roomServices';
|
||||
|
||||
// Constants
|
||||
import * as messages from '@constant/messages';
|
||||
|
||||
/**
|
||||
* Delete the room from database
|
||||
* @returns The boolean of status deleting and deleteRoom function
|
||||
*/
|
||||
const useDeleteRoom = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { isPending: isDeleting, mutate: deleteRoom } = useMutation({
|
||||
mutationFn: deleteRoomFn,
|
||||
onSuccess: () => {
|
||||
toast.success(messages.DELETE_SUCCESS);
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['rooms'],
|
||||
});
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
});
|
||||
|
||||
return { isDeleting, deleteRoom };
|
||||
};
|
||||
|
||||
export { useDeleteRoom };
|
||||
@@ -0,0 +1,34 @@
|
||||
import toast from "react-hot-toast";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
|
||||
// Services
|
||||
import { getAllRooms } from "@service/roomServices";
|
||||
|
||||
/**
|
||||
* Fetch room from database
|
||||
* @returns The status of loading rooms from database and data of rooms
|
||||
*/
|
||||
const useRooms = () => {
|
||||
const [searchParams] = useSearchParams();
|
||||
const sortByValue = searchParams.get('sortBy') || 'id';
|
||||
const orderByValue = searchParams.get('orderBy') || 'asc';
|
||||
const phoneSearch = searchParams.get('search') || ''
|
||||
|
||||
const {
|
||||
isLoading,
|
||||
data: rooms,
|
||||
error,
|
||||
} = useQuery({
|
||||
queryKey: ['rooms', sortByValue, orderByValue, phoneSearch],
|
||||
queryFn: () => getAllRooms(sortByValue, orderByValue, phoneSearch),
|
||||
});
|
||||
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
|
||||
return { isLoading, rooms };
|
||||
};
|
||||
|
||||
export { useRooms };
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
// Services
|
||||
import { updateRoom as updateRoomFn } from '@service/roomServices';
|
||||
|
||||
// Constants
|
||||
import { UPDATE_SUCCESS } from '@constant/messages';
|
||||
|
||||
/**
|
||||
* Update room from database
|
||||
* @returns The status of updating and updateRoom function
|
||||
*/
|
||||
const useUpdateRoom = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { mutate: updateRoom, isPending: isUpdating } = useMutation({
|
||||
mutationFn: updateRoomFn,
|
||||
onSuccess: () => {
|
||||
toast.success(UPDATE_SUCCESS);
|
||||
queryClient.invalidateQueries({ queryKey: ['rooms'] });
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
});
|
||||
|
||||
return { isUpdating, updateRoom };
|
||||
};
|
||||
|
||||
export { useUpdateRoom };
|
||||
@@ -1,25 +0,0 @@
|
||||
import { ForwardedRef, useEffect, useRef } from 'react';
|
||||
|
||||
// Types
|
||||
import { Nullable } from '@type/common';
|
||||
|
||||
const useForwardRef = <T>(
|
||||
ref: ForwardedRef<T>,
|
||||
initialValue: Nullable<T> = null
|
||||
) => {
|
||||
const targetRef = useRef<T>(initialValue);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ref) return;
|
||||
|
||||
if (typeof ref === 'function') {
|
||||
ref(targetRef.current);
|
||||
} else {
|
||||
ref.current = targetRef.current;
|
||||
}
|
||||
}, [ref]);
|
||||
|
||||
return targetRef;
|
||||
};
|
||||
|
||||
export { useForwardRef };
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
// Services
|
||||
import { createUser as createUserFn } from '@service/userServices';
|
||||
|
||||
// Constants
|
||||
import { ADD_SUCCESS } from '@constant/messages';
|
||||
|
||||
/**
|
||||
* Create user in database
|
||||
* @returns The status of creating users and createUser function
|
||||
*/
|
||||
const useCreateUser = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { mutate: createUser, isPending: isCreating } = useMutation({
|
||||
mutationFn: createUserFn,
|
||||
onSuccess: () => {
|
||||
toast.success(ADD_SUCCESS);
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] });
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
});
|
||||
|
||||
return { isCreating, createUser };
|
||||
};
|
||||
|
||||
export { useCreateUser };
|
||||
@@ -0,0 +1,29 @@
|
||||
import toast from 'react-hot-toast';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
// Services
|
||||
import { updateUser as updateUserFn } from '@service/userServices';
|
||||
|
||||
// Messages
|
||||
import { UPDATE_SUCCESS } from '@constant/messages';
|
||||
|
||||
/**
|
||||
* Update user from database
|
||||
* @returns The status of updating user and updateUser function
|
||||
*/
|
||||
const useUpdateUser = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { mutate: updateUser, isPending: isUpdating } = useMutation({
|
||||
mutationFn: updateUserFn,
|
||||
onSuccess: () => {
|
||||
toast.success(UPDATE_SUCCESS);
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] });
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
});
|
||||
|
||||
return { isUpdating, updateUser };
|
||||
};
|
||||
|
||||
export { useUpdateUser };
|
||||
@@ -0,0 +1,34 @@
|
||||
import toast from "react-hot-toast";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
|
||||
// Services
|
||||
import { getAllUsers } from "@service/userServices";
|
||||
|
||||
/**
|
||||
* Fetch data of users from database
|
||||
* @returns The status of loading users and data of users
|
||||
*/
|
||||
const useUsers = () => {
|
||||
const [searchParams] = useSearchParams();
|
||||
const sortByValue = searchParams.get('sortBy') || 'id';
|
||||
const orderByValue = searchParams.get('orderBy') || 'asc';
|
||||
const phoneSearch = searchParams.get('search') || ''
|
||||
|
||||
const {
|
||||
isLoading,
|
||||
data: users,
|
||||
error,
|
||||
} = useQuery({
|
||||
queryKey: ['users', sortByValue, orderByValue, phoneSearch],
|
||||
queryFn: () => getAllUsers(sortByValue, orderByValue, phoneSearch),
|
||||
});
|
||||
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
|
||||
return { isLoading, users };
|
||||
};
|
||||
|
||||
export { useUsers };
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
|
||||
// Components
|
||||
import Menus from '@component/Menus';
|
||||
@@ -21,23 +20,17 @@ import { StyledOperationTable } from './styled';
|
||||
import Direction from '@commonStyle/Direction';
|
||||
import Spinner from '@commonStyle/Spinner';
|
||||
|
||||
// Hooks
|
||||
import { useRooms } from '@hook/rooms/useRooms';
|
||||
|
||||
interface IRoomTable {
|
||||
reload: boolean;
|
||||
setReload: Dispatch<SetStateAction<boolean>>;
|
||||
}
|
||||
|
||||
const RoomTable = ({ reload, setReload }: IRoomTable) => {
|
||||
const RoomTable = () => {
|
||||
const columnName = ['Id', 'Name', 'Price', 'Status'];
|
||||
const [nameSearch, setNameSearch] = useState('');
|
||||
const [searchParams] = useSearchParams();
|
||||
const [rooms, setRooms] = useState<IRoom[]>([]);
|
||||
const sortByValue = searchParams.get('sortBy')
|
||||
? searchParams.get('sortBy')!
|
||||
: '';
|
||||
const orderByValue = searchParams.get('orderBy')
|
||||
? searchParams.get('orderBy')!
|
||||
: '';
|
||||
const { isLoading, rooms } = useRooms();
|
||||
|
||||
const renderRoomRow = useCallback(
|
||||
(room: IRoom) => <RoomRow room={room} key={room.id} />,
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -46,33 +39,20 @@ const RoomTable = ({ reload, setReload }: IRoomTable) => {
|
||||
<OrderBy options={ORDERBY_OPTIONS} />
|
||||
|
||||
<SortBy options={ROOM_PAGE.SORTBY_OPTIONS} />
|
||||
<Search
|
||||
setValueSearch={setNameSearch}
|
||||
setPlaceHolder="Search by name..."
|
||||
/>
|
||||
<Search setPlaceHolder="Search by name..." />
|
||||
</StyledOperationTable>
|
||||
|
||||
{isPending && <Spinner />}
|
||||
{isLoading && <Spinner />}
|
||||
|
||||
{rooms.length ? (
|
||||
{rooms && rooms.length ? (
|
||||
<Menus>
|
||||
<Table columns="10% 40% 20% 20% 5%">
|
||||
<Table.Header headerColumn={columnName}/>
|
||||
<Table.Body<IRoom>
|
||||
data={rooms}
|
||||
render={(room: IRoom) => (
|
||||
<RoomRow
|
||||
room={room}
|
||||
key={room.id}
|
||||
reload={reload}
|
||||
setReload={setReload}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Table.Header headerColumn={columnName} />
|
||||
<Table.Body<IRoom> data={rooms} render={renderRoomRow} />
|
||||
</Table>
|
||||
</Menus>
|
||||
) : (
|
||||
!isPending && <Message>No data to show here!</Message>
|
||||
!isLoading && <Message>No data to show here!</Message>
|
||||
)}
|
||||
</Direction>
|
||||
</>
|
||||
|
||||
@@ -1,40 +1,30 @@
|
||||
import { Dispatch, SetStateAction, useEffect } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import styled from 'styled-components';
|
||||
|
||||
// Hooks
|
||||
import { useForm } from 'react-hook-form';
|
||||
|
||||
// Styled
|
||||
import Button from '@commonStyle/Button.ts';
|
||||
import Input from '@commonStyle/Input.ts';
|
||||
|
||||
// Types
|
||||
import { Nullable } from '@type/common.ts';
|
||||
import { IRoom } from '@type/rooms.ts';
|
||||
|
||||
// Constants
|
||||
import { ADD_SUCCESS, EDIT_SUCCESS } from '@constant/messages.ts';
|
||||
import {
|
||||
INVALID_DISCOUNT,
|
||||
INVALID_FIELD,
|
||||
REQUIRED_FIELD_ERROR,
|
||||
} from '@constant/formValidateMessage.ts';
|
||||
import { INIT_VALUE_ROOM_FORM, REGEX } from '../../constants/commons.ts';
|
||||
import { REGEX } from '../../constants/commons.ts';
|
||||
|
||||
// Helpers
|
||||
import {
|
||||
isValidDiscount,
|
||||
isValidRegex,
|
||||
isValidString,
|
||||
} from '@helper/validators.ts';
|
||||
import { isValidRegex, isValidString } from '@helper/validators.ts';
|
||||
|
||||
// Components
|
||||
import FormRow from '@component/LabelControl/index.tsx';
|
||||
import Form from '@component/Form/index.tsx';
|
||||
|
||||
// Services
|
||||
import { addRoom, updateRoom } from '@service/roomServices.ts';
|
||||
// Hooks
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useCreateRoom } from '@hook/rooms/useCreateRoom.ts';
|
||||
import { useUpdateRoom } from '@hook/rooms/useUpdateRoom.ts';
|
||||
|
||||
const FormBtn = styled(Button)`
|
||||
width: 100%;
|
||||
@@ -48,65 +38,51 @@ const FormBtn = styled(Button)`
|
||||
|
||||
interface IRoomFormProp {
|
||||
onCloseModal?: () => void;
|
||||
reload?: boolean;
|
||||
setReload?: Dispatch<SetStateAction<boolean>>;
|
||||
roomEdit?: Nullable<IRoom>;
|
||||
room?: IRoom;
|
||||
}
|
||||
|
||||
const RoomForm = ({
|
||||
onCloseModal,
|
||||
reload,
|
||||
setReload,
|
||||
roomEdit,
|
||||
}: IRoomFormProp) => {
|
||||
const formMethods = useForm<IRoom>();
|
||||
const RoomForm = ({ onCloseModal, room }: IRoomFormProp) => {
|
||||
const { isCreating, createRoom } = useCreateRoom();
|
||||
const { isUpdating, updateRoom } = useUpdateRoom();
|
||||
const isLoading = isCreating || isUpdating;
|
||||
const { id: editId, ...editValues } = { ...room };
|
||||
const formMethods = useForm<IRoom>({
|
||||
defaultValues: editId
|
||||
? editValues
|
||||
: {},
|
||||
});
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors, isDirty, isValid, isSubmitting },
|
||||
formState: { errors, isDirty, isValid },
|
||||
trigger,
|
||||
} = formMethods;
|
||||
|
||||
useEffect(() => {
|
||||
if (roomEdit) {
|
||||
reset(roomEdit);
|
||||
} else {
|
||||
reset(INIT_VALUE_ROOM_FORM);
|
||||
}
|
||||
}, [roomEdit, reset]);
|
||||
|
||||
// Submit form
|
||||
const onSubmit = async (room: IRoom) => {
|
||||
// Calculate final price
|
||||
room.finalPrice = room.price - (room.price * room.discount) / 100;
|
||||
|
||||
if (!roomEdit) {
|
||||
const onSubmit = async (newRoom: IRoom) => {
|
||||
if (!editId) {
|
||||
// Add request
|
||||
const response = await addRoom(room);
|
||||
|
||||
if (response) {
|
||||
toast.success(ADD_SUCCESS);
|
||||
}
|
||||
createRoom(newRoom, {
|
||||
onSuccess: () => {
|
||||
reset();
|
||||
onCloseModal?.();
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Edit request
|
||||
const response = await updateRoom(room);
|
||||
|
||||
if (response) {
|
||||
toast.success(EDIT_SUCCESS);
|
||||
}
|
||||
}
|
||||
|
||||
// Reload table data
|
||||
setReload!(!reload);
|
||||
|
||||
newRoom.id = editId!;
|
||||
updateRoom(newRoom, {
|
||||
onSuccess: () => {
|
||||
reset();
|
||||
onCloseModal!();
|
||||
onCloseModal?.();
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Form onSubmit={handleSubmit(onSubmit)}>
|
||||
<Input type="hidden" id="id" {...register('id')} />
|
||||
<FormRow label="Name" error={errors?.name?.message}>
|
||||
<Input
|
||||
type="text"
|
||||
@@ -114,7 +90,8 @@ const RoomForm = ({
|
||||
{...register('name', {
|
||||
required: REQUIRED_FIELD_ERROR,
|
||||
validate: {
|
||||
checkValidRoomName: (value) => isValidString(value) || INVALID_FIELD,
|
||||
checkValidRoomName: (value) =>
|
||||
isValidString(value) || INVALID_FIELD,
|
||||
},
|
||||
onChange: () => trigger('name'),
|
||||
})}
|
||||
@@ -130,41 +107,27 @@ const RoomForm = ({
|
||||
required: REQUIRED_FIELD_ERROR,
|
||||
validate: {
|
||||
checkPrice: (v) =>
|
||||
isValidRegex(new RegExp(REGEX.NUMBER), v.toString()) || INVALID_FIELD,
|
||||
isValidRegex(new RegExp(REGEX.NUMBER), v.toString()) ||
|
||||
INVALID_FIELD,
|
||||
},
|
||||
onChange: () => trigger('price'),
|
||||
})}
|
||||
/>
|
||||
</FormRow>
|
||||
|
||||
<FormRow label="discount" error={errors?.discount?.message}>
|
||||
<Input
|
||||
type="text"
|
||||
id="phone"
|
||||
{...register('discount', {
|
||||
valueAsNumber: true,
|
||||
required: REQUIRED_FIELD_ERROR,
|
||||
validate: {
|
||||
checkDiscount: (v) => isValidDiscount(v) || INVALID_DISCOUNT,
|
||||
},
|
||||
onChange: () => trigger('discount'),
|
||||
})}
|
||||
/>
|
||||
</FormRow>
|
||||
|
||||
<Form.Action>
|
||||
<FormBtn
|
||||
type="submit"
|
||||
name="submit"
|
||||
disabled={!isDirty || !isValid || isSubmitting}
|
||||
disabled={!isDirty || !isValid || isLoading}
|
||||
>
|
||||
{
|
||||
!roomEdit
|
||||
!editId
|
||||
? 'Add'
|
||||
: 'Save'
|
||||
}
|
||||
</FormBtn>
|
||||
<FormBtn type="button" styled="secondary" onClick={onCloseModal}>
|
||||
<FormBtn type="button" variations="secondary" onClick={onCloseModal}>
|
||||
Close
|
||||
</FormBtn>
|
||||
</Form.Action>
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
// Constants
|
||||
import { ROOM_PATH } from '@constant/path';
|
||||
import { STATUS_CODE } from '@constant/responseStatus';
|
||||
import { CONFIRM_DELETE, DELETE_SUCCESS } from '@constant/messages';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
|
||||
// Helpers
|
||||
import { sendRequest } from '@helper/sendRequest';
|
||||
import { formatCurrency } from '@helper/helper';
|
||||
|
||||
// Types
|
||||
@@ -20,38 +13,47 @@ import Table from '@component/Table';
|
||||
import Menus from '@component/Menus';
|
||||
import { RiEditBoxFill } from 'react-icons/ri';
|
||||
import { HiTrash } from 'react-icons/hi';
|
||||
import ConfirmMessage from '@component/ConfirmMessage';
|
||||
|
||||
// Hooks
|
||||
import { useDeleteRoom } from '@hook/rooms/useDeleteRoom';
|
||||
|
||||
// Constants
|
||||
import { FORM } from '@constant/commons';
|
||||
|
||||
interface IRoomRow {
|
||||
room: IRoom;
|
||||
reload: boolean;
|
||||
setReload: Dispatch<SetStateAction<boolean>>;
|
||||
}
|
||||
|
||||
const RoomRow = ({ room, reload, setReload }: IRoomRow) => {
|
||||
const handleDelete = async (room: IRoom) => {
|
||||
if (confirm(CONFIRM_DELETE)) {
|
||||
const response = await sendRequest(ROOM_PATH + `/${room.id}`, 'DELETE');
|
||||
|
||||
if (response.statusCode === STATUS_CODE.OK) {
|
||||
toast.success(DELETE_SUCCESS);
|
||||
|
||||
// Reload table
|
||||
setReload(!reload);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const { id, name, finalPrice, status } = room;
|
||||
|
||||
const RoomRow = ({ room }: IRoomRow) => {
|
||||
const { id, name, price, status } = room;
|
||||
const { isDeleting, deleteRoom } = useDeleteRoom();
|
||||
const statusText = status
|
||||
? 'Unavailable'
|
||||
: 'Available';
|
||||
const formattedPrice = useMemo(() => formatCurrency(price), [price]);
|
||||
const renderEditBtn = useCallback(
|
||||
(onCloseModal: () => void) => (
|
||||
<Menus.Button onClick={onCloseModal} icon={<RiEditBoxFill />}>
|
||||
Edit
|
||||
</Menus.Button>
|
||||
),
|
||||
[]
|
||||
);
|
||||
const renderDeleteBtn = useCallback(
|
||||
(onCloseModal: () => void) => (
|
||||
<Menus.Button icon={<HiTrash />} onClick={onCloseModal}>
|
||||
Delete
|
||||
</Menus.Button>
|
||||
),
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<Table.Row>
|
||||
<div>{id}</div>
|
||||
<div>{name}</div>
|
||||
<div>{formatCurrency(finalPrice)}</div>
|
||||
<div>{formattedPrice}</div>
|
||||
<div>{statusText}</div>
|
||||
|
||||
<div>
|
||||
@@ -61,24 +63,25 @@ const RoomRow = ({ room, reload, setReload }: IRoomRow) => {
|
||||
|
||||
<Menus.List id={id.toString()}>
|
||||
<Modal.Open
|
||||
modalName="edit"
|
||||
renderChildren={(onCloseModal) => (
|
||||
<Menus.Button onClick={onCloseModal} icon={<RiEditBoxFill />}>
|
||||
Edit
|
||||
</Menus.Button>
|
||||
)}
|
||||
modalName={FORM.EDIT}
|
||||
renderChildren={renderEditBtn}
|
||||
/>
|
||||
<Modal.Open
|
||||
modalName={FORM.DELETE}
|
||||
renderChildren={renderDeleteBtn}
|
||||
/>
|
||||
|
||||
<Menus.Button
|
||||
icon={<HiTrash />}
|
||||
onClick={() => handleDelete(room)}
|
||||
>
|
||||
Delete
|
||||
</Menus.Button>
|
||||
</Menus.List>
|
||||
|
||||
<Modal.Window name="edit" title="Edit Room">
|
||||
<RoomForm roomEdit={room} setReload={setReload} reload={reload} />
|
||||
<Modal.Window name={FORM.EDIT} title="Edit Room">
|
||||
<RoomForm room={room} />
|
||||
</Modal.Window>
|
||||
|
||||
<Modal.Window name={FORM.DELETE} title="Delete Room">
|
||||
<ConfirmMessage
|
||||
disabled={isDeleting}
|
||||
message={`Are you sure to delete ${name}?`}
|
||||
onConfirm={() => deleteRoom(id)}
|
||||
/>
|
||||
</Modal.Window>
|
||||
</Menus.Menu>
|
||||
</Modal>
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
// Components
|
||||
import RoomTable from './RomTable';
|
||||
import RoomForm from './RoomForm';
|
||||
import Modal from '@component/Modal';
|
||||
|
||||
// Styled
|
||||
import { StyledRoom, Title } from './styled';
|
||||
import Direction from '@commonStyle/Direction.ts';
|
||||
import Button from '@commonStyle/Button';
|
||||
|
||||
// Types
|
||||
import Modal from '@component/Modal';
|
||||
|
||||
const Room = () => {
|
||||
const [reload, setReload] = useState(true);
|
||||
|
||||
return (
|
||||
<>
|
||||
<StyledRoom>
|
||||
@@ -29,12 +23,12 @@ const Room = () => {
|
||||
)}
|
||||
/>
|
||||
<Modal.Window name="room-form" title="Add form">
|
||||
<RoomForm setReload={setReload} reload={reload} />
|
||||
<RoomForm />
|
||||
</Modal.Window>
|
||||
</Modal>
|
||||
</Direction>
|
||||
|
||||
<RoomTable reload={reload} setReload={setReload} />
|
||||
<RoomTable />
|
||||
</StyledRoom>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
import {
|
||||
Dispatch,
|
||||
SetStateAction,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useState,
|
||||
} from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
// Hooks
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
import { useCreateUser } from '@hook/users/useCreateUser.ts';
|
||||
import { useUpdateUser } from '@hook/users/useUpdateUser.ts';
|
||||
|
||||
// Styled
|
||||
import Input from '@commonStyle/Input.ts';
|
||||
@@ -16,139 +9,73 @@ import Input from '@commonStyle/Input.ts';
|
||||
// Components
|
||||
import Form from '@component/Form/index.tsx';
|
||||
import FormRow from '@component/LabelControl/index.tsx';
|
||||
import Select, { ISelectOptions } from '@component/Select/index.tsx';
|
||||
|
||||
// Helpers
|
||||
import { isEmptyObj, isValidRegex } from '@helper/validators.ts';
|
||||
import { isValidRegex } from '@helper/validators.ts';
|
||||
|
||||
// Constants
|
||||
import { ADD_SUCCESS, EDIT_SUCCESS } from '@constant/messages.ts';
|
||||
import {
|
||||
INVALID_FIELD,
|
||||
INVALID_PHONE,
|
||||
REQUIRED_FIELD_ERROR,
|
||||
} from '@constant/formValidateMessage.ts';
|
||||
import { INIT_VALUE_USER_FORM, REGEX } from '@constant/commons.ts';
|
||||
import { REGEX } from '@constant/commons.ts';
|
||||
|
||||
// Styled
|
||||
import { FormBtn } from './styled.ts';
|
||||
|
||||
// Services
|
||||
import { getAllRoom, updateRoomStatus } from '@service/roomServices.ts';
|
||||
import { createUser, updateUser } from '@service/userServices.ts';
|
||||
|
||||
// Types
|
||||
import { Nullable } from '@type/common.ts';
|
||||
import { IUser } from '@type/users.ts';
|
||||
import { IRoom } from '@type/rooms.ts';
|
||||
|
||||
interface IUserFormProp {
|
||||
onCloseModal?: () => void;
|
||||
reload: boolean;
|
||||
setReload: Dispatch<SetStateAction<boolean>>;
|
||||
user?: Nullable<IUser>;
|
||||
user?: IUser;
|
||||
}
|
||||
|
||||
const UserForm = ({ onCloseModal, reload, setReload, user }: IUserFormProp) => {
|
||||
const formMethods = useForm<IUser>();
|
||||
const UserForm = ({ onCloseModal, user }: IUserFormProp) => {
|
||||
const { isCreating, createUser } = useCreateUser();
|
||||
const { isUpdating, updateUser } = useUpdateUser();
|
||||
const isLoading = isCreating || isUpdating;
|
||||
const {id: editId, ...editValues} = {...user};
|
||||
|
||||
const formMethods = useForm<IUser>({
|
||||
defaultValues: editId
|
||||
? editValues
|
||||
: {}
|
||||
});
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors, isDirty, isValid, isSubmitting },
|
||||
formState: { errors, isDirty, isValid },
|
||||
trigger,
|
||||
} = formMethods;
|
||||
const [rooms, setRooms] = useState<IRoom[]>([]);
|
||||
const [options, setOptions] = useState<ISelectOptions[]>();
|
||||
|
||||
// Init value when edit form and load options
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
const options: ISelectOptions[] = [];
|
||||
const tempUser = !user ? { roomId: 0 } : { ...user };
|
||||
|
||||
// Load and set default options room
|
||||
if (rooms.length > 0) {
|
||||
// Init first options
|
||||
options.push({
|
||||
label: '---Select---',
|
||||
value: '0',
|
||||
});
|
||||
|
||||
rooms.forEach((item) => {
|
||||
if (!item.status || tempUser?.roomId === item.id)
|
||||
options.push({
|
||||
label: item.name!,
|
||||
value: item.id!.toString(),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (options.length > 0) {
|
||||
setOptions(options);
|
||||
}
|
||||
|
||||
if (!isEmptyObj(tempUser)) {
|
||||
// Init value
|
||||
reset(tempUser);
|
||||
} else {
|
||||
reset(INIT_VALUE_USER_FORM);
|
||||
}
|
||||
};
|
||||
|
||||
load();
|
||||
}, [reset, user, rooms]);
|
||||
|
||||
// Submit form
|
||||
const onSubmit = useCallback(
|
||||
async (newUser: IUser) => {
|
||||
const onSubmit =
|
||||
(newUser: IUser) => {
|
||||
if (!user) {
|
||||
// Add request
|
||||
const response = await createUser(newUser);
|
||||
|
||||
if (response) {
|
||||
toast.success(ADD_SUCCESS);
|
||||
}
|
||||
|
||||
// Update room status
|
||||
updateRoomStatus(newUser.roomId, true);
|
||||
createUser(newUser, {
|
||||
onSuccess: () => {
|
||||
reset();
|
||||
onCloseModal?.();
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Edit request
|
||||
const response = await updateUser(newUser);
|
||||
|
||||
if (response) {
|
||||
toast.success(EDIT_SUCCESS);
|
||||
}
|
||||
|
||||
// Update room status
|
||||
updateRoomStatus(user!.roomId, true, newUser.roomId);
|
||||
}
|
||||
// Reload table data
|
||||
setReload(!reload);
|
||||
|
||||
newUser.id = editId!;
|
||||
updateUser(newUser, {
|
||||
onSuccess: () => {
|
||||
reset();
|
||||
onCloseModal!();
|
||||
},
|
||||
[onCloseModal, reload, reset, setReload, user]
|
||||
);
|
||||
|
||||
// Load all rooms
|
||||
useEffect(() => {
|
||||
const loadRoom = async () => {
|
||||
const rooms = await getAllRoom();
|
||||
|
||||
if (rooms) {
|
||||
setRooms(rooms);
|
||||
onCloseModal?.();
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
loadRoom();
|
||||
}, [onSubmit]);
|
||||
|
||||
return (
|
||||
<FormProvider {...formMethods}>
|
||||
<Form onSubmit={handleSubmit(onSubmit)}>
|
||||
<Input type="hidden" id="id" {...register('id')} />
|
||||
<FormRow label="Full Name" error={errors?.name?.message}>
|
||||
<Input
|
||||
type="text"
|
||||
@@ -164,25 +91,6 @@ const UserForm = ({ onCloseModal, reload, setReload, user }: IUserFormProp) => {
|
||||
/>
|
||||
</FormRow>
|
||||
|
||||
<FormRow
|
||||
label="Identified Code"
|
||||
error={errors?.identifiedCode?.message}
|
||||
>
|
||||
<Input
|
||||
type="text"
|
||||
id="identifiedCode"
|
||||
{...register('identifiedCode', {
|
||||
required: REQUIRED_FIELD_ERROR,
|
||||
validate: {
|
||||
checkIdentifiedCode: (v) =>
|
||||
isValidRegex(new RegExp(REGEX.NUMBER), v.toString()) ||
|
||||
INVALID_FIELD,
|
||||
},
|
||||
onChange: () => trigger('identifiedCode'),
|
||||
})}
|
||||
/>
|
||||
</FormRow>
|
||||
|
||||
<FormRow label="Phone" error={errors?.phone?.message}>
|
||||
<Input
|
||||
type="text"
|
||||
@@ -198,32 +106,19 @@ const UserForm = ({ onCloseModal, reload, setReload, user }: IUserFormProp) => {
|
||||
/>
|
||||
</FormRow>
|
||||
|
||||
<FormRow label="Room">
|
||||
{options && options.length > 1 ? (
|
||||
<Select
|
||||
id="roomId"
|
||||
options={options!}
|
||||
ariaLabel="RoomId"
|
||||
optionsConfigForm={{
|
||||
valueAsNumber: true,
|
||||
onChange: () => trigger('roomId'),
|
||||
validate: (v) => v !== 0,
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<p>No room available!</p>
|
||||
)}
|
||||
</FormRow>
|
||||
|
||||
<Form.Action>
|
||||
<FormBtn
|
||||
type="submit"
|
||||
name="submit"
|
||||
disabled={!isDirty || !isValid || isSubmitting}
|
||||
disabled={!isDirty || !isValid || isLoading}
|
||||
>
|
||||
{!user ? 'Add' : 'Save'}
|
||||
{
|
||||
!user
|
||||
? 'Add'
|
||||
: 'Save'
|
||||
}
|
||||
</FormBtn>
|
||||
<FormBtn type="button" styled="secondary" onClick={onCloseModal}>
|
||||
<FormBtn type="button" variations="secondary" onClick={onCloseModal}>
|
||||
Close
|
||||
</FormBtn>
|
||||
</Form.Action>
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { Dispatch, SetStateAction } from 'react';
|
||||
|
||||
// Components
|
||||
import { RiEditBoxFill } from 'react-icons/ri';
|
||||
import Modal from '@component/Modal';
|
||||
@@ -13,11 +11,9 @@ import { IUser } from '@type/users';
|
||||
|
||||
interface IUserRow {
|
||||
user: IUser;
|
||||
reload: boolean;
|
||||
setReload: Dispatch<SetStateAction<boolean>>;
|
||||
}
|
||||
|
||||
const UserRow = ({ user, reload, setReload }: IUserRow) => {
|
||||
const UserRow = ({ user }: IUserRow) => {
|
||||
const { id, name, phone } = user;
|
||||
|
||||
return (
|
||||
@@ -42,7 +38,7 @@ const UserRow = ({ user, reload, setReload }: IUserRow) => {
|
||||
</Menus.List>
|
||||
|
||||
<Modal.Window name="edit" title="Edit user">
|
||||
<UserForm user={user} setReload={setReload} reload={reload} />
|
||||
<UserForm user={user} />
|
||||
</Modal.Window>
|
||||
</Menus.Menu>
|
||||
</Modal>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { Dispatch, SetStateAction, useCallback, useState } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
|
||||
// Components
|
||||
import Menus from '@component/Menus';
|
||||
@@ -21,50 +20,21 @@ import Direction from '@commonStyle/Direction';
|
||||
import { StyledOperationTable } from './styled';
|
||||
import Spinner from '@commonStyle/Spinner';
|
||||
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { getAllUsers } from '@service/userServices';
|
||||
import toast from 'react-hot-toast';
|
||||
// Hooks
|
||||
import { useUsers } from '@hook/users/useUsers';
|
||||
|
||||
interface IUserTable {
|
||||
reload: boolean;
|
||||
setReload: Dispatch<SetStateAction<boolean>>;
|
||||
}
|
||||
|
||||
const UserTable = ({ reload, setReload }: IUserTable) => {
|
||||
const UserTable = () => {
|
||||
const columnName = ['Id', 'Name', 'Phone'];
|
||||
|
||||
const [phoneSearch, setPhoneSearch] = useState('');
|
||||
const [searchParams] = useSearchParams();
|
||||
const sortByValue = searchParams.get('sortBy')
|
||||
? searchParams.get('sortBy')!
|
||||
: 'id';
|
||||
const orderByValue = searchParams.get('orderBy')
|
||||
? searchParams.get('orderBy')!
|
||||
: 'asc';
|
||||
|
||||
const {
|
||||
isLoading,
|
||||
data: users,
|
||||
error,
|
||||
} = useQuery({
|
||||
queryKey: ['cabins', sortByValue, orderByValue, phoneSearch],
|
||||
queryFn: () => getAllUsers(sortByValue, orderByValue, phoneSearch),
|
||||
});
|
||||
|
||||
if(error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
const { isLoading, users } = useUsers();
|
||||
|
||||
const renderUserRow = useCallback(
|
||||
(user: IUser) => (
|
||||
<UserRow
|
||||
user={user}
|
||||
key={user.id}
|
||||
reload={reload}
|
||||
setReload={setReload}
|
||||
/>
|
||||
),
|
||||
[reload, setReload]
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -74,10 +44,7 @@ const UserTable = ({ reload, setReload }: IUserTable) => {
|
||||
<OrderBy options={ORDERBY_OPTIONS} />
|
||||
|
||||
<SortBy options={USER_PAGE.SORTBY_OPTIONS} />
|
||||
<Search
|
||||
setValueSearch={setPhoneSearch}
|
||||
setPlaceHolder="Search by phone..."
|
||||
/>
|
||||
<Search setPlaceHolder="Search by phone..." />
|
||||
</StyledOperationTable>
|
||||
|
||||
{isLoading && <Spinner />}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
// Components
|
||||
import UserTable from './UserTable';
|
||||
|
||||
@@ -17,7 +15,6 @@ import { FORM } from '@constant/commons';
|
||||
|
||||
const User = () => {
|
||||
const TITLE = 'Add user';
|
||||
const [reload, setReload] = useState(true);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -33,12 +30,12 @@ const User = () => {
|
||||
)}
|
||||
/>
|
||||
<Modal.Window name={FORM.USER} title={TITLE}>
|
||||
<UserForm setReload={setReload} reload={reload} />
|
||||
<UserForm />
|
||||
</Modal.Window>
|
||||
</Modal>
|
||||
</Direction>
|
||||
|
||||
<UserTable reload={reload} setReload={setReload} />
|
||||
<UserTable />
|
||||
</StyledUser>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,173 +1,80 @@
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
// Types
|
||||
import { Nullable } from '@type/common';
|
||||
import { IResponse } from '@type/responses';
|
||||
import { IRoom } from '@type/rooms';
|
||||
|
||||
// Helpers
|
||||
import { sendRequest } from '@helper/sendRequest';
|
||||
import { errorMsg } from '@helper/helper';
|
||||
// Services
|
||||
import supabase from './supabaseService';
|
||||
|
||||
// Constants
|
||||
import { STATUS_CODE, RESPONSE_MESSAGE } from '@constant/responseStatus';
|
||||
import { ROOM_PATH } from '@constant/path';
|
||||
const ROOMS_TABLE = 'rooms';
|
||||
const ERROR_FETCHING = "Can't fetch room data!";
|
||||
const ERROR_UPDATE_ROOM = "Can't update room!";
|
||||
const ERROR_CREATE_ROOM = "Can't create room!";
|
||||
const ERROR_DELETE_ROOM = "Can't delete room!";
|
||||
|
||||
/**
|
||||
* Get all rooms from server
|
||||
* @returns Return all rooms in server
|
||||
* Get all rooms from database
|
||||
* @returns Return all rooms in database
|
||||
*/
|
||||
const getAllRoom = async (): Promise<Nullable<IRoom[]>> => {
|
||||
try {
|
||||
const response = await sendRequest<IRoom[]>(ROOM_PATH);
|
||||
const getAllRooms = async (
|
||||
sortBy: string,
|
||||
orderBy: string,
|
||||
roomName: string
|
||||
): Promise<IRoom[]> => {
|
||||
const { data, error } = await supabase
|
||||
.from(ROOMS_TABLE)
|
||||
.select('*')
|
||||
.order(sortBy, { ascending: orderBy === 'asc' })
|
||||
.like('name', `%${roomName}%`);
|
||||
|
||||
if (response.statusCode === STATUS_CODE.OK) {
|
||||
const rooms = response.data!;
|
||||
|
||||
return rooms;
|
||||
} else {
|
||||
throw new Error(errorMsg(response.statusCode, response.msg));
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
if (error) {
|
||||
console.error(error.message);
|
||||
throw new Error(ERROR_FETCHING);
|
||||
}
|
||||
|
||||
return null;
|
||||
return data;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get room by id
|
||||
* @param roomId The id room need to be get
|
||||
* @returns Return the room object depend on room id
|
||||
*/
|
||||
const getRoom = async (roomId: number): Promise<Nullable<IRoom>> => {
|
||||
try {
|
||||
const response = await sendRequest<IRoom>(ROOM_PATH + '/' + roomId);
|
||||
|
||||
if (response.statusCode !== STATUS_CODE.OK) {
|
||||
throw new Error(errorMsg(response.statusCode, response.msg));
|
||||
}
|
||||
|
||||
const rooms = response.data!;
|
||||
|
||||
return rooms;
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Update room into server
|
||||
* Update room into database
|
||||
* @param room Room object need to be updated
|
||||
* @returns The response object
|
||||
*/
|
||||
const updateRoom = async (room: IRoom): Promise<Nullable<IResponse<IRoom>>> => {
|
||||
try {
|
||||
const response = await sendRequest<IRoom>(
|
||||
ROOM_PATH + '/' + room.id,
|
||||
'PUT',
|
||||
JSON.stringify(room)
|
||||
);
|
||||
const updateRoom = async (room: IRoom): Promise<void> => {
|
||||
const { error } = await supabase.from(ROOMS_TABLE).update(room).eq("id", room.id);
|
||||
|
||||
return response;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
toast.error(error.message);
|
||||
if(error) {
|
||||
console.error(error.message);
|
||||
throw new Error(ERROR_UPDATE_ROOM);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Update room status
|
||||
* @param roomId The id room need to be updated
|
||||
* @param status Status of room
|
||||
* @param roomIdNew The new id room need to be updated
|
||||
* @returns Return the response object
|
||||
*/
|
||||
const updateRoomStatus = async (
|
||||
roomId: number,
|
||||
status: boolean,
|
||||
roomIdNew?: number
|
||||
): Promise<Nullable<IResponse<IRoom>>> => {
|
||||
try {
|
||||
if (!roomIdNew) {
|
||||
const response = await sendRequest<IRoom>(
|
||||
ROOM_PATH + '/' + roomId,
|
||||
'PATCH',
|
||||
JSON.stringify({ status: status })
|
||||
);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// Update new room status
|
||||
const resNewRoom = await sendRequest<IRoom>(
|
||||
ROOM_PATH + '/' + roomIdNew,
|
||||
'PATCH',
|
||||
JSON.stringify({ status: status })
|
||||
);
|
||||
|
||||
// Update old room status;
|
||||
const resOldRoom = await sendRequest<IRoom>(
|
||||
ROOM_PATH + '/' + roomId,
|
||||
'PATCH',
|
||||
JSON.stringify({ status: !status })
|
||||
);
|
||||
|
||||
if (
|
||||
resNewRoom.statusCode === STATUS_CODE.OK &&
|
||||
resOldRoom.statusCode === STATUS_CODE.OK
|
||||
) {
|
||||
return {
|
||||
statusCode: STATUS_CODE.OK,
|
||||
msg: RESPONSE_MESSAGE.UPDATE_SUCCESS,
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add room to server
|
||||
* Add room to database
|
||||
* @param room The room object need to be add
|
||||
* @returns The response object if complete or null
|
||||
*/
|
||||
const addRoom = async (room: IRoom): Promise<Nullable<IResponse<IRoom>>> => {
|
||||
try {
|
||||
// Set default status room
|
||||
const createRoom = async (room: IRoom): Promise<void> => {
|
||||
// Set default status
|
||||
room.status = false;
|
||||
|
||||
const response = await sendRequest<IRoom>(
|
||||
ROOM_PATH,
|
||||
'POST',
|
||||
JSON.stringify(room)
|
||||
);
|
||||
const { error } = await supabase.from(ROOMS_TABLE).insert([room]);
|
||||
|
||||
if (response.statusCode !== STATUS_CODE.CREATE) {
|
||||
throw new Error(errorMsg(response.statusCode, response.msg));
|
||||
if(error) {
|
||||
console.error(error.message);
|
||||
throw new Error(ERROR_CREATE_ROOM);
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
toast.error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export { getRoom, updateRoom, updateRoomStatus, getAllRoom, addRoom };
|
||||
/**
|
||||
* Delete room in database
|
||||
* @param idRoom The id of room need to delete
|
||||
*/
|
||||
const deleteRoom = async(idRoom: number) => {
|
||||
const { error } = await supabase.from(ROOMS_TABLE).delete().eq('id', idRoom);
|
||||
|
||||
if(error) {
|
||||
console.error(error.message);
|
||||
throw new Error(ERROR_DELETE_ROOM);
|
||||
}
|
||||
}
|
||||
|
||||
export { getAllRooms, updateRoom, createRoom, deleteRoom };
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createClient } from "@supabase/supabase-js";
|
||||
import { Database } from "@type/supabase";
|
||||
|
||||
// Constants
|
||||
import { supabaseKey, supabaseUrl } from "@constant/config";
|
||||
|
||||
const supabase = createClient<Database>(supabaseUrl, supabaseKey!);
|
||||
|
||||
export default supabase;
|
||||
@@ -1,96 +1,47 @@
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
// Constants
|
||||
import { USER_PATH } from '@constant/path';
|
||||
import { STATUS_CODE } from '@constant/responseStatus';
|
||||
|
||||
// Types
|
||||
import { Nullable } from '@type/common';
|
||||
import { IResponse } from '@type/responses';
|
||||
import { IUser } from '@type/users';
|
||||
|
||||
// Helpers
|
||||
import { sendRequest } from '@helper/sendRequest';
|
||||
import { errorMsg } from '@helper/helper';
|
||||
import supabase from '@constant/supabaseConfig';
|
||||
// Services
|
||||
import supabase from './supabaseService';
|
||||
|
||||
const USERS_TABLE = 'users';
|
||||
const ERROR_FETCHING = "Users can't be loaded!";
|
||||
const ERROR_CREATE_USER = "Can't create user!";
|
||||
const ERROR_UPDATE_USER = "Can't update user!";
|
||||
|
||||
/**
|
||||
* Create user to the server
|
||||
* Create user to the database
|
||||
* @param user The user object need to be created
|
||||
* @returns The IResponse object if success or null
|
||||
*/
|
||||
const createUser = async (user: IUser): Promise<Nullable<IResponse<IUser>>> => {
|
||||
// try {
|
||||
// const response = await sendRequest<IUser>(
|
||||
// USER_PATH,
|
||||
// 'POST',
|
||||
// JSON.stringify(user)
|
||||
// );
|
||||
const createUser = async (user: IUser): Promise<void> => {
|
||||
const { error } = await supabase.from(USERS_TABLE).insert([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;
|
||||
if(error) {
|
||||
console.error(error.message);
|
||||
throw new Error(ERROR_CREATE_USER);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Update the user to the server
|
||||
* Update the user to the database
|
||||
* @param user The user object need to be updated
|
||||
* @returns The IResponse object if update success or null
|
||||
*/
|
||||
const updateUser = async (user: IUser): Promise<Nullable<IResponse<IUser>>> => {
|
||||
// try {
|
||||
// const response = await sendRequest<IUser>(
|
||||
// USER_PATH + '/' + user.id,
|
||||
// 'PUT',
|
||||
// JSON.stringify(user)
|
||||
// );
|
||||
const updateUser = async (user: IUser): Promise<void> => {
|
||||
const { error } = await supabase.from(USERS_TABLE).update(user).eq("id", user.id);
|
||||
|
||||
// if (response.statusCode !== STATUS_CODE.OK) {
|
||||
// throw new Error(errorMsg(response.statusCode, response.msg));
|
||||
// }
|
||||
|
||||
// return response;
|
||||
// } catch (error: unknown) {
|
||||
// if (error instanceof Error) {
|
||||
// toast.error(error.message);
|
||||
// }
|
||||
// }
|
||||
|
||||
return null;
|
||||
if(error) {
|
||||
console.error(error.message);
|
||||
throw new Error(ERROR_UPDATE_USER);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Checkout user
|
||||
* @param user The user need to be checkout
|
||||
* @returns The IResponse object if checkout success or not
|
||||
* Return data of users from database
|
||||
* @param sortBy Sort by column
|
||||
* @param orderBy Order by ascending or descending
|
||||
* @param phoneSearch The phone need to be search
|
||||
* @returns The data of users from database
|
||||
*/
|
||||
const checkOutUser = async (
|
||||
user: IUser
|
||||
): Promise<Nullable<IResponse<IUser>>> => {
|
||||
// const tempUser = user;
|
||||
|
||||
// if (tempUser) {
|
||||
// tempUser.roomId = 0;
|
||||
// const resUpdateUser = await updateUser(tempUser);
|
||||
|
||||
// return resUpdateUser;
|
||||
// }
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const getAllUsers = async (
|
||||
sortBy: string,
|
||||
orderBy: string,
|
||||
@@ -103,10 +54,11 @@ const getAllUsers = async (
|
||||
.like('phone', `%${phoneSearch}%`);
|
||||
|
||||
if (error) {
|
||||
console.error(error.message);
|
||||
throw new Error(ERROR_FETCHING);
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
export { updateUser, checkOutUser, createUser, getAllUsers };
|
||||
export { updateUser, createUser, getAllUsers };
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
--secondary-btn-color: #d1d1d1;
|
||||
--disabled-btn-color: #7f82a6;
|
||||
--danger-btn-color: #ff4f4f;
|
||||
|
||||
--hover-background-color: #f3f4f6;
|
||||
--hover-dark-background-color: #d0d0d0;
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
interface IResponse<T> {
|
||||
statusCode: number;
|
||||
msg: string;
|
||||
data?: T;
|
||||
}
|
||||
|
||||
export type { IResponse };
|
||||
@@ -2,8 +2,6 @@ interface IRoom {
|
||||
id: number;
|
||||
name: string;
|
||||
price: number;
|
||||
discount: number;
|
||||
finalPrice: number;
|
||||
status: boolean;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user