1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { auth, firestore } from '../firebase/firebaseConfig';
import { getStorage, ref, uploadBytes, deleteObject } from "firebase/storage";
import { collection, getDocs, addDoc, deleteDoc, doc } from "firebase/firestore";
import { Bar } from 'react-chartjs-2';
const Dashboard = () => {
const history = useHistory();
const [ads, setAds] = useState([]);
const [views, setViews] = useState([]);
const storage = getStorage();
const adsCollectionRef = collection(firestore, "ads");
useEffect(() => {
const fetchAds = async () => {
const adsSnapshot = await getDocs(adsCollectionRef);
setAds(adsSnapshot.docs.map(doc => ({ ...doc.data(), id: doc.id })));
};
const fetchViews = async () => {
// Assume we have a 'views' collection to track ad views
const viewsSnapshot = await getDocs(collection(firestore, "views"));
setViews(viewsSnapshot.docs.map(doc => doc.data()));
};
fetchAds();
fetchViews();
}, []);
const handleLogout = () => {
auth.signOut();
localStorage.removeItem('token');
history.push('/login');
};
const handleUpload = async (event) => {
const file = event.target.files[0];
const storageRef = ref(storage, `ads/${file.name}`);
await uploadBytes(storageRef, file);
await addDoc(adsCollectionRef, { name: file.name, url: `ads/${file.name}` });
setAds([...ads, { name: file.name, url: `ads/${file.name}` }]);
};
const handleDelete = async (id, url) => {
const storageRef = ref(storage, url);
await deleteObject(storageRef);
await deleteDoc(doc(firestore, "ads", id));
setAds(ads.filter(ad => ad.id !== id));
};
const viewData = {
labels: ads.map(ad => ad.name),
datasets: [
{
label: 'Ad Views',
data: views.map(view => view.count),
backgroundColor: 'rgba(75, 192, 192, 0.6)',
},
],
};
return (
<div>
<h2>Dashboard</h2>
<button onClick={handleLogout}>Logout</button>
<input type="file" onChange={handleUpload} />
<div>
{ads.map(ad => (
<div key={ad.id}>
<p>{ad.name}</p>
<button onClick={() => handleDelete(ad.id, ad.url)}>Delete</button>
</div>
))}
</div>
<div>
<Bar data={viewData} />
</div>
</div>
);
};
export default Dashboard;
|