22

mail@pastecode.io avatar
unknown
plain_text
5 months ago
6.1 kB
2
Indexable
import React, { useState } from "react";
import "./RenewBook.css";
import { BASE_URL } from "../server/Endpoint";
import QrScanner from "react-qr-scanner";

const RenewBook = () => {
  const [memberId, setMemberId] = useState("");
  const [copyId, setCopyId] = useState("");
  const [additionalDays, setAdditionalDays] = useState("");
  const [updatedBy, setUpdatedBy] = useState("");
  const [message, setMessage] = useState("");
  const [messageType, setMessageType] = useState("");
  const [showMemberScanner, setShowMemberScanner] = useState(false);
  const [showCopyScanner, setShowCopyScanner] = useState(false);

  const handleRenew = async () => {
    if (!memberId || !copyId || !additionalDays || !updatedBy) {
      setMessage("Please fill in all required fields.");
      setMessageType("error");
      return;
    }

    const token = localStorage.getItem("token");
    const url = `${BASE_URL}api/staff/loans/extend?memberId=${memberId}&bookCopyId=${copyId}&additionalDays=${additionalDays}&updateBy=${updatedBy}`;
    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "ngrok-skip-browser-warning": "69420",
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        setMessage("Book renewed successfully!");
        setMessageType("success");
      } else if (response.status === 404) {
        setMessage("Member ID or Book ID not found.");
        setMessageType("error");
      } else if (response.status === 400) {
        setMessage("Invalid request. Please check the entered details.");
        setMessageType("error");
      } else {
        const errorText = await response.text();
        setMessage(`Failed to renew book: ${errorText}`);
        setMessageType("error");
      }
    } catch (error) {
      console.error("Error renewing book:", error);
      setMessage(`Error: ${error.message}`);
      setMessageType("error");
    }
  };

  const handleError = (err) => {
    console.error(err);
  };

  const handleScan = (data, isMemberScanner) => {
    if (data) {
      try {
        const parsedData = JSON.parse(data.text);
        if (isMemberScanner) {
          setMemberId(parsedData.memberid || "");
        } else {
          setCopyId(parsedData.bookCopyId || "");
        }
        setShowMemberScanner(false);
        setShowCopyScanner(false);
      } catch (error) {
        console.error("Error parsing QR code data:", error);
        setMessage("Invalid QR code data.");
        setMessageType("error");
      }
    }
  };

  const previewStyle = {
    height: 200,
    width: 260,
  };

  return (
    <div className="renew-book">
      <div className="form-group">
        <label htmlFor="memberId">Member ID:</label>
        <div className="input-container">
          <input
            id="memberId"
            type="number"
            value={memberId}
            onChange={(e) => setMemberId(e.target.value)}
            required
          />
          <button
            type="button"
            onClick={() => {
              setShowMemberScanner(!showMemberScanner);
              setShowCopyScanner(false);
            }}
            className="scan-button"
          >
            {showMemberScanner ? "Close Scanner" : "Scan QR"}
          </button>
        </div>
        {showMemberScanner && (
          <div className="qr-scanner-container">
            <QrScanner
              delay={300}
              style={previewStyle}
              onError={handleError}
              onScan={(data) => handleScan(data, true)}
            />
            <button
              type="button"
              onClick={() => setShowMemberScanner(false)}
              className="close-button-return"
            >
              X
            </button>
          </div>
        )}
      </div>

      <div className="form-group">
        <label htmlFor="copyId">Book ID:</label>
        <div className="input-container">
          <input
            id="copyId"
            type="number"
            value={copyId}
            onChange={(e) => setCopyId(e.target.value)}
            required
          />
          <button
            type="button"
            onClick={() => {
              setShowCopyScanner(!showCopyScanner);
              setShowMemberScanner(false);
            }}
            className="scan-button"
          >
            {showCopyScanner ? "Close Scanner" : "Scan QR"}
          </button>
        </div>
        {showCopyScanner && (
          <div className="qr-scanner-container">
            <QrScanner
              delay={300}
              style={previewStyle}
              onError={handleError}
              onScan={(data) => handleScan(data, false)}
            />
            <button
              type="button"
              onClick={() => setShowCopyScanner(false)}
              className="close-button-return"
            >
              X
            </button>
          </div>
        )}
      </div>

      <div className="form-group">
        <label htmlFor="additionalDays">Additional Days:</label>
        <input
          id="additionalDays"
          type="number"
          value={additionalDays}
          onChange={(e) => setAdditionalDays(e.target.value)}
          required
        />
      </div>

      <div className="form-group">
        <label htmlFor="updatedBy">Updated By:</label>
        <input
          id="updatedBy"
          type="number"
          value={updatedBy}
          onChange={(e) => setUpdatedBy(e.target.value)}
          required
        />
      </div>

      <button onClick={handleRenew} className="submit-button">
        Extend Book
      </button>

      {message && (
        <div className={`message ${messageType === "success" ? "success" : "error"}`}>
          {message}
        </div>
      )}
    </div>
  );
};

export default RenewBook;
Leave a Comment