Bhaskar 4 months ago
commit 3cd12707c9

@ -1,67 +0,0 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
.btn{
width: 90px;
height: 32px;
font-size:13px;
background-color: #47AFE8;
color: #fff;
border: none;
margin: 0 2px;
border-radius: 2px;
cursor:pointer;
outline:none;
}
.txt{
width: 100px;
height: 30px;
font-size:13px;
background-color: transparent;
border: 1px solid #47AFE8;
color: #fff;
padding:0 8px;
margin: 0 2px;
border-radius: 2px;
outline:none;
}
rapi-doc{
width:100%;
}
</style>
<script type="module" src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
<script>
function setApiKey(){
const docEl = document.getElementById('thedoc');
const keyInputEl = document.getElementById('key-val-input');
docEl.setAttribute('api-key-name','Authorization');
docEl.setAttribute('api-key-location','header');
docEl.setAttribute('api-key-value',keyInputEl.value);
}
</script>
</head>
<body>
<!-- Do not commit this file into the server , ignore it by adding it to .gitignore -->
<!----------------**************************--------------------->
<rapi-doc
spec-url="http://35.207.198.35.207.198.44:3000/documentation/json"
show-header = 'false'
allow-authentication ="true"
>
<!--
below html is custom html that adds an input field and a button in header
on clicking the button the 'api-key-value' is set to the value in input box
-->
<!--div slot='header' style='display:flex; margin:0 16px;'>
<input class='txt' id='key' type='text' >
<button class='btn' onclick='setApiKey()' > Set Key </button >
</div-->
</rapi-doc>
</body>
</html>

@ -6426,6 +6426,7 @@ setInterval(logSets, 30000);
const sendMotorNotifications = async () => { const sendMotorNotifications = async () => {
// console.log("🔄 Checking for motor notifications..."); // console.log("🔄 Checking for motor notifications...");
@ -6533,6 +6534,78 @@ exports.getPendingAndCompletedsurveyOfparticularInstaller = async (request, repl
//const mqtt = require('mqtt');
// Connect to test MQTT broker
const client2 = mqtt.connect('mqtt://34.100.133.20:1884', {
clientId: `mqtt_test_${Math.random().toString(16).substr(2, 8)}`,
clean: true,
reconnectPeriod: 2000,
});
// Sets to track active devices
const subscribedTopics2 = new Set();
const activeDevices2 = new Set(); // Keep track of active devices
client2.on('connect', () => {
console.log('✅ Connected to TEST MQTT broker');
// Subscribe to the announcement topic
client2.subscribe('water/iot-data/announce', { qos: 1 }, (err) => {
if (err) {
console.error('❌ Failed to subscribe to announce topic:', err);
} else {
console.log('📡 Subscribed to water/iot-data/announce');
}
});
});
client2.on('message', (topic, message) => {
console.log(`📩 [${topic}] ${message.toString()}`);
try {
const data = JSON.parse(message.toString());
// If announcement message received
if (topic === 'water/iot-data/announce') {
if (data.objects && data.objects.hw_Id) {
const hw_Id = data.objects.hw_Id;
const deviceTopic = `water/iot-data/${hw_Id}`;
if (!subscribedTopics2.has(deviceTopic)) {
client2.subscribe(deviceTopic, { qos: 1 }, (err) => {
if (err) {
console.error(`❌ Failed to subscribe to ${deviceTopic}:`, err);
} else {
console.log(`✅ Subscribed to ${deviceTopic}`);
subscribedTopics2.add(deviceTopic);
}
});
} else {
console.log(`🔄 Already subscribed to ${deviceTopic}`);
}
} else {
console.error('❌ Invalid announce message, missing hw_Id');
}
}
} catch (err) {
console.error('❌ Failed to parse message:', err);
}
});
client2.on('error', (err) => console.error('❌ MQTT Error:', err));
client2.on('close', () => console.log('⚠️ MQTT2 Connection Closed.'));
client2.on('offline', () => console.log('⚠️ MQTT Broker Offline.'));
function logSets1() {
console.log("Subscribed Topics2:", Array.from(subscribedTopics2));
console.log("Active Devices2:", Array.from(activeDevices2));
}
// Call logSets every 30 seconds
setInterval(logSets1, 30000);
@ -7851,4 +7924,75 @@ exports.compareMeasuredHeight = async (req, reply) => {
console.error("Error in compareMeasuredHeight:", err); console.error("Error in compareMeasuredHeight:", err);
reply.status(500).send({ message: err.message }); reply.status(500).send({ message: err.message });
} }
}; };
//const ExcelJS = require('exceljs');
//const IotData = require('../models/IotData'); // adjust the path
// async function generateAndSaveTankExcel() {
// const startDate = "2025-06-03T00:00:00.000Z";
// const endDate = new Date().toISOString();
// const getFilteredData = async (hardwareId) => {
// const query = {
// hardwareId,
// date: {
// $gte: startDate,
// $lte: endDate,
// },
// };
// console.log(`Fetching data for hardwareId: ${hardwareId}`);
// const results = await IotData.find(query).sort({ date: 1 });
// console.log(`Found ${results.length} records for hardwareId ${hardwareId}`);
// const data = [];
// for (const entry of results) {
// if (!entry.tanks || !Array.isArray(entry.tanks)) continue;
// for (const tank of entry.tanks) {
// if (tank.tankhardwareId === 'tank-1' || tank.tankhardwareId === 'tank-2') {
// data.push({
// hardwareId: entry.hardwareId,
// tankhardwareId: tank.tankhardwareId,
// tankHeight: tank.tankHeight,
// date: tank.date.split('T')[0], // safe because it's a string
// time: tank.time,
// });
// }
// }
// }
// console.log(`Filtered ${data.length} tank records for hardwareId ${hardwareId}`);
// return data;
// };
// const data140924 = await getFilteredData("140924");
// const data150924 = await getFilteredData("150924");
// const workbook = new ExcelJS.Workbook();
// const worksheet = workbook.addWorksheet("Tank Data");
// worksheet.columns = [
// { header: "Hardware ID", key: "hardwareId", width: 15 },
// { header: "Tank ID", key: "tankhardwareId", width: 15 },
// { header: "Tank Height", key: "tankHeight", width: 15 },
// { header: "Date", key: "date", width: 15 },
// { header: "Time", key: "time", width: 15 },
// ];
// const allData = [...data140924, ...data150924];
// allData.forEach(row => worksheet.addRow(row));
// await workbook.xlsx.writeFile("tank_data.xlsx");
// console.log("✅ Excel file saved as tank_data.xlsx with rows:", allData.length);
// }
// generateAndSaveTankExcel();

@ -1,6 +1,7 @@
//Get the data models //Get the data models
const { Supplier, DeliveryBoy, profilePictureSupplier } = require("../models/supplier"); const { Supplier, DeliveryBoy, profilePictureSupplier } = require("../models/supplier");
const { FriendRequest } = require("../models/supplier"); const { FriendRequest } = require("../models/supplier");
const { Tanker,Tankerbooking } = require("../models/tankers");
const { ProfilePicture, User } = require("../models/User"); const { ProfilePicture, User } = require("../models/User");
const supplierController = require("../controllers/supplierController"); const supplierController = require("../controllers/supplierController");
const customJwtAuth = require("../customAuthJwt"); const customJwtAuth = require("../customAuthJwt");
@ -938,44 +939,105 @@ exports.getCurrentSupplier = async (req, reply) => {
// } // }
// }; // };
exports.getSuppliers = async (req, reply) => {
const customerId = req.params.customerId;
const {
type_of_water,
capacity: requestedCapacityStr,
quantity: requestedQuantityStr,
date,
time
} = req.body;
const parseCapacity = (value) => parseFloat((value || "0").toString().replace(/,/g, ""));
const requestedCapacity = parseCapacity(requestedCapacityStr);
const requestedQuantity = parseInt(requestedQuantityStr || "0");
const totalRequiredCapacity = requestedCapacity * requestedQuantity;
exports.getSuppliers = async (req, reply) => {
const limit = parseInt(req.query.limit) || 100;
const page = parseInt(req.query.page) || 1;
const startindex = (page - 1) * limit;
const customerId = req.params.customerId; // Assuming you have already authenticated the user and stored their ID in the request object
try { try {
const friendRequests = await FriendRequest.find({ customerId }); const tankerBookings = await Tankerbooking.find({ date });
const supplierIdsToExclude = friendRequests.map( const bookedTankerSet = new Set(
(request) => request.supplierId tankerBookings.map(booking => `${booking.supplierId}_${booking.tankerName}`)
); );
const suppliers = await Supplier.find({ supplierId: { $nin: supplierIdsToExclude } })
.limit(limit)
.skip(startindex)
.exec();
const supplierIds = suppliers.map((supplier) => supplier.supplierId); // 1⃣ Only filter typeofwater first
const profilePictures = await profilePictureSupplier.find({ let tankers = await Tanker.find({ typeofwater: type_of_water });
supplierId: { $in: supplierIds },
}).exec();
const data = suppliers.map((supplier) => { // 2⃣ Exclude booked tankers
const profilePicture = profilePictures.find( tankers = tankers.filter(tanker => {
(picture) => picture.supplierId === supplier.supplierId const key = `${tanker.supplierId}_${tanker.tankerName}`;
return !bookedTankerSet.has(key);
});
// 3⃣ Group by supplierId
const supplierTankerMap = {};
for (let tanker of tankers) {
if (!supplierTankerMap[tanker.supplierId]) {
supplierTankerMap[tanker.supplierId] = [];
}
supplierTankerMap[tanker.supplierId].push(tanker);
}
// 4⃣ Aggregate supplier capacities
const qualifiedSuppliers = [];
for (let [supplierId, supplierTankers] of Object.entries(supplierTankerMap)) {
const totalAvailableCapacity = supplierTankers.reduce(
(sum, t) => sum + parseCapacity(t.capacity),
0
); );
return {
...supplier.toObject(), if (totalAvailableCapacity >= totalRequiredCapacity) {
picture: profilePicture ? profilePicture.picture : null, qualifiedSuppliers.push({ supplierId, tankers: supplierTankers });
}
}
const connected_suppliers = [];
const non_connected_suppliers = [];
for (let supplierObj of qualifiedSuppliers) {
const supplierData = await Supplier.findOne({ supplierId: supplierObj.supplierId });
const responseData = {
supplier: supplierData,
tankers: supplierObj.tankers
}; };
// 🔥 The correct friend request check:
const friendRequest = await FriendRequest.findOne({
customerId: customerId,
supplierId: supplierObj.supplierId
});
if (friendRequest && friendRequest.status === "accepted") {
connected_suppliers.push(responseData);
} else {
non_connected_suppliers.push(responseData);
}
}
reply.send({
status_code: 200,
connected_suppliers,
non_connected_suppliers
}); });
reply.send({ status_code: 200, data, count: data.length });
} catch (err) { } catch (err) {
throw boom.boomify(err); console.error(err);
reply.send({
status_code: 500,
message: "Something went wrong",
error: err.message
});
} }
}; };
// Get single user by ID // Get single user by ID
exports.getSingleSupplier = async (req, reply) => { exports.getSingleSupplier = async (req, reply) => {
try { try {

@ -8,7 +8,7 @@ const { profilePictureSupplier } = require("../models/supplier");
module.exports = function (fastify, opts, next) { module.exports = function (fastify, opts, next) {
fastify.get("/api/suppliers/:customerId", { fastify.post("/api/suppliersforbooking/:customerId", {
schema: { schema: {
tags: ["Supplier-Data"], tags: ["Supplier-Data"],
description: "This is for Get All Suppliers", description: "This is for Get All Suppliers",
@ -22,6 +22,18 @@ module.exports = function (fastify, opts, next) {
}, },
}, },
}, },
body: {
type: "object",
properties: {
type_of_water: { type: "string" },
capacity: { type: "string" },
quantity: { type: "string" },
date: { type: "string" },
time: { type: "string" },
},
},
security: [ security: [
{ {

Loading…
Cancel
Save