GWM : hs products added in establishment create and update

This commit is contained in:
Gowtham M 2025-11-09 18:59:27 +05:30
parent 0ae3303d86
commit 83fabc7292
2 changed files with 139 additions and 8 deletions

View File

@ -3,6 +3,7 @@ const bcrypt = require("bcryptjs");
const Establishment = db.Establishment;
const EstablishmentUser = db.EstablishmentUser;
const EstablishmentPasswordResetRequest = db.EstablishmentPasswordResetRequest;
const EstablishmentProduct = db.EstablishmentProduct;
const CityTown = db.CityTown;
const Emirate = db.Emirate;
const user = db.user;
@ -70,6 +71,7 @@ exports.createEstablishment = async (req, res) => {
total_employees,
created_by,
establishment_user,
establishment_products
} = req.body;
// Basic Validation
@ -153,6 +155,41 @@ exports.createEstablishment = async (req, res) => {
}
await sendEmailService(establishment_user.email, 'establishment_user_creation_to_user', placeHolderData);
// insert establishment_products
if (Array.isArray(establishment_products) && establishment_products.length > 0) {
// remove duplicates from request itself
let uniqueProducts = [...new Set(establishment_products.map(x => x.product_id))];
// now check which already exist for this establishment
const existing = await EstablishmentProduct.findAll({
where: {
establishment_id: establishment.id,
product_id: uniqueProducts
},
attributes: ['product_id']
});
const existingIds = existing.map(x => x.product_id);
// filter only new ones (not existing)
const newProducts = uniqueProducts
.filter(pid => !existingIds.includes(pid))
.map(pid => ({
establishment_id: establishment.id,
product_id: pid,
created_at: new Date(),
}));
// only insert if have new ones
if (newProducts.length) {
await EstablishmentProduct.bulkCreate(newProducts);
}
}
// 🔹 Return success response
return res.status(201).send({
status: "success",
@ -433,22 +470,100 @@ exports.getEstablishmentById = async (req, res) => {
};
// Update establishment
exports.updateEstablishment = async (req, res) => {
try {
const { id } = req.params;
const { establishment_products, establishment_user, ...estData } = req.body;
const [updated] = await Establishment.update(req.body, {
where: { id: req.params.id },
});
const establishment = await Establishment.findByPk(id);
if (!establishment) {
return res.status(404).json({ status: "failed", message: "Record not found" });
}
if (!updated){ return res.status(404).send({'status':"failed",'message':"Record Not found",'data': "" }); }
return res.status(200).send({'status':"success",'message':"Updated successfully",'data': "" });
// check duplicate establishment_code
if (estData.establishment_code) {
const exists = await Establishment.findOne({
where: { establishment_code: estData.establishment_code, id: { [Op.ne]: id } }
});
if (exists) {
return res.status(400).json({ status:"failed", message:"establishment_code already exists" });
}
}
} catch (err) {
return res.status(500).send({'status':"failed",'message':err.message });
// update establishment
await establishment.update(estData);
// update user if needed
if (establishment_user) {
const user = await EstablishmentUser.findOne({where:{establishment_id:id}});
if (user) {
let updateUser = {
name: establishment_user.name,
email: establishment_user.email
};
if (establishment_user.password) {
updateUser.password = await bcrypt.hash(establishment_user.password,10);
}
await user.update(updateUser);
}
}
// update establishment products
if (Array.isArray(establishment_products)) {
let incomingIds = establishment_products.map(e => e.product_id);
const oldProducts = await EstablishmentProduct.findAll({ where:{ establishment_id:id } });
const oldIds = oldProducts.map(e => e.product_id);
// remove products not in new list
const removeIds = oldIds.filter(v => !incomingIds.includes(v));
if (removeIds.length) {
await EstablishmentProduct.destroy({ where:{ establishment_id:id, product_id:removeIds } });
}
// add only new ones
const newIds = incomingIds.filter(v => !oldIds.includes(v));
for (let pid of newIds) {
await EstablishmentProduct.create({ establishment_id:id, product_id:pid });
}
}
return res.json({ status:"success", message:"Updated successfully" , data:"" });
} catch(err) {
if (err.name === "SequelizeUniqueConstraintError") {
const field = err.errors[0].path;
return res.status(400).json({ status:"failed", message:`${field} already exists` });
}
return res.status(500).json({ status:"failed", message: err.message });
}
};
// exports.updateEstablishment = async (req, res) => {
// try {
// const [updated] = await Establishment.update(req.body, {
// where: { id: req.params.id },
// });
// if (!updated){ return res.status(404).send({'status':"failed",'message':"Record Not found",'data': "" }); }
// return res.status(200).send({'status':"success",'message':"Updated successfully",'data': "" });
// } catch (err) {
// return res.status(500).send({'status':"failed",'message':err.message });
// }
// };
// Delete establishment
exports.deleteEstablishment = async (req, res) => {
try {

View File

@ -465,6 +465,14 @@ router.get("/testEmail", establishmentController.testEmail);
* name: { type: string }
* email: { type: string }
* password: { type: string }
* establishment_products:
* type: array
* items:
* type: object
* required:
* - product_id
* properties:
* product_id: { type: integer }
* responses:
* 201:
* description: Establishment and linked user created successfully
@ -615,6 +623,14 @@ router.get("/establishments/:id",[verifySignature, verifyToken], establishmentCo
* total_emirati: { type: integer }
* total_employees: { type: integer }
* updated_by: { type: integer }
* establishment_products:
* type: array
* items:
* type: object
* required:
* - product_id
* properties:
* product_id: { type: integer }
* responses:
* 200:
* description: Establishment updated successfully