6C
68lottery Cam

Default Component - Copy this React, Mui Component to your project

import React, { useState, useEffect } from 'react'; import { Box, Avatar, Typography, Card, TextField, Button, Modal, List, ListItem, ListItemText, IconButton, CircularProgress } from '@mui/material'; import { db, doc, getDoc, updateDoc, collection, query, where, getDocs, setDoc } from '../firebase'; import { FaTimes } from 'react-icons/fa'; import { v4 as uuidv4 } from 'uuid'; const ProfileTab = () => { const [userData, setUserData] = useState(null); const [bankAccount, setBankAccount] = useState({ accountNumber: '', bankName: '', holderName: '' }); const [openModal, setOpenModal] = useState(false); const [referrals, setReferrals] = useState([]); const [referrer, setReferrer] = useState(null); useEffect(() => { async function fetchUserData() { try { const initDataUnsafe = window.Telegram.WebApp.initDataUnsafe || {}; const user = initDataUnsafe.user || {}; const userId = user.id || 'anonymous'; const userRef = doc(db, 'users', userId.toString()); const userDoc = await getDoc(userRef); if (userDoc.exists()) { const data = userDoc.data(); setUserData(data); setBankAccount(data.bankAccount || { accountNumber: '', bankName: '', holderName: '' }); setReferrals(data.referrals?.referredUsers || []); setReferrer(data.referrerId); } else { let referralCode; let checkSnapshot; do { referralCode = `ref_${uuidv4().substring(0, 8)}`; // Tạo mã ngẫu nhiên với tiền tố "ref_" const checkQuery = query(collection(db, 'users'), where('referralCode', '==', referralCode)); checkSnapshot = await getDocs(checkQuery); // Khai báo và gán checkSnapshot trong phạm vi } while (!checkSnapshot.empty); // Sử dụng checkSnapshot đã khai báo setUserData({ username: `user_${userId}`, firstName: 'Unknown', lastName: '', photoUrl: '', points: 0, dailyTasksCompleted: 0, isLocked: false, cryptoWallet: '', bankAccount: null, referrals: { referredUsers: [], referralPoints: 0 }, referralCode, }); setBankAccount({ accountNumber: '', bankName: '', holderName: '' }); await setDoc(userRef, userData); } } catch (error) { console.error('Error fetching user data:', error); setUserData(null); } } if (!userData) { fetchUserData(); } }, [userData]); // Xử lý referral từ startapp parameter useEffect(() => { if (!userData || !userData.telegramId) return; const url = new URL(window.location.href); const urlParams = new URLSearchParams(url.search); const referralParam = urlParams.get('startapp') || ''; if (referralParam && referralParam.startsWith('ref_')) { async function handleReferral() { try { const q = query(collection(db, 'users'), where('referralCode', '==', referralParam)); const referrerSnapshot = await getDocs(q); if (!referrerSnapshot.empty) { const referrerDoc = referrerSnapshot.docs[0]; const referrerId = referrerDoc.id; const referrerData = referrerDoc.data(); const referredUsers = [...(referrerData.referrals.referredUsers || []), userData.telegramId.toString()]; await updateDoc(doc(db, 'users', referrerId), { 'referrals.referredUsers': referredUsers, 'referrals.referralPoints': (referrerData.referrals.referralPoints || 0) + 50000, }); await updateDoc(doc(db, 'users', userData.telegramId.toString()), { referrerId }); setReferrals(referredUsers); setReferrer(referrerId); } } catch (error) { console.error('Error handling referral:', error); } } handleReferral(); } }, [userData, userData?.telegramId]); const handleSaveBankAccount = async () => { if (!userData || !userData.telegramId) return; try { const userRef = doc(db, 'users', userData.telegramId.toString()); await updateDoc(userRef, { bankAccount }); setUserData((prev) => ({ ...prev, bankAccount })); alert('Thông tin ngân hàng đã được cập nhật!'); } catch (error) { console.error('Error updating bank account:', error); alert('Có lỗi khi cập nhật thông tin ngân hàng. Vui lòng thử lại.'); } }; const handleCloseModal = () => setOpenModal(false); const handleInviteFriend = () => { // Chỉ lấy phần referralCode sau "ref_" nếu đã có, tránh thêm "ref_" thừa const referralCode = userData.referralCode.replace(/^ref_/, ''); // Loại bỏ "ref_" khỏi referralCode const inviteLink = `https://t.me/junobeo_Bot/App?startapp=ref_${referralCode}`; // Thêm "ref_" một lần const shareText = `Join me on this awesome Telegram mini app!`; const fullUrl = `https://t.me/share/url?url=${encodeURIComponent(inviteLink)}&text=${encodeURIComponent(shareText)}`; window.Telegram.WebApp.openTelegramLink(fullUrl); }; const handleCopyReferralLink = () => { // Chỉ lấy phần referralCode sau "ref_" nếu đã có, tránh thêm "ref_" thừa const referralCode = userData.referralCode.replace(/^ref_/, ''); // Loại bỏ "ref_" khỏi referralCode const inviteLink = `https://t.me/junobeo_Bot/App?startapp=ref_${referralCode}`; // Thêm "ref_" một lần navigator.clipboard.writeText(inviteLink); alert('Invite link copied to clipboard!'); }; if (!userData) { return ( <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh', bgcolor: 'background.default' }}> <Box sx={{ textAlign: 'center' }}> <CircularProgress sx={{ mb: 2 }} /> <Typography variant="h6">Đang tiến hành tạo tài khoản...</Typography> </Box> </Box> ); } return ( <Box display="flex" flexDirection="column" alignItems="center" gap={2}> <Avatar sx={{ width: 80, height: 80 }} src={userData.photoUrl || ''}> {userData.firstName.charAt(0).toUpperCase()} </Avatar> <Typography variant="h6"> {userData.firstName} {userData.lastName} </Typography> <Card sx={{ padding: 2, width: '100%', mb: 2 }}> <Typography variant="subtitle1">Basic Information</Typography> <Typography>Points: {userData.points}</Typography> <Typography>Tasks Completed Today: {userData.dailyTasksCompleted}</Typography> <Typography>Account Status: {userData.isLocked ? 'Locked' : 'Active'}</Typography> </Card> <Card sx={{ padding: 2, width: '100%', mb: 2 }}> <Typography variant="subtitle1">THÔNG TIN THANH TOÁN</Typography> <Typography variant="subtitle2">Ví Crypto: {userData.cryptoWallet || 'Chưa cài đặt'}</Typography> <Box sx={{ mt: 1 }}> <Typography variant="subtitle2">Thẻ Ngân Hàng</Typography> {userData.bankAccount ? ( <Typography> {`${userData.bankAccount.accountNumber || 'Not set'} - ${userData.bankAccount.bankName || 'Not set'} - ${userData.bankAccount.holderName || 'Not set'}`} </Typography> ) : ( <Box> <TextField label="Số Tài Khoản" value={bankAccount.accountNumber} onChange={(e) => setBankAccount({ ...bankAccount, accountNumber: e.target.value })} fullWidth margin="normal" /> <TextField label="Ngân Hàng" value={bankAccount.bankName} onChange={(e) => setBankAccount({ ...bankAccount, bankName: e.target.value })} fullWidth margin="normal" /> <TextField label="Tên Tài Khoản" value={bankAccount.holderName} onChange={(e) => setBankAccount({ ...bankAccount, holderName: e.target.value })} fullWidth margin="normal" /> <Button variant="contained" color="primary" onClick={handleSaveBankAccount} sx={{ mt: 2 }}> Lưu Thông Tin </Button> </Box> )} </Box> </Card> <Card sx={{ padding: 2, width: '100%', mb: 2 }}> <Typography variant="subtitle1">Referral Information</Typography> {referrer && ( <Typography variant="body2" sx={{ color: '#4CAF50', mb: 2 }}> You were referred by user {referrer} </Typography> )} <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}> <Button variant="contained" color="primary" onClick={handleInviteFriend} sx={{ py: 1, px: 2 }} > Invite Friend </Button> <Button variant="contained" color="success" onClick={handleCopyReferralLink} sx={{ py: 1, px: 2 }} > Copy Invite Link </Button> </Box> {referrals.length > 0 && ( <Box sx={{ mt: 4 }}> <Typography variant="h6" sx={{ mb: 2 }}> Your Referrals </Typography> <List> {referrals.map((referral, index) => ( <ListItem key={index} sx={{ bgcolor: '#f5f5f5', mb: 1, borderRadius: 1 }}> <ListItemText primary={`User ${index + 1}: ${referral}`} /> </ListItem> ))} </List> </Box> )} </Card> <Modal open={openModal} onClose={handleCloseModal} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}> <Box sx={{ bgcolor: 'background.paper', p: 4, borderRadius: 2, width: '90%', maxWidth: 400, position: 'relative' }}> <IconButton onClick={handleCloseModal} sx={{ position: 'absolute', top: 8, right: 8 }}> <FaTimes /> </IconButton> <Typography variant="h6" gutterBottom> Referral Details </Typography> <List> {userData.referrals.referredUsers.map((referredUser, index) => ( <ListItem key={index}> <ListItemText primary={`User ${index + 1}: ${referredUser}`} /> </ListItem> ))} <ListItem> <ListItemText primary={`Referral Points: ${userData.referrals.referralPoints}`} /> </ListItem> </List> </Box> </Modal> </Box> ); }; export default ProfileTab;

Prompt

About

DefaultComponent - Easily display custom information with flexible layouts and styles, built with React and MUI. Start coding now!

Share

Last updated 1 month ago