import React, { useState, useRef, useEffect } from "react"; import jsQR from "jsqr"; import { getImageUrl } from "../helpers/itemHelper"; import { getCafe, saveCafeDetails, setConfirmationStatus, } from "../helpers/cafeHelpers"; import Switch from "react-switch"; // Main Component const SetPaymentQr = ({ shopId }) => { const [qrPosition, setQrPosition] = useState([50, 50]); const [qrSize, setQrSize] = useState(50); const [qrPayment, setQrPayment] = useState(); const [qrCodeDetected, setQrCodeDetected] = useState(false); const qrPaymentInputRef = useRef(null); const qrCodeContainerRef = useRef(null); const [isNeedConfirmation, setIsNeedConfirmation] = useState(false); const [cafe, setCafe] = useState({}); // Fetch cafe details on mount or shopId change useEffect(() => { const fetchCafe = async () => { try { const response = await getCafe(shopId); setCafe(response); setQrPayment(getImageUrl(response.qrPayment)); setIsNeedConfirmation(response.needsConfirmation); setQrPosition([response.xposition, response.yposition]); setQrSize(response.scale); } catch (error) { console.error("Error fetching cafe:", error); } }; fetchCafe(); }, [shopId]); // Detect QR code when qrPayment updates useEffect(() => { if (qrPayment) { detectQRCodeFromContainer(); } }, [qrPayment]); // Handle file input change const handleFileChange = (e) => { const file = e.target.files[0]; if (file) { const newqrPayment = URL.createObjectURL(file); setQrPayment(newqrPayment); } }; // Detect QR code from the container const detectQRCodeFromContainer = () => { const container = qrCodeContainerRef.current; const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); const img = new Image(); img.crossOrigin = "Anonymous"; img.onload = () => { canvas.width = container.offsetWidth; canvas.height = container.offsetHeight; context.drawImage(img, 0, 0, canvas.width, canvas.height); const imageData = context.getImageData(0, 0, canvas.width, canvas.height); const qrCode = jsQR(imageData.data, canvas.width, canvas.height); setQrCodeDetected(!!qrCode); if (qrCode) { console.log("QR Code detected:", qrCode.data); } }; img.src = qrPayment; }; // Save cafe details const handleSave = async () => { const qrPaymentFile = qrPaymentInputRef.current.files[0]; const details = { qrPosition, qrSize, qrPaymentFile, }; try { const response = await saveCafeDetails(cafe.cafeId, details); console.log("Cafe details saved:", response); } catch (error) { console.error("Error saving cafe details:", error); } }; // Toggle confirmation status const handleChange = async () => { try { const response = await setConfirmationStatus( cafe.cafeId, !isNeedConfirmation ); setIsNeedConfirmation(response.needsConfirmation); } catch (error) { console.error(error); setIsNeedConfirmation(cafe.needsConfirmation); } }; return (
QR Code Detected
:Tidak ada qr yang terdeteksi
}Nyalakan agar kasir memeriksa kembali ketersediaan produk sebelum pelanggan membayar.