estatesfunding/ef-api/controllers/property.js

290 lines
8.0 KiB
JavaScript
Raw Normal View History

2024-09-12 08:11:07 +00:00
import PropertyModal from "../models/property.js";
import UserModal from "../models/user.js";
import mongoose from "mongoose";
2024-09-15 08:58:40 +00:00
// import { v4 as uuidv4 } from "uuid";
2024-09-12 08:11:07 +00:00
export const createProperty = async (req, res) => {
2024-09-15 08:11:03 +00:00
const propertyData = req.body;
2024-09-22 11:03:36 +00:00
console.log('Property received:', propertyData);
2024-09-16 05:00:05 +00:00
function generateRandomNumber() {
return Math.floor(Math.random() * 90000) + 10000;
}
const randomNumber = generateRandomNumber().toString();
2024-09-22 11:03:36 +00:00
const propertyId = `ELPI${randomNumber}`;
2024-09-15 08:11:03 +00:00
const newProperty = new PropertyModal({
...propertyData,
2024-09-22 11:03:36 +00:00
_id: new mongoose.Types.ObjectId(), // Explicitly generating _id
2024-09-16 05:00:05 +00:00
creator: req.userId,
createdAt: new Date().toISOString(),
publishedAt: new Date().toISOString(),
currentYear: new Date().getFullYear(),
propertyId: propertyId,
2024-09-15 08:11:03 +00:00
});
2024-09-22 11:03:36 +00:00
console.log('newProperty received:', newProperty);
2024-09-15 08:11:03 +00:00
try {
await newProperty.save();
res.status(201).json(newProperty);
} catch (error) {
2024-09-22 11:03:36 +00:00
// Log the full error object to see what's inside
console.log("Error fetching properties:", error);
// Capture and return a meaningful error message
if (error.response && error.response.data) {
return rejectWithValue(error.response.data);
} else {
return rejectWithValue({ message: "Unknown error occurred" });
}
2024-09-15 08:11:03 +00:00
}
};
2024-09-12 08:11:07 +00:00
2024-09-22 11:03:36 +00:00
// Fetch property by userId.. Gets the specific user properties
2024-09-16 10:55:17 +00:00
export const getUserProperties = async (req, res) => {
2024-09-22 11:03:36 +00:00
const { userId } = req.params;
const { page = 1, limit = 10 } = req.query; // Defaults to page 1 and limit 10
const skip = (page - 1) * limit;
2024-09-16 10:55:17 +00:00
try {
2024-09-22 11:03:36 +00:00
const properties = await PropertyModal.find({ userId: userId })
.skip(skip)
.limit(Number(limit));
const total = await PropertyModal.countDocuments({ userId });
const totalPages = Math.ceil(total / limit);
res.json({
properties,
totalPages,
currentPage: Number(page),
});
2024-09-16 10:55:17 +00:00
} catch (error) {
res.status(500).json({ message: "Error retrieving properties", error });
}
2024-09-16 15:03:26 +00:00
};
2024-09-22 11:03:36 +00:00
2024-10-30 14:10:14 +00:00
2024-09-20 11:18:56 +00:00
// Fetch property by ID.. which is property view page
2024-09-16 15:03:26 +00:00
export const getPropertyById = async (req, res) => {
const { propertyId } = req.params;
try {
const property = await PropertyModal.findOne({ propertyId });
res.status(200).json(property);
} catch (error) {
res.status(404).json({ message: "Something went wrong" });
}
};
2024-09-17 14:36:35 +00:00
2024-09-21 19:01:44 +00:00
// Update property by ID..
export const updatePropertyById = async (req, res) => {
const { id } = req.params; // This should be the propertyId
const updateData = req.body;
2024-09-17 14:36:35 +00:00
2024-10-23 17:46:58 +00:00
const { fundValue, fundPercentage } = req.body;
2024-09-21 19:01:44 +00:00
try {
// Find the property by propertyId instead of _id
const updatedProperty = await PropertyModal.findOneAndUpdate(
{ propertyId: id }, // Search by propertyId
updateData,
{ new: true }
);
2024-10-23 17:46:58 +00:00
// Push the new fund details into the existing fundDetails array
updatedProperty.fundDetails.push({
fundValue,
fundPercentage,
});
// Save the updated document
await updatedProperty.save();
console.log("Received propertyId:", updatedProperty); // Log the received propertyId
2024-09-21 19:01:44 +00:00
if (!updatedProperty) {
return res.status(404).json({ message: "Property not found" });
}
res.status(200).json(updatedProperty);
} catch (error) {
console.error("Error updating property:", error.message);
res.status(500).json({ message: "Failed to update property", error: error.message });
}
};
2024-09-25 14:20:59 +00:00
2024-10-23 17:46:58 +00:00
// Function to update fundDetails
export const addFundDetails = async (req, res) => {
const { id } = req.params; // This should be the propertyId
2024-10-25 05:34:27 +00:00
const { fundValue, fundPercentage, userId } = req.body;
2024-10-23 17:46:58 +00:00
2024-10-25 05:34:27 +00:00
console.log("d", id, { fundValue, fundPercentage, userId });
2024-10-23 17:46:58 +00:00
try {
// Change findById to findOne with the correct field name
const property = await PropertyModal.findOne({ propertyId: id });
if (!property) {
return res.status(404).json({ message: 'Property not found' });
}
// Create new fund detail
const newFundDetail = {
fundValue,
fundPercentage,
2024-10-25 05:34:27 +00:00
userId
2024-10-23 17:46:58 +00:00
};
// Add new fund detail to fundDetails array
property.fundDetails.push(newFundDetail);
// Save updated property
await property.save();
// Return success response with updated property
res.status(200).json({ message: 'Fund details added', property });
} catch (error) {
console.error("Error adding fund details:", error); // Log error for debugging
res.status(500).json({ message: error.message });
}
};
2024-10-25 05:34:27 +00:00
export const deleteFundDetail = async (req, res) => {
const { id, fundDetailId } = req.params;
const userId = req.userId;
console.log("Attempting to delete Fund Detail...");
console.log("Property ID:", id);
console.log("Fund Detail ID:", fundDetailId);
console.log("User ID from token:", userId);
try {
const property = await PropertyModal.findOne({ propertyId: id });
if (!property) {
return res.status(404).json({ message: 'Property not found' });
}
console.log("Fund Details:", property.fundDetails);
const fundDetailIndex = property.fundDetails.findIndex(
(detail) => detail._id.toString() === fundDetailId && detail.userId.toString() === userId
);
console.log("Fund Detail Index:", fundDetailIndex);
if (fundDetailIndex === -1) {
return res.status(403).json({ message: 'Not authorized to delete this fund detail' });
}
property.fundDetails.splice(fundDetailIndex, 1);
await property.save();
res.status(200).json({ message: 'Fund detail deleted', property });
} catch (error) {
console.error("Error deleting fund detail:", error);
res.status(500).json({ message: error.message });
}
};
2024-10-23 17:46:58 +00:00
// Getting funds from the DB
export const getFundDetails = async (req, res) => {
const { id } = req.params; // Property ID
try {
const property = await PropertyModal.findOne({ propertyId: id }, 'fundDetails');
if (!property) {
return res.status(404).json({ message: 'Property not found' });
}
// Return fund details
res.status(200).json({ fundDetails: property.fundDetails });
} catch (error) {
console.error("Error fetching fund details:", error);
res.status(500).json({ message: error.message });
}
};
2024-09-26 14:26:23 +00:00
// export const getProperties = async (req, res) => {
// try {
// const properties = await PropertyModal.find(); // Fetch all properties from MongoDB
// res.status(200).json(properties);
// } catch (error) {
// res.status(500).json({ message: "Server error" });
// }
// };
2024-09-28 08:51:29 +00:00
// export const getProperties = async (req, res) => {
// try {
// const { page = 1, limit = 10 } = req.query;
// const skip = (page - 1) * limit;
// const totalProperties = await PropertyModal.countDocuments();
// const properties = await PropertyModal.find()
// .sort({ createdAt: -1 })
// .skip(skip)
// .limit(parseInt(limit));
// res.status(200).json({
// success: true,
// data: properties,
// totalPages: Math.ceil(totalProperties / limit),
// currentPage: parseInt(page), // Include the currentPage in the response
// });
// } catch (err) {
// res.status(500).json({ success: false, message: 'Server error' });
// }
// };
2024-09-25 14:20:59 +00:00
export const getProperties = async (req, res) => {
try {
2024-09-28 08:51:29 +00:00
const { page = 1, limit = 10, keyword = "" } = req.query;
2024-09-26 14:26:23 +00:00
const skip = (page - 1) * limit;
2024-09-28 08:51:29 +00:00
// Use a filter to match the keyword if provided
const keywordFilter = keyword
? { address: { $regex: keyword, $options: "i" } }
: {};
const totalProperties = await PropertyModal.countDocuments(keywordFilter);
const properties = await PropertyModal.find(keywordFilter)
2024-09-26 14:26:23 +00:00
.sort({ createdAt: -1 })
.skip(skip)
.limit(parseInt(limit));
res.status(200).json({
success: true,
data: properties,
totalPages: Math.ceil(totalProperties / limit),
2024-09-28 08:51:29 +00:00
currentPage: parseInt(page),
2024-09-26 14:26:23 +00:00
});
} catch (err) {
res.status(500).json({ success: false, message: 'Server error' });
2024-09-25 14:20:59 +00:00
}
};
2024-09-26 14:26:23 +00:00
2024-09-28 08:51:29 +00:00