function DocumentReview()

in microservices/adp_ui/src/components/DocumentReview.js [62:408]


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)
  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();

    console.log(`Calling ${baseURL}/hitl_service/v1/get_document?uid=${uid}`);
    axios.post(`${baseURL}/hitl_service/v1/get_document?uid=${uid}`, {
    }).then(res => {
      console.info("document data:");
      console.info(res);

      console.info("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.info("INPUTDATA", inputData)
      let auditTrail = []
      if (inputData && inputData['audit_trail']) {
        console.info("inputData['audit_trail']")
        console.info(inputData['audit_trail'])
        setComment(inputData['audit_trail'] || []);
      } else {
        setComment([]);
      }

      setInputList(inputData.entities)
      console.info("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.error("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() {
    headerHeight = (inputData.document_type === 'supporting_documents' ? '220px' : '170px')

    //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(startPage, pageNumber, obj, color) {
    console.log("pageNumber,obj", startPage, pageNumber, obj)
    currPage = startPage;
    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");
        if (pageNumber === currPage) {
          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, pageNumber, obj, color));
        }
      });

    })
  }

  // 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);
      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)')
      callPage(pageN, obj, color)

    }
    else {
      console.log("else condition")
      const element = document.querySelectorAll('canvas').forEach(e => {
        console.log("e", e.className)
        e.remove()
      });
      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");
      }

    }
  }

  function callPage(pageN, obj, color) {
    let url = `${baseURL}/hitl_service/v1/fetch_file?case_id=${caseid}&uid=${uid}`
    // context = '';
    //canvas = '';
    //viewer='';
    const element = document.querySelectorAll('canvas').forEach(e => {
      console.log("e", e.className)
      e.remove()
    });
    //pdfjsLib.getDocument(url).promise.then(function (pdf) {
    //thePdf = pdf;
    //viewer = document.getElementById('pdf-viewer');
    //console.log("viwer 1",viewer);
    againrenderPage(1, pageN, obj, color)
    //});
  }

  return (
    <div>
      <Headers />
      <div className="subHeaderReview">

        <div className="row">
          <div className="col-7" style={{ position: "relative", paddingBottom: '0px' }}>
            <Link to={{ pathname: '/', }} className="drBack">
              <Back fill="#aaa" />
            </Link>{' '}

            {inputData && inputData.document_type === 'supporting_documents' ?
              <>
                <label className={["subTitle", "drSpace"].join(" ")}> <span> <File /></span>{inputDocType + ' > ' + inputDocClass}  </label>

                <label className="applicationVerticalLine">&nbsp;</label>
                <span style={{ marginLeft: '3rem' }} >
                  <label className="applicationLabel" style={{ marginTop: '10px' }}>Application (Case ID):</label>
                  {applicationForm.length === 0 ? 'N/A' :
                    <Link target="_blank" to={{
                      pathname: `/documentreview/${applicationForm}/${caseid}`,
                    }}>{caseid}</Link>
                  }
                </span>
              </>
              :
              <>
                <label className={["subTitle", "drSpace"].join(" ")}> <span> <File /></span>{(inputDocType || 'No Type') + ' > ' + (inputDocClass || 'Unclassfied') + ' > ' + caseid} </label>
              </>}
          </div>
          <div className="col-3" style={{ paddingBottom: '0px', textAlign: 'end' }}>
            <label className="approveLeftVerticalLine">&nbsp;</label>
            <Button type="button" className="buttonStyles" style={{ backgroundColor: "#4285F4" }} onClick={() => hitlStatusButton('Approved')}>Approve</Button>