import React, { useState, useRef, useEffect } from "react"; import API_BASE_URL from "../config.js"; import { getImageUrl } from "../helpers/itemHelper"; import { getTables, updateTable, createTable } from "../helpers/tableHelper"; import { getCafe, saveCafeDetails, setConfirmationStatus, } from "../helpers/cafeHelpers"; import { toPng } from 'html-to-image'; import { ColorRing } from "react-loader-spinner"; const SetPaymentQr = ({ shop }) => { const [initialPos, setInitialPos] = useState({ left: shop.xposition, top: shop.yposition, }); const [isViewingQR, setIsViewingQR] = useState(false); const [isConfigFont, setIsConfigFont] = useState(false); const [fontsize, setfontsize] = useState(shop.fontsize); const [fontcolor, setfontcolor] = useState(shop.fontcolor); const [initialFontPos, setInitialFontPos] = useState({ left: shop.fontxposition, top: shop.fontyposition, }); const [initialSize, setInitialSize] = useState(shop.scale); const [bgImageUrl, setBgImageUrl] = useState(getImageUrl(shop.qrBackground)); const qrBackgroundInputRef = useRef(null); const [cafeIdentifyNameUpdate, setCafeIdentifyNameUpdate] = useState(shop.cafeIdentifyName); const shopUrl = window.location.hostname + "/" + cafeIdentifyNameUpdate; const cafeIdentifyNameRef = useRef(null); const [isconfigcafeidentityname, setIsConfigCafeIdentityName] = useState(false); const generateQRCodeUrl = (tableCode) => { if (tableCode != null) { return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent( shopUrl + "/" + tableCode )}`; } else { return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent( shopUrl )}`; } }; const [isConfig, setIsConfig] = useState(false); const [isConfigQR, setIsConfigQR] = useState(false); const [isViewTables, setIsViewTables] = useState(false); const [tables, setTables] = useState([]); const [selectedTable, setSelectedTable] = useState(null); const [tableNo, setTableNo] = useState(null); const [isLoading, setIsLoading] = useState(false); const [identifyNameResponse, setIdentifyNameResponse] = useState('-----------------'); useEffect(() => { const fetchData = async () => { try { console.log(shop); const fetchedTables = await getTables(shop.cafeId); setTables(fetchedTables); } catch (error) { console.error("Error fetching tables:", error); } }; fetchData(); }, [shop.cafeId]); const handleSave = () => { const qrBackgroundFile = qrBackgroundInputRef.current.files[0]; // Get the selected file for qrBackground // Prepare the details object const details = { qrSize: initialSize, qrPosition: initialPos, qrBackgroundFile, fontsize, fontcolor, fontPosition: initialFontPos, }; // Call saveCafeDetails function with the updated details object saveCafeDetails(shop.cafeId, details) .then((response) => { console.log("Cafe details saved:", response); }) .catch((error) => { console.error("Error saving cafe details:", error); }); }; const handlePositionChange = (e) => { const { name, value } = e.target; setInitialPos((prevPosition) => ({ ...prevPosition, [name]: parseFloat(value).toFixed(2), })); }; const handleFontPositionChange = (e) => { const { name, value } = e.target; setInitialFontPos((prevPosition) => ({ ...prevPosition, [name]: parseFloat(value).toFixed(2), })); }; const handleSizeChange = (e) => { setInitialSize(parseFloat(e.target.value).toFixed(2)); }; const handleFontSizeChange = (e) => { setfontsize(parseFloat(e.target.value).toFixed(2)); }; const handleFileChange = (e) => { const file = e.target.files[0]; if (file) { const newBgImage = URL.createObjectURL(file); // Create a temporary URL for display setBgImageUrl(newBgImage); } }; const handleCreate = async () => { // if (newTable) { try { const createdTable = await createTable(shop.cafeId, { // ...newTable, tableNo, }); setTables([...tables, createdTable]); setTableNo(""); } catch (error) { console.error("Error creating table:", error); } }; function downloadQrCodeContainer({ selectedTable, shop }) { const node = document.getElementById('qr-code-container'); if (!node) return; // Save the original background color const originalBackgroundColor = node.style.backgroundColor; // Temporarily remove the background color node.style.backgroundColor = 'transparent'; const isTableSelected = selectedTable != null; toPng(node, { pixelRatio: 2 }) // Adjust pixel ratio for higher resolution .then((dataUrl) => { const link = document.createElement('a'); link.href = dataUrl; // Set the file name based on whether selectedTable exists link.download = isTableSelected ? `QR Meja (${selectedTable.tableNo}).png` : `QR ${shop.name}.png`; link.click(); }) .catch((err) => { console.error('Could not download the image', err); }) .finally(() => { // Restore the original background color after the download node.style.backgroundColor = originalBackgroundColor; }); } // This will hold the timeout ID so we can clear it when needed const typingTimeoutRef = useRef(null); const handleInputChange = (e) => { setIsLoading(true) const updatedValue = e.target.value .toLowerCase() .replace(/ /g, '_') .replace(/[^a-z0-9_]/g, ''); setCafeIdentifyNameUpdate(updatedValue); // Clear the existing timeout if (typingTimeoutRef.current) { clearTimeout(typingTimeoutRef.current); } // Set a new timeout typingTimeoutRef.current = setTimeout(() => { // Call the function to check if the name is already used checkIfNameIsUsed(updatedValue); }, 1000); // 1 second delay }; const checkIfNameIsUsed = async (newIdentifyName) => { // Replace this with your actual API call try { const response = await fetch(API_BASE_URL+`/cafe/check-identifyName/${newIdentifyName}`); console.log(response) if (response.ok) { setIsLoading(false); setIdentifyNameResponse(200) } else { setIsLoading(false); setIdentifyNameResponse(409) } } catch (error) { } }; return (

Identifikasi kedai

{window.location.hostname}/
{ setIsConfigCafeIdentityName(true); // Set the state to true when input is focused }} />
KedaiMaster .
{!isconfigcafeidentityname ? <>

Klik untuk ganti alamat

-----------------

{ setIsConfigCafeIdentityName(true); cafeIdentifyNameRef.current && cafeIdentifyNameRef.current.focus(); }} style={styles.changeButton}>Ganti
: ( <>

{cafeIdentifyNameUpdate == shop.cafeIdentifyName ? '-----------------' : !isLoading && identifyNameResponse == 200 ? 'Alamat tersedia' : !isLoading && identifyNameResponse != 200 ? 'Alamat terpakai' : < ColorRing height="16" width="16" style={{ marginTop: '5px' }} /> }

{cafeIdentifyNameUpdate != shop.cafeIdentifyName && identifyNameResponse == 200 && !isLoading ?

setIsConfigCafeIdentityName(false)} style={styles.changeButton2}>Terapkan
: '----------'}

{isconfigcafeidentityname ?
{ setIdentifyNameResponse(0); setCafeIdentifyNameUpdate(shop.cafeIdentifyName); setIsConfigCafeIdentityName(false); }} style={styles.changeButton}>Batal
:
{ setIsConfigCafeIdentityName(true); cafeIdentifyNameRef.current && cafeIdentifyNameRef.current.focus(); }} style={styles.changeButton}>Ganti
}
{/*
{ }} style={styles.changeButton}>Simpan {isLoading && }
*/} )}
QR Code QR Code
50 ? -1 : 1})`, position: "absolute", fontSize: `${fontsize * 3}%`, left: `${initialFontPos.left}%`, top: `${initialFontPos.top}%`, textAlign: initialFontPos.left > 50 ? 'right' : 'left' }}>

50 ? -1 : 1})`, width: '200%', lineHeight: 0, fontFamily: 'Plus Jakarta Sans', color: fontcolor }} >{selectedTable == null ? (isConfigFont ? 'Nomor meja' : '') : selectedTable.tableNo}

{!isViewingQR ? <>

Klik untuk ganti background

{ setIsConfig(!isConfig); setIsConfigQR(!isConfigQR); setIsConfigFont(false) }}> {isConfig ? '˅' : '˃'} Konfigurasi QR

qrBackgroundInputRef.current.click()} style={styles.changeButton}>Ganti
{isConfig &&
{/*

{ setIsConfigQR(!isConfigQR); setIsConfigFont(false) }}> {isConfigQR ? '˅' : '˃'} Konfigurasi QR

*/} {isConfigQR && <>
} {/*

{ setIsConfigFont(!isConfigFont); setIsConfigQR(false) }}> {isConfigFont ? '˅' : '˃'} Konfigurasi nomor

*/} {isConfigFont && ( <>
)}
} {/*

setIsViewTables(!isViewTables)}> {isViewTables ? '˅' : '˃'} Daftar meja

*/} {isViewTables &&
setTableNo(e.target.value)} value={tableNo} />
Buat meja
{tables && tables .filter((table) => table.tableNo !== 0) .map((table) => (
  • setSelectedTable(selectedTable == table ? null : table)} >
    {table.tableNo}
  • )) }
    }
    : <>

    Ini adalah QR yang dapat di scan oleh tamu untuk memesan

    {/*

    QR ini akan menjadi identifikasi bahwa pelanggan memesan dari {selectedTable? `(${selectedTable?.tableNo})` : 'link kafe ini. Untuk mengantarkan pelanggan ke meja yang teridentifikasi, anda perlu membuat meja.'}

    */}

    setIsViewingQR(false)} > Kembali

    }
    ); }; // Styles const styles = { container: { overflowY: 'auto', overflowX: 'hidden', maxHeight: '80vh', width: '100%', backgroundColor: "white", padding: "20px", borderRadius: "8px", boxShadow: "0 2px 10px rgba(0, 0, 0, 0.1)", textAlign: "center", // Center text and children }, title: { marginBottom: "20px", fontWeight: "bold", }, qrCodeContainer: { backgroundColor: '#999999', borderRadius: '8px', position: "relative", width: "100%", height: "200px", backgroundSize: "contain", overflow: "hidden", margin: "0 auto", // Center the QR code container }, uploadMessage: { fontWeight: 600, textAlign: "left", fontSize: "15px" }, changeButton: { paddingRight: '10px', backgroundColor: 'rgb(40, 167, 69)', borderRadius: '30px', color: 'white', fontWeight: 700, height: '31px', lineHeight: '32px', paddingLeft: '10px', paddingHeight: '10px', marginBottom: '22px', width: '80px', textAlign: 'center' }, changeButton2: { color: 'black', fontWeight: 700, textAlign: 'left' }, uploadButton: { paddingRight: '10px', backgroundColor: 'green', borderRadius: '30px', color: 'white', fontWeight: 700, height: '36px', lineHeight: '36px', paddingLeft: '10px', paddingHeight: '10px', width: '40%', textAlign: 'center' }, resultMessage: { marginTop: "-24px", marginBottom: "10px", textAlign: "left", display: 'flex', justifyContent: 'space-between' }, resultMessage2: { marginTop: "-24px", marginBottom: "10px", textAlign: "left", display: 'flex', justifyContent: 'space-evenly' }, buttonContainer: { marginTop: "20px", textAlign: "left", display: 'flex', justifyContent: 'space-evenly' }, backButtonContainer: { marginTop: "2px", marginBottom: "-10px", textAlign: "left", display: 'flex', justifyContent: 'space-evenly' }, saveButton: { padding: '6px 15px', fontSize: '13px', backgroundColor: 'rgb(40, 167, 69)', color: 'rgb(255, 255, 255)', border: ' none', borderRadius: '30px', cursor: 'pointer', transition: 'background-color 0.3s', }, switchContainer: { textAlign: "left", marginTop: '-15px' }, description: { margin: "10px 0", }, sliderContainer: { marginBottom: "20px", }, label: { display: "block", marginBottom: "10px", }, sliderWrapper: { display: "flex", alignItems: "center", }, input: { flex: "1", margin: "0 10px", }, }; export default SetPaymentQr;