diff --git a/src/controllers/userController.js b/src/controllers/userController.js index 6e6e79ec..bcd8fec1 100644 --- a/src/controllers/userController.js +++ b/src/controllers/userController.js @@ -1645,6 +1645,11 @@ exports.getuserRequestbookingsforplansforsupplier = async (req, reply) => { } }; + +// Assuming you have these models imported somewhere above: +// const RecurringRequestedBooking = require("..."); +// const Supplier = require("..."); + exports.getuserRequestbookingsforplansforcustomer = async (req, reply) => { try { const { customerId } = req.params; @@ -1656,27 +1661,71 @@ exports.getuserRequestbookingsforplansforcustomer = async (req, reply) => { }); } - // 1) Find all bookings that include this supplier - const bookings = await RecurringRequestedBooking.find({ - customerId: customerId, - }) + // 1) Get bookings + const bookings = await RecurringRequestedBooking.find({ customerId }) .sort({ createdAt: -1 }) .lean(); - // 2) For each booking, expose only this supplier's subdocument - + if (!bookings.length) { + return reply.send({ + status_code: 200, + message: `Orders for customer ${customerId} fetched successfully`, + data: [], + }); + } + + // 2) Collect unique supplierIds from requested_suppliers + const supplierIdSet = new Set(); + for (const b of bookings) { + const rs = Array.isArray(b.requested_suppliers) ? b.requested_suppliers : []; + for (const s of rs) { + if (s && typeof s.supplierId === "string" && s.supplierId.trim() && s.supplierId !== "string") { + supplierIdSet.add(s.supplierId.trim()); + } + } + } + const supplierIds = Array.from(supplierIdSet); + + // 3) Fetch suppliers and index by supplierId + const suppliers = supplierIds.length + ? await Supplier.find({ supplierId: { $in: supplierIds } }) + .select("-__v") // tweak projection as you like + .lean() + : []; + + const supplierById = new Map(); + for (const s of suppliers) { + // Key is Supplier.supplierId (string), not _id + supplierById.set(s.supplierId, s); + } + + // 4) Attach supplier details into each requested_suppliers entry + const data = bookings.map((b) => { + const rs = Array.isArray(b.requested_suppliers) ? b.requested_suppliers : []; + const enriched = rs.map((item) => ({ + ...item, + supplier: supplierById.get(item?.supplierId) || null, // attach or null if not found + })); + return { + ...b, + requested_suppliers: enriched, + }; + }); - return reply.send({ status_code: 200, message: `Orders for customer ${customerId} fetched successfully`, - data:bookings, + data, }); } catch (err) { console.error(err); throw boom.boomify(err); } }; + + + + const mongoose = require('mongoose'); diff --git a/src/index.js b/src/index.js index 1caf0421..9fa69d76 100644 --- a/src/index.js +++ b/src/index.js @@ -7,7 +7,7 @@ const createConnectionController = require("./controllers/createConnectionContro const storeController = require("./controllers/storeController.js") const boom = require("boom"); const bcrypt = require('bcrypt'); -const { ProfilePictureStore,generateinstallationId,Store, Survey, PlumbingWorkPictures, ElectrictyWorkPictures, MaterialRecievedPictures, Support, ManualTestVideo} = require("./models/store"); +const { ProfilePictureStore,generateinstallationId,Store, Survey, PlumbingWorkPictures, ElectrictyWorkPictures, MaterialRecievedPictures, Support, ManualTestVideo, ProfilePictureInstallTeamMember} = require("./models/store"); const cors = require('fastify-cors'); @@ -1232,6 +1232,102 @@ fastify.post('/api/uploads_company_profile/:customerId', async (request, reply) } }); +fastify.post("/api/uploads_installation_TeamMember_profile/:installationId/:teamMemberId", { + preHandler: upload.single("file"), +}, async (request, reply) => { + try { + const { installationId ,teamMemberId} = request.params; + //const teamMemberId = request.body?.teamMemberId; // OPTIONAL + const file = request.file; + + if (!file) { + return reply.code(400).send({ error: "No file uploaded (field name 'file')." }); + } + + // Validate image type + const allowed = ["image/jpeg", "image/jpg", "image/png"]; + if (!allowed.includes(file.mimetype)) { + return reply.code(400).send({ error: "Only JPEG/PNG images are allowed." }); + } + + // Build GCS path + const ext = (mime.extension(file.mimetype) || path.extname(file.originalname).slice(1) || "png").toLowerCase(); + const safeBase = path.parse(file.originalname).name.replace(/[^\w.-]/g, "_"); + const filePath = `arminta_team_profiles/${safeBase}-${Date.now()}.${ext}`; + const bucketName = "arminta_profile_pictures"; + + // Upload + const buffer = await fs.promises.readFile(file.path); + const bucket = storage.bucket(bucketName); + const gcsFile = bucket.file(filePath); + await gcsFile.save(buffer, { + resumable: false, + public: true, + contentType: file.mimetype, + metadata: { cacheControl: "public, max-age=31536000" }, + }); + await gcsFile.makePublic(); + + const publicUrl = `https://storage.googleapis.com/${bucketName}/${filePath}`; + + // Always upsert the installation-level picture doc + await ProfilePictureInstall.findOneAndUpdate( + { installationId }, + { picture: publicUrl }, + { new: true, upsert: true } + ); + + // Update department picture where departmentId === installationId + const deptUpdate = await Deparments.findOneAndUpdate( + { departmentId: installationId }, + { picture: publicUrl }, + { new: true } + ); + + let teamMemberUpdated = false; + if (teamMemberId) { + // 1) Upsert team-member picture collection + await ProfilePictureInstallTeamMember.findOneAndUpdate( + { teamMemberId }, + { picture: publicUrl }, + { new: true, upsert: true } + ); + + // 2) Update nested item inside Installations.team_member.team_member[] + // Using arrayFilters to match the correct team member element + const res = await Install.updateOne( + { installationId }, + { + $set: { + "team_member.team_member.$[tm].picture": publicUrl + } + }, + { + arrayFilters: [{ "tm.teamMemberId": teamMemberId }] + } + ); + teamMemberUpdated = res.modifiedCount > 0; + } + + return reply.send({ + installationId, + teamMemberId: teamMemberId || null, + picture: publicUrl, + departmentUpdated: Boolean(deptUpdate), + teamMemberUpdated, + message: teamMemberId + ? (teamMemberUpdated + ? "Upload successful. Installation + team member picture updated." + : "Upload successful. Team member not found under this installation.") + : "Upload successful. Installation picture updated.", + }); + } catch (err) { + request.log.error(err); + return reply.code(500).send({ error: "Upload failed", details: err.message }); + } finally { + try { if (request.file?.path) await fs.promises.unlink(request.file.path); } catch {} + } +}); fastify.post('/api/uploads/:supplierId', async (request, reply) => { try {