retailer distributor address add,edit and delete

This commit is contained in:
Sibunnayak 2024-10-16 12:04:25 +05:30
parent 9a03c93164
commit 0b38bbac46
14 changed files with 559 additions and 10 deletions

3
app.js
View File

@ -169,6 +169,7 @@ import ConfigRouter from "./resources/setting/Configration/Config_routes.js";
//specialties
import SpecialtiesRouter from "./resources/Specialties/SpecialtiesRoute.js";
import ShippingAddressRoute from "./resources/ShippingAddresses/ShippingAddressRoute.js";
import RdShippingAddressRoute from "./resources/ShippingAddressesRD/RDShippingAddressRoute.js";
import stripeRoute from "./resources/StripePayment/stripeRoute.js";
import SeoRoute from "./resources/SEO&Analytics/SEORouter.js";
@ -230,6 +231,8 @@ app.use("/api/content", ContentRoute);
// User Address
app.use("/api/user-address", UserAddressRoute);
app.use("/api/shipping/address", ShippingAddressRoute);
//Shipping Address of RD
app.use("/api/rd/shipping/address", RdShippingAddressRoute);
//SalesCoOrdinator Routes
app.use("/api/salescoordinator", SalesCoOrdinatorRoute);
// Kyc Routes

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

View File

@ -9,6 +9,7 @@ import { Notification } from "../Notification/notificationModal.js";
import RetailDistributor from "../RetailDistributor/RetailDistributorModel.js";
import { generatePassword } from "../../Utils/generatepassword.js";
import sendEmail, { sendOtp } from "../../Utils/sendEmail.js";
import ShippingAddressRD from "../ShippingAddressesRD/RDShippingAddressModel.js";
export const createKyc = async (req, res) => {
const {
name,
@ -244,7 +245,22 @@ export const createretaildistributor = async (req, res) => {
password,
};
const retailDistributor = new RetailDistributor(retailDistributorData);
await retailDistributor.save();
const newRd = await retailDistributor.save();
// Now create the address for the new user
const addressData = {
Name: name,
phoneNumber: mobile_number,
street: address,
city: city,
state: state,
postalCode: pincode,
district: district,
country: "India", // Default country
tradeName: trade_name,
user: newRd._id, // Use the saved user's ID
isDefault: true,
};
await ShippingAddressRD.create(addressData);
// Send email with the new password
await sendEmail({
to: `${email}`, // Change to your recipient
@ -442,8 +458,22 @@ export const updateKycStatus = async (req, res) => {
};
const retailDistributor = new RetailDistributor(retailDistributorData);
await retailDistributor.save();
const newRd = await retailDistributor.save();
// Now create the address for the new user
const addressData = {
Name: kyc.name,
phoneNumber: kyc.mobile_number,
street: kyc.address,
city: kyc.city,
state: kyc.state,
postalCode: kyc.pincode,
district: kyc.district,
country: "India", // Default country
tradeName: kyc.trade_name,
user: newRd._id, // Use the saved user's ID
isDefault: true,
};
await ShippingAddressRD.create(addressData);
// Send email with the new password
await sendEmail({
to: kyc.email,

View File

@ -10,6 +10,7 @@ import { generatePassword } from "../../Utils/generatepassword.js";
import XLSX from "xlsx";
import fs from "fs";
import path from "path";
import ShippingAddressRD from "../ShippingAddressesRD/RDShippingAddressModel.js";
export const uploadRetaildistributors = async (req, res) => {
try {
@ -183,31 +184,85 @@ export const uploadRetaildistributors = async (req, res) => {
let Retaildistributor = await RetailDistributor.findOne({
email: item.email,
});
let existingAddress = await ShippingAddressRD.findOne({
user: Retaildistributor?._id,
isDefault: true,
}).exec();
if (!existingAddress) {
existingAddress = await ShippingAddressRD.findOne({
user: Retaildistributor?._id,
})
.sort({ createdAt: 1 })
.exec();
}
if (Kyc) {
// Track updated fields
const updatedFields = [];
const addressFields = [
"Name",
"phoneNumber",
"state",
"city",
"street",
"tradeName",
"postalCode",
"district",
];
// Check for changes in user details
let kycUpdated = false;
for (let field in item) {
const currentValue = Kyc[field]?.toString();
const newValue = item[field]?.toString();
if (currentValue !== newValue) {
updatedFields.push(field);
Kyc[field] = item[field]; // Update Kyc with the new value
if (Retaildistributor && field !== 'email') {
if (Retaildistributor && field !== "email") {
Retaildistributor[field] = item[field];
}
kycUpdated = true;
}
}
// Update Kyc and Retaildistributor if there are any changes
if (kycUpdated) {
await Kyc.save();
await Retaildistributor.save();
// Check for changes in address details
const addressData = {
Name: item.name,
phoneNumber: item.mobile_number.toString(),
street: item.address,
city: item.city,
state: item.state,
postalCode: item.pincode,
district: item.district,
country: "India", // Default country
tradeName: item.trade_name,
user: Retaildistributor._id,
};
console.log(addressData);
let addressUpdated = false;
if (existingAddress) {
const addressUpdates = [];
addressFields.forEach((field) => {
if (existingAddress[field] !== addressData[field]) {
addressUpdates.push(field);
addressUpdated = true;
}
});
if (addressUpdated) {
await ShippingAddressRD.updateOne(
{ user: Retaildistributor._id },
addressData
);
}
} else {
// Create new address
await ShippingAddressRD.create(addressData);
}
updatedDistributors.push({
...Kyc._doc,
updatedFields: updatedFields.join(", "),
@ -228,7 +283,22 @@ export const uploadRetaildistributors = async (req, res) => {
password,
};
Retaildistributor = new RetailDistributor(retailDistributorData);
await Retaildistributor.save();
const newRd = await Retaildistributor.save();
// Now create the address for the new user
const addressData = {
Name: item.name,
phoneNumber: item.mobile_number.toString(),
street: item.address,
city: item.city,
state: item.state,
postalCode: item.pincode,
district: item.district,
country: "India", // Default country
tradeName: item.trade_name,
user: newRd._id, // Use the saved user's ID
isDefault: true,
};
await ShippingAddressRD.create(addressData);
// Send email with the new password
await sendEmail({
to: `${item.email}`, // Change to your recipient

View File

@ -0,0 +1,339 @@
import ShippingAddressRD from "./RDShippingAddressModel.js";
export const AddshippingAddress = async (req, res) => {
// console.log("request came here");
try {
const {
Name,
phoneNumber,
street,
city,
state,
postalCode,
country,
district,
} = req.body;
// console.log(req.body);
switch (true) {
//validation
case !Name: {
return res.status(404).json({ msg: "please provide Name" });
}
case !phoneNumber: {
return res.status(404).json({ msg: "please provide phoneNumber" });
}
case !street: {
return res.status(404).json({ msg: "please provide street" });
}
case !city: {
return res.status(404).json({ msg: "please provide city" });
}
case !state: {
return res.status(404).json({ msg: "please provide state" });
}
case !postalCode: {
return res.status(404).json({ msg: "please provide postalCode" });
}
case !country: {
return res.status(404).json({ msg: "please provide country" });
}
case !tradeName: {
return res.status(404).json({ msg: "please provide tradeName" });
}
case !district: {
return res.status(404).json({ msg: "please provide district" });
}
}
req.body.user = req.user._id;
const address = await ShippingAddressRD.create(req.body);
res.status(201).json({
success: true,
address,
message: "shipping Address Added",
});
} catch (error) {
console.log(error.message);
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};
export const AddshippingAddressByAdmin = async (req, res) => {
try {
const {
Name,
phoneNumber,
street,
district,
city,
state,
postalCode,
country,
tradeName,
isDefault,
} = req.body;
// Validate required fields
if (
!Name ||
!phoneNumber ||
!street ||
!city ||
!state ||
!postalCode ||
!tradeName ||
!district
) {
return res
.status(400)
.json({
msg: "Please provide all required fields: Name, phone number, street, city, state, postal code, district and tradeName",
});
}
// Create new shipping address
const newAddress = await ShippingAddressRD.create({
Name,
phoneNumber,
street,
district,
city,
state,
postalCode,
country,
tradeName,
user: req.params._id,
isDefault,
});
// If this address is marked as default, set all other addresses for this user to isDefault: false
if (isDefault) {
await ShippingAddressRD.updateMany(
{ user: req.params._id, _id: { $ne: newAddress._id } }, // Exclude the new address
{ $set: { isDefault: false } }
);
}
// Respond with success
res.status(201).json({
success: true,
address: newAddress,
message: "Shipping address added successfully",
});
} catch (error) {
// Check for validation errors
if (error.name === "ValidationError") {
const errorMessages = Object.values(error.errors).map(
(err) => err.message
);
return res.status(400).json({
success: false,
message: errorMessages.join(", "),
});
}
// General error response
res.status(500).json({
success: false,
message: error.message || "Something went wrong",
});
}
};
// For website
export const getSingleUserSippingAddress = async (req, res) => {
try {
const UserShippingAddress = await ShippingAddressRD.find({
user: req.user._id,
}).sort({ createdAt: -1 });
if (UserShippingAddress) {
res.status(201).json({
success: true,
UserShippingAddress,
message: "All User Shipping Address Fetched",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};
// For Admin
export const getSingleUserSippingAddressForAdmin = async (req, res) => {
try {
// console.log(req.params._id);
const UserShippingAddress = await ShippingAddressRD.find({
user: req.params._id,
}).sort({ createdAt: -1 });
// console.log(UserShippingAddress);
if (UserShippingAddress) {
res.status(201).json({
success: true,
UserShippingAddress,
message: "All User Shipping Address Fetched",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};
///
export const deleteSelfShippingAddress = async (req, res) => {
try {
if (!req.params.id)
return res
.status(400)
.json({ message: "please Provide shipping Address Id" });
const getselfAddress = await ShippingAddressRD.findById(req.params.id);
const userId = req.body.userId ? req.body.userId : req.user._id;
if (!getselfAddress) {
return res.status(404).json({
success: false,
message: "No shipping Address Found!",
});
}
if (getselfAddress?.user.toString() === userId.toString()) {
const address = await ShippingAddressRD.findByIdAndDelete(req.params.id);
await address.remove();
return res.status(200).json({
success: true,
message: "Shipping Address Deleted Successfully!",
});
} else {
return res.status(400).json({
success: false,
message: "you can only delete self shipping address!!",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};
// update shipping addresss
export const updateShippingAddress = async (req, res) => {
try {
const {
Name,
phoneNumber,
street,
city,
district,
state,
postalCode,
country,
tradeName,
isDefault,
} = req.body;
// console.log(req.body);
const _id = req.params.id;
if (!req.params.id)
return res
.status(400)
.json({ message: "please Provide shipping Address Id" });
const getselfAddress = await ShippingAddressRD.findById(_id);
if (!getselfAddress) {
return res.status(404).json({
success: false,
message: "No shipping Address Found!",
});
}
switch (true) {
//validation
case !Name: {
return res.status(404).json({ msg: "please provide Name" });
}
case !phoneNumber: {
return res.status(404).json({ msg: "please provide phone_Number" });
}
case !street: {
return res.status(404).json({ msg: "please provide street" });
}
case !city: {
return res.status(404).json({ msg: "please provide city" });
}
case !state: {
return res.status(404).json({ msg: "please provide state" });
}
case !postalCode: {
return res.status(404).json({ msg: "please provide postalCode" });
}
case !country: {
return res.status(404).json({ msg: "please provide country" });
}
case !tradeName: {
return res.status(404).json({ msg: "please provide tradeName" });
}
case !district: {
return res.status(404).json({ msg: "please provide district" });
}
}
// If the updated address is marked as default, update all other addresses to isDefault: false
if (isDefault) {
await ShippingAddressRD.updateMany(
{ user: getselfAddress.user, _id: { $ne: _id } }, // exclude current address
{ $set: { isDefault: false } }
);
}
const updateAddressData = {
Name,
phoneNumber,
street,
district,
city,
state,
postalCode,
country,
tradeName,
isDefault,
};
const updateShippingAddress = await ShippingAddressRD.findByIdAndUpdate(
{ _id: _id },
{ $set: updateAddressData },
{ new: true }
);
res.status(201).json({
success: true,
updateShippingAddress,
message: "Shipping Address updated",
});
} catch (error) {
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};
export const getSingleSippingAddress = async (req, res) => {
try {
let _id = req.params.id;
const address = await ShippingAddressRD.findById({ _id: _id });
if (address) {
res.status(201).json({
success: true,
address,
message: "Shipping Address Fetched",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message ? error.message : "Something went Wrong",
});
}
};

View File

@ -0,0 +1,62 @@
import mongoose from "mongoose";
const shippingAddressSchema = new mongoose.Schema(
{
Name: {
type: String,
},
phoneNumber: {
type: Number,
},
street: {
type: String,
required: true,
},
district: {
type: String,
required: true,
},
city: {
type: String,
required: true,
trim: true,
},
state: {
type: String,
required: true,
},
postalCode: {
type: String,
required: true,
trim: true,
validate: {
validator: function (v) {
return /^\d{6}$/.test(v);
},
message: "Postal code must be a 6-digit number",
},
},
country: {
type: String,
required: true,
},
tradeName: {
type: String,
required: true,
},
isDefault: {
type: Boolean,
default: false,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "RetailDistributor",
required: true,
},
},
{ timestamps: true, versionKey: false }
);
const ShippingAddressRD = mongoose.model("ShippingAddressRD", shippingAddressSchema);
export default ShippingAddressRD;

View File

@ -0,0 +1,43 @@
import express from "express";
import {
AddshippingAddress,
getSingleUserSippingAddress,
deleteSelfShippingAddress,
getSingleUserSippingAddressForAdmin,
updateShippingAddress,
getSingleSippingAddress,
AddshippingAddressByAdmin,
} from "./RDShippingAddressController.js";
import { authorizeRoles, isAuthenticatedUser } from "../../middlewares/auth.js";
import { isAuthenticatedRD } from "../../middlewares/rdAuth.js";
const router = express.Router();
router.route("/new").post(isAuthenticatedRD, AddshippingAddress);
router
.route("/admin/new/:_id")
.post(
isAuthenticatedUser,
authorizeRoles("admin"),
AddshippingAddressByAdmin
);
router
.route("/user/address/")
.get(isAuthenticatedUser, getSingleUserSippingAddress);
router.route("/").get(isAuthenticatedRD, getSingleUserSippingAddress);
router
.route("/user/address/:_id")
.get(
isAuthenticatedUser,
authorizeRoles("admin"),
getSingleUserSippingAddressForAdmin
);
router
.route("/delete/:id")
.delete(isAuthenticatedUser, deleteSelfShippingAddress);
router.route("/update/:id").patch(isAuthenticatedUser, updateShippingAddress);
router.route("/get/:id").get(isAuthenticatedUser, getSingleSippingAddress);
export default router;

View File

@ -499,6 +499,8 @@ export const uploadPrincipaldistributors = async (req, res) => {
// Track updated fields
const updatedFields = [];
const addressFields = [
"Name",
"phoneNumber",
"panNumber",
"gstNumber",
"state",
@ -551,7 +553,7 @@ export const uploadPrincipaldistributors = async (req, res) => {
// Check for changes in address details
const addressData = {
Name: item.name,
phoneNumber: item.phone,
phoneNumber: item.phone.toString(),
street: item.street,
city: item.city,
state: item.state,