feat:Fixed all the UI Pages

This commit is contained in:
2025-03-26 21:31:14 +05:30
parent aba9651c43
commit b961ef8fd3
27 changed files with 232 additions and 125 deletions
+2 -2
View File
@@ -6,7 +6,7 @@ import { BACKEND_URL } from "../constants";
const Navbar = () => {
const user = useSelector((store) => store.user);
//console.log("User is : ", user);
const navigate = useNavigate();
@@ -18,7 +18,7 @@ const Navbar = () => {
const data = await responce.json();
//console.log("User Logged out data is : ", data);
if (data.success == true) {
navigate("/user/login");
+2 -2
View File
@@ -5,7 +5,7 @@ import { Link } from "react-router-dom";
const Navbar2 = () => {
const user = useSelector((store) => store.user);
console.log("User is : ", user);
const [isLoggedIn, setLoggedIn] = useState(false);
@@ -23,7 +23,7 @@ const Navbar2 = () => {
const user = await responce.json();
//console.log("User Login Data is here : ", user);
dispatch(userSliceActions.addUser(user.data));
};
+2 -2
View File
@@ -6,7 +6,7 @@ const Notification = ({ notification }) => {
// const dateStr = "2024-09-26T04:31:50.646+00:00";
const date = new Date(dateStr);
const dayName = date.toLocaleDateString("en-US", { weekday: "long" });
//console.log(dayName);
return dayName;
};
@@ -27,7 +27,7 @@ const Notification = ({ notification }) => {
};
const istDate = date.toLocaleString("en-US", options);
//console.log(istDate); // Output: "September 26, 2024, 10:01:50 AM"
return istDate;
};
+1 -1
View File
@@ -22,7 +22,7 @@ const TotalSpent = () => {
}
}, [farmList]);
console.log("My farm list is : ", farmList);
return (
<div className="h-full">
<a
@@ -1,5 +1,5 @@
// PerformanceChart.jsx
import React from "react";
import React, { useEffect, useState } from "react";
import { Line } from "react-chartjs-2";
import {
Chart as ChartJS,
@@ -11,6 +11,7 @@ import {
Tooltip,
Legend,
} from "chart.js";
import { useGetFarmsQuery } from "../../store/api/farmApi";
ChartJS.register(
CategoryScale,
@@ -22,7 +23,35 @@ ChartJS.register(
Legend
);
const calculateSpend = (farmList) => {
let totalSpend = [];
for (let i = 0; i < farmList.length; i++) {
if (!farmList[i]) continue;
if (!farmList[i]?.finances) continue;
if (!farmList[i]?.finances?.transactions) continue;
for (let j = 0; j < farmList[i]?.finances?.transactions.length; j++) {
if (!farmList[i]?.finances?.transactions[j]) continue;
if (!farmList[i]?.finances?.transactions[j]?.amount) continue;
if (farmList[i]?.finances?.transactions[j]?.type == "Revenue") continue;
totalSpend.push(farmList[i]?.finances?.transactions[j]?.amount);
}
}
return totalSpend;
};
const PerformanceChart = () => {
const [totalSpend, setTotalSpend] = useState(0);
const [spentList, setSpentList] = useState([]);
const { data: farmList, isLoading, error } = useGetFarmsQuery();
useEffect(() => {
if (!isLoading && !error && farmList) {
setTotalSpend(calculateSpend(farmList));
setSpentList(calculateSpend(farmList));
}
}, [farmList]);
const data = {
labels: [
"Jan",
@@ -40,8 +69,8 @@ const PerformanceChart = () => {
],
datasets: [
{
label: "Yield",
data: [75, 68, 85, 88, 60, 62, 78, 90, 95, 92, 88, 80], // slightly improved values
label: "Expences",
data: spentList, // slightly improved values
fill: false,
backgroundColor: "rgb(75, 192, 192)",
borderColor: "rgba(75, 192, 192, 0.2)",
@@ -53,7 +82,7 @@ const PerformanceChart = () => {
responsive: true,
plugins: {
legend: { position: "top" },
title: { display: true, text: "Performance Trend" },
title: { display: true, text: "Expences Tracking " },
},
};
@@ -0,0 +1,96 @@
// PerformanceChart.jsx
import React, { useEffect, useState } from "react";
import { Line } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from "chart.js";
import { useGetFarmsQuery } from "../../store/api/farmApi";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
const calculateSpend = (farmList) => {
let totalSpend = [];
for (let i = 0; i < farmList.length; i++) {
if (!farmList[i]) continue;
if (!farmList[i]?.finances) continue;
if (!farmList[i]?.finances?.transactions) continue;
for (let j = 0; j < farmList[i]?.finances?.transactions.length; j++) {
if (!farmList[i]?.finances?.transactions[j]) continue;
if (!farmList[i]?.finances?.transactions[j]?.amount) continue;
if (farmList[i]?.finances?.transactions[j]?.type == "Expense") continue;
totalSpend.push(farmList[i]?.finances?.transactions[j]?.amount);
}
}
return totalSpend;
};
const PerformanceChart2 = () => {
const [totalSpend, setTotalSpend] = useState(0);
const [spentList, setSpentList] = useState([]);
const { data: farmList, isLoading, error } = useGetFarmsQuery();
useEffect(() => {
if (!isLoading && !error && farmList) {
setTotalSpend(calculateSpend(farmList));
setSpentList(calculateSpend(farmList));
}
}, [farmList]);
const data = {
labels: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
],
datasets: [
{
label: "Expences",
data: spentList, // slightly improved values
fill: false,
backgroundColor: "rgb(75, 192, 192)",
borderColor: "rgba(75, 192, 192, 0.2)",
},
],
};
const options = {
responsive: true,
plugins: {
legend: { position: "top" },
title: { display: true, text: "Expences Tracking " },
},
};
return <Line data={data} options={options} />;
};
export default PerformanceChart2;
+2 -2
View File
@@ -7,7 +7,7 @@ import { Link } from "react-router-dom";
export const HeroSecn = () => {
const user = useSelector((store) => store.user);
console.log("User is : ", user);
const [isLoggedIn, setLoggedIn] = useState(false);
@@ -25,7 +25,7 @@ export const HeroSecn = () => {
const user = await responce.json();
//console.log("User Login Data is here : ", user);
dispatch(userSliceActions.addUser(user.data));
};
+1 -1
View File
@@ -28,7 +28,7 @@ const LoginPage = () => {
const user = await responce.json();
//console.log("User Login Data is here : ", user);
dispatch(userSliceActions.addUser(user.data));
+1 -1
View File
@@ -33,7 +33,7 @@ const SignupPage = () => {
});
const data = await responce.json();
//console.log("Our user data is : ", data);
firstNameElement.current.value = "";
lastNameElement.current.value = "";
@@ -14,7 +14,7 @@ const ResetPassword = () => {
const { token } = useParams();
// console.log("So our Token is : ", token);
const handleResetPassword = async (event) => {
event.preventDefault();
@@ -41,7 +41,7 @@ const ResetPassword = () => {
const data = await responce.json();
//console.log("Status of the Reset password", data);
if (data.success === true) {
navigate("/user/login");
@@ -30,7 +30,7 @@ const AddCrop = ({ farmId }) => {
if (image) {
formData.append("image", image);
}
console.log(formData);
try {
const response = await createCrop(formData);
// const response = await fetch(`http://localhost:8000/api/v1/crop`, {
@@ -42,7 +42,7 @@ const AddCrop = ({ farmId }) => {
// throw new Error("Failed to create crop");
// }
console.log(response);
setSuccess("Crop created successfully!");
// Reset form fields
setName("");
@@ -24,11 +24,11 @@ const AddFarm = () => {
size: sizeContent,
};
console.log(farmData);
try {
const res = await createFarm(farmData);
console.log(res);
if (res.error) {
return null;
@@ -21,7 +21,7 @@ const AddTransaction = ({ farmId, financeId }) => {
amount: parseFloat(amount),
description,
};
console.log("Transaction data:", transactionData);
try {
const response = await addTransaction({ financeId, transactionData });
@@ -46,7 +46,7 @@ const AddTransaction = ({ farmId, financeId }) => {
// }
// const data = await response.json();
console.log("Transaction created:", response);
setMessage("Transaction created successfully!");
// Optionally clear the form
setType("Expense");
@@ -30,7 +30,7 @@ const CreateTask = ({ farmId, onTaskCreated }) => {
status,
};
console.log("Task Data is worked : ", taskData);
try {
const res = await createTask(taskData).unwrap();
@@ -1,15 +1,27 @@
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import Loader from "../../../components/Loader";
import { useParams } from "react-router-dom";
import { useCreateFinanceMutation } from "../../../store/api/financeApi";
import { useGetFarmByIdQuery } from "../../../store/api/farmApi";
const CreateFinance = () => {
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState("");
const [farm, setFarm] = useState("");
// Hardcoded farm ID from your example
const { farmId } = useParams();
const [createFinance] = useCreateFinanceMutation();
const { data: farmData, isLoading, error } = useGetFarmByIdQuery(farmId);
useEffect(() => {
if (!isLoading && !error && farmData) {
setFarm(farmData);
}
}, [farmData]);
const handleCreateFinance = async () => {
setLoading(true);
setMessage("");
@@ -24,12 +36,12 @@ const CreateFinance = () => {
// body: JSON.stringify({ farm: farmId }),
// });
console.log("Trance opdien ", responce);
if (!response.ok) {
throw new Error("Failed to create finance");
}
const data = await response.json();
console.log("Finance response:", data);
setMessage("Finance created successfully!");
} catch (error) {
console.error("Error creating finance:", error);
@@ -38,7 +38,7 @@ export default function CropPage() {
const farmId = cropId;
console.log("Farm id is : ", farmId);
const { data: farm, error, isLoading } = useGetFarmByIdQuery(farmId);
const {
@@ -54,14 +54,14 @@ export default function CropPage() {
}
}, [farm]);
console.log("djoejwrru9", crop);
const {
data: harvest,
isLoading: harvestLoading,
error: harvestError,
} = useCropHarvestQuery(cropId);
console.log("Haraufugfudg : ", harvest);
const {
data: pesticides,
@@ -16,7 +16,7 @@ const CropTable = ({ farmId }) => {
isLoading: cropsLoading,
} = useGetCropsByFarmQuery(farmId);
console.log("Crops data is :", cropsData);
const handleRemoveCrop = async (cropId) => {
try {
await fetch(`http://localhost:8000/api/v1/crop/${cropId}`, {
@@ -13,7 +13,7 @@ const DisplayTast = ({ farmId }) => {
isLoading,
} = useGetTasksByFarmQuery(farmId);
console.log("Task list is : ", taskList);
// Function to delete a task and update the state
const handleDeleteTask = async (taskId) => {
@@ -32,7 +32,7 @@ const DisplayTast = ({ farmId }) => {
// Optionally check the response, but we'll update state regardless.
// Remove the deleted task from state.
setTasks((prevTasks) => prevTasks.filter((task) => task._id !== taskId));
console.log(`Task ${taskId} deleted successfully.`);
} catch (error) {
console.error("Error deleting task:", error);
// Optionally, you could set an error state here.
@@ -14,7 +14,7 @@ const EditFarm = ({ _id, onDelete }) => {
// credentials: "include",
// });
// const data = await response.json();
console.log("Delete response:", res);
if (!res) {
return null;
+2 -37
View File
@@ -17,7 +17,7 @@ export default function FarmPage() {
const [farmData, setFarmData] = useState("");
const [loading, setLoading] = useState(true);
console.log("Farm id is : ", farmId);
const { data: farm, error, isLoading } = useGetFarmByIdQuery(farmId);
@@ -28,46 +28,11 @@ export default function FarmPage() {
}
}, [farm]);
console.log("djoejwrru9", farmData);
// useEffect(() => {
// async function fetchFarmData() {
// try {
// const response = await fetch(
// `http://localhost:8000/api/v1/farm/${farmId}`,
// {
// method: "GET",
// credentials: "include",
// headers: {
// "Content-Type": "application/json",
// },
// }
// );
// const jsonData = await response.json();
// console.log("Fetched farm data:", jsonData);
// setFarmData(jsonData);
// } catch (error) {
// console.error("Error fetching farm data: ", error);
// } finally {
// setLoading(false);
// }
// }
// fetchFarmData();
// }, [farmId]);
// if (loading) {
// return <Loader />;
// }
// if (!farmData) {
// return (
// <div className="w-full bg-white rounded-lg shadow p-4">
// <p>No farm data found.</p>
// </div>
// );
// }
console.log("Backend URI ", import.meta.env.VITE_API_URL);
return (
<div className="w-full bg-white rounded-lg shadow p-4 space-y-8">
@@ -20,7 +20,7 @@ const FinanceSummary = ({ farmId, financeId }) => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
console.log("Finance id /mljkfgj is : ", financeId);
const {
data: transaction,
@@ -28,7 +28,7 @@ const FinanceSummary = ({ farmId, financeId }) => {
isLoading,
} = useGetTransactionsQuery(financeId);
console.log("Transaction data is : ", transaction);
useEffect(() => {
const fetchSummary = async () => {
@@ -39,7 +39,7 @@ const FinanceSummary = ({ farmId, financeId }) => {
`http://localhost:8000/api/v1/finance/summary/${financeId}`,
{ credentials: "include" }
);
console.log("Summary response:", response);
if (!response.ok) {
throw new Error("Failed to fetch summary");
}
@@ -13,7 +13,7 @@ const Transactions = ({ farmId }) => {
.then((response) => response.json())
.then((data) => {
setData(data);
console.log("Fetched data:", data);
setLoading(false);
})
.catch((error) => {
@@ -25,7 +25,7 @@ const MainUserPanel = () => {
const data = await responce.json();
//console.log("User Logged out data is : ", data);
if (data.success === true) {
navigate("/user/login");
@@ -20,14 +20,14 @@ const MentorSessionCard = ({ session }) => {
const user = useSelector((store) => store.user);
//console.log("User in the Dashborde : ");
let timeStringToDayName = (dateStr) => {
// for getting day name by time string
// const dateStr = "2024-09-26T04:31:50.646+00:00";
const date = new Date(dateStr);
const dayName = date.toLocaleDateString("en-US", { weekday: "long" });
//console.log(dayName);
return dayName;
};
@@ -48,7 +48,7 @@ const MentorSessionCard = ({ session }) => {
};
const istDate = date.toLocaleString("en-US", options);
console.log(istDate); // Output: "September 26, 2024, 10:01:50 AM"
return istDate;
};
+44 -8
View File
@@ -5,31 +5,67 @@ import PerformanceChart from "../../components/monitoring charts/PerformanceChar
import AlertsPanel from "../../components/monitoring charts/AlertsPanel";
import ActivityFeed from "../../components/monitoring charts/ActivityField";
import Piechart from "../../components/monitoring charts/Piechart";
import { useGetFarmsQuery } from "../../store/api/farmApi";
import PerformanceChart2 from "../../components/monitoring charts/PerformanceChart2";
const calculateSpend = (farms) => {
let totalSpend = 0;
for (let i = 0; i < farms.length; i++) {
if (!farms[i]) continue;
if (!farms[i]?.finances) continue;
if (!farms[i]?.finances?.totalExpenses) continue;
totalSpend += farms[i]?.finances?.totalExpenses;
}
return totalSpend;
};
const calculateRevenue = (farms) => {
let totalSpend = 0;
for (let i = 0; i < farms.length; i++) {
if (!farms[i]) continue;
if (!farms[i]?.finances) continue;
if (!farms[i]?.finances?.totalRevenue) continue;
totalSpend += farms[i]?.finances?.totalRevenue;
}
return totalSpend;
};
const MonitoringPage = () => {
const { data: farms, error, isLoading } = useGetFarmsQuery();
return (
<div className="w-full bg-white rounded-lg shadow p-4">
<div className="p-6">
{/* Summary Metrics */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
<MetricsCard title="Active Farms" value="12" />
<MetricsCard title="Total Yield" value="3500 kg" />
<MetricsCard title="Alerts" value="3" />
<MetricsCard title="Active Farms" value={farms?.length} />
<MetricsCard
title="Total Expence"
value={farms && calculateSpend(farms)}
/>
<MetricsCard
title="Total Revenue"
value={farms && calculateRevenue(farms)}
/>
<MetricsCard title="Uptime" value="99.9%" />
</div>
{/* Performance Trend Chart */}
<div className="mb-6 bg-white p-4 rounded-lg shadow">
<h2 className="text-lg font-semibold mb-2">Performance Trend</h2>
<h2 className="text-lg font-semibold mb-2">Expence Trend</h2>
<PerformanceChart />
<h2 className="text-lg font-semibold mb-2 mt-10">Revenue Trend</h2>
<PerformanceChart2 />
</div>
<div className="mb-6 bg-white p-4 rounded-lg shadow">
{/* <div className="mb-6 bg-white p-4 rounded-lg shadow">
<h2 className="text-lg font-semibold mb-2">Performance Trend</h2>
<Piechart></Piechart>
</div>
</div> */}
{/* Alerts and Activity Feed */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="bg-white p-4 rounded-lg shadow">
<h2 className="text-lg font-semibold mb-2">Alerts</h2>
<AlertsPanel />
@@ -38,7 +74,7 @@ const MonitoringPage = () => {
<h2 className="text-lg font-semibold mb-2">Recent Activity</h2>
<ActivityFeed />
</div>
</div>
</div> */}
</div>
</div>
);
@@ -75,29 +75,7 @@ const Notifications = () => {
},
];
// for getting day name by time string
// const dateStr = '2024-09-26T04:31:50.646+00:00';
// const date = new Date(dateStr);
// const dayName = date.toLocaleDateString('en-US', { weekday: 'long' });
// console.log(dayName); // Output: "Thursday"
// for converting the to get time in am or pm
// const utcDateStr = '2024-09-26T04:31:50.646+00:00';
// const date = new Date(utcDateStr);
// India TimeZone is Asia/Kolkata, which is UTC+5:30
// const options = {
// timeZone: 'Asia/Kolkata',
// hour: 'numeric',
// minute: 'numeric',
// second: 'numeric',
// hour12: true,
// year: 'numeric',
// month: 'long',
// day: 'numeric'
// };
// const istDate = date.toLocaleString('en-US', options);
// console.log(istDate); // Output: "September 26, 2024, 10:01:50 AM"
return (
<>
+4 -13
View File
@@ -18,8 +18,6 @@ const Settings = () => {
const loader = useSelector((store) => store.loader);
//console.log("Before the user is : ", user);
const dispatch = useDispatch();
// Optimise the call for the database here you are refreshing the page again and again which makes read and write operation
@@ -27,11 +25,9 @@ const Settings = () => {
event.preventDefault();
formData.append("avatar", avatar);
//console.log("forma daata is : ", formData);
if (avatar) {
dispatch(loaderSliceActions.showLoader());
//console.log("The loader values is : ", loader);
const responce = await fetch(`${BACKEND_URL}/api/v1/user/avatar`, {
method: "PUT",
credentials: "include",
@@ -40,13 +36,11 @@ const Settings = () => {
const finalResponce = await responce.json();
//console.log("Our final responce is : ", finalResponce);
if (finalResponce.success) {
dispatch(loaderSliceActions.hideLoader());
//console.log("The loader values is : ", loader);
dispatch(userSliceActions.addUser(finalResponce.data));
// console.log("Updated User is : ", user);
window.location.reload();
}
}
@@ -68,8 +62,6 @@ const Settings = () => {
const user = await responce.json();
//console.log("User Login Data is here : ", user);
dispatch(userSliceActions.addUser(user.data));
emailElement.current.value = "";
@@ -90,7 +82,7 @@ const Settings = () => {
<div className="w-full h-auto flex items-center justify-center py-7">
<div className="w-[9rem] h-[9rem] overflow-hidden rounded-full object-center">
<img src={`${user.avatar}`} alt="Avatar" />
<img src={`/images/default1.png`} alt="Avatar" />
</div>
</div>
</div>
@@ -144,7 +136,6 @@ const Settings = () => {
className="hidden"
onChange={(e) => {
setAvatar(e.target.files[0]);
//console.log(e.target.files[0]);
}}
/>
</label>