product and pd multiple data upload with error handling done

This commit is contained in:
Sibunnayak 2024-08-09 12:56:01 +05:30
parent 1c4fce921c
commit 23b835cbf0
8 changed files with 152 additions and 76 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -56,7 +56,8 @@ export const uploadProducts = async (req, res) => {
}
const errors = [];
const productsProcessed = [];
const newlyCreated = [];
const updatedProducts = [];
for (let i = 1; i < data.length; i++) {
const row = data[i];
@ -85,12 +86,14 @@ export const uploadProducts = async (req, res) => {
if (!GST) missingFields.add("GST");
// Validate category
let categoryName = "";
if (category) {
const categoryDoc = await CategoryModel.findOne({
categoryName: { $regex: new RegExp(`^${category.trim()}$`, "i") },
}).exec();
if (categoryDoc) {
item.category = categoryDoc._id;
categoryName = categoryDoc.categoryName;
} else {
notFoundErrors.add("category");
}
@ -99,12 +102,14 @@ export const uploadProducts = async (req, res) => {
}
// Validate GST
let gstName = "";
if (GST) {
const gstDoc = await Tax.findOne({
name: { $regex: new RegExp(`^${GST}$`, "i") },
}).exec();
if (gstDoc) {
item.GST = gstDoc._id;
gstName = gstDoc.name;
} else {
notFoundErrors.add("GST");
}
@ -127,6 +132,7 @@ export const uploadProducts = async (req, res) => {
productName: name || "N/A",
category: category || "N/A",
GST: GST || "N/A",
price: price || "N/A",
message: errorMessage.trim(),
});
continue;
@ -142,44 +148,65 @@ export const uploadProducts = async (req, res) => {
}).exec();
if (existingProduct) {
// Validate that the existing product can be updated
const updateErrors = [];
if (missingFields.size > 0) {
updateErrors.push(`Missing fields: ${Array.from(missingFields).join(", ")}`);
// Track changes
const updatedFields = [];
let updatedProduct = { ...existingProduct._doc };
// Fetch existing category name and GST name
const existingCategory = await CategoryModel.findById(existingProduct.category).exec();
const existingGST = await Tax.findById(existingProduct.GST).exec();
if (category && existingProduct.category.toString() !== item.category.toString()) {
updatedFields.push("category");
updatedProduct.category = categoryName;
} else {
updatedProduct.category = existingCategory ? existingCategory.categoryName : "";
}
if (notFoundErrors.size > 0) {
updateErrors.push(`Not found: ${Array.from(notFoundErrors).join(", ")}`);
if (price !== undefined && price !== "" && existingProduct.price !== price) {
updatedFields.push("price");
updatedProduct.price = price;
}
if (GST && existingProduct.GST.toString() !== item.GST.toString()) {
updatedFields.push("GST");
updatedProduct.GST = gstName;
} else {
updatedProduct.GST = existingGST ? existingGST.name : "";
}
if (description !== existingProduct.description) {
updatedFields.push("description");
updatedProduct.description = description;
}
if (special_instructions !== existingProduct.special_instructions) {
updatedFields.push("special_instructions");
updatedProduct.special_instructions = special_instructions;
}
if (updateErrors.length > 0) {
errors.push({
productName: name,
message: updateErrors.join(". "),
});
continue;
}
// Update existing product
try {
await Product.updateOne(
{ _id: existingProduct._id },
{
$set: {
category: item.category || existingProduct.category,
price: price !== undefined && price !== "" ? price : existingProduct.price,
GST: item.GST || existingProduct.GST,
description: description, // Ensure description is included
special_instructions: special_instructions, // Ensure special_instructions is included
product_Status: item.product_Status || existingProduct.product_Status || "Active",
},
}
);
productsProcessed.push({ ...existingProduct._doc, ...item }); // Track updated product
} catch (error) {
errors.push({
productName: name,
message: "Failed to update product",
});
// Only update if there are changes
if (updatedFields.length > 0) {
try {
await Product.updateOne(
{ _id: existingProduct._id },
{
$set: {
category: item.category || existingProduct.category,
price: price !== undefined && price !== "" ? price : existingProduct.price,
GST: item.GST || existingProduct.GST,
description: description,
special_instructions: special_instructions,
product_Status: item.product_Status || existingProduct.product_Status || "Active",
},
}
);
updatedProducts.push({
...updatedProduct,
updatedFields: updatedFields.join(", "), // Track updated fields
});
} catch (error) {
errors.push({
productName: name,
message: "Failed to update product",
});
}
}
continue;
}
@ -191,14 +218,18 @@ export const uploadProducts = async (req, res) => {
category: item.category,
price,
GST: item.GST,
description: description, // Ensure description is included
special_instructions: special_instructions, // Ensure special_instructions is included
description: description,
special_instructions: special_instructions,
product_Status: item.product_Status || "Active",
addedBy: req.user._id,
};
try {
const newProduct = await Product.create(productData);
productsProcessed.push(newProduct); // Track new product
newlyCreated.push({
...newProduct._doc,
category: categoryName,
GST: gstName,
});
} catch (error) {
errors.push({
productName: name,
@ -215,8 +246,11 @@ export const uploadProducts = async (req, res) => {
errors.length > 0
? "Products processed with errors!"
: "Products processed successfully!",
productsProcessed: productsProcessed.length, // Total processed products
newlyCreated: newlyCreated,
updatedProducts: updatedProducts,
errors,
newlyCreated,
updatedProducts,
});
} catch (error) {
console.error("Error:", error);

View File

@ -110,7 +110,8 @@ export const uploadPrincipaldistributors = async (req, res) => {
}
const errors = [];
const processedUsers = [];
const newlyCreated = [];
const updatedDistributors = [];
for (let i = 1; i < data.length; i++) {
const row = data[i];
@ -195,14 +196,76 @@ export const uploadPrincipaldistributors = async (req, res) => {
const currentYear = new Date().getFullYear().toString().slice(-2);
const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase();
item.uniqueId = `${currentYear}-${randomChars}`;
// Check for existing user
let user = await User.findOne({ email: item.email });
if (user) {
// Update existing user details
user.name = item.name;
user.phone = item.phone;
await user.save();
// Track updated fields
const updatedFields = [];
const addressFields = ['panNumber', 'gstNumber', 'state','city', 'street', 'tradeName', 'postalCode'];
const existingAddress = await ShippingAddress.findOne({ user: user._id });
// Check for changes in user details
let userUpdated = false;
if (user.name !== item.name) {
updatedFields.push("name");
user.name = item.name;
userUpdated = true;
}
if (user.phone !== item.phone.toString()) {
updatedFields.push("phone");
user.phone = item.phone;
userUpdated = true;
}
// Update user
if (userUpdated) {
await user.save();
}
// Check for changes in address details
const addressData = {
street: item.street,
city: item.city,
state: item.state,
postalCode: item.postalCode.toString(),
country: "India", // Default country
panNumber: item.panNumber,
tradeName: item.tradeName,
gstNumber: item.gstNumber,
user: user._id,
};
let addressUpdated = false;
if (existingAddress) {
const addressUpdates = [];
addressFields.forEach(field => {
if (existingAddress[field] !== addressData[field]) {
addressUpdates.push(field);
addressUpdated = true;
}
});
if (addressUpdated) {
await ShippingAddress.updateOne({ user: user._id }, addressData);
if (addressUpdates.length > 0) {
updatedFields.push(`Address fields: ${addressUpdates.join(", ")}`);
}
}
} else {
// Create new address
await ShippingAddress.create(addressData);
updatedFields.push("New address created");
}
// Add to updatedDistributors only if there are updated fields
if (updatedFields.length > 0) {
updatedDistributors.push({
...user._doc,
updatedFields: updatedFields.join(", ")
});
}
} else {
// Create a new user
user = new User({
@ -229,35 +292,9 @@ export const uploadPrincipaldistributors = async (req, res) => {
If you have not requested this email, please ignore it.
`,
});
newlyCreated.push(user._doc);
}
// Create or update shipping address
const addressData = {
street: item.street,
city: item.city,
state: item.state,
postalCode: item.postalCode,
country: "India", // Default country
panNumber: item.panNumber,
tradeName: item.tradeName,
gstNumber: item.gstNumber,
user: user._id,
};
let existingAddress = await ShippingAddress.findOne({ user: user._id });
if (existingAddress) {
// Update existing address
await ShippingAddress.updateOne({ user: user._id }, addressData);
} else {
// Create new address
await ShippingAddress.create(addressData);
}
processedUsers.push({
...user._doc,
...addressData,
});
}
fs.unlinkSync(filePath); // Clean up uploaded file
@ -267,12 +304,17 @@ export const uploadPrincipaldistributors = async (req, res) => {
errors.length > 0
? "File processed with errors!"
: "File processed successfully!",
processedUsers: processedUsers.length, // Total processed users
processedUsers: {
newlyCreated: newlyCreated.length,
updatedDistributors: updatedDistributors.length
},
errors,
newlyCreated,
updatedDistributors
});
} catch (error) {
console.error("Error:", error);
res.status(500).json({ message: error.message || "Something went wrong!" });
console.error("Error processing file:", error);
res.status(500).json({ message: "Internal server error" });
}
};