Merge pull request #148 from SDSRV-IDP/factory/review

refactor call api
This commit is contained in:
Đỗ Xuân Tân 2024-06-28 13:34:40 +07:00 committed by GitHub Enterprise
commit 61a9ad98eb
4 changed files with 67 additions and 51 deletions

View File

@ -5,7 +5,7 @@ import { Button, Modal, Tag } from 'antd';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { useState } from 'react'; import { useState } from 'react';
import { RecentRequest } from './const'; import { RecentRequest } from './const';
const RecentRequesModal = () => { const RecentRequestModal = () => {
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const [listData, setListData] = useState<RecentRequest[]>([]); const [listData, setListData] = useState<RecentRequest[]>([]);
@ -23,7 +23,7 @@ const RecentRequesModal = () => {
return ( return (
<div> <div>
<Button onClick={handleShowModal} icon={<HistoryOutlined />}>Recents </Button> <Button onClick={handleShowModal} icon={<HistoryOutlined />}>Recent </Button>
<Modal <Modal
style={{ overflow: 'auto' }} style={{ overflow: 'auto' }}
footer={ footer={
@ -59,13 +59,13 @@ const RecentRequesModal = () => {
onCancel={handleCloseModal} onCancel={handleCloseModal}
> >
{listData.map((item, index) => ( {listData.map((item, index) => (
<div style={{ marginBottom: '4px' }}> <div style={{ marginBottom: '4px' }} key={item.request_id}>
<a <a
href={`?request_id=${item.request_id}`} href={`?request_id=${item.request_id}`}
target='_blank' target='_blank'
key={index} key={index}
> >
<Tag color='blue'>{dayjs(item.time).format('hh:mm - DD/MM')}</Tag> <Tag color={item.success ? 'blue' : 'red'}>{dayjs(item.time).format('hh:mm - DD/MM')}</Tag>
<span>{item.request_id}</span> <span>{item.request_id}</span>
</a> </a>
</div> </div>
@ -75,4 +75,4 @@ const RecentRequesModal = () => {
); );
}; };
export default RecentRequesModal; export default RecentRequestModal;

View File

@ -42,23 +42,19 @@ export const fetchAllRequests = async (
return data; return data;
}; };
export const updateRevisedData = async (requestID: any) => { export const confirmRequest = async (requestID: any) => {
// const requestID = ; // const requestID = ;
const token = localStorage.getItem('sbt-token') || ''; const token = localStorage.getItem('sbt-token') || '';
const result = await fetch(`${baseURL}/ctel/request/${requestID}/`, { return fetch(`${baseURL}/ctel/request/${requestID}/`, {
method: 'POST', method: 'POST',
headers: { headers: {
Authorization: `${JSON.parse(token)}`, Authorization: `${JSON.parse(token)}`,
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ request_file_results: [] }), body: JSON.stringify({ request_file_results: [] }),
}).catch((error) => { })
console.log(error);
throw error;
});
if (!result.ok) {
throw new Error('Could not update revised data');
}
}; };
export const updateRevisedDataByFile = async ( export const updateRevisedDataByFile = async (
@ -68,7 +64,7 @@ export const updateRevisedDataByFile = async (
) => { ) => {
// const requestID = ; // const requestID = ;
const token = localStorage.getItem('sbt-token') || ''; const token = localStorage.getItem('sbt-token') || '';
const result = await fetch( return fetch(
`${baseURL}/ctel/request_image/${requestID}/${fileID}/`, `${baseURL}/ctel/request_image/${requestID}/${fileID}/`,
{ {
method: 'POST', method: 'POST',
@ -78,13 +74,7 @@ export const updateRevisedDataByFile = async (
}, },
body: JSON.stringify(newRevisedData), body: JSON.stringify(newRevisedData),
}, },
).catch((error) => { )
console.log(error);
throw error;
});
if (result.status != 200) {
throw new Error('Could not update revised data');
}
}; };
export const fetchRequest = async (id) => { export const fetchRequest = async (id) => {
@ -100,7 +90,11 @@ export const fetchRequest = async (id) => {
).subscription_requests[0]; ).subscription_requests[0];
}; };
export const addRecentRequest = (requestId: string) => { export const addRecentRequest = (
requestId: string,
res: any,
success: boolean,
) => {
let data = localStorage.getItem('recent-request'); let data = localStorage.getItem('recent-request');
let requests: RecentRequest[] = []; let requests: RecentRequest[] = [];
if (data) { if (data) {
@ -111,10 +105,19 @@ export const addRecentRequest = (requestId: string) => {
// find and remove element in array that has request_id equal to requestId // find and remove element in array that has request_id equal to requestId
requests = requests.filter((request) => request.request_id !== requestId); requests = requests.filter((request) => request.request_id !== requestId);
// remove request if it is older than 7 days
requests = requests.filter(
(request) =>
new Date(request.time).getTime() >
new Date().getTime() - 7 * 24 * 60 * 60 * 1000,
);
requests.unshift({ requests.unshift({
request_id: requestId, request_id: requestId,
time: new Date time: new Date(),
}) res: res,
success: success,
});
localStorage.setItem('recent-request', JSON.stringify(requests)) localStorage.setItem('recent-request', JSON.stringify(requests));
}; };

View File

@ -71,5 +71,7 @@ export const SOURCE_OBJECT_NAMES = [
export type RecentRequest = { export type RecentRequest = {
request_id: string, request_id: string,
time: Date time: Date,
res?: any,
success: boolean,
} }

View File

@ -34,9 +34,9 @@ import { useSearchParams } from 'react-router-dom';
import { getErrorMessage } from 'utils/error-handler'; import { getErrorMessage } from 'utils/error-handler';
import { import {
addRecentRequest, addRecentRequest,
confirmRequest,
fetchAllRequests, fetchAllRequests,
fetchRequest, fetchRequest,
updateRevisedData,
updateRevisedDataByFile, updateRevisedDataByFile,
} from './api'; } from './api';
import { import {
@ -210,6 +210,7 @@ const ReviewPage = () => {
setImageLoading(false); setImageLoading(false);
}; };
const loadCurrentRequest = (requestIndex) => { const loadCurrentRequest = (requestIndex) => {
setCurrentRequestIndex(requestIndex);
setLoading(true); setLoading(true);
setImageLoading(true); setImageLoading(true);
fetchAllRequests( fetchAllRequests(
@ -224,18 +225,22 @@ const ReviewPage = () => {
.then((data) => { .then((data) => {
setTotalPages(data?.page?.total_requests); setTotalPages(data?.page?.total_requests);
setHasNextRequest(requestIndex < data?.page?.total_requests); setHasNextRequest(requestIndex < data?.page?.total_requests);
const requestData = fetchRequest(
data?.subscription_requests[0].RequestID, fetchRequest(data?.subscription_requests[0].RequestID)
);
requestData
.then(async (data) => { .then(async (data) => {
if (data) setCurrentRequest(data); if (data) setCurrentRequest(data);
setAndLoadSelectedFile(data, 0); setAndLoadSelectedFile(data, 0);
}) })
.catch((error) => {
notification.error({ message: getErrorMessage(error) });
})
.finally(() => { .finally(() => {
setLoading(false); setLoading(false);
}); });
}) })
.catch((error) => {
notification.error({ message: getErrorMessage(error) });
})
.finally(() => { .finally(() => {
setLoading(false); setLoading(false);
}); });
@ -246,7 +251,6 @@ const ReviewPage = () => {
return; return;
} }
const nextRequestIndex = currentRequestIndex + 1; const nextRequestIndex = currentRequestIndex + 1;
setCurrentRequestIndex(nextRequestIndex);
loadCurrentRequest(nextRequestIndex); loadCurrentRequest(nextRequestIndex);
}; };
@ -255,7 +259,6 @@ const ReviewPage = () => {
return; return;
} }
const previousRequestIndex = currentRequestIndex - 1; const previousRequestIndex = currentRequestIndex - 1;
setCurrentRequestIndex(previousRequestIndex);
loadCurrentRequest(previousRequestIndex); loadCurrentRequest(previousRequestIndex);
}; };
@ -282,23 +285,26 @@ const ReviewPage = () => {
firstRequest.then(async (data) => { firstRequest.then(async (data) => {
if (data) setCurrentRequest(data); if (data) setCurrentRequest(data);
setAndLoadSelectedFile(data, 0); setAndLoadSelectedFile(data, 0);
// setTimeout(() => {
// loadCurrentRequest(1);
// }, 500);
}); });
}); });
}; };
const handleConfirmReview = async () => { const handleConfirmRequest = async () => {
try { try {
await updateRevisedData(currentRequest?.RequestID); const res = await confirmRequest(currentRequest?.RequestID);
addRecentRequest(currentRequest?.RequestID); if (res.status == 200) {
setCurrentRequest({ addRecentRequest(currentRequest?.RequestID, res, true);
...currentRequest, notification.success({ message: 'Update file success' });
['Is Reviewed']: true, setCurrentRequest({
}); ...currentRequest,
notification.success({ message: 'Update file success' }); ['Is Reviewed']: true,
});
} else {
throw new Error(await res.text());
}
} catch (error) { } catch (error) {
console.log('🚀 ~ handleConfirmRequest ~ error:', error);
addRecentRequest(currentRequest?.RequestID, error, false);
notification.error({ notification.error({
message: getErrorMessage(error), message: getErrorMessage(error),
}); });
@ -324,11 +330,16 @@ const ReviewPage = () => {
solution: solution !== 'other' ? solution : otherSolution, solution: solution !== 'other' ? solution : otherSolution,
}; };
try { try {
await updateRevisedDataByFile(currentRequest?.RequestID, fileId, data); let res = await updateRevisedDataByFile(
currentRequest?.RequestID,
fileId,
data,
);
if (res.status != 200) {
throw new Error('Could not update revised data');
}
let newData = currentRequest; let newData = currentRequest;
newData.Files[selectedFileId]['Is Reviewed'] = true; newData.Files[selectedFileId]['Is Reviewed'] = true;
setCurrentRequest({ setCurrentRequest({
...newData, ...newData,
}); });
@ -347,7 +358,7 @@ const ReviewPage = () => {
useHotkeys('left', gotoPreviousRequest); useHotkeys('left', gotoPreviousRequest);
useHotkeys('right', gotoNextRequest); useHotkeys('right', gotoNextRequest);
useHotkeys('u', submitRevisedData); useHotkeys('u', submitRevisedData);
useHotkeys('c', handleConfirmReview); useHotkeys('c', handleConfirmRequest);
const fileExtension = selectedFileName const fileExtension = selectedFileName
? selectedFileName.split('.').pop() ? selectedFileName.split('.').pop()
@ -674,7 +685,7 @@ const ReviewPage = () => {
message.error('RequestID is out of range.'); message.error('RequestID is out of range.');
return; return;
} }
setCurrentRequestIndex(pageIndexToGoto);
loadCurrentRequest(pageIndexToGoto); loadCurrentRequest(pageIndexToGoto);
}} }}
> >
@ -1013,7 +1024,7 @@ const ReviewPage = () => {
open={isOpenConfirmRequest} open={isOpenConfirmRequest}
onOk={() => { onOk={() => {
setIsOpenConfirmRequest(false); setIsOpenConfirmRequest(false);
handleConfirmReview(); handleConfirmRequest();
}} }}
onCancel={() => { onCancel={() => {
setIsOpenConfirmRequest(false); setIsOpenConfirmRequest(false);