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 { useState } from 'react';
import { RecentRequest } from './const';
const RecentRequesModal = () => {
const RecentRequestModal = () => {
const [showModal, setShowModal] = useState(false);
const [listData, setListData] = useState<RecentRequest[]>([]);
@ -23,7 +23,7 @@ const RecentRequesModal = () => {
return (
<div>
<Button onClick={handleShowModal} icon={<HistoryOutlined />}>Recents </Button>
<Button onClick={handleShowModal} icon={<HistoryOutlined />}>Recent </Button>
<Modal
style={{ overflow: 'auto' }}
footer={
@ -59,13 +59,13 @@ const RecentRequesModal = () => {
onCancel={handleCloseModal}
>
{listData.map((item, index) => (
<div style={{ marginBottom: '4px' }}>
<div style={{ marginBottom: '4px' }} key={item.request_id}>
<a
href={`?request_id=${item.request_id}`}
target='_blank'
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>
</a>
</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;
};
export const updateRevisedData = async (requestID: any) => {
export const confirmRequest = async (requestID: any) => {
// const requestID = ;
const token = localStorage.getItem('sbt-token') || '';
const result = await fetch(`${baseURL}/ctel/request/${requestID}/`, {
return fetch(`${baseURL}/ctel/request/${requestID}/`, {
method: 'POST',
headers: {
Authorization: `${JSON.parse(token)}`,
'Content-Type': 'application/json',
},
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 (
@ -68,7 +64,7 @@ export const updateRevisedDataByFile = async (
) => {
// const requestID = ;
const token = localStorage.getItem('sbt-token') || '';
const result = await fetch(
return fetch(
`${baseURL}/ctel/request_image/${requestID}/${fileID}/`,
{
method: 'POST',
@ -78,13 +74,7 @@ export const updateRevisedDataByFile = async (
},
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) => {
@ -100,7 +90,11 @@ export const fetchRequest = async (id) => {
).subscription_requests[0];
};
export const addRecentRequest = (requestId: string) => {
export const addRecentRequest = (
requestId: string,
res: any,
success: boolean,
) => {
let data = localStorage.getItem('recent-request');
let requests: RecentRequest[] = [];
if (data) {
@ -111,10 +105,19 @@ export const addRecentRequest = (requestId: string) => {
// find and remove element in array that has request_id equal to 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({
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 = {
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 {
addRecentRequest,
confirmRequest,
fetchAllRequests,
fetchRequest,
updateRevisedData,
updateRevisedDataByFile,
} from './api';
import {
@ -210,6 +210,7 @@ const ReviewPage = () => {
setImageLoading(false);
};
const loadCurrentRequest = (requestIndex) => {
setCurrentRequestIndex(requestIndex);
setLoading(true);
setImageLoading(true);
fetchAllRequests(
@ -224,18 +225,22 @@ const ReviewPage = () => {
.then((data) => {
setTotalPages(data?.page?.total_requests);
setHasNextRequest(requestIndex < data?.page?.total_requests);
const requestData = fetchRequest(
data?.subscription_requests[0].RequestID,
);
requestData
fetchRequest(data?.subscription_requests[0].RequestID)
.then(async (data) => {
if (data) setCurrentRequest(data);
setAndLoadSelectedFile(data, 0);
})
.catch((error) => {
notification.error({ message: getErrorMessage(error) });
})
.finally(() => {
setLoading(false);
});
})
.catch((error) => {
notification.error({ message: getErrorMessage(error) });
})
.finally(() => {
setLoading(false);
});
@ -246,7 +251,6 @@ const ReviewPage = () => {
return;
}
const nextRequestIndex = currentRequestIndex + 1;
setCurrentRequestIndex(nextRequestIndex);
loadCurrentRequest(nextRequestIndex);
};
@ -255,7 +259,6 @@ const ReviewPage = () => {
return;
}
const previousRequestIndex = currentRequestIndex - 1;
setCurrentRequestIndex(previousRequestIndex);
loadCurrentRequest(previousRequestIndex);
};
@ -282,23 +285,26 @@ const ReviewPage = () => {
firstRequest.then(async (data) => {
if (data) setCurrentRequest(data);
setAndLoadSelectedFile(data, 0);
// setTimeout(() => {
// loadCurrentRequest(1);
// }, 500);
});
});
};
const handleConfirmReview = async () => {
const handleConfirmRequest = async () => {
try {
await updateRevisedData(currentRequest?.RequestID);
addRecentRequest(currentRequest?.RequestID);
setCurrentRequest({
...currentRequest,
['Is Reviewed']: true,
});
notification.success({ message: 'Update file success' });
const res = await confirmRequest(currentRequest?.RequestID);
if (res.status == 200) {
addRecentRequest(currentRequest?.RequestID, res, true);
notification.success({ message: 'Update file success' });
setCurrentRequest({
...currentRequest,
['Is Reviewed']: true,
});
} else {
throw new Error(await res.text());
}
} catch (error) {
console.log('🚀 ~ handleConfirmRequest ~ error:', error);
addRecentRequest(currentRequest?.RequestID, error, false);
notification.error({
message: getErrorMessage(error),
});
@ -324,11 +330,16 @@ const ReviewPage = () => {
solution: solution !== 'other' ? solution : otherSolution,
};
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;
newData.Files[selectedFileId]['Is Reviewed'] = true;
setCurrentRequest({
...newData,
});
@ -347,7 +358,7 @@ const ReviewPage = () => {
useHotkeys('left', gotoPreviousRequest);
useHotkeys('right', gotoNextRequest);
useHotkeys('u', submitRevisedData);
useHotkeys('c', handleConfirmReview);
useHotkeys('c', handleConfirmRequest);
const fileExtension = selectedFileName
? selectedFileName.split('.').pop()
@ -674,7 +685,7 @@ const ReviewPage = () => {
message.error('RequestID is out of range.');
return;
}
setCurrentRequestIndex(pageIndexToGoto);
loadCurrentRequest(pageIndexToGoto);
}}
>
@ -1013,7 +1024,7 @@ const ReviewPage = () => {
open={isOpenConfirmRequest}
onOk={() => {
setIsOpenConfirmRequest(false);
handleConfirmReview();
handleConfirmRequest();
}}
onCancel={() => {
setIsOpenConfirmRequest(false);