Create and Test User and Farm Routes

This commit is contained in:
2025-02-22 17:03:24 +05:30
parent 1fdb739950
commit 330589bdf1
14 changed files with 617 additions and 27 deletions
+128
View File
@@ -0,0 +1,128 @@
import Crop from "../models/cropModel.js";
import Farm from "../models/farmModel.js";
// Create a new crop
export const createCrop = async (req, res) => {
try {
const { name, farm, image, harvestDate, growthStage, healthStatus } =
req.body;
// Check if the farm exists
const existingFarm = await Farm.findById(farm);
if (!existingFarm)
return res.status(404).json({ message: "Farm not found" });
const crop = new Crop({
name,
farm,
image,
harvestDate,
growthStage,
healthStatus,
});
await crop.save();
// Add crop to farm
existingFarm.crops.push(crop._id);
await existingFarm.save();
res.status(201).json(crop);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Get all crops for a specific farm
export const getCropsByFarm = async (req, res) => {
try {
const crops = await Crop.find({ farm: req.params.farmId });
res.status(200).json(crops);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Get a single crop by ID
export const getCropById = async (req, res) => {
try {
const crop = await Crop.findById(req.params.cropId).populate("farm");
if (!crop) return res.status(404).json({ message: "Crop not found" });
res.status(200).json(crop);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Update crop details
export const updateCrop = async (req, res) => {
try {
const updatedCrop = await Crop.findByIdAndUpdate(
req.params.cropId,
req.body,
{ new: true }
);
if (!updatedCrop)
return res.status(404).json({ message: "Crop not found" });
res.status(200).json(updatedCrop);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Delete a crop
export const deleteCrop = async (req, res) => {
try {
const crop = await Crop.findById(req.params.cropId);
if (!crop) return res.status(404).json({ message: "Crop not found" });
await crop.deleteOne();
// Remove crop from the farm
await Farm.findByIdAndUpdate(crop.farm, { $pull: { crops: crop._id } });
res.status(200).json({ message: "Crop deleted successfully" });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Update crop growth stage
export const updateGrowthStage = async (req, res) => {
try {
const { growthStage } = req.body;
const crop = await Crop.findById(req.params.cropId);
if (!crop) return res.status(404).json({ message: "Crop not found" });
crop.growthStage = growthStage;
await crop.save();
res.status(200).json({ message: "Growth stage updated", crop });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Update crop health status
export const updateHealthStatus = async (req, res) => {
try {
const { healthStatus } = req.body;
const crop = await Crop.findById(req.params.cropId);
if (!crop) return res.status(404).json({ message: "Crop not found" });
crop.healthStatus = healthStatus;
await crop.save();
res.status(200).json({ message: "Health status updated", crop });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
+130
View File
@@ -0,0 +1,130 @@
const Farm = require("../Models/farm.model.js");
const Crop = require("../Models/crop.model.js");
const Finance = require("../Models/finance.model.js");
// Create a farm
const createFarm = async (req, res) => {
try {
const { name, location, waterContent, soilType } = req.body;
const farm = new Farm({
name,
location,
waterContent,
soilType,
owner: req.user._id,
});
await farm.save();
res.status(201).json(farm);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Get all farms for a user
const getUserFarms = async (req, res) => {
try {
const farms = await Farm.find({ owner: req.user._id })
.populate("crops")
.populate("finances");
res.status(200).json(farms);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Get a single farm by ID
const getFarmById = async (req, res) => {
try {
const farm = await Farm.findById(req.params.farmId)
.populate("crops")
.populate("finances");
if (!farm) return res.status(404).json({ message: "Farm not found" });
res.status(200).json(farm);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Update farm details
const updateFarm = async (req, res) => {
try {
const updatedFarm = await Farm.findByIdAndUpdate(
req.params.farmId,
req.body,
{ new: true }
);
if (!updatedFarm)
return res.status(404).json({ message: "Farm not found" });
res.status(200).json(updatedFarm);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Delete a farm
const deleteFarm = async (req, res) => {
try {
const farm = await Farm.findById(req.params.farmId);
if (!farm) return res.status(404).json({ message: "Farm not found" });
await Crop.deleteMany({ farm: farm._id });
await Finance.findByIdAndDelete(farm.finances);
await farm.deleteOne();
res.status(200).json({ message: "Farm deleted successfully" });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Add fertilizer to a farm
const addFertilizer = async (req, res) => {
try {
const { name, quantity } = req.body;
const farm = await Farm.findById(req.params.farmId);
if (!farm) return res.status(404).json({ message: "Farm not found" });
farm.fertilizer.push({ name, quantity });
await farm.save();
res.status(200).json({ message: "Fertilizer added", farm });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Add pesticide to a farm
const addPesticide = async (req, res) => {
try {
const { name, quantity } = req.body;
const farm = await Farm.findById(req.params.farmId);
if (!farm) return res.status(404).json({ message: "Farm not found" });
farm.pestisides.push({ name, quantity });
await farm.save();
res.status(200).json({ message: "Pesticide added", farm });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
module.exports = {
createFarm,
getUserFarms,
getFarmById,
updateFarm,
deleteFarm,
addFertilizer,
addPesticide,
};
+126
View File
@@ -0,0 +1,126 @@
import Finance from "../models/financeModel.js";
import Farm from "../models/farmModel.js";
// Create finance record for a farm
export const createFinance = async (req, res) => {
try {
const { farm } = req.body;
// Check if the farm exists
const existingFarm = await Farm.findById(farm);
if (!existingFarm)
return res.status(404).json({ message: "Farm not found" });
const finance = new Finance({
farm,
transactions: [],
totalExpenses: 0,
totalRevenue: 0,
});
await finance.save();
// Link finance to farm
existingFarm.finances = finance._id;
await existingFarm.save();
res.status(201).json(finance);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Get finance details by farm ID
export const getFinanceByFarm = async (req, res) => {
try {
const finance = await Finance.findOne({ farm: req.params.farmId });
if (!finance)
return res.status(404).json({ message: "Finance record not found" });
res.status(200).json(finance);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Add a transaction (expense/revenue)
export const addTransaction = async (req, res) => {
try {
const { type, amount, description } = req.body;
const finance = await Finance.findById(req.params.financeId);
if (!finance)
return res.status(404).json({ message: "Finance record not found" });
finance.transactions.push({ type, amount, description });
// Update totals
if (type === "Expense") {
finance.totalExpenses += amount;
} else if (type === "Revenue") {
finance.totalRevenue += amount;
}
await finance.save();
res.status(200).json({ message: "Transaction added", finance });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Delete a transaction
export const deleteTransaction = async (req, res) => {
try {
const finance = await Finance.findById(req.params.financeId);
if (!finance)
return res.status(404).json({ message: "Finance record not found" });
const transaction = finance.transactions.id(req.params.transactionId);
if (!transaction)
return res.status(404).json({ message: "Transaction not found" });
// Adjust totals before removing
if (transaction.type === "Expense") {
finance.totalExpenses -= transaction.amount;
} else if (transaction.type === "Revenue") {
finance.totalRevenue -= transaction.amount;
}
transaction.remove();
await finance.save();
res.status(200).json({ message: "Transaction deleted", finance });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Get all transactions for a farm's finance
export const getTransactions = async (req, res) => {
try {
const finance = await Finance.findById(req.params.financeId);
if (!finance)
return res.status(404).json({ message: "Finance record not found" });
res.status(200).json(finance.transactions);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Get total expenses and revenue
export const getFinancialSummary = async (req, res) => {
try {
const finance = await Finance.findById(req.params.financeId);
if (!finance)
return res.status(404).json({ message: "Finance record not found" });
res.status(200).json({
totalExpenses: finance.totalExpenses,
totalRevenue: finance.totalRevenue,
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};
+111
View File
@@ -0,0 +1,111 @@
import Task from "../models/taskModel.js";
import Farm from "../models/farmModel.js";
import Crop from "../models/cropModel.js";
// Create a new task
export const createTask = async (req, res) => {
try {
const { farm, crop, taskType, description, assignedDate, status } =
req.body;
// Validate farm existence
const existingFarm = await Farm.findById(farm);
if (!existingFarm)
return res.status(404).json({ message: "Farm not found" });
// Validate crop if provided
if (crop) {
const existingCrop = await Crop.findById(crop);
if (!existingCrop)
return res.status(404).json({ message: "Crop not found" });
}
const task = new Task({
farm,
crop,
taskType,
description,
assignedDate,
status,
});
await task.save();
res.status(201).json(task);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Get all tasks for a specific farm
export const getTasksByFarm = async (req, res) => {
try {
const tasks = await Task.find({ farm: req.params.farmId }).populate("crop");
res.status(200).json(tasks);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Get a single task by ID
export const getTaskById = async (req, res) => {
try {
const task = await Task.findById(req.params.taskId).populate("farm crop");
if (!task) return res.status(404).json({ message: "Task not found" });
res.status(200).json(task);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Update task details
export const updateTask = async (req, res) => {
try {
const updatedTask = await Task.findByIdAndUpdate(
req.params.taskId,
req.body,
{ new: true }
);
if (!updatedTask)
return res.status(404).json({ message: "Task not found" });
res.status(200).json(updatedTask);
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Delete a task
export const deleteTask = async (req, res) => {
try {
const task = await Task.findById(req.params.taskId);
if (!task) return res.status(404).json({ message: "Task not found" });
await task.deleteOne();
res.status(200).json({ message: "Task deleted successfully" });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
// Update task status (Pending → Completed)
export const updateTaskStatus = async (req, res) => {
try {
const { status } = req.body;
const task = await Task.findById(req.params.taskId);
if (!task) return res.status(404).json({ message: "Task not found" });
task.status = status;
await task.save();
res.status(200).json({ message: "Task status updated", task });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
+2
View File
@@ -260,6 +260,8 @@ const resetPassword = catchAsyncErrors(async (req, res) => {
// get user personal details
const getUserDetails = catchAsyncErrors(async (req, res) => {
const user = await User.findById(req.user._id);
if (!user) {