sbt-idp/cope2n-fe/src/pages/reviews2/index.tsx
2024-05-31 16:55:02 +07:00

1066 lines
31 KiB
TypeScript

import {
ArrowLeftOutlined,
ArrowRightOutlined,
CheckCircleOutlined,
ClockCircleFilled,
CopyOutlined,
FullscreenExitOutlined,
FullscreenOutlined,
} from '@ant-design/icons';
import { t } from '@lingui/macro';
import { Viewer } from '@react-pdf-viewer/core';
import '@react-pdf-viewer/core/lib/styles/index.css';
import { defaultLayoutPlugin } from '@react-pdf-viewer/default-layout';
import '@react-pdf-viewer/default-layout/lib/styles/index.css';
import {
Button,
DatePicker,
Form,
Input,
InputNumber,
message,
Modal,
notification,
Select,
Spin,
Tag,
} from 'antd';
import { useEffect, useState } from 'react';
import Lightbox from 'react-awesome-lightbox';
import 'react-awesome-lightbox/build/style.css';
import { useHotkeys } from 'react-hotkeys-hook';
import { badQualityReasonSubmit } from 'request';
import { getErrorMessage } from 'utils/error-handler';
import {
fetchAllRequests,
fetchRequest,
updateRevisedData,
updateRevisedDataByFile,
} from './api';
import {
counter_measure_map,
FEEDBACK_ACCURACY,
FEEDBACK_RESULT,
PREDICTED_RESULT,
REASON_BAD_QUALITY,
REVIEWED_RESULT,
SOLUTION_BAD_QUALITY,
SOURCE_KEYS,
SOURCE_OBJECT_NAMES,
SUBSIDIARIES,
} from './const';
import FileCard from './FileCard';
const ReviewPage = () => {
const [loading, setLoading] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isReasonModalOpen, setIsReasonModalOpen] = useState(false);
const [selectedFileId, setSelectedFileId] = useState(0);
const [selectedFileData, setSelectedFileData] = useState(null);
const [selectedFileDataSource, setSelectedFileDataSource] = useState({});
const [selectedFileName, setSelectedFileName] = useState(null);
// Default date range: 1 month ago to today
const [filterDateRange, setFilterDateRange] = useState(['', '']);
const [filterSubsidiaries, setFilterSubsidiaries] = useState('SEAO');
const [filterAccuracy, setFilterAccuracy] = useState(100);
const [filterReviewState, setFilterReviewState] = useState('all');
const [filterIncludeTests, setFilterIncludesTests] = useState('true');
// const [requests, setRequests] = useState([]);
const [currentRequest, setCurrentRequest] = useState(null);
const [currentRequestIndex, setCurrentRequestIndex] = useState(1);
const [hasNextRequest, setHasNextRequest] = useState(true);
const [totalRequests, setTotalPages] = useState(0);
const [pageIndexToGoto, setPageIndexToGoto] = useState(1);
const [reason, setReason] = useState('');
const [otherReason, setOtherReason] = useState('');
const [solution, setSolution] = useState('');
const [otherSolution, setOtherSolution] = useState('');
const [imageLoading, setImageLoading] = useState(false);
const defaultLayoutPluginInstance = defaultLayoutPlugin();
useEffect(() => {
if (reason) {
setSolution(counter_measure_map[reason]);
}
}, [reason]);
const updateSelectedFileDataSource = (fileContent) => {
let tempData = {};
SOURCE_KEYS.forEach((k) => {
tempData[k] = {};
SOURCE_OBJECT_NAMES.forEach((name) => {
tempData[k][name] = fileContent[name][k];
});
});
setSelectedFileDataSource(tempData);
};
const setAndLoadSelectedFile = async (requestData, index) => {
setSelectedFileId(index);
if (!requestData['Files'][index]) {
setSelectedFileData('FAILED_TO_LOAD_FILE');
setImageLoading(false);
return;
}
const fileName = requestData['Files'][index]['File Name'];
const fileURL = requestData['Files'][index]['File URL'];
let fileDataSource = requestData['Files'][index];
updateSelectedFileDataSource(fileDataSource);
let reason = fileDataSource.Reason;
let solution = fileDataSource['Counter Measures'];
if (!reason) {
setReason(null);
} else if (REASON_BAD_QUALITY.some((r) => r.value === reason)) {
setReason(reason);
} else {
setReason('other');
setOtherReason(reason);
}
if (!solution) {
setSolution(null);
} else if (SOLUTION_BAD_QUALITY.some((r) => r.value === solution)) {
setSolution(solution);
} else {
setSolution('other');
setOtherSolution(solution);
}
setSelectedFileName(fileName);
const response = await fetch(fileURL);
if (response.status === 200) {
setSelectedFileData(fileURL);
} else {
setSelectedFileData('FAILED_TO_LOAD_FILE');
}
setImageLoading(false);
};
const loadCurrentRequest = (requestIndex) => {
setLoading(true);
setImageLoading(true);
fetchAllRequests(
filterDateRange,
filterSubsidiaries,
filterReviewState,
filterIncludeTests,
requestIndex,
1,
filterAccuracy,
)
.then((data) => {
setTotalPages(data?.page?.total_requests);
setHasNextRequest(requestIndex < data?.page?.total_requests);
const requestData = fetchRequest(
data?.subscription_requests[0].RequestID,
);
requestData
.then(async (data) => {
if (data) setCurrentRequest(data);
setAndLoadSelectedFile(data, 0);
})
.finally(() => {
setLoading(false);
});
})
.finally(() => {
setLoading(false);
});
};
const gotoNextRequest = () => {
if (currentRequestIndex >= totalRequests) {
return;
}
const nextRequestIndex = currentRequestIndex + 1;
setCurrentRequestIndex(nextRequestIndex);
loadCurrentRequest(nextRequestIndex);
};
const gotoPreviousRequest = () => {
if (currentRequestIndex === 1) {
return;
}
const previousRequestIndex = currentRequestIndex - 1;
setCurrentRequestIndex(previousRequestIndex);
loadCurrentRequest(previousRequestIndex);
};
const reloadFilters = () => {
setCurrentRequestIndex(1);
fetchAllRequests(
filterDateRange,
filterSubsidiaries,
filterReviewState,
filterIncludeTests,
1,
1,
filterAccuracy,
).then((data) => {
setTotalPages(data?.page?.total_requests);
setHasNextRequest(1 < data?.page?.total_requests);
const firstRequest = fetchRequest(
data?.subscription_requests[0].RequestID,
);
firstRequest.then(async (data) => {
if (data) setCurrentRequest(data);
setAndLoadSelectedFile(data, 0);
setTimeout(() => {
loadCurrentRequest(1);
}, 500);
});
});
};
useEffect(() => {
setCurrentRequestIndex(1);
fetchAllRequests(
filterDateRange,
filterSubsidiaries,
filterReviewState,
filterIncludeTests,
1,
1,
filterAccuracy,
).then((data) => {
setTotalPages(data?.page?.total_requests);
setHasNextRequest(1 < data?.page?.total_requests);
const firstRequest = fetchRequest(
data?.subscription_requests[0].RequestID,
);
firstRequest.then(async (data) => {
if (data) setCurrentRequest(data);
setAndLoadSelectedFile(data, 0);
});
});
}, []);
const handleConfirmReview = async () => {
const isConfirmed = window.confirm(
'Are you sure you want to confirm this request is reviewed?',
);
if (isConfirmed) {
try {
await updateRevisedData(currentRequest?.RequestID);
setCurrentRequest({
...currentRequest,
['Is Reviewed']: true,
});
notification.success({ message: 'Update file success' });
} catch (error) {
notification.error({
message: getErrorMessage(error),
});
}
}
};
const submitRevisedData = async () => {
const fileId = selectedFileName.split('.')[0];
let request_file_result = {};
SOURCE_KEYS.forEach((k) => {
request_file_result[k] = selectedFileDataSource[k][REVIEWED_RESULT];
});
let data = {
request_file_result,
reason: reason ? reason : otherReason,
solution: solution ? solution : otherSolution,
};
try {
await updateRevisedDataByFile(currentRequest?.RequestID, fileId, data);
let newData = currentRequest;
newData.Files[selectedFileId]['Is Reviewed'] = true;
setCurrentRequest({
...newData,
});
notification.success({ message: 'Update file success' });
const requestData = await fetchRequest(currentRequest?.RequestID);
setCurrentRequest(requestData);
} catch (error) {
notification.error({
message: getErrorMessage(error),
});
}
};
// use left/right keys to navigate
useHotkeys('left', gotoPreviousRequest);
useHotkeys('right', gotoNextRequest);
const fileExtension = selectedFileName
? selectedFileName.split('.').pop()
: '';
const [lightBox, setLightBox] = useState(false);
const updateRevised = (fieldName) => {
setSelectedFileDataSource((prevData) => {
prevData[fieldName][REVIEWED_RESULT] =
prevData[fieldName][FEEDBACK_RESULT];
return {
...prevData,
};
});
};
const handleUpdateFileInField = (fieldName, fieldValue) => {
setSelectedFileDataSource((prevData) => {
prevData[fieldName][REVIEWED_RESULT] = fieldValue;
return {
...prevData,
};
});
};
return (
<div
style={
fullscreen
? {
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%',
backgroundColor: '#fff',
zIndex: 1000,
}
: {
height: '100%',
position: 'relative',
}
}
>
<div
style={{
height: '100%',
position: 'absolute',
top: 0,
left: 0,
width: '100%',
background: '#00000033',
zIndex: 1000,
display: loading ? 'block' : 'none',
}}
>
<Spin
spinning={true}
style={{
position: 'absolute',
top: '50%',
left: '50%',
marginTop: -12,
marginLeft: -12,
width: 24,
height: 24,
borderRadius: '50%',
}}
size='large'
/>
</div>
<div
style={{
overflow: 'auto',
width: '100%',
height: fullscreen ? 'calc(100% - 32px)' : '100%',
maxWidth: '100%',
display: 'flex',
}}
>
<div
style={{
height: '100%',
flexGrow: 1,
display: 'flex',
flexDirection: 'column',
position: 'relative',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
margin: '0 0 4px 0',
}}
>
<Button
onClick={() => {
setFullscreen(!fullscreen);
}}
>
{fullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
</Button>
{totalRequests && (
<div
style={{
flexGrow: 1,
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr',
marginLeft: '16px',
}}
>
<div style={{ gridColumn: 'span 2 / span 2' }}>
<b>Request ID: &nbsp;</b>
{currentRequest?.RequestID}
</div>{' '}
<div>
<b>Created at: &nbsp;</b>
{currentRequest?.created_at}
</div>{' '}
<div>
<b>Request time: &nbsp;</b>
{currentRequest?.['Client Request Time (ms)']}
</div>{' '}
<div style={{ gridColumn: 'span 2 / span 2' }}>
<b>Redemption ID: &nbsp;</b>
{currentRequest?.RedemptionID}
</div>{' '}
<div>
<b>Raw accuracy: &nbsp;</b>
{currentRequest?.raw_accuracy}
</div>{' '}
<div style={{ gridColumn: 'span 2 / span 2' }}>
<b>Processing time: &nbsp;</b>
{currentRequest?.['Server Processing Time (ms)']}
</div>{' '}
</div>
)}
</div>
{totalRequests > 0 && (
<div
style={{
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
flexGrow: 0,
margin: '8px 0 0 0',
}}
>
<p
style={{
color: '#333',
fontWeight: 'bold',
margin: '0 16px 0 0',
}}
>
Files ({currentRequest?.Files?.length})
</p>
{currentRequest?.Files.map((file, index) => (
<FileCard
key={index}
file={file}
isSelected={index === selectedFileId}
onClick={() => {
setAndLoadSelectedFile(currentRequest, index);
setImageLoading(true);
}}
setIsReasonModalOpen={setIsReasonModalOpen}
/>
))}
</div>
)}
{selectedFileData === 'FAILED_TO_LOAD_FILE' ? (
<p style={{ color: '#333' }}>Failed to load file.</p>
) : fileExtension === 'pdf' ? (
<div
style={{
flexGrow: 1,
overflow: 'auto',
}}
>
<Viewer
plugins={[defaultLayoutPluginInstance]}
fileUrl={selectedFileData}
onDocumentLoad={() => setImageLoading(false)}
/>
</div>
) : (
<div
style={{
flexGrow: 1,
overflow: 'auto',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
overflowX: 'visible',
}}
>
<img
style={{
maxHeight: '100%',
maxWidth: '100%',
height: 'auto',
width: 'auto',
cursor: 'zoom-in',
}}
src={selectedFileData}
alt='file'
onClick={() => setLightBox(true)}
onLoad={() => {
setImageLoading(false);
}}
/>
{lightBox && (
<Lightbox
image={selectedFileData}
onClose={() => setLightBox(false)}
></Lightbox>
)}
</div>
)}
<Spin spinning={imageLoading}></Spin>
<div
style={{
flexGrow: 0,
display: 'flex',
justifyContent: 'space-between',
margin: '8px 0 0',
alignItems: 'center',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
<h3 style={{ margin: '0 8px ' }}>
{totalRequests
? 'No: ' + currentRequestIndex + '/' + totalRequests
: 'No Request. Adjust your search criteria to see more results.'}
</h3>
{currentRequest &&
(currentRequest['Is Reviewed'] ? (
<Tag
icon={<CheckCircleOutlined />}
color='success'
style={{ padding: '4px 16px' }}
>
Reviewed
</Tag>
) : (
<Tag
icon={<ClockCircleFilled />}
color='warning'
style={{ padding: '4px 16px' }}
>
Not Reviewed
</Tag>
))}
</div>
<div
style={{
display: 'flex',
justifyContent: 'center',
}}
>
<div>
<Button
type='default'
style={{ height: 38 }}
disabled={currentRequestIndex === 1}
onClick={() => {
gotoPreviousRequest();
}}
>
<ArrowLeftOutlined />
Prev
</Button>
<Button
type='default'
style={{ height: 38 }}
disabled={!hasNextRequest}
onClick={() => {
if (!hasNextRequest) {
return;
}
gotoNextRequest();
}}
>
Next
<ArrowRightOutlined />
</Button>
<Input
size='middle'
addonBefore='To'
style={{ marginBottom: '4px', marginLeft: '4px', width: 180 }}
defaultValue={currentRequestIndex}
addonAfter={
<Button
type='default'
onClick={() => {
if (pageIndexToGoto > totalRequests) {
message.error('RequestID is out of range.');
return;
}
if (pageIndexToGoto < 1) {
message.error('RequestID is out of range.');
return;
}
setCurrentRequestIndex(pageIndexToGoto);
loadCurrentRequest(pageIndexToGoto);
}}
>
Go to
</Button>
}
value={pageIndexToGoto}
onChange={(e) => {
setPageIndexToGoto(parseInt(e.target.value));
}}
/>
</div>
</div>
<Button
type='primary'
shape='default'
size='middle'
disabled={currentRequest && currentRequest['Is Reviewed']}
style={{ minWidth: '120px', alignSelf: 'flex-end' }}
onClick={handleConfirmReview}
>
Confirm request
</Button>
</div>
</div>
<div
style={{
flexBasis: 400,
flexShrink: 0,
display: 'flex',
flexDirection: 'column',
paddingLeft: '8px',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
marginBottom: '8px',
}}
>
<Input
size='middle'
value={`Sub: ${filterSubsidiaries}, Date:${
filterDateRange[0]
? filterDateRange[0] + ' to ' + filterDateRange[1]
: 'All'
}, Reviewed: ${filterReviewState}, Tests: ${filterIncludeTests}`}
readOnly
/>
<Button
type='primary'
size='middle'
style={{
height: '36px',
}}
onClick={() => {
setIsModalOpen(true);
}}
>
Filters
</Button>
</div>
<div style={{ flexGrow: 1, overflowY: 'auto', overflowX: 'hidden' }}>
{SOURCE_KEYS?.map((data) => {
let shouldRevised = false;
try {
if (
selectedFileDataSource[data]?.[FEEDBACK_ACCURACY].length > 0
) {
shouldRevised =
selectedFileDataSource[data][FEEDBACK_ACCURACY][0] < 1;
}
} catch (error) {}
return (
<div style={{ margin: '0 0 8px' }}>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
margin: '0 0 4px',
}}
>
<p style={{ fontWeight: 'bold', margin: 0 }}>{data}</p>
<Button
shape='round'
type='primary'
ghost
icon={<CopyOutlined />}
size='small'
onClick={() => updateRevised(data)}
/>
</div>
<Input
addonBefore='Feedback'
size='small'
readOnly
value={selectedFileDataSource[data]?.[FEEDBACK_RESULT]}
/>
<Input
addonBefore='Predicted'
readOnly
size='small'
value={selectedFileDataSource[data]?.[PREDICTED_RESULT]}
/>
<Input
addonBefore='Revised'
style={{ background: shouldRevised ? 'yellow' : '' }}
size='small'
value={selectedFileDataSource[data]?.[REVIEWED_RESULT]}
onChange={(e) =>
handleUpdateFileInField(data, e.target.value)
}
/>
</div>
);
})}
<b>{t`Bad image reason:`}</b>
<div
style={{
display: 'flex',
margin: '8px 0px',
justifyContent: 'space-between',
}}
>
<Select
placeholder='Select a reason'
style={{ width: 170, flexBasis: '50%', height: '32px' }}
options={REASON_BAD_QUALITY}
onChange={setReason}
value={reason}
/>
{reason === 'other' && (
<Input
placeholder='Other reason'
value={otherReason}
style={{ width: 170, flexBasis: '50%', height: '32px' }}
onChange={(e) => {
setOtherReason(e.target.value);
}}
/>
)}
</div>
<b>{t`Solution:`}</b>
<div
style={{
display: 'flex',
margin: '8px 0px',
justifyContent: 'space-between',
}}
>
<Select
placeholder='Select a solution'
style={{ width: 170, flexBasis: '50%', height: '32px' }}
options={SOLUTION_BAD_QUALITY}
onChange={setSolution}
value={solution}
// defaultValue={solution}
/>
{solution === 'other' && (
<Input
style={{ width: 170, flexBasis: '50%', height: '32px' }}
placeholder='Other solution'
value={otherSolution}
onChange={(e) => {
setOtherSolution(e.target.value);
}}
/>
)}
</div>
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<Button
type='primary'
color='success'
size='middle'
style={{
height: '36px',
}}
onClick={submitRevisedData}
>
Update File
</Button>
</div>
</div>
</div>
<Modal
title={t`Report Filters`}
open={isModalOpen}
width={700}
onOk={() => {
setIsModalOpen(false);
reloadFilters();
}}
onCancel={() => {
setIsModalOpen(false);
}}
>
<Form
style={{
marginTop: 30,
}}
>
<Form.Item
name='dateRange'
label={t`Date (GMT+8)`}
rules={[
{
required: true,
message: 'Please select a date range',
},
]}
style={{
marginBottom: 24,
}}
>
<DatePicker.RangePicker
onChange={(date, dateString) => {
setFilterDateRange(dateString);
}}
style={{ width: 200 }}
/>
</Form.Item>
<div
style={{
marginTop: 10,
display: 'flex',
justifyContent: 'space-between',
marginLeft: 0,
padding: 0,
}}
>
<Form.Item
name='subsidiary'
label={t`Subsidiary`}
rules={[
{
required: true,
message: 'Please select a subsidiary',
},
]}
>
<Select
placeholder='Select a subsidiary'
style={{ width: 200 }}
options={SUBSIDIARIES}
value={filterSubsidiaries}
defaultValue={filterSubsidiaries}
onChange={setFilterSubsidiaries}
/>
</Form.Item>
<Form.Item
name='max_accuracy'
label={t`max_accuracy` + ' (1-100)'}
rules={[
{
required: true,
message: 'Please select max accuracy',
},
]}
>
<InputNumber
min={1}
max={100}
defaultValue={filterAccuracy}
onChange={(value) => setFilterAccuracy(value)}
/>
</Form.Item>
</div>
<div
style={{
marginTop: 10,
display: 'flex',
justifyContent: 'space-between',
marginLeft: 0,
padding: 0,
}}
>
<Form.Item
name='reviewed'
label={t`Reviewed`}
rules={[
{
required: true,
message: 'Please select review status',
},
]}
>
<Select
style={{ width: 200 }}
options={[
{ label: 'All', value: 'all' },
{ label: 'Reviewed', value: 'reviewed' },
{ label: 'Not Reviewed', value: 'not_reviewed' },
]}
value={filterReviewState}
defaultValue={filterReviewState}
onChange={setFilterReviewState}
/>
</Form.Item>
<Form.Item
name='is_test'
label={t`Is Test`}
rules={[
{
required: true,
message: 'Please select test status',
},
]}
style={{ marginLeft: 16 }}
>
<Select
style={{ width: 200 }}
options={[
{ label: 'Include tests', value: 'true' },
{ label: 'Exclude tests', value: 'false' },
]}
value={filterIncludeTests}
defaultValue={filterIncludeTests}
onChange={setFilterIncludesTests}
/>
</Form.Item>
</div>
</Form>
</Modal>
<Modal
title={t`Review`}
open={isReasonModalOpen}
width={700}
onOk={async () => {
// call submit api
if (!reason || !solution) {
notification.warning({
message: 'Please select a reason or a solution',
});
} else {
const params = {
request_id: currentRequest?.RequestID,
request_image_id: selectedFileName.replace(/\.[^/.]+$/, ''),
};
let submitReason = reason;
let submitSolution = solution;
if (reason === 'other') {
if (!otherReason) {
notification.warning({
message: 'Please input other reason',
});
return;
}
submitReason = otherReason;
}
if (solution === 'other') {
if (!otherSolution) {
notification.warning({
message: 'Please input other solution',
});
return;
}
submitSolution = otherSolution;
}
const res = await badQualityReasonSubmit(
params,
submitReason,
submitSolution,
);
if (res.message) {
notification.success({ message: 'Update reason success' });
setIsReasonModalOpen(false);
}
}
}}
onCancel={() => {
setIsReasonModalOpen(false);
}}
>
<div style={{ display: 'flex', justifyContent: 'flex-start' }}>
<Form
style={{
marginTop: 30,
}}
>
<Form.Item name='reason' label={t`Reason for bad quality:`}>
<Select
placeholder='Select a reason'
style={{ width: 200 }}
options={REASON_BAD_QUALITY}
onChange={setReason}
value={reason}
/>
</Form.Item>
</Form>
{reason === 'other' && (
<Input
placeholder='Other reason'
value={otherReason}
onChange={(e) => {
setOtherReason(e.target.value);
}}
style={{
width: 200,
marginTop: 30,
marginBottom: 24,
marginLeft: 10,
}}
/>
)}
</div>
<div style={{ display: 'flex', justifyContent: 'flex-start' }}>
<Form>
<Form.Item name='reason' label={t`Solution:`}>
<span style={{ display: 'none' }}>
{counter_measure_map[reason]}
</span>
<Select
placeholder='Select a solution'
style={{ width: 200 }}
options={SOLUTION_BAD_QUALITY}
onChange={setSolution}
value={solution}
// defaultValue={solution}
/>
</Form.Item>
</Form>
{solution === 'other' && (
<Input
placeholder='Other solution'
value={otherSolution}
onChange={(e) => {
setOtherSolution(e.target.value);
}}
style={{
width: 200,
marginBottom: 24,
marginLeft: 10,
}}
/>
)}
</div>
</Modal>
</div>
);
};
export default ReviewPage;