function DocumentReview()

in microservices/adp_ui/src/components/DocumentReviewPdfHighlight.js [60:383]


function DocumentReview() {
  const myRef = useRef(null)

  const toastId = React.useRef(null);

  // Set the states and retireving the navigation parameters
  var context = '';
  let canvas = '';

  //  const { state: { uid, caseid } } = useLocation();
  const { uid, caseid } = useParams();
  console.log("USE PARMAS", uid)
  console.log("caseid", caseid)
  console.log("uid", uid)
  const history = useHistory();
  const [comments, setComment] = useState([]);
  const [inputList, setInputList] = useState([]);
  const [notes, setNotes] = useState('');
  const [applicationForm, setApplicationForm] = useState('')


  useEffect(() => {
    // based on the uid, get the document for the page
    let url = `${baseURL}/hitl_service/v1/fetch_file?case_id=${caseid}&uid=${uid}`
    applicationFormAPICall()

    axios.post(`${baseURL}/hitl_service/v1/get_document?uid=${uid}`, {
    }).then(res => {
      console.log("API RESPONSE DATA", res.data);
      inputData = res.data.data;
      if (inputData && inputData.document_type !== null) {
        inputDocClass = inputData.document_class.split('_').join(" ");
        inputDocType = inputData.document_type.split('_').join(" ")
      }

      console.log("INPUTDATA", inputData)
      if ((inputData && inputData['hitl_status'] !== null && inputData['hitl_status'].length === 0) || inputData['hitl_status'] === null) {
        setComment([]);
      }
      else {
        setComment(inputData.hitl_status);
      }
      setInputList(inputData.entities)
      console.log("INPUT LIST", inputList);

      // To display PDF onload
      pdfjsLib.getDocument(url).promise.then(function (pdf) {
        thePdf = pdf;
        viewer = document.getElementById('pdf-viewer');
        renderPage(pdf.numPages)
      });

    }).catch((err) => {
      console.log("error", err);
      toast.error(`${err}`, {
        position: "bottom-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const applicationFormAPICall = () => {
    axios.post(`${baseURL}/hitl_service/v1/search`, { filter_key: "case_id", filter_value: caseid }).then((appForm) => {
      console.log("searchFilterText", appForm.data.data)
      let appForms = appForm.data.data;
      appForms.forEach((ele) => {
        if (ele.document_type === 'application_form') {
          setApplicationForm(ele.uid);
        }
      })

    }).catch((error) => {
      console.log("error", error);
    })
  }

  let currPage = 1;
  // Based on the pagenumbers the PDF can be rendered
  function renderPage() {

    //pageNumber = 1;
    thePdf.getPage(currPage).then(function (page) {
      console.log('Page loaded');
      canvas = document.createElement("canvas");
      canvas.className = `pdf-page-canvas-${currPage}`;
      canvas.strokeStyle = 'black'
      viewer.appendChild(canvas);
      var scale = 1.5;
      var rotation = 0;
      var dontFlip = 0;
      var viewport = page.getViewport({ scale, rotation, dontFlip });

      // Prepare canvas using PDF page dimensions
      context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      //page.render({canvasContext: canvas.getContext('2d'), viewport: viewport});
      var renderContext = {
        canvasContext: context,
        viewport: viewport
      };
      var renderTask = page.render(renderContext);
      renderTask.promise.then(function () {
        console.log("Pahge rendered")
      });

      currPage++;
      if (thePdf !== null && currPage <= thePdf.numPages) {
        console.log("currpage")

        thePdf.getPage(currPage).then(renderPage);
      }
    })
  }

  // This function is called when we draw the rectangles on any of the PDF document by removing a page and replacing that page with the hightlited of the selected field.
  function againrenderPage(pageNumber, obj, color) {
    console.log("pageNumber,obj", pageNumber, obj)
    // if(pageNumber === 1){
    console.log("DIV", document.getElementById('pdf-viewer'));
    console.log("DIV", document.querySelectorAll('canvas'));
    const element = document.querySelectorAll('canvas').forEach(e => {
      console.log("e", e.className)
      if (e.className === `pdf-page-canvas-${pageNumber}`) {
        e.remove(`pdf-page-canvas-${pageNumber}`)
      }
    });
    console.log("ele", element)
    //}
    //pageNumber = 1;
    console.log("OBJ", obj, pageNumber)
    currPage = pageNumber;
    console.log("&&&&&&&", currPage, thePdf)
    thePdf.getPage(currPage).then(function (page) {
      console.log('Page loaded', page);
      canvas = document.createElement("canvas");
      canvas.className = `pdf-page-canvas-${currPage}`;
      canvas.strokeStyle = 'black'
      viewer.appendChild(canvas);
      var scale = 1.5;
      var rotation = 0;
      var dontFlip = 0;
      var viewport = page.getViewport({ scale, rotation, dontFlip });

      // Prepare canvas using PDF page dimensions
      context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      //page.render({canvasContext: canvas.getContext('2d'), viewport: viewport});
      var renderContext = {
        canvasContext: context,
        viewport: viewport
      };
      var renderTask = page.render(renderContext);
      renderTask.promise.then(function () {
        console.log("Pahge rendered");
        const { x1, x2, y1, y2 } = obj;
        console.log("OBJJJJJ", obj);
        let x = x1 * canvas.width;
        let y = y1 * canvas.height;
        let w = (x2 * canvas.width) - (x1 * canvas.width)
        let h = (y2 * canvas.height) - (y1 * canvas.height)

        console.log("X,Y,W,H", x, y, w, h)
        context.strokeStyle = "#4285F4";
        context.fillStyle = color;
        context.fillRect(x, y, w, h);
        context.lineWidth = 5;
        context.strokeRect(x, y, w, h);
        currPage++;
        console.log("currpageeeeee", currPage, thePdf.numPages, thePdf)
        if (thePdf !== null && currPage <= thePdf.numPages) {
          console.log("currpagesssssssssssss", currPage)
          thePdf.getPage(currPage).then(againrenderPage(currPage, 0));
        }
      });

    })
  }

  // handle input change, when the inputboxes are clicked
  const handleInputChange = (e, index, rectData) => {
    console.log("onchange input", e, index);
    const { value } = e.target;
    const list = [...inputList];
    list[index]['corrected_value'] = value;
    console.log("LIST", list)
    setInputList(list);
  };

  // to save the edited fields record
  const saveUpdatedButton = () => {
    console.log("SAVE UPDATES CLICKED updated correct value", inputList);
    console.log("comment in save update", comments)
    console.log("API DATA", inputData)
    setComment(comments);
    axios.post(`${baseURL}/hitl_service/v1/update_entity?uid=${inputData.uid}`, inputData).then((saveUpdates) => {
      console.log("Updates saved", saveUpdates);
      console.log("API DATAAAAAAAAAAAAA", inputData)
      toast.success("Changes Saved Successfully !", {
        position: "bottom-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      })
      history.push('/')


    }).catch((err) => {
      console.log("error", err);
      toast.error(`${err}`, {
        position: "bottom-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    })
  };


  //HITL Status for Approve,Reject and Pending/Review
  const hitlStatusButton = (status) => {
    console.log("hitl status clicked");
    const sendObj = {
      uid: inputData.uid,
      status: status,
      user: localStorage.getItem('user').split('@')[0],
      comment: notes
    }
    console.log("sendObj", sendObj);
    axios.post(`${baseURL}/hitl_service/v1/update_hitl_status?uid=${sendObj.uid}&status=${sendObj.status}&user=${sendObj.user}&comment=${sendObj.comment}`).then((responseData) => {
      console.log("status updated API response", responseData);
      history.push('/')
      toast.success(`Successfully changed Status to ${status}`, {
        position: "bottom-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      })

    }).catch((err) => {
      console.log("error", err);
      toast.error(`${err}`, {
        position: "bottom-center",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    })
  }

  // When the user selects the button, the associated values are passed so that a rectangle can be drawn on PDF
  function inputClicked(data) {
    console.log("DATA", data)
    if (data.value_coordinates !== undefined) {
      console.log("Data", data)
      console.log("data cordinates", data.value_coordinates)
      let obj = {
        x1: data.value_coordinates[0] - 0.01,
        x2: data.value_coordinates[2] + 0.01,
        y1: data.value_coordinates[1] - 0.01,
        y2: data.value_coordinates[7] + 0.01,
        page: data.page_no
      }
      console.log("+3 added", obj)
      let pageN = data.page_no
      let color = data.extraction_confidence > 0.90 ? 'hsla(120,100%,75%,0.3)' : (data.extraction_confidence < '0.70' ? 'hsl(0, 100%, 50%,0.3)' : 'hsl(39, 100%, 50%,0.3)')
      againrenderPage(pageN, obj, color)
    }
    else {
      console.log("else condition")
      againrenderPage(1, 0, 0)
      //toast.error('Unable to Detect Field Location',{ pauseOnFocusLoss: false})
      if (!toast.isActive(toastId.current)) {
        console.log(inputData);
        toastId.current = toast.error("Unable to Detect Field Location");
      }
    }
  }

  return (
    <div>
      <Headers />
      <div className="subHeaderReview">
        <Link to={{ pathname: '/', }} className="drBack"> {'<'} Back</Link>{' '}
        <Row>
          <Col>
            <label className={["subTitle", "drSpace"].join(" ")}> <span> <File /></span>{inputDocType + ' > ' + inputDocClass}  </label>

            {inputData && inputData.document_type === 'supporting_documents' ?
              <span style={{ marginLeft: '1rem' }} >
                <label className="applicationLabel" style={{ marginTop: '10px' }}>Application (Case ID):</label>
                {applicationForm.length === 0 ? 'N/A' :
                  <Link target="_blank" to={{
                    pathname: `/documentreview/${applicationForm}/${caseid}`,

                  }} >{applicationForm}</Link>
                }
              </span>
              : null}
          </Col>
          {/* <Col className="col-5"></Col> */}

          <Col className="verticalLines" style={{ textAlign: 'end' }}>
            <Button type="button" className="buttonStyles" style={{ backgroundColor: "#4285F4" }} onClick={() => hitlStatusButton('Approved')}>Approve</Button>