UNPKG

powr-sdk-api

Version:

Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.

363 lines (351 loc) 9.71 kB
"use strict"; const express = require("express"); const router = express.Router(); const multer = require('multer'); const path = require('path'); const { getDb } = require("../services/mongo"); const { verifyToken } = require("../middleware/jwtToken"); const upload = multer({ storage: multer.memoryStorage(), fileFilter: function (req, file, cb) { if (file.mimetype === 'application/json' || path.extname(file.originalname).toLowerCase() === '.json') { cb(null, true); } else { cb(new Error('Only JSON files are allowed!'), false); } }, limits: { fileSize: 5 * 1024 * 1024 } }); // GET all powrForm data based on projectId router.get("/powrform", verifyToken, async (req, res) => { const projectId = req.projectId; try { const db = await getDb(); const collection = db.collection("powrForm"); const forms = await collection.find({ projectId }).toArray(); res.status(200).json({ success: true, message: "Fetching powrForm data", count: forms.length, data: forms }); } catch (error) { res.status(500).json({ success: false, message: "Internal server error", error: error.message }); } }); // GET specific form by formName and projectId router.get('/:formName', async (req, res) => { try { const { formName } = req.params; const projectId = req.projectId; const db = await getDb(); const collection = db.collection("powrForm"); const formData = await collection.findOne({ formName, projectId }); if (!formData) { return res.status(404).json({ success: false, message: 'Form not found' }); } res.status(200).json({ success: true, message: "Form fetched successfully", data: formData }); } catch (error) { res.status(500).json({ success: false, message: 'Error fetching form', error: error.message }); } }); // POST /studentform router.post('/studentform', async (req, res) => { try { const formData = req.body; const projectId = req.projectId; const { whatsapp, formName, email, ...otherFormFields } = formData; const db = await getDb(); const studentsFormCollection = db.collection('studentsForm'); const existingForm = await studentsFormCollection.findOne({ whatsapp: whatsapp, projectId: projectId, email: email, formName: formName }); if (existingForm) { return res.status(409).json({ message: 'You have already submitted this form. Only one submission per form type is allowed.', existingFormId: existingForm._id, submittedAt: existingForm.submittedAt }); } const studentFormData = { whatsapp: whatsapp, formName: formName, projectId: projectId, email: email, ...otherFormFields, submittedAt: new Date() }; const formResult = await studentsFormCollection.insertOne(studentFormData); res.status(201).json({ success: true, message: 'Student form submitted successfully', submittedFormId: formResult.insertedId, data: studentFormData }); } catch (error) { res.status(500).json({ success: false, message: 'Error submitting student form', error: error.message }); } }); //get form router.get('/getCount/:formName', verifyToken, async (req, res) => { try { const { formName } = req.params; const projectId = req.projectId; const db = await getDb(); const studentsFormCollection = db.collection('studentsForm'); // Build query object let query = { formName, projectId }; const submissions = await studentsFormCollection.find(query).toArray(); res.status(200).json({ success: true, message: 'Submission count retrieved successfully', formName: formName, projectId: projectId, count: submissions.length, data: submissions }); } catch (error) { res.status(500).json({ success: false, message: 'Error counting form submissions', error: error.message }); } }); async function createPowrForm(formData, projectId, res) { if (!(formData !== null && formData !== void 0 && formData.formName)) { return res.status(400).json({ success: false, message: 'formName is required' }); } const db = await getDb(); const powrFormCollection = db.collection('powrForm'); const existingForm = await powrFormCollection.findOne({ formName: formData.formName, projectId: projectId }); if (existingForm) { return res.status(409).json({ success: false, message: 'Form with this name already exists for this project', existingFormId: existingForm._id }); } const finalFormData = { ...formData, projectId: projectId, createdAt: new Date() }; const result = await powrFormCollection.insertOne(finalFormData); return res.status(201).json({ success: true, message: 'Form created and stored successfully', formId: result.insertedId, formName: formData.formName, projectId: projectId, data: finalFormData }); } // POST /create-form - JSON body or legacy JSON file upload router.post('/create-form', verifyToken, async (req, res) => { try { const projectId = req.projectId; const contentType = req.headers['content-type'] || ''; if (contentType.includes('application/json')) { return createPowrForm(req.body, projectId, res); } upload.single('jsonFile')(req, res, async uploadError => { if (uploadError) { return res.status(400).json({ success: false, message: uploadError.message }); } if (!req.file) { return res.status(400).json({ success: false, message: 'Form data is required. Send JSON body or upload a JSON file.' }); } try { const fileContent = req.file.buffer.toString('utf8'); const formData = JSON.parse(fileContent); return createPowrForm(formData, projectId, res); } catch (parseError) { return res.status(400).json({ success: false, message: 'Invalid JSON file format', error: parseError.message }); } }); } catch (error) { res.status(500).json({ success: false, message: 'Error creating form', error: error.message }); } }); // PUT /update-form/:formName - Update existing form schema router.put('/update-form/:formName', verifyToken, async (req, res) => { try { const { formName } = req.params; const projectId = req.projectId; const { formTitle, formId, description, imageUrl, fields } = req.body; if (!(formTitle !== null && formTitle !== void 0 && formTitle.trim()) || !(formId !== null && formId !== void 0 && formId.trim())) { return res.status(400).json({ success: false, message: 'formTitle and formId are required' }); } if (!Array.isArray(fields) || fields.length === 0) { return res.status(400).json({ success: false, message: 'At least one field is required' }); } const db = await getDb(); const powrFormCollection = db.collection('powrForm'); const existingForm = await powrFormCollection.findOne({ formName, projectId }); if (!existingForm) { return res.status(404).json({ success: false, message: 'Form not found' }); } const updateData = { formTitle: formTitle.trim(), formId: formId.trim(), description: (description === null || description === void 0 ? void 0 : description.trim()) || '', imageUrl: (imageUrl === null || imageUrl === void 0 ? void 0 : imageUrl.trim()) || '', fields, updatedAt: new Date() }; await powrFormCollection.updateOne({ formName, projectId }, { $set: updateData }); return res.status(200).json({ success: true, message: 'Form updated successfully', formName, projectId, data: { ...existingForm, ...updateData, formName } }); } catch (error) { return res.status(500).json({ success: false, message: 'Error updating form', error: error.message }); } }); // Get form submissions router.get("/submissions", verifyToken, async (req, res) => { const projectId = req.projectId; // Use middleware-injected projectId try { const db = await getDb(); const submissions = await db.collection("formSubmissions").find({ projectId }).toArray(); return res.json({ success: true, data: submissions }); } catch (error) { console.error("Error fetching form submissions:", error); return res.status(500).json({ success: false, message: "Failed to fetch form submissions." }); } }); // Get form submissions by form ID router.get("/submissions/:formId", verifyToken, async (req, res) => { const { formId } = req.params; const projectId = req.projectId; // Use middleware-injected projectId try { const db = await getDb(); const submissions = await db.collection("formSubmissions").find({ formId, projectId }).toArray(); return res.json({ success: true, data: submissions }); } catch (error) { console.error("Error fetching form submissions:", error); return res.status(500).json({ success: false, message: "Failed to fetch form submissions." }); } }); module.exports = router;