require("dotenv").config(); const express = require("express"); const session = require("express-session"); const multer = require("multer"); const fs = require('fs'); const path = require('path'); const app = express(); const bcrypt = require("bcrypt"); const bodyParser = require("body-parser"); const cors = require("cors"); const mysql = require("mysql2"); let cookieParser = require("cookie-parser"); app.use( session({ secret: "your-secret-key", resave: false, saveUninitialized: false, cookie: { secure: false, }, }) ); app.use(cookieParser()); const pool = mysql.createPool({ host: "localhost", user: "newroot", password: "some_password", database: "kadev_kinaryaPos", connectionLimit: 100, // Set your preferred connection limit }); app.use(bodyParser.json()); app.use( cors({ origin: "https://syskinaryacorp.com", credentials: true, // Allow credentials (cookies) }) ); app.use((req, res, next) => { req.mysql = pool.promise(); next(); }); const storage = multer.diskStorage({ destination: function (req, file, cb) { let destinationDir = ""; // Check the request path to determine the destination directory if (req.path === "/updateItems") { destinationDir = "../../syskinaryacorp.com/public_html/assets/img/itemImg"; } else if (req.path === "/updateProfile") { destinationDir = "../../syskinaryacorp.com/public_html/assets/img/profileImg"; } else { // Default destination directory destinationDir = "../../syskinaryacorp.com/public_html/assets/img"; } cb(null, destinationDir); }, filename: function (req, file, cb) { const destinationDir = this.destinationDir || ""; // Access destinationDir from multer storage context // Check if the file with the same name already exists const fileExt = path.extname(file.originalname); fs.access( path.join(destinationDir, file.originalname), fs.constants.F_OK, (err) => { if (err) { if (req.path === "/updateItems") { cb(null, req.body.itemCode+fileExt); } else if (req.path === "/updateProfile") { cb(null, req.body.username+fileExt); } } else { if (req.path === "/updateItems") { cb(null, req.body.itemCode+fileExt); } else if (req.path === "/updateProfile") { cb(null, req.body.username+fileExt); } } } ); }, }); const upload = multer({ storage: storage }); app.get("/", (req, res) => { res.send("C'mon Bros send me request! Got it!."); console.log(req.session); // Log the entire session object }); app.post("/updateItems", upload.single("itemPicture"), async (req, res) => { try { const { itemId, brandItem, categoryItem, description, itemCode, itemHpp, itemName, itemPrice, itemStock, itemUnit, } = req.body; const itemPicture = req.file ? `item_picture='${req.file.filename}',` : ""; // Get the filename if file was uploaded // Update the item details in the database const query = "UPDATE pos_inventory SET brand_id=?, category_id=?, item_descript=?, item_code=?, item_hpp=?, item_name=?, "+itemPicture+" item_price=?, item_stock=?, conversion_id=? WHERE item_id=?"; const [result] = await req.mysql.query(query, [ brandItem, categoryItem, description, itemCode, itemHpp, itemName, itemPrice, itemStock, itemUnit, itemId, ]); res.json(result); } catch (error) { console.error("Error updating item:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.get("/iseng", (req, res) => { req.session.user = "example"; res.send("stored"); console.log(req.session); }); app.get("/cekSession", (req, res) => { if (req.session.user) { res.json({login:1,userDetail:req.session}); } else { res.json({ login: 0 }); } }); app.get("/profile", (req, res) => { res.send(`welcome your login Session ${req.session.user}, id=${req.session.user_id}`); }); app.post("/saveSetting", async (req, res) => { try { const { auth, auther, userPower, corp_name, corp_code, corp_address } = req.body; // Update pos_corp table const queryCorp = "UPDATE pos_corp SET corp_name=?, corp_code=?, corp_address=? WHERE corp_id=1"; await req.mysql.query(queryCorp, [corp_name, corp_code, corp_address]); // Update pos_auth table const promises = Object.entries(auth).map(([key, value]) => { const queryAuth = `UPDATE pos_auth SET ${key}=? WHERE auth_id=?`; console.log(queryAuth) console.log(value) console.log(userPower) return req.mysql.query(queryAuth, [value, userPower]); }); await Promise.all(promises); // Update pos_auther table const promisese = Object.entries(auther).map(async ([key, value]) => { const [transactionType_id, id_auth] = key.split('||||'); const checkDB = `SELECT * FROM pos_authTransaction WHERE user_power=? AND transactionType_id=?`; const [existingEntry] = await req.mysql.query(checkDB, [userPower, id_auth]); let queryAuther; if (value == 0 && existingEntry.length > 0) { queryAuther = `DELETE FROM pos_authTransaction WHERE user_power=? AND transactionType_id=?`; await req.mysql.query(queryAuther, [userPower, id_auth]); } else if (value == 1 && existingEntry.length === 0) { queryAuther = `INSERT INTO pos_authTransaction (user_power, transactionType_id) VALUES (?, ?)`; await req.mysql.query(queryAuther, [userPower, id_auth]); } }); await Promise.all(promisese); res.json({ success: true }); } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/addUser", async (req, res) => { try { const { username, password, email, displayName } = req.body; const hashedPassword = await bcrypt.hash(password, 10); const query = "INSERT INTO pos_user (user_username,user_password,user_email,user_url,user_activationKey,user_status,user_power,user_displayName) values (?,?,?,?,?,?,?,?)"; const [result] = await req.mysql.query(query, [ username, hashedPassword, email, `https://syskinaryacorp.com/${username}`, hashedPassword, 0, 3, displayName, ]); res.json(result); } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.get("/getBranch", (req, res) => { const query = "SELECT * from pos_branch"; req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getSellingData", (req, res) => { let brancher; if(isNaN(req.query.branch)) brancher=`where pos_sellingDetail.user_username='${req.query.branch}'` else brancher=`where pos_sellingDetail.branch_id='${req.query.branch}'` const query = `SELECT pos_selling.selling_date,pos_selling.selling_totalAmmount,pos_selling.customer_id, pos_sellingDetail.* FROM pos_sellingDetail JOIN pos_selling ON pos_selling.selling_code = pos_sellingDetail.selling_code ${brancher}`; req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getSupplier", (req, res) => { const query = "SELECT * from pos_supplier"; req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getUser", (req, res) => { let branchi = ""; if (Number(req.query.branch) !== 0 && !isNaN(Number(req.query.branch))) branchi = `where user_branch='${req.query.branch}'`; else if(Number(req.query.branch) !== 0 &&isNaN(Number(req.query.branch))) branchi = `where user_username='${req.query.branch}'`; const query = `SELECT * from pos_user ${branchi}`; console.log(query); req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getPosition", (req, res) => { const query = "SELECT * from pos_auth"; req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getAuthTrans", (req, res) => { const query = "SELECT * from pos_transactionType"; req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getTxType", (req, res) => { const query = "SELECT * from pos_transactionType"; req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/makeInvNumb", (req, res) => { const today = new Date(); const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1); const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0); const query = `SELECT * FROM pos_selling WHERE user_username="${req.query.user}" AND selling_date BETWEEN '${firstDayOfMonth.toISOString().split('T')[0]}' AND '${lastDayOfMonth.toISOString().split('T')[0]}'`; console.log(query) req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getCorp", (req, res) => { const query = `SELECT * from pos_corp`; req.mysql .query(query) .then((result) => { res.json(result[0][0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getCategory", (req, res) => { const query = "SELECT * from pos_category"; req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getCustomer", (req, res) => { const query = `SELECT *, pos_customerAddress.customer_address,pos_customerContact.customerContact_contact FROM pos_customer JOIN pos_customerAddress ON pos_customer.customer_id = pos_customerAddress.customer_id JOIN pos_customerContact ON pos_customer.customer_id = pos_customerContact.customer_id`; req.mysql.query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getBrand", (req, res) => { const query = "SELECT * from pos_brand"; req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getItems", (req, res) => { let branchi; if (Number(req.query.branch) !== 0) branchi = `where branch_id='${req.query.branch}'`; else branchi = ""; const query = "SELECT * from pos_inventory " + branchi; console.log(query); req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/getConversion", (req, res) => { const query = "SELECT * from pos_conversion"; req.mysql .query(query) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/deletePos", (req, res) => { const query = "DELETE FROM pos_auth WHERE auth_id = ?"; req.mysql .query(query, [req.query.id]) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.get("/deleteConv", (req, res) => { const query = "DELETE FROM pos_conversion WHERE conversion_id = ?"; req.mysql .query(query, [req.query.id]) .then((result) => { res.json(result[0]); }) .catch((error) => { console.error(error); res.status(500).json({ error: "Internal Server Error" }); }); }); app.post("/insertPos", async (req, res) => { try { const { position } = req.body; position.forEach(async (element) => { const query = "INSERT INTO pos_auth (auth_position) VALUES (?)"; try { await req.mysql.query(query, [element]); } catch (error) { console.error("Error executing query:", error); throw error; // Throw the error to catch it in the outer catch block } }); res.json({ position: "inserted" }); } catch (error) { console.error("Error inserting positions:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/insertCategory", async (req, res) => { try { const { category } = req.body; category.forEach(async (element) => { const query = "INSERT INTO pos_category (category_name) VALUES (?)"; try { await req.mysql.query(query, [element]); } catch (error) { console.error("Error executing query:", error); throw error; // Throw the error to catch it in the outer catch block } }); res.json({ category: "inserted" }); } catch (error) { console.error("Error inserting category:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/insertBrand", async (req, res) => { try { const { brand } = req.body; brand.forEach(async (element) => { const query = "INSERT INTO pos_brand (brand_name) VALUES (?)"; try { await req.mysql.query(query, [element]); } catch (error) { console.error("Error executing query:", error); throw error; // Throw the error to catch it in the outer catch block } }); res.json({ brand: "inserted" }); } catch (error) { console.error("Error inserting brand:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/insertPurcashing", async (req, res) => { try { const { dateIn, dueTime, items, noInv, supplier, term, branch } = req.body; console.log(req.body) const query1 = "INSERT INTO pos_purcashingNotes (purcashingNotes_date, purcashingNotes_code, supplier_id, purcashingNotes_terms, purcashingNotes_dueTime, purcashingNotes_branch) VALUES (?, ?, ?, ?, ?, ?)"; await req.mysql.query(query1, [ dateIn, noInv, supplier, term, dueTime, branch, ]); const query2 = "INSERT INTO pos_purcashing (branch_id,purcashingNotes_code, item_code, item_name, purcashing_itemDisc, purcashing_itemPrice, purcashing_itemQty, purcashing_itemUnit) VALUES (?,?, ?, ?, ?, ?, ?, ?)"; for (const data of items) { await req.mysql.query(query2, [ branch, noInv, data.code, data.name, data.discount, data.price, data.qty, data.unit, ]); } res.json({ position: "inserted" }); } catch (error) { console.error("Error inserting positions:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/paymentInput", async (req, res) => { try { const { branch_id, cust, dateSell, invCode,totalAmmount,username,itemList } = req.body; const query1 = "INSERT INTO pos_selling (selling_code,customer_id, selling_date, selling_dueTime, selling_totalAmmount,user_username,branch_id) VALUES (?, ?, ?, ?, ?, ?,?)"; await req.mysql.query(query1, [ invCode, cust, dateSell, dateSell, totalAmmount, username,branch_id ]); console.log(itemList) const query2 = "INSERT INTO pos_sellingDetail (selling_code, item_code, sellingDetail_qty, sellingDetail_unit, sellingDetail_hpp,sellingDetail_Price,branch_id,user_username) VALUES (?,?, ?, ?, ?, ?, ?,?)"; for (const data of itemList) { console.log(data) await req.mysql.query(query2, [ invCode, data.itemCode, data.itemQty, data.itemUnit, data.itemHpp, data.itemPrice, branch_id, username ]); } res.json({ inserted:1 }); } catch (error) { console.error("Error inserting positions:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/insertInternTx", async (req, res) => { try { const { recievedBy, txCode, txDate, typeTx,branchId,txNotes,itemList } = req.body; const query1 = "INSERT INTO pos_internTransaction (internTxDetail_recievedBy,internTransaction_code, transactionType_id, internTransaction_notes, branch_id,internTransaction_date) VALUES (?, ?, ?, ?, ?, ?)"; await req.mysql.query(query1, [ recievedBy, txCode, typeTx, txNotes, branchId, txDate ]); console.log(itemList) const query2 = "INSERT INTO pos_internTxDetail (internTransactrion_code, branch_id, item_id, internTxDetail_qty, conversion_unit, internTxDetail_sendBy, internTxDetail_recievedBy) VALUES (?,?, ?, ?, ?, ?, ?)"; for (const data of itemList) { console.log(data) await req.mysql.query(query2, [ txCode, branchId, data.itemCode, data.itemQty, data.itemUnit, req.session.user_id, recievedBy, ]); } res.json({ inserted:1 }); } catch (error) { console.error("Error inserting positions:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/insertConversion", async (req, res) => { try { const { conversionList } = req.body; const promises = conversionList.map(async (element) => { const query = "INSERT INTO pos_conversion (conversion_unit, conversion_conv) VALUES (?,?)"; try { const result = await req.mysql.query(query, [ element.conversion_unit, element.conversion_val, ]); return result[0]; // Assuming result is an array and you want the first result } catch (error) { console.error("Error executing query:", error); throw error; } }); const results = await Promise.all(promises); res.json({ results }); } catch (error) { console.error("Error inserting positions:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/addBranch", async (req, res) => { try { const { branchCode, branchName, address } = req.body; const query = "INSERT INTO pos_branch (branch_code,branch_name,branch_address) values (?,?,?)"; const [result] = await req.mysql.query(query, [ branchCode, branchName, address, ]); res.json(result); } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/addCustomer", async (req, res) => { try { const { customerName, customerAddress, customerContact } = req.body; // Insert customer data into pos_customer table const query1 = "INSERT INTO pos_customer (customer_name) VALUES (?)"; const [result1] = await req.mysql.query(query1, [customerName]); const customerId = result1.insertId; // Get the inserted customer ID // Insert customer address into pos_customerAddress table const query2 = "INSERT INTO pos_customerAddress (customer_id, customer_address) VALUES (?, ?)"; const [result2] = await req.mysql.query(query2, [customerId, customerAddress]); // Insert customer contact into pos_customerContact table const query3 = "INSERT INTO pos_customerContact (customer_id, customerContact_contact) VALUES (?, ?)"; const [result3] = await req.mysql.query(query3, [customerId, customerContact]); res.json(result1); // Return the result of the first query } catch (error) { console.error("Error inserting customer data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/addStaff", async (req, res) => { try { const { branch, position, staffCode, staffName } = req.body; const hashedPassword = await bcrypt.hash("kinaryacorp", 10); const email = `${staffCode}@syskinaryacorp.com`; const query = "INSERT INTO pos_user (user_username,user_password,user_email,user_url,user_activationKey,user_status,user_power,user_displayName,user_branch) values (?,?,?,?,?,?,?,?,?)"; const [result] = await req.mysql.query(query, [ staffCode, hashedPassword, email, `https://syskinaryacorp.com/${staffCode}`, hashedPassword, 0, position, staffName, branch, ]); res.json(result); } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/updateBranch", async (req, res) => { try { const { branchCode, branchName, address } = req.body; const query = "UPDATE pos_branch set branch_name=?,branch_address=? where branch_code=?"; const [result] = await req.mysql.query(query, [ branchName, address, branchCode, ]); res.json(result); } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/updateCustomer", async (req, res) => { try { const { customerName, customerId, customerAddress, customerContact } = req.body; let query = "UPDATE pos_customer SET customer_name = ? WHERE customer_id = ?"; const [result1] = await req.mysql.query(query, [customerName, customerId]); query = "UPDATE pos_customerAddress SET customer_address = ? WHERE customer_id = ?"; const [result2] = await req.mysql.query(query, [customerAddress, customerId]); query = "UPDATE pos_customerContact SET customerContact_contact = ? WHERE customer_id = ?"; const [result3] = await req.mysql.query(query, [customerContact, customerId]); res.json({ success: true }); } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/updateStaff", async (req, res) => { try { const { staffCode, staffName, position } = req.body; const query = "UPDATE pos_user set user_displayName=?,user_power=? where user_username=?"; const [result] = await req.mysql.query(query, [ staffName, position, staffCode, ]); res.json(result); } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/deleteBranch", async (req, res) => { try { const { branchCode } = req.body; const query = "DELETE FROM pos_branch where branch_code=?"; const [result] = await req.mysql.query(query, branchCode); res.json(result); } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/deleteCustomer", async (req, res) => { try { const { customerId } = req.body; const query = "DELETE FROM pos_customer where customer_id=?"; const [result] = await req.mysql.query(query, customerId); res.json(result); } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/deleteStaff", async (req, res) => { try { const { staffCode } = req.body; const query = "DELETE FROM pos_user where user_username=?"; const [result] = await req.mysql.query(query, staffCode); res.json(result); } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); app.post("/loginUser", async (req, res) => { try { const { username, password } = req.body; const query = "SELECT * FROM pos_user WHERE user_username=?"; const [result] = await req.mysql.query(query, [username]); if (result.length > 0) { const hashedPassword = result[0].user_password; // Accessing the user_password property of the first row const isPasswordMatch = await bcrypt.compare(password, hashedPassword); // Await the comparison result if (isPasswordMatch) { req.session.user = username; req.session.user_id =result[0].user_id; req.session.user_branch =result[0].user_branch; req.session.displayName =result[0].user_displayName; req.session.userPow =result[0].user_power; req.session.save(() => { console.log("Session after saving:", req.session); res.json({ login: 1 }); }); } else { res.json({ login: 0 }); } } else { res.json({ login: 0 }); } } catch (error) { console.error("Error fetching data:", error); res.status(500).json({ error: "Internal Server Error" }); } }); // Route to destroy session app.get("/destroySession", (req, res) => { req.session.destroy((err) => { if (err) { console.error("Error destroying session:", err); res.json({ login: 0 }); } else { res.json({ login: 1 }); } }); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); Coming Soon

We're working on it!

This site is currently under construction.

Please check back soon.