POS_node/index.js

740 lines
20 KiB
JavaScript

import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import atob from "atob";
import dotenv from "dotenv";
import multer from "multer";
import helmet from "helmet";
import morgan from "morgan";
import path from "path";
import { fileURLToPath } from "url";
import authRoutes from "./routes/auth.js";
import userRoutes from "./routes/users.js";
import kdsRoutes from "./routes/kds.js";
import http from 'http';
import Odoo from "odoo-xmlrpc";
// import webemailRoutes from "./routes/webemail.js";
import axios from "axios";
import WebSocket, { WebSocketServer } from "ws";
// import nodemailer from "nodemailer";
// export const ws = new WebSocket("ws://192.168.50.15:4028/sT1eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjY2NDE3OTI4MmE3M2ZlZWQ3MjgyM2ViOCIsImlhdCI6MTcxNTY2ODI4Nn0.ziEOLreXbCJRlyjRyIVLDsJNpeIvk73rf3kU7_HtO8E"
// );
// ws.onopen = () => {
// console.log("WebSocket connected------------------------------------------");
// // You can send initial messages after the connection is established if needed
// // ws.send("Hello, server!");
// // const userId = "meeeee2";
// ws.send(JSON.stringify({ type: "join", userId: "obnPay_test" }));
// // ws.send(encryptedMessage2);
// };
// ws.onclose = () => {
// console.log("Connection closed");
// };
/* CONFIGURATIONS */
let cachedOrders = []; // Cache for storing the last fetched orders
function fetchTodayOrders() {
// Connect to Odoo server
odooClient2.connect(function (err) {
if (err) {
console.log("Connection Error:", err);
return; // Handle connection error
}
console.log("Connected to Odoo server.");
// Get today's date range
const today = new Date();
const startOfDay = new Date(today.setHours(0, 0, 0, 0));
const endOfDay = new Date(today.setHours(23, 59, 59, 999));
// Fetch order IDs for today
const inParams = [];
inParams.push([["date_order", ">=", startOfDay], ["date_order", "<=", endOfDay]]);
const params = [inParams];
// Search for today's orders
odooClient2.execute_kw("pos.order", "search", params, function (err, ids) {
if (err) {
console.log("Search Error:", err);
return; // Handle search error
}
// If no orders found for today
if (ids.length === 0) {
console.log("No orders found for today.");
return; // No orders found
}
// Fetch order records
const inParamsRead = [ids]; // IDs
const paramsRead = [inParamsRead];
odooClient2.execute_kw("pos.order", "read", paramsRead, function (err2, records) {
if (err2) {
console.log("Read Error:", err2);
return; // Handle read error
} else {
const newOrders = records; // New orders fetched from Odoo
// Check for new orders against cached orders
if (JSON.stringify(newOrders) !== JSON.stringify(cachedOrders)) {
cachedOrders = newOrders; // Update cache
// Notify WebSocket clients of the new data
const messageContent = {
type: "new_order",
content: {
message: "The KDS has been updated with new data"
}
};
console.log("New orders:");
// Broadcast the message to all WebSocket clients
broadcastMessage(messageContent);
}
}
});
});
});
}
const orderCheckInterval = setInterval(fetchTodayOrders, 3000);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config();
const app = express();
let wss;
app.use(express.json());
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
app.use(morgan("common"));
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
app.use("/assets", express.static(path.join(__dirname, "upload_files")));
/* FILE STORAGE */
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const category = req.body.category;
// if (category == "message") {
// cb(null, "message_uploads");
// } else if (category == "user") {
// cb(null, "user_uploads");
// } else {
cb(null, "upload_files");
// }
},
filename: (req, file, cb) => {
const image_id = req.body.image_id;
cb(null, image_id + "-" + file.originalname);
},
});
const upload = multer({ storage });
/* ROUTES */
app.use("/api/auth", authRoutes);
app.use("/api/users", userRoutes);
app.use("/api/kds", kdsRoutes);
// app.use("/api/web-emails", webemailRoutes);
app.post("/api/upload_images", upload.single("image"), async (req, res) => {
try {
const { filename } = req.file;
const { image_id, category } = req.body;
res.status(201).send({ filename, category, image_id });
} catch (error) {
res.status(400).send(error);
}
});
function sendEmail(req, res, next) {
const apiKey =
"ODA4MDc4ZThjMDA4NjVhYzU4MTcyNDJjNTMxY2JlZGU6MGQ4ODg3ZTdiZjY1ZWNkMmQ0NzdiOWJhZGIyYTJhY2Q=";
const apiUrl = "https://api.mailjet.com/v3.1/send";
// const otp = generateOTP(6); // You should have a function to generate the OTP
const email2 = "kramblooda@gmail.com";
const min = 100000; // Minimum 6-digit number
const max = 999999; // Maximum 6-digit number
const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
const requestData = {
Messages: [
{
From: {
Email: "webdev@obanana.com",
Name: "Obanana B2B",
},
To: [
{
Email: req.body.email,
Name: "Subscriber",
},
],
Subject: "Obanana OTP",
TextPart: "Greetings from Obanana!",
HTMLPart: req.body.html,
},
],
};
const config = {
headers: {
"Content-Type": "application/json",
Authorization: `Basic ${apiKey}`,
},
};
axios
.post(apiUrl, requestData, config)
.then((response) => {
// const status = response.data.Messages[0].Status;
// console.log(response.data.Messages[0].Status);
// console.log(randomNumber);
// setotpSent(randomNumber);
res.status(200).json(response.data);
// return `${status},${randomNumber}`;
})
.catch((error) => {
res.status(404).json({ message: error });
// console.error("Error sending OTP email:", error);
// Handle the error here
});
}
app.post("/api/send-email/", sendEmail);
app.post('/odoo-webhook', (req, res) => {
const newOrder = req.body;
console.log('New POS order received:', newOrder);
// Process the order data as needed
// For example, send it to a WebSocket, log it, or store it in a database
res.status(200).send('Webhook received');
});
// const odooClient = new Odoo({
// url: "http://192.168.50.15:8070",
// db: "gis.pivi.com.ph",
// username: "egalang@obanana.com",
// password: "P@$$w0rd!",
// });
const odooClient2 = new Odoo({
url: "http://192.168.50.15:8071",
db: "pos.obanana.com",
username: "mahipe@obanana.com",
password: "P@$$w0rd!",
});
app.get("/get-orders", async (req, res) => {
try {
odooClient2.connect(async function (err) {
if (err) {
console.log(err);
return res
.status(500)
.json({ error: "Connection Error: " + err.message });
}
console.log("Connected to Odoo server.");
// Fetch asset IDs
const inParams = [];
inParams.push([["name", "!=", false]]);
inParams.push(parseInt(req.query.offset) || 0); //offset
inParams.push(parseInt(req.query.limit) || 0); //Limit
const params = [inParams];
const assets = [];
let recordsArray = [];
let attributes = [];
let bounds = [];
let images = [];
odooClient2.execute_kw(
"pos.order",
"search",
params,
async function (err, ids) {
if (err) {
console.log(err);
return res
.status(500)
.json({ error: "Search Error: " + err.message });
}
if (ids.length === 0) {
return res.json([]); // No assets found
}
// Fetch asset records
const inParamsRead = [];
inParamsRead.push(ids); // IDs
const paramsRead = [inParamsRead];
odooClient2.execute_kw(
"pos.order",
"read",
paramsRead,
async function (err2, records) {
if (err2) {
console.log(err2);
return res
.status(500)
.json({ error: "Read Error: " + err2.message });
} else {
recordsArray = records;
res.json(recordsArray);
}
let pendingRequests = records.length;
}
);
}
);
});
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: "Data Fetch Error: " + error.message });
}
});
app.get("/get-products", async (req, res) => {
try {
odooClient2.connect(async function (err) {
if (err) {
console.log(err);
return res
.status(500)
.json({ error: "Connection Error: " + err.message });
}
console.log("Connected to Odoo server.");
// Fetch asset IDs
const inParams = [];
inParams.push([["name", "!=", false]]);
inParams.push(parseInt(req.query.offset) || 0); //offset
inParams.push(parseInt(req.query.limit) || 0); //Limit
const params = [inParams];
const assets = [];
let recordsArray = [];
let attributes = [];
let bounds = [];
let images = [];
odooClient2.execute_kw(
"product.template",
"search",
params,
async function (err, ids) {
if (err) {
console.log(err);
return res
.status(500)
.json({ error: "Search Error: " + err.message });
}
if (ids.length === 0) {
return res.json([]); // No assets found
}
// Fetch asset records
const inParamsRead = [];
inParamsRead.push(ids); // IDs
inParamsRead.push(["id", "name"]);
const paramsRead = [inParamsRead];
odooClient2.execute_kw(
"product.template",
"read",
paramsRead,
async function (err2, records) {
if (err2) {
console.log(err2);
return res
.status(500)
.json({ error: "Read Error: " + err2.message });
} else {
recordsArray = records;
res.json(recordsArray);
}
let pendingRequests = records.length;
}
);
}
);
});
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: "Data Fetch Error: " + error.message });
}
});
app.get("/get-product_ordered", async (req, res) => {
try {
odooClient2.connect(async function (err) {
if (err) {
console.log(err);
return res
.status(500)
.json({ error: "Connection Error: " + err.message });
}
console.log("Connected to Odoo server.");
// Fetch asset IDs
const inParams = [];
inParams.push([["name", "!=", false]]);
inParams.push(parseInt(req.query.offset) || 0); //offset
inParams.push(parseInt(req.query.limit) || 0); //Limit
const params = [inParams];
const assets = [];
let recordsArray = [];
let attributes = [];
let bounds = [];
let images = [];
odooClient2.execute_kw(
"pos.order.line",
"search",
params,
async function (err, ids) {
if (err) {
console.log(err);
return res
.status(500)
.json({ error: "Search Error: " + err.message });
}
if (ids.length === 0) {
return res.json([]); // No assets found
}
// Fetch asset records
const inParamsRead = [];
inParamsRead.push(ids); // IDs
// inParamsRead.push([
// "id",
// "name",
// ]);
const paramsRead = [inParamsRead];
odooClient2.execute_kw(
"pos.order.line",
"read",
paramsRead,
async function (err2, records) {
if (err2) {
console.log(err2);
return res
.status(500)
.json({ error: "Read Error: " + err2.message });
} else {
recordsArray = records;
res.json(recordsArray);
}
let pendingRequests = records.length;
}
);
}
);
});
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: "Data Fetch Error: " + error.message });
}
});
app.get("/get-stages", async (req, res) => {
try {
odooClient2.connect(async function (err) {
if (err) {
console.log(err);
return res
.status(500)
.json({ error: "Connection Error: " + err.message });
}
console.log("Connected to Odoo server.");
// Fetch asset IDs
const inParams = [];
inParams.push([["name", "!=", false]]);
inParams.push(parseInt(req.query.offset) || 0);
inParams.push(parseInt(req.query.limit) || 0);
const params = [inParams];
const assets = [];
let recordsArray = [];
let attributes = [];
let bounds = [];
let images = [];
odooClient2.execute_kw(
"kds.stages",
"search",
params,
async function (err, ids) {
if (err) {
console.log(err);
return res
.status(500)
.json({ error: "Search Error: " + err.message });
}
if (ids.length === 0) {
return res.json([]); // No assets found
}
// Fetch asset records
const inParamsRead = [];
inParamsRead.push(ids); // IDs
// inParamsRead.push([
// "id",
// "name",
// ]);
const paramsRead = [inParamsRead];
odooClient2.execute_kw(
"kds.stages",
"read",
paramsRead,
async function (err2, records) {
if (err2) {
console.log(err2);
return res
.status(500)
.json({ error: "Read Error: " + err2.message });
} else {
recordsArray = records;
res.json(recordsArray);
}
let pendingRequests = records.length;
}
);
}
);
});
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: "Data Fetch Error: " + error.message });
}
});
app.post('/update-order-state', async (req, res) => {
const { id, state } = req.body;
if (!id || !state) {
return res.status(400).json({ error: 'Order ID and state are required.' });
}
try {
odooClient2.connect(function (err) {
if (err) {
console.log(err);
return res.status(500).json({ error: 'Connection Error: ' + err.message });
}
console.log('Connected to Odoo server.');
const inParams = [];
inParams.push([['id', '=', id]]);
const params = [inParams];
odooClient2.execute_kw('pos.order', 'search', params, function (err, orderIds) {
if (err) {
console.log(err);
return res.status(500).json({ error: 'Search Error: ' + err.message });
}
if (orderIds.length === 0) {
return res.status(404).json({ error: 'Order not found.' });
}
const inParamsUpdate = [];
inParamsUpdate.push(orderIds);
inParamsUpdate.push({ state: state });
const paramsUpdate = [inParamsUpdate];
odooClient2.execute_kw('pos.order', 'write', paramsUpdate, function (err2, result) {
if (err2) {
console.log(err2);
return res.status(500).json({ error: 'Update Error: ' + err2.message });
}
if (result) {
return res.json({ success: true, message: `Order ID ${id} updated to state: ${state}` });
} else {
return res.status(500).json({ error: 'Failed to update order state.' });
}
});
});
});
} catch (error) {
console.error('Error:', error);
return res.status(500).json({ error: 'Update Error: ' + error.message });
}
});
app.get("/get-tables", async (req, res) => {
try {
odooClient2.connect(async function (err) {
if (err) {
console.log(err);
return res
.status(500)
.json({ error: "Connection Error: " + err.message });
}
console.log("Connected to Odoo server.");
// Fetch asset IDs
const inParams = [];
inParams.push([["name", "!=", false]]);
inParams.push(parseInt(req.query.offset) || 0);
inParams.push(parseInt(req.query.limit) || 0);
const params = [inParams];
const assets = [];
let recordsArray = [];
let attributes = [];
let bounds = [];
let images = [];
odooClient2.execute_kw(
"restaurant.table",
"search",
params,
async function (err, ids) {
if (err) {
console.log(err);
return res
.status(500)
.json({ error: "Search Error: " + err.message });
}
if (ids.length === 0) {
return res.json([]); // No assets found
}
// Fetch asset records
const inParamsRead = [];
inParamsRead.push(ids); // IDs
// inParamsRead.push([
// "id",
// "name",
// ]);
const paramsRead = [inParamsRead];
odooClient2.execute_kw(
"restaurant.table",
"read",
paramsRead,
async function (err2, records) {
if (err2) {
console.log(err2);
return res
.status(500)
.json({ error: "Read Error: " + err2.message });
} else {
recordsArray = records;
res.json(recordsArray);
}
let pendingRequests = records.length;
}
);
}
);
});
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: "Data Fetch Error: " + error.message });
}
});
// function fetchOdooData(model, method, params) {
// return new Promise((resolve, reject) => {
// odooClient.execute_kw(model, method, params, (err, data) => {
// if (err) return reject(err);
// resolve(data);
// });
// });
// }
/* MONGOOSE SETUP */
const PORT = process.env.PORT || 3002;
// mongoose
// .connect(process.env.MONGO_URL, {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// })
// .then(() => {
// app.listen(PORT, () => console.log(`Server Port: ${PORT}`));
// // /* ADD DATA ONE TIME */
// })
// .catch((error) => console.log(`${error} did not connect`));
// mongoose
// .connect(process.env.DATABASE_URL)
// .then(() => {
// app.listen(PORT, () => console.log(`Server Port: ${PORT}`));
// // /* ADD DATA ONE TIME */
// })
// .catch((error) => console.log(`${error} did not connect`));
mongoose.connect(process.env.DATABASE_URL)
.then(() => {
const server = http.createServer(app);
try {
wss = new WebSocketServer({ server });
wss.on('connection', (ws) => {
console.log('A user connected');
ws.on('message', (message) => {
console.log('Received from client: ', message);
});
ws.on('close', () => {
console.log('A user disconnected');
});
});
wss.on('listening', () => {
console.log('WebSocket server is running and ready to accept connections');
});
}catch(error){
console.log(`Server failed on port ${PORT}`);
}
// Start the server and WebSocket
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
})
.catch((error) => console.log(`${error} did not connect`));
export const broadcastMessage = (message) => {
wss.clients.forEach((client) => {
if (client.readyState === client.OPEN) {
client.send(JSON.stringify(message));
}
});
};