diff --git a/src/index.js b/src/index.js index 47079054..e1ad2965 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} = require("./models/store"); +const { ProfilePictureStore,generateinstallationId,Store, Survey, PlumbingWorkPictures, ElectrictyWorkPictures, MaterialRecievedPictures} = require("./models/store"); const cors = require('fastify-cors'); @@ -1024,6 +1024,64 @@ fastify.post("/api/uploads-plumbing-work/:customerId/:installationId", async (re } }); +fastify.post("/api/uploads-material-recieved/:customerId/:installationId", async (request, reply) => { + try { + const { customerId, installationId } = request.params; + const files = await request.files(); // Await files properly + + if (!files || files.length === 0) { + return reply.code(400).send({ error: "No files uploaded" }); + } + + const bucketName = "arminta_profile_pictures"; + const publicUrls = []; + + for await (const file of files) { + const uniqueFileName = `${Date.now()}-${Math.random().toString(36).substring(7)}-${file.filename}`; + const filePath = `plumbing_work_picture/${uniqueFileName}`; + + console.log(`Uploading file: ${file.filename} → ${filePath}`); + + const writeStream = storage.bucket(bucketName).file(filePath).createWriteStream(); + + file.file.pipe(writeStream); + + await new Promise((resolve, reject) => { + writeStream.on("finish", async () => { + try { + await storage.bucket(bucketName).file(filePath).makePublic(); + const publicUrl = `https://storage.googleapis.com/${bucketName}/${filePath}`; + publicUrls.push(publicUrl); + console.log(`File uploaded: ${publicUrl}`); + resolve(); + } catch (error) { + console.error("Failed to make file public:", error); + reject(error); + } + }); + + writeStream.on("error", (err) => { + console.error("Failed to upload file:", err); + reject(err); + }); + }); + } + + // Update MongoDB: Convert URLs to { url: "..." } objects + const updatedRecord = await MaterialRecievedPictures.findOneAndUpdate( + { customerId, installationId }, + { $push: { pictureUrl: { $each: publicUrls.map(url => ({ url })) } } }, // Append new images + { new: true, upsert: true } + ); + + reply.send({ success: true, pictures: publicUrls, details: updatedRecord }); + } catch (err) { + console.error("Upload Error:", err); + reply.code(500).send({ error: "An error occurred", details: err.message }); + } +}); + + fastify.post("/api/installLogin", { schema: { description: "This is for Login Install",