update
This commit is contained in:
parent
136daeab74
commit
3bfc1779c5
@ -57,11 +57,6 @@ export const getBrands = async (req, res) => {
|
|||||||
.sort({ createdAt: -1 })
|
.sort({ createdAt: -1 })
|
||||||
.exec();
|
.exec();
|
||||||
|
|
||||||
// If no brands are found, return 404 error
|
|
||||||
if (!brands.length) {
|
|
||||||
return res.status(404).json({ message: "No brands found" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return the paginated and filtered brands list
|
// Return the paginated and filtered brands list
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
|
@ -57,11 +57,6 @@ export const getCategories = async (req, res) => {
|
|||||||
.sort({ createdAt: -1 })
|
.sort({ createdAt: -1 })
|
||||||
.exec();
|
.exec();
|
||||||
|
|
||||||
// If no categories are found, return a 404 error
|
|
||||||
if (!categories.length) {
|
|
||||||
return res.status(404).json({ message: "No categories found" });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return success response with total data and total pages
|
// Return success response with total data and total pages
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
|
@ -557,20 +557,12 @@ export const getAllProductUser = async (req, res) => {
|
|||||||
.sort({ createdAt: -1 })
|
.sort({ createdAt: -1 })
|
||||||
.exec();
|
.exec();
|
||||||
|
|
||||||
// Check if any products were found
|
return res.status(200).json({
|
||||||
if (products && products.length > 0) {
|
success: true,
|
||||||
return res.status(200).json({
|
total_data: total,
|
||||||
success: true,
|
total_pages: Math.ceil(total / PAGE_SIZE),
|
||||||
total_data: total,
|
products,
|
||||||
total_pages: Math.ceil(total / PAGE_SIZE),
|
});
|
||||||
products,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
return res.status(404).json({
|
|
||||||
success: false,
|
|
||||||
msg: "No products found!",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return res.status(500).json({
|
return res.status(500).json({
|
||||||
success: false,
|
success: false,
|
||||||
|
@ -16,322 +16,7 @@ import validator from "validator";
|
|||||||
import ShippingAddress from "../ShippingAddresses/ShippingAddressModel.js";
|
import ShippingAddress from "../ShippingAddresses/ShippingAddressModel.js";
|
||||||
import { generatePassword } from "../../Utils/generatepassword.js";
|
import { generatePassword } from "../../Utils/generatepassword.js";
|
||||||
import { PdOrder } from "../PD_Orders/pdOrderModal.js";
|
import { PdOrder } from "../PD_Orders/pdOrderModal.js";
|
||||||
// const generatePassword = (name, email) => {
|
|
||||||
// // Combine name and email, and convert to lowercase
|
|
||||||
// const combinedStr = (name + email).toLowerCase();
|
|
||||||
|
|
||||||
// // Define character pools
|
|
||||||
// const specialChars = "@#*";
|
|
||||||
// const numbers = "0123456789";
|
|
||||||
// const alphaLower = combinedStr.match(/[a-z]/g) || [];
|
|
||||||
// const alphaUpper = combinedStr.match(/[A-Z]/g) || [];
|
|
||||||
|
|
||||||
// // Ensure at least one character from each category
|
|
||||||
// const specialChar = specialChars.charAt(
|
|
||||||
// Math.floor(Math.random() * specialChars.length)
|
|
||||||
// );
|
|
||||||
// const numberChar = numbers.charAt(Math.floor(Math.random() * numbers.length));
|
|
||||||
// const lowerChar =
|
|
||||||
// alphaLower.length > 0
|
|
||||||
// ? alphaLower[Math.floor(Math.random() * alphaLower.length)]
|
|
||||||
// : String.fromCharCode(Math.floor(Math.random() * 26) + 97);
|
|
||||||
// const upperChar =
|
|
||||||
// alphaUpper.length > 0
|
|
||||||
// ? alphaUpper[Math.floor(Math.random() * alphaUpper.length)]
|
|
||||||
// : String.fromCharCode(Math.floor(Math.random() * 26) + 65);
|
|
||||||
|
|
||||||
// // Combine required characters
|
|
||||||
// let passwordChars = [specialChar, numberChar, lowerChar, upperChar];
|
|
||||||
|
|
||||||
// // Fill remaining positions with random characters from the combined string
|
|
||||||
// const allChars = combinedStr + specialChars + numbers;
|
|
||||||
// while (passwordChars.length < 8) {
|
|
||||||
// passwordChars.push(
|
|
||||||
// allChars.charAt(Math.floor(Math.random() * allChars.length))
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Shuffle characters to ensure randomness
|
|
||||||
// passwordChars = passwordChars.sort(() => Math.random() - 0.5);
|
|
||||||
|
|
||||||
// // Generate password of length 8
|
|
||||||
// const password = passwordChars.slice(0, 8).join("");
|
|
||||||
|
|
||||||
// return password;
|
|
||||||
// };
|
|
||||||
|
|
||||||
// export const uploadPrincipaldistributors = async (req, res) => {
|
|
||||||
// try {
|
|
||||||
// if (!req.files || !req.files.file) {
|
|
||||||
// return res.status(400).json({ message: "No file uploaded" });
|
|
||||||
// }
|
|
||||||
|
|
||||||
// const file = req.files.file;
|
|
||||||
// const filePath = path.join("public", "uploads", file.name);
|
|
||||||
|
|
||||||
// // Ensure 'uploads' directory exists
|
|
||||||
// if (!fs.existsSync(path.dirname(filePath))) {
|
|
||||||
// fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Move the file from temp to the uploads directory
|
|
||||||
// await file.mv(filePath);
|
|
||||||
|
|
||||||
// // Process the file
|
|
||||||
// const fileBuffer = fs.readFileSync(filePath);
|
|
||||||
// const workbook = XLSX.read(fileBuffer, { type: "buffer" });
|
|
||||||
// const sheetName = workbook.SheetNames[0];
|
|
||||||
// const worksheet = workbook.Sheets[sheetName];
|
|
||||||
// const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
|
|
||||||
|
|
||||||
// if (data.length <= 1) {
|
|
||||||
// return res.status(400).json({ message: "Empty spreadsheet or no data found" });
|
|
||||||
// }
|
|
||||||
|
|
||||||
// const headers = data[0];
|
|
||||||
|
|
||||||
// // Map headers from the Excel file to your schema
|
|
||||||
// const headerMapping = {
|
|
||||||
// "PD ID (From SAP)": "uniqueId",
|
|
||||||
// "SBU":"SBU",
|
|
||||||
// "Principal Distributor Name": "name",
|
|
||||||
// "Email": "email",
|
|
||||||
// "Phone Number": "phone",
|
|
||||||
// "PAN Number": "panNumber",
|
|
||||||
// "Trade Name": "tradeName",
|
|
||||||
// "GST Number": "gstNumber",
|
|
||||||
// "State": "state",
|
|
||||||
// "City": "city",
|
|
||||||
// "Street": "street",
|
|
||||||
// "Pincode": "postalCode",
|
|
||||||
// };
|
|
||||||
|
|
||||||
// const requiredHeaders = Object.keys(headerMapping);
|
|
||||||
|
|
||||||
// if (!requiredHeaders.every((header) => headers.includes(header))) {
|
|
||||||
// return res.status(400).json({ message: "Missing required columns in spreadsheet" });
|
|
||||||
// }
|
|
||||||
|
|
||||||
// const errors = [];
|
|
||||||
// const newlyCreated = [];
|
|
||||||
// const updatedDistributors = [];
|
|
||||||
|
|
||||||
// for (let i = 1; i < data.length; i++) {
|
|
||||||
// const row = data[i];
|
|
||||||
// const item = {};
|
|
||||||
|
|
||||||
// headers.forEach((header, index) => {
|
|
||||||
// if (headerMapping[header]) {
|
|
||||||
// item[headerMapping[header]] = row[index] !== undefined ? row[index] : "";
|
|
||||||
// }
|
|
||||||
// });
|
|
||||||
|
|
||||||
// // Initialize error tracking for each item
|
|
||||||
// const missingFields = new Set();
|
|
||||||
// const validationErrors = new Set();
|
|
||||||
|
|
||||||
// // Validate required fields
|
|
||||||
// if (!item.uniqueId) missingFields.add("uniqueId");
|
|
||||||
// if(!item.SBU) missingFields.add("SBU");
|
|
||||||
// if (!item.name) missingFields.add("name");
|
|
||||||
// if (!item.email) missingFields.add("email");
|
|
||||||
// if (!item.phone) missingFields.add("phone");
|
|
||||||
// if (!item.panNumber) missingFields.add("panNumber");
|
|
||||||
// if (!item.tradeName) missingFields.add("tradeName");
|
|
||||||
// if (!item.gstNumber) missingFields.add("gstNumber");
|
|
||||||
// if (!item.state) missingFields.add("state");
|
|
||||||
// if (!item.city) missingFields.add("city");
|
|
||||||
// if (!item.street) missingFields.add("street");
|
|
||||||
// if (!item.postalCode) missingFields.add("postalCode");
|
|
||||||
|
|
||||||
// // Check email validity
|
|
||||||
// if (item.email && !validator.isEmail(item.email)) {
|
|
||||||
// validationErrors.add("incorrect mail");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Validate mobile number
|
|
||||||
// if (item.phone && !/^\d{10}$/.test(item.phone)) {
|
|
||||||
// validationErrors.add("Invalid Mobile Number (should be 10 digits)");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Check GST, PAN, and postal code validation
|
|
||||||
// item.panNumber = item.panNumber ? item.panNumber.toUpperCase() : "";
|
|
||||||
// item.gstNumber = item.gstNumber ? item.gstNumber.toUpperCase() : "";
|
|
||||||
|
|
||||||
// // Validate PAN Number
|
|
||||||
// if (item.panNumber && !/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(item.panNumber)) {
|
|
||||||
// validationErrors.add("Invalid PAN Number");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Validate GST Number
|
|
||||||
// if (item.gstNumber && !/^(\d{2}[A-Z]{5}\d{4}[A-Z]{1}\d[Z]{1}[A-Z\d]{1})$/.test(item.gstNumber)) {
|
|
||||||
// validationErrors.add("Invalid GST Number");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Validate Postal Code
|
|
||||||
// if (item.postalCode && !/^\d{6}$/.test(item.postalCode)) {
|
|
||||||
// validationErrors.add("Invalid Postal Code");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Combine all errors into a single message
|
|
||||||
// let errorMessage = "";
|
|
||||||
// if (missingFields.size > 0) {
|
|
||||||
// errorMessage += `Missing fields: ${Array.from(missingFields).join(", ")}. `;
|
|
||||||
// }
|
|
||||||
// if (validationErrors.size > 0) {
|
|
||||||
// errorMessage += `Validation errors: ${Array.from(validationErrors).join(", ")}.`;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // If there are errors, push them to the errors array
|
|
||||||
// if (errorMessage.trim()) {
|
|
||||||
// errors.push({
|
|
||||||
// uniqueId: item.uniqueId || "N/A",
|
|
||||||
// SBU:item.SBU || "N/A",
|
|
||||||
// name: item.name || "N/A",
|
|
||||||
// email: item.email || "N/A",
|
|
||||||
// phone: item.phone || "N/A",
|
|
||||||
// panNumber: item.panNumber || "N/A",
|
|
||||||
// gstNumber: item.gstNumber || "N/A",
|
|
||||||
// message: errorMessage.trim(),
|
|
||||||
// });
|
|
||||||
// continue;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Generate a password
|
|
||||||
// const password = generatePassword(item.name, item.email);
|
|
||||||
// item.role = "principal-Distributor";
|
|
||||||
|
|
||||||
// // Check for existing user by uniqueId
|
|
||||||
// let distributor = await User.findOne({ uniqueId: item.uniqueId });
|
|
||||||
|
|
||||||
// if (distributor) {
|
|
||||||
// // Track updated fields
|
|
||||||
// const updatedFields = [];
|
|
||||||
// const addressFields = ['panNumber', 'gstNumber', 'state', 'city', 'street', 'tradeName', 'postalCode'];
|
|
||||||
// const existingAddress = await ShippingAddress.findOne({ user: distributor._id });
|
|
||||||
|
|
||||||
// // Check for changes in user details
|
|
||||||
// let userUpdated = false;
|
|
||||||
// if (distributor.name !== item.name) {
|
|
||||||
// updatedFields.push("name");
|
|
||||||
// distributor.name = item.name;
|
|
||||||
// userUpdated = true;
|
|
||||||
// }
|
|
||||||
// if (distributor.email !== item.email) {
|
|
||||||
// updatedFields.push("email");
|
|
||||||
// distributor.email = item.email;
|
|
||||||
// userUpdated = true;
|
|
||||||
// }
|
|
||||||
// if(distributor.SBU !== item.SBU){
|
|
||||||
// updatedFields.push("SBU");
|
|
||||||
// distributor.SBU = item.SBU;
|
|
||||||
// userUpdated = true;
|
|
||||||
// }
|
|
||||||
// if (distributor.phone !== item.phone.toString()) {
|
|
||||||
// updatedFields.push("phone");
|
|
||||||
// distributor.phone = item.phone;
|
|
||||||
// userUpdated = true;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// // Update user
|
|
||||||
// if (userUpdated) {
|
|
||||||
// await distributor.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: distributor._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: distributor._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({
|
|
||||||
// ...distributor._doc,
|
|
||||||
// updatedFields: updatedFields.join(", ")
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// // Create a new user
|
|
||||||
// distributor = new User({
|
|
||||||
// name: item.name,
|
|
||||||
// SBU:item.SBU,
|
|
||||||
// email: item.email,
|
|
||||||
// phone: item.phone,
|
|
||||||
// password,
|
|
||||||
// role: item.role,
|
|
||||||
// uniqueId: item.uniqueId,
|
|
||||||
// });
|
|
||||||
// await distributor.save();
|
|
||||||
|
|
||||||
// // Send email with the new user details
|
|
||||||
// await sendEmail({
|
|
||||||
// to: item.email,
|
|
||||||
// from: process.env.SEND_EMAIL_FROM,
|
|
||||||
// subject: `Cheminova Account Created`,
|
|
||||||
// html: `
|
|
||||||
// Your Principal Distributor Account is created successfully.
|
|
||||||
// <br/>Name: <strong>${item.name}</strong><br/>
|
|
||||||
// <br/>Mobile Number: <strong>${item.phone}</strong><br/>
|
|
||||||
// <br/>Password: <strong>${password}</strong><br/><br/>
|
|
||||||
// <a href="${process.env.PD_APP_URL}/login">Click here to login</a><br/><br/>
|
|
||||||
// If you have not requested this email, please ignore it.
|
|
||||||
// `,
|
|
||||||
// });
|
|
||||||
|
|
||||||
// newlyCreated.push(distributor._doc);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// fs.unlinkSync(filePath); // Clean up uploaded file
|
|
||||||
|
|
||||||
// res.status(201).json({
|
|
||||||
// message:
|
|
||||||
// errors.length > 0
|
|
||||||
// ? "File processed with errors!"
|
|
||||||
// : "File processed successfully!",
|
|
||||||
// processedUsers: {
|
|
||||||
// newlyCreated: newlyCreated.length,
|
|
||||||
// updatedDistributors: updatedDistributors.length
|
|
||||||
// },
|
|
||||||
// errors,
|
|
||||||
// newlyCreated,
|
|
||||||
// updatedDistributors
|
|
||||||
// });
|
|
||||||
// } catch (error) {
|
|
||||||
// console.error("Error processing file:", error);
|
|
||||||
// res.status(500).json({ message: "Error processing file", error: error.message });
|
|
||||||
// }
|
|
||||||
// };
|
|
||||||
export const uploadPrincipaldistributors = async (req, res) => {
|
export const uploadPrincipaldistributors = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
if (!req.files || !req.files.file) {
|
if (!req.files || !req.files.file) {
|
||||||
@ -493,112 +178,146 @@ export const uploadPrincipaldistributors = async (req, res) => {
|
|||||||
item.role = "principal-Distributor";
|
item.role = "principal-Distributor";
|
||||||
|
|
||||||
// Check for existing user by uniqueId
|
// Check for existing user by uniqueId
|
||||||
let distributor = await User.findOne({ uniqueId: item.uniqueId });
|
let distributorbyid = await User.findOne({ uniqueId: item.uniqueId });
|
||||||
|
let distributorbymail = await User.findOne({ email: item.email });
|
||||||
|
// Case 1: Both uniqueId and mobileNumber exist
|
||||||
|
if (distributorbyid && distributorbymail) {
|
||||||
|
if (distributorbyid._id.equals(distributorbymail._id)) {
|
||||||
|
// Track updated fields
|
||||||
|
const updatedFields = [];
|
||||||
|
const addressFields = [
|
||||||
|
"Name",
|
||||||
|
"phoneNumber",
|
||||||
|
"panNumber",
|
||||||
|
"gstNumber",
|
||||||
|
"state",
|
||||||
|
"city",
|
||||||
|
"street",
|
||||||
|
"tradeName",
|
||||||
|
"postalCode",
|
||||||
|
];
|
||||||
|
let existingAddress = await ShippingAddress.findOne({
|
||||||
|
user: distributorbyid._id,
|
||||||
|
isDefault: true,
|
||||||
|
}).exec();
|
||||||
|
|
||||||
if (distributor) {
|
if (!existingAddress) {
|
||||||
// Track updated fields
|
existingAddress = await ShippingAddress.findOne({
|
||||||
const updatedFields = [];
|
user: distributorbyid._id,
|
||||||
const addressFields = [
|
})
|
||||||
"Name",
|
.sort({ createdAt: 1 }) // Get the first created address as fallback
|
||||||
"phoneNumber",
|
.exec();
|
||||||
"panNumber",
|
}
|
||||||
"gstNumber",
|
|
||||||
"state",
|
|
||||||
"city",
|
|
||||||
"street",
|
|
||||||
"tradeName",
|
|
||||||
"postalCode",
|
|
||||||
];
|
|
||||||
let existingAddress = await ShippingAddress.findOne({
|
|
||||||
user: distributor._id,
|
|
||||||
isDefault: true,
|
|
||||||
}).exec();
|
|
||||||
|
|
||||||
if (!existingAddress) {
|
// Check for changes in user details
|
||||||
existingAddress = await ShippingAddress.findOne({
|
let userUpdated = false;
|
||||||
user: distributor._id,
|
if (distributorbyid.name !== item.name) {
|
||||||
})
|
updatedFields.push("name");
|
||||||
.sort({ createdAt: 1 }) // Get the first created address as fallback
|
distributorbyid.name = item.name;
|
||||||
.exec();
|
userUpdated = true;
|
||||||
}
|
}
|
||||||
|
if (distributorbyid.email !== item.email) {
|
||||||
|
updatedFields.push("email");
|
||||||
|
distributorbyid.email = item.email;
|
||||||
|
userUpdated = true;
|
||||||
|
}
|
||||||
|
if (distributorbyid.SBU !== item.SBU) {
|
||||||
|
updatedFields.push("SBU");
|
||||||
|
distributorbyid.SBU = item.SBU;
|
||||||
|
userUpdated = true;
|
||||||
|
}
|
||||||
|
if (distributorbyid.phone !== item.phone.toString()) {
|
||||||
|
updatedFields.push("phone");
|
||||||
|
distributorbyid.phone = item.phone;
|
||||||
|
userUpdated = true;
|
||||||
|
}
|
||||||
|
|
||||||
// Check for changes in user details
|
// Update user
|
||||||
let userUpdated = false;
|
if (userUpdated) {
|
||||||
if (distributor.name !== item.name) {
|
await distributor.save();
|
||||||
updatedFields.push("name");
|
}
|
||||||
distributor.name = item.name;
|
|
||||||
userUpdated = true;
|
|
||||||
}
|
|
||||||
if (distributor.email !== item.email) {
|
|
||||||
updatedFields.push("email");
|
|
||||||
distributor.email = item.email;
|
|
||||||
userUpdated = true;
|
|
||||||
}
|
|
||||||
if (distributor.SBU !== item.SBU) {
|
|
||||||
updatedFields.push("SBU");
|
|
||||||
distributor.SBU = item.SBU;
|
|
||||||
userUpdated = true;
|
|
||||||
}
|
|
||||||
if (distributor.phone !== item.phone.toString()) {
|
|
||||||
updatedFields.push("phone");
|
|
||||||
distributor.phone = item.phone;
|
|
||||||
userUpdated = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update user
|
// Check for changes in address details
|
||||||
if (userUpdated) {
|
const addressData = {
|
||||||
await distributor.save();
|
Name: item.name,
|
||||||
}
|
phoneNumber: item.phone.toString().trim(),
|
||||||
|
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: distributorbyid._id,
|
||||||
|
};
|
||||||
|
|
||||||
// Check for changes in address details
|
let addressUpdated = false;
|
||||||
const addressData = {
|
if (existingAddress) {
|
||||||
Name: item.name,
|
const addressUpdates = [];
|
||||||
phoneNumber: item.phone.toString().trim(),
|
addressFields.forEach((field) => {
|
||||||
street: item.street,
|
if (existingAddress[field] !== addressData[field]) {
|
||||||
city: item.city,
|
addressUpdates.push(field);
|
||||||
state: item.state,
|
addressUpdated = true;
|
||||||
postalCode: item.postalCode.toString(),
|
}
|
||||||
country: "India", // Default country
|
});
|
||||||
panNumber: item.panNumber,
|
|
||||||
tradeName: item.tradeName,
|
|
||||||
gstNumber: item.gstNumber,
|
|
||||||
user: distributor._id,
|
|
||||||
};
|
|
||||||
|
|
||||||
let addressUpdated = false;
|
if (addressUpdated) {
|
||||||
if (existingAddress) {
|
await ShippingAddress.updateOne(
|
||||||
const addressUpdates = [];
|
{ user: distributor._id },
|
||||||
addressFields.forEach((field) => {
|
addressData
|
||||||
if (existingAddress[field] !== addressData[field]) {
|
|
||||||
addressUpdates.push(field);
|
|
||||||
addressUpdated = true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (addressUpdated) {
|
|
||||||
await ShippingAddress.updateOne(
|
|
||||||
{ user: distributor._id },
|
|
||||||
addressData
|
|
||||||
);
|
|
||||||
if (addressUpdates.length > 0) {
|
|
||||||
updatedFields.push(
|
|
||||||
`Address fields: ${addressUpdates.join(", ")}`
|
|
||||||
);
|
);
|
||||||
|
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({
|
||||||
|
...distributor._doc,
|
||||||
|
updatedFields: updatedFields.join(", "),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Create new address
|
// Both exist but refer to different users
|
||||||
await ShippingAddress.create(addressData);
|
errors.push({
|
||||||
updatedFields.push("New address created");
|
uniqueId: item.uniqueId || "N/A",
|
||||||
}
|
SBU: item.SBU || "N/A",
|
||||||
|
name: item.name || "N/A",
|
||||||
// Add to updatedDistributors only if there are updated fields
|
email: item.email || "N/A",
|
||||||
if (updatedFields.length > 0) {
|
phone: item.phone || "N/A",
|
||||||
updatedDistributors.push({
|
panNumber: item.panNumber || "N/A",
|
||||||
...distributor._doc,
|
gstNumber: item.gstNumber || "N/A",
|
||||||
updatedFields: updatedFields.join(", "),
|
message: ` Employee Code (${distributorbyid.uniqueId}) is refer to (${distributorbyid.name}) and Email ID (${distributorbymail.mobileNumber}) refer to (${distributorbymail.name}) Principal Distributor. Please provide the correct employee code or Email ID.`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
} else if (distributorbyid) {
|
||||||
|
// Case 2: uniqueId exists, but Email is new
|
||||||
|
distributorbyid.email = item.email;
|
||||||
|
await distributorbyid.save();
|
||||||
|
updatedDistributors.push({
|
||||||
|
...distributor._doc,
|
||||||
|
updatedFields: "Email",
|
||||||
|
});
|
||||||
|
} else if (distributorbymail) {
|
||||||
|
// Case 3: Email exists, but uniqueId is new
|
||||||
|
errors.push({
|
||||||
|
uniqueId: item.uniqueId || "N/A",
|
||||||
|
SBU: item.SBU || "N/A",
|
||||||
|
name: item.name || "N/A",
|
||||||
|
email: item.email || "N/A",
|
||||||
|
phone: item.phone || "N/A",
|
||||||
|
panNumber: item.panNumber || "N/A",
|
||||||
|
gstNumber: item.gstNumber || "N/A",
|
||||||
|
message: `Email already exists for Employee Code (${distributorbymail.uniqueId})`,
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
// Create a new user
|
// Create a new user
|
||||||
distributor = new User({
|
distributor = new User({
|
||||||
|
@ -41,6 +41,7 @@ const userSchema = new mongoose.Schema(
|
|||||||
},
|
},
|
||||||
email: {
|
email: {
|
||||||
type: String,
|
type: String,
|
||||||
|
unique: true,
|
||||||
required: [true, "Please Enter Your Email"],
|
required: [true, "Please Enter Your Email"],
|
||||||
validate: [validator.isEmail, "Please Enter a valid Email"],
|
validate: [validator.isEmail, "Please Enter a valid Email"],
|
||||||
},
|
},
|
||||||
|
Loading…
Reference in New Issue
Block a user