unique folder name + mysql + node

PHOTO EMBED

Sat Jun 15 2024 11:06:26 GMT+0000 (Coordinated Universal Time)

Saved by @codeing #javascript

const express = require('express');
const app = express();

const bodyParser = require('body-parser');
app.use(bodyParser.json());
const cors = require('cors');

const dotenv = require('dotenv');
dotenv.config();

//! add db hear
const dbService = require('./utils/dbService');
const connection = require('./utils/dbService');
const multer = require('multer')
const moment = require("moment")
const fs = require('fs');
const path = require('path');



app.use(cors());

app.use(express.json());
app.use(express.urlencoded({ extended: false }));





// Import the routes from routes.js
const routes = require('./routes/userRoute');

// Use the imported routes in your app.js file
// app.use(routes);


// Add a prefix to all routes
app.use('/api/v1', routes);




app.post('/login', (req, res) => {
    const { ao_name, ao_status } = req.body;
    console.log('Received login data:', req.body);

    var sql = "INSERT INTO app_occasion ( ao_name, ao_status ) VALUES ?";
    var values = [[ao_name, ao_status]];

    connection.query(sql, [values], function (err, result) {
        if (err) throw err;
        console.log("Records inserted: " + result.affectedRows);
        // Show alert message
        res.status(200).json({ message: 'Login data received' });
    });
});


 // TODO testing

 app.use("/uploads", express.static("./uploads"))
// // Image storage config
// const imgconfig = multer.diskStorage({
//     destination: (req, file, callback) => {
//         callback(null, "./uploads");
//     },
//     filename: (req, file, callback) => {
//         const uniqueName = `image-${Date.now()}-${file.originalname}`;
//         callback(null, uniqueName);
//     }
// });
// // Image filter
// const isImage = (req, file, callback) => {
//     if (file.mimetype.startsWith("image")) {
//         callback(null, true);
//     } else {
//         callback(new Error("Only images are allowed"));
//     }
// };
// const upload = multer({
//     storage: imgconfig,
//     fileFilter: isImage
// });


// 


// Function to generate folder name from organization name


// checking if same name folder name is exist  
// fs.readdir(uploadsPath, (err, files) => {
//     if (err) {
//         console.error('Error reading directory:', err);
//     } else {
//         if (files.includes(newFolderName)) {
//             console.log('Found  folder in uploads directory');


//         } else {
//             console.log(' folder NOT found in uploads directory');
//         }
//     }
// });





// Helper function to create a folder name based on the organization name
const generateFolderName = (orgName, basePath) => {
    // Start with the first letter of each word
    const folderName = orgName
        .split(" ")
        .map((word) => word[0].toLowerCase())
        .join("");

    // Check if the folder already exists
    const existingFolders = fs.readdirSync(basePath);
    let uniqueFolderName = folderName;
    let folderSuffix = '';
    const words = orgName.split(" ");

    // If the folder exists and has more words, add the second word in parentheses
    if (existingFolders.includes(uniqueFolderName) && words.length > 1) {
        folderSuffix = `(${words[1].toLowerCase()})`;
        uniqueFolderName += folderSuffix;
    }

    // If it still exists, keep adding next words in parentheses until unique
    let index = 2; // Start with the third word if needed
    while (existingFolders.includes(uniqueFolderName) && index < words.length) {
        folderSuffix = `(${words[index].toLowerCase()})`;
        uniqueFolderName = folderName + folderSuffix;
        index++;
    }

    // If after all words, it's still not unique, append a number to make it unique
    let counter = 2;
    while (existingFolders.includes(uniqueFolderName)) {
        uniqueFolderName = `${folderName}${folderSuffix}(${counter})`;
        counter++;
    }

    return uniqueFolderName;
};

// multer disk storage configuration
const imgconfig = multer.diskStorage({
    destination: (req, file, callback) => {
        const { ar_org_name } = req.body;
        if (!ar_org_name) {
            return callback(new Error("Organization name not provided"), false);
        }

        const uploadsPath = path.join(__dirname, 'uploads');
        const newFolderName = generateFolderName(ar_org_name, uploadsPath);
        const newFolderPath = path.join(uploadsPath, newFolderName);
        
        // Create the new directory if it doesn't exist
        fs.mkdirSync(newFolderPath, { recursive: true });

        callback(null, newFolderPath);
    },
    filename: (req, file, callback) => {
        const uniqueName = `image-${Date.now()}-${file.originalname}`;
        callback(null, uniqueName);
    }
});
















// Image filter
const isImage = (req, file, callback) => {
    if (file.mimetype.startsWith("image")) {
        callback(null, true);
    } else {
        callback(new Error("Only images are allowed"), false);
    }
};



const upload = multer({
    storage: imgconfig,
    fileFilter: isImage
});








// Middleware
app.use(express.json());
app.use(cors());

// Handle form submission
app.post("/testing", upload.single("ar_org_logo"), (req, res) => {
    const {
        ar_org_name,
        ar_cp_signature,
        ar_contract_number,
        ar_emaill,
        ar_password,
        ar_conform_password,
        // ar_occecation_id
    } = req.body;

    // console.log("ar_org_name:", ar_org_name); 

// const newFolderName = ar_org_name;   //'newFolder'; // Replace with your logic to generate the folder name
// const uploadsPath = path.join(__dirname, 'uploads');
// const newFolderPath = path.join(uploadsPath, newFolderName);

// // Create the new directory
// fs.mkdirSync(newFolderPath, { recursive: true });

// console.log( "res.json({ message: 'Directory created successfully' });" );





    const { filename } = req.file;

    if (!ar_org_name || !ar_cp_signature || !ar_contract_number || !ar_emaill || !ar_password || !ar_conform_password  || !filename) {
        return res.status(422).json({ status: 422, message: "Fill all the details" });
    }

    try {
        const date = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");

        const userData = {
            ar_org_name,
            ar_cp_signature,
            ar_contract_number,
            ar_emaill,
            ar_password,
            ar_conform_password,
            // ar_occecation_id,
            ar_org_logo: filename,
            ar_creat_at: date,
            ar_status: 'pending'
        };
     

        connection.query("INSERT INTO app_cp_info SET ?", userData, (err, result) => {
            if (err) {
                console.error("Error inserting data", err);
                return res.status(500).json({ status: 500, message: "Database insertion error" });
            }
            console.log("Data added successfully");
            res.status(201).json({ status: 201, data: userData });
        });







       


    } catch (error) {
        console.error("Error in try block", error);
        res.status(500).json({ status: 500, message: "Internal server error" });
    }
});




// ! i want to show all data of app_registration 
app.get("/all-data-app_registration",(req,res)=>
{
    try {
        connection.query("SELECT * FROM app_registration",(err,result)=>{
            if(err){
                console.log(err)
            }else{
                console.log("get data successfully");
                res.status(201).json({ status: 201, data: result })
            }
        })
    } catch (error) {
        res.status(422).json({ status: 422, error })
    }
}
)



// Get all data (assuming this is for populating the select dropdown)
// app.get("/testing-get-data", (req, res) => {
//     conn.query("SELECT ao_id, ao_name FROM some_table", (err, results) => {
//         if (err) {
//             console.error("Error fetching data", err);
//             return res.status(500).json({ status: 500, message: "Database fetching error" });
//         }
//         res.status(200).json(results);
//     });
// });


// !
// // Multer storage configuration
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         cb(null, './public/Images');
//     },
//     filename: function (req, file, cb) {
//         cb(null, `${Date.now()}_${file.originalname}`);
//     }
// });

// const upload = multer({ storage });

// app.post('/testing', upload.single('ar_org_logo'), (req, res) => {
//     const { ar_org_name, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id } = req.body;
//     const ar_org_logo = req.file.filename;

//     const sql = "INSERT INTO app_registration (ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
//     const values = [ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id];

//     connection.query(sql, values, function (err, result) {
//         if (err) {
//             console.error('Error inserting into app_registration:', err);
//             return res.status(500).json({ message: 'Registration failed', error: err.message });
//         }
//         console.log("Registration record inserted: " + result.affectedRows);
//         res.status(200).json({ message: 'Successfully registered', ao_id: ar_occecation_id });
//     });
// });




                                                                                                                                                                                                                                


// !

// app.post('/testing', (req, res) => {
//     const { ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id } = req.body;

//     const sql = "INSERT INTO app_registration (ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id) VALUES ?";
//     const values = [[ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id]];

//     connection.query(sql, [values], function (err, result) {
//         if (err) {
//             console.error('Error inserting into app_registration:', err);
//             return res.status(500).json({ message: 'Registration failed not send ' });
//         }
//         console.log("Registration record inserted: " + result.affectedRows);
//         res.status(200).json({ message: 'Successfully send bireswar', ao_id: ar_occecation_id });
//     });
// });




app.get('/testing-get-data', (req, res) => {
    const query = 'SELECT * FROM app_occasion';
    connection.query(query, (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json(results);
    });
});



// // for file upload
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         return cb(null, "./public/Images")
//     },
//     filename: function (req, file, cb) {
//         return cb(null, `${Date.now()}_${file.originalname}`)
//     }
// })

// const upload = multer({ storage })

// app.post('/upload', upload.single('file'), (req, res) => {
//     console.log(req.body)
//     console.log(req.file)
// })


// // app.post('/upload', upload.single('image'), (req, res) => {
// //     const image = req.file.filename;
// //     const sql = "UPDATE app_registration SET ar_org_logo = ?";
// //     db.query(sql, [image], (err, result) => {
// //         if (err) return res.json({ Message: "Error" });
// //         return res.json({ Status: "Success" });
// //     });
// // });


// // demo 002
// app.post('/upload', upload.single('image'), (req, res) => {
//     const image = req.file.filename;

//     const sql = "UPDATE users SET image = ? WHERE id = ?";  // Adjust the query as needed
//     const userId = 3;  // Replace with the actual user ID
//     const values = [image, userId];

//     db.query(sql, values, (err, result) => {
//         if (err) {
//             return res.json({ Message: "Error" });
//         }
//         return res.json({ Status: "Success" });
//     });
// });













// TODO testing



app.put('/update-application-status/:userId', async (req, res) => {
    const { userId } = req.params;
    const { application_status } = req.body;

    // Update logic for the database (example using a fictitious database function)
    // await database.updateApplicationStatus(userId, application_status);

    // var sql = "UPDATE  leave_from_rgpl SET application_status = 1 WHERE id = ?",[userId];
    connection.query('UPDATE leave_from_rgpl SET ? WHERE id = ?', [{ application_status: "1" }, userId]);


    // connection.query(sql, function (err, result) {
    //     if (err) throw err;
    //     console.log("Records updated: " + result.affectedRows);
    //     // Show alert message
    //     res.status(200).send('Login data received');
    //   });
    console.log("working")




});







app.put('/rejected/:userId', async (req, res) => {
    const { userId } = req.params;
    const { application_status } = req.body;

    // Update logic for the database (example using a fictitious database function)
    // await database.updateApplicationStatus(userId, application_status);

    // var sql = "UPDATE  leave_from_rgpl SET application_status = 1 WHERE id = ?",[userId];
    connection.query('UPDATE leave_from_rgpl SET ? WHERE id = ?', [{ application_status: "2" }, userId]);


    // connection.query(sql, function (err, result) {
    //     if (err) throw err;
    //     console.log("Records updated: " + result.affectedRows);
    //     // Show alert message
    //     res.status(200).send('Login data received');
    //   });
    console.log("working")




});











// app_super_section
// login_table_rgpl


// !  login from app_super_section
app.post('/aa', (req, res) => {
    const sql = "SELECT * FROM app_super_section WHERE email = ? AND password = ?";
    // const values = [
    //     req.body.email,
    //     req.body.password
    // ];

    connection.query(sql, [req.body.email, req.body.password], (err, data) => {
        if (err) return res.json("Login Failed");
        if (data.length > 0) {
            return res.json("Login Successful")

        } else {
            return res.json("INCORRECT EMAIL OR PASSWORD");
        }


    });
});









// var sql = "INSERT INTO leave_from_rgpl (name, college_name, class_coordinator_name, leave_date_from, leave_time_from, leave_date_up_to, leave_time_up_to, leave_type, reason_for_leave) VALUES ?";
// var values = [
//   [name, college_name, class_coordinator_name, `DATE_FORMAT('${leave_date_from}', '%Y-%m-%d`, // Format the date `TIME_FORMAT('${leave_time_from}', '%H:%i:%s.%f`, // Format the time `DATE_FORMAT('${leave_date_up_to}', '%Y-%m-%d`, // Format the date `TIME_FORMAT('${leave_time_up_to}', '%H:%i:%%f')`, // Format the time leave_type, reason_for_leave,
//   ],
// ];

// connection.query(sql, [values], function (err, result) {
//   if (err) throw err;
//   console.log("Records inserted: " + result.affectedRows);
//   // Show alert message
//   res.status(200).send('Login data received');
// });








// !my code
// app.post('/login', (req, res) => {
//     const { username, password } = req.body;

//     console.log('Received login data:');
//     // console.log('Username:', username);
//     // console.log('Password:', password);

//   var q = req.body.username;
//   var w = req.body.password;
// //   console.log(q,w);

// // module.exports =q;

//   // Export q and w variables




//   res.status(200).send('Login data received');


// });






// connection.connect((err) => {
//   if (err) {
//       console.log(err.message);
//   }
// //     //! this is i added for database state 
//   console.log('db ' + connection.state);
//   // console.log(q)
//   // console.log(msg);
// // });

// var sql = "INSERT INTO login (name,user_name,password) VALUES ?";

// // var { q, w } = require('./app');
// // console.log(q,w);

// var values =[[q,w,'123456']];

// connection.query(sql, [values], function (err, result) {
// if (err) throw err;
// console.log("records inserted: "+result.affectedRows);
// });

// });




// // Get all beers
// app.get('', (req, res) => {
//     pool.getConnection((err, connection) => {
//         if (err) throw err;
//         console.log(`connected as id ${connection.threadId}`);

//         connection.query('SELECT * from login', (err, rows) => {
//             connection.release(); // return the connection to the pool

//             if (err) {
//                 res.send(rows);
//             } else {
//                 console.log(err);
//             }
//         });
//     });
// });











app.get('/get-all-data', (req, res) => {
    const query = 'SELECT * FROM leave_from_rgpl';
    connection.query(query, (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json(results);
    });
});









app.put('/update-data/:id', (req, res) => {
    const { id } = req.params;
    const { newData } = req.body; // Replace `newData` with actual fields you want to update
    const query = 'UPDATE login SET ? WHERE id = ?'; // Replace with your table and field names

    connection.query(query, [newData, id], (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json({ success: true, message: 'Data updated successfully', results });
    });
});





// Endpoint to delete data
app.delete('/delete-data/:id', (req, res) => {
    const { id } = req.params;
    const query = 'DELETE FROM login WHERE id = ?';
    connection.query(query, [id], (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json({ success: true, message: 'Data deleted successfully', results });
    });
});






app.listen(process.env.PORT, () => console.log('app is running -->', process.env.PORT));


// module.exports = 'hello world';
content_copyCOPY