You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

676 lines
24 KiB

//const Supplier = require("../models/supplier");
const { Supplier, generateSupplierId, FriendRequest,DeliveryBoy} = require("../models/supplier")
const { Tank } = require('../models/tanks')
const http = require('https');
const boom = require("boom");
const fastify = require("fastify")({
logger: true,
});
const { Tanker, Tankerbooking,Bore,GovtPipeLine } = require('../models/tankers')
const moment = require("moment");
exports.orderStartedSms = async (request, reply) => {
//console.log(bookingId,supplierContact,deliveryAgentContact,mobile)
const bookingId = request.params.bookingId;
const booking_data = await Tankerbooking.findOne({ bookingid: bookingId})
console.log(booking_data)
const supplierContact = booking_data.supplierPhone
const deliveryAgentContact = booking_data.delivery_agent_mobile
const user_name = booking_data.customerName
const mobile = booking_data.customerPhone
const username = 'Arminta';
const apiKey = '2068323bea61494d315b';
const senderId = 'ARMNTA';
const message = `Hello ${user_name}, We are pleased to inform you that your booking with bookingId ${bookingId} has been started,you can track the current location of tanker here {#var#}. Please note that the supplier's contact number is ${supplierContact} and deliver agent contact number is ${deliveryAgentContact} Thank you for choosing our services. If you have any further questions or concerns, please do not hesitate to contact us. Best regards, Arminta Water Services`;
const apiUrl = `https://smslogin.co/v3/api.php?username=${username}&apikey=${apiKey}&senderid=${senderId}&mobile=${mobile}&message=${encodeURIComponent(message)}`;
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
const req = http.request(apiUrl, options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
console.log(req)
res.on('end', () => {
reply.send(data);
});
});
req.on('error', (error) => {
console.error(error);
reply.send({ error: 'Failed to send SMS' });
});
req.end();
}
exports.orderNow = async (req, reply) => {
try {
const customerId = req.body.customerId;
const bookingId = req.params.bookingId;
const tankerName = req.body.tankerName;
const booking_info = await Tankerbooking.findOne({ bookingid: bookingId})
const action = req.body.action
const typeofwater = req.body.typeofwater
const expectedDateOfDelivery = req.body.expectedDateOfDelivery;
if(action === "accept"){
const price = req.body.price
const delivery_agent = req.body.delivery_agent
const agent_mobile = req.body.agent_mobile
const agent_alternative_mobile = req.body.agent_alternative_mobile
const booking_data = await Tankerbooking.findOne({ bookingid: bookingId})
const supplierContact = booking_data.supplierPhone
const deliveryAgentContact = agent_mobile
const mobile = booking_data.customerPhone
// hash = await orderStartedSms(bookingId,supplierContact,deliveryAgentContact,mobile);
booking_info.orderStatus = "accepted"
booking_info.delivery_agent = delivery_agent
booking_info.delivery_agent_mobile = agent_mobile
booking_info.delivery_agent_alternative_mobile = agent_alternative_mobile
booking_info.price = price
booking_info.amount_due = price
}
else {
booking_info.orderStatus = "rejected"
}
booking_info.expectedDateOfDelivery = expectedDateOfDelivery;
const booking = await booking_info.save();
return booking;
} catch (err) {
throw boom.boomify(err);
}
};
exports.addDeliveryboy = async (req, reply) => {
try {
const supplierId = req.params.supplierId
//const username = req.params.username;
console.log(req.params);
//const {username} = loginObject.user.username;
//console.log(loginObject.user.username)
// const userInfo = await User.findOne({ username: username.toString() });
// const updateData = req.body;
// console.log("This is the reply in the handler after the validations", reply);
deliveryData = {
supplierId: supplierId,
suppliername: req.body.suppliername,
name: req.body.Name,
phone: req.body.phone,
alternativeContactNumber: req.body.alternativeContactNumber,
address: req.body.address,
city:req.body.city,
state:req.body.state,
zip:req.body.zip,
status:req.body.status,
longitude: req.body.longitude,
latitude:req.body.latitude,
fcmId: req.body.fcmId
};
var agent_mobile = req.body.phone
var i_agent = await DeliveryBoy.findOne({ phone: agent_mobile})
if(i_agent){
throw new Error('phone already exists');
}
else {
var agent = new DeliveryBoy(deliveryData);
checkFormEncoding = isUserFormUrlEncoded(req);
if (checkFormEncoding.isUserFormUrlEncoded) {
usertobeInserted = checkFormEncoding.agent;
console.log("thsi true url string");
agent.supplierId = usertobeInserted.supplierId
agent.suppliername = usertobeInserted.suppliername
agent.name = usertobeInserted.name;
agent.phone = usertobeInserted.phone;
agent.alternativeContactNumber = usertobeInserted.alternativeContactNumber;
agent.address = usertobeInserted.address;
agent.city = usertobeInserted.city
agent.state = usertobeInserted.state
agent.zip = usertobeInserted.zip
agent.status = usertobeInserted.status
agent.longitude = usertobeInserted.longitude
agent.latitude = usertobeInserted.latitude
agent.fcmId = usertobeInserted.fcmId
}
}
const insertedagent = await agent.save();
console.log("inster...", insertedagent)
return insertedagent;
} catch (err) {
throw boom.boomify(err);
}
};
exports.getbookingsofsupplier = async (req, reply) => {
try {
console.log(req.params.supplierId)
await Tankerbooking.find({supplierId: req.params.supplierId})
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
.catch((err) => {
console.log(err);
reply.send({ error: err });
});
} catch (err) {
throw boom.boomify(err);
}
};
exports.getbookingsofdeliveryboy = async (req, reply) => {
try {
console.log(req.params.supplierId)
await Tankerbooking.find({delivery_agent_mobile: req.params.agent_mobile})
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
.catch((err) => {
console.log(err);
reply.send({ error: err });
});
} catch (err) {
throw boom.boomify(err);
}
};
exports.getalldeliveryboysofsupplier = async (req, reply) => {
try {
console.log(req.params.supplierId)
await DeliveryBoy.find({supplierId: req.params.supplierId})
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
.catch((err) => {
console.log(err);
reply.send({ error: err });
});
} catch (err) {
throw boom.boomify(err);
}
};
exports.getactivedeliveryboysofsupplier = async (req, reply) => {
try {
console.log(req.params.supplierId)
await DeliveryBoy.find({supplierId: req.params.supplierId,status:"active"})
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
.catch((err) => {
console.log(err);
reply.send({ error: err });
});
} catch (err) {
throw boom.boomify(err);
}
};
exports.deliveryboystartandstop = async (req, reply) => {
try {
//let start_time,stop_time
const bookingId = req.params.bookingId
const bookingdata = await Tankerbooking.findOne({bookingid: bookingId})
const ordered_quantity = parseInt((bookingdata.capacity).replace(/,/g, ''), 10)
const price = parseInt((bookingdata.price).replace(/,/g, ''), 10)
const price_per_liter = ordered_quantity/price
// console.log(bookingdata.supplierId,"6")
const customerId = bookingdata.customerId;
console.log(customerId)
const action = req.body.action
const receiver_tank = bookingdata.tankName
// console.log(receiver_tank,"5")
const receiver_tank_info = await Tank.findOne({ customerId ,tankName:receiver_tank,tankLocation:"sump"});
// console.log(receiver_tank_info,"1")
const receiver_capacity = parseInt((receiver_tank_info.capacity).replace(/,/g, ''), 10)
//console.log(bookingdata,customerId,receiver_tank,receiver_tank_info,receiver_capacity,"2")
const intervals = {};
if(action === "start"){
// console.log("started")
const start_time = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'})
const initial_receiver_waterlevel = parseInt(receiver_tank_info.waterlevel.replace(/,/g, ''), 10)
await Tankerbooking.findOneAndUpdate({bookingid:bookingId}, { $set: { initial_water_level: initial_receiver_waterlevel ,start_time:start_time,tankerRunningStatus:"1"} });
let receiver_waterlevel = parseInt(receiver_tank_info.waterlevel.replace(/,/g, ''), 10)
// console.log(receiver_waterlevel,"1")
intervals[bookingId]= setInterval(async function () {
// Calculate new water levels
const newWaterLevel = receiver_waterlevel+450;
const booking_data = await Tankerbooking.findOne({bookingid:bookingId})
const tankerStatus = booking_data.tankerRunningStatus
//console.log(newWaterLevel,"2",receiver_tank_info.tankName)
// Check if updating should stop
if ((newWaterLevel/receiver_capacity)*100 >= 97, tankerStatus ==="0" ) {
clearInterval(intervals[bookingId]); // Clear the interval for this tank
delete intervals[bookingId];
await Tankerbooking.findOneAndUpdate({bookingid:bookingId}, { $set: { initial_water_level: initial_receiver_waterlevel ,start_time:start_time,tankerRunningStatus:"0"} });
stop_time = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'})
const final_tank_info = await Tank.findOne({ customerId ,tankName:receiver_tank,tankLocation:"sump"});
const final_receiver_waterlevel = parseInt(final_tank_info.waterlevel.replace(/,/g, ''), 10)
// console.log(final_receiver_waterlevel)
// clearInterval(intervalId);
await Tankerbooking.findOneAndUpdate({bookingid:bookingId}, { $set: { final_water_level: final_receiver_waterlevel ,stop_time:stop_time} });
// console.log("end for" + receiver_tank);
} else {
// Update water levels in database
receiver_waterlevel = newWaterLevel;
// console.log(receiver_tank+""+newWaterLevel+""+"bore to sump")
//console.log((newWaterLevel/receiver_capacity)*100,"4",receiver_tank_info.tankName)
await Tank.findOneAndUpdate({customerId, tankName: receiver_tank,tankLocation:"sump"}, { $set: { waterlevel: newWaterLevel } })
// console.log(intervals,"check1")
}
}, 2000);
// console.log(customerId,req.body.from,req.body.from_type,receiver_tank,req.body.to_type,)
reply.send({ status_code: 200, "start time": start_time,"initial water level":initial_receiver_waterlevel});
console.log(start_time)
}
if (action === "stop") {
const booking_data = await Tankerbooking.findOne({bookingid: bookingId})
console.log(intervals,"hii3")
try {
clearInterval(intervals[bookingId]); // Clear the interval for this tank
delete intervals[bookingId]; // Delete the interval ID for this tank from the intervals object
} catch (err) {
console.log(err);
}
const stop_time = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'})
const final_tank_info = await Tank.findOne({ customerId ,tankName:receiver_tank,tankLocation:"sump"});
// console.log(final_tank_info,"hii")
const final_receiver_waterlevel = parseInt(final_tank_info.waterlevel.replace(/,/g, ''), 10)
const start_water_level = parseInt(booking_data.initial_water_level.replace(/,/g, ''), 10)
const quantity_delivered = final_receiver_waterlevel-start_water_level
const distrubance_price = parseInt(quantity_delivered.replace(/,/g, ''), 10)*price_per_liter
const amount_difference = price - distrubance_price
await Tankerbooking.findOneAndUpdate({bookingid:bookingId}, { $set: { final_water_level: final_receiver_waterlevel ,stop_time:stop_time,quantityDelivered:quantity_delivered,distrubance_price:distrubance_price,amount_difference:amount_difference,tankerRunningStatus:"0"} });
reply.send({ status_code: 200, "stop time": stop_time,"final water level":final_receiver_waterlevel});
} else {
throw new Error("Invalid action");
}
return { message: 'Water level updates started' };
} catch (err) {
throw new Error(`Failed to start/stop water level updates: ${err.message}`);
};
};
exports.amountUpdateByDeliveryBoy = async (req, reply) => {
try {
const { bookingId } = req.params;
const { amount_paid, payment_mode, orderStatus, deliveredDate } = req.body;
const booking = await Tankerbooking.findOne({ bookingid: bookingId });
if (!booking) {
return reply.status(404).send({ message: "Booking not found" });
}
// const amount_initial_due = parseInt(booking.amount_due.replace(/,/g, ""), 10);
const amount_initial_due = booking.amount_due ? parseInt(booking.amount_due.replace(/,/g, ""), 10) : 0;
const amount_due = amount_initial_due - parseInt(amount_paid.replace(/,/g, ""), 10);
const updateData = {
amount_paid,
payment_mode,
orderStatus,
amount_due,
payment_status: amount_due === 0 ? "paid" : "due",
deliveredDate: moment(deliveredDate, "DD-MM-YYYY HH:mm:ss").tz('Asia/Kolkata').format("DD-MM-YYYY HH:mm:ss"),
};
await Tankerbooking.findOneAndUpdate(
{ bookingid: bookingId },
{ $set: updateData }
);
reply.send({ status_code: 200, message: "Successfully updated" });
} catch (err) {
console.error(err);
throw boom.boomify(err);
}
};
exports.userAccounts = async (req, reply) => {
try {
const booking = await Tankerbooking.find({customerId: req.params.customerId})
// console.log(booking)
let acceptedCount = 0;
let pendingRejectedCount = 0;
let deliveredCount = 0;
let deliveredTotalPrice = 0;
let deliveredTotalAmountPaid = 0;
let deliveredTotalAmountDue = 0;
for (let i = 0; i < booking.length; i++) {
let order = booking[i];
if (order.orderStatus === "accepted") {
acceptedCount++;
} else if (order.orderStatus === "pending" || order.orderStatus === "rejected") {
pendingRejectedCount++;
} else if (order.orderStatus === "delivered") {
deliveredCount++;
deliveredTotalPrice += parseInt(order.price.replace(/,/g, ''), 10)
deliveredTotalAmountPaid += parseInt(order.amount_paid.replace(/,/g, ''), 10)
deliveredTotalAmountDue += parseInt(order.amount_due.replace(/,/g, ''), 10)
}
}
console.log("Accepted orders count:", acceptedCount);
console.log("Pending or rejected orders count:", pendingRejectedCount);
console.log("Delivered orders count:", deliveredCount);
console.log("Delivered orders total price:", deliveredTotalPrice);
console.log("Delivered orders total amount paid:", deliveredTotalAmountPaid);
console.log("Delivered orders total amount due:", deliveredTotalAmountDue);
reply.send({ status_code: 200, count: booking.length, data: booking,acceptedCount:acceptedCount,pendingRejectedCount:pendingRejectedCount,deliveredCount:deliveredCount,deliveredTotalPrice:deliveredTotalPrice,deliveredTotalAmountPaid:deliveredTotalAmountPaid,deliveredTotalAmountDue:deliveredTotalAmountDue });
} catch (err) {
throw boom.boomify(err);
}
};
exports.userAccountsofparticularSupplier = async (req, reply) => {
try {
const booking = await Tankerbooking.find({customerId: req.params.customerId,supplierId: req.body.supplierId,})
console.log(booking,)
let acceptedCount = 0;
let pendingRejectedCount = 0;
let deliveredCount = 0;
let deliveredTotalPrice = 0;
let deliveredTotalAmountPaid = 0;
let deliveredTotalAmountDue = 0;
for (let i = 0; i < booking.length; i++) {
let order = booking[i];
if (order.orderStatus === "accepted") {
acceptedCount++;
} else if (order.orderStatus === "pending" || order.orderStatus === "rejected") {
pendingRejectedCount++;
} else if (order.orderStatus === "delivered") {
deliveredCount++;
deliveredTotalPrice += parseInt(order.price.replace(/,/g, ''), 10)
deliveredTotalAmountPaid += parseInt(order.amount_paid.replace(/,/g, ''), 10)
deliveredTotalAmountDue += parseInt(order.amount_due.replace(/,/g, ''), 10)
}
}
console.log("Accepted orders count:", acceptedCount);
console.log("Pending or rejected orders count:", pendingRejectedCount);
console.log("Delivered orders count:", deliveredCount);
console.log("Delivered orders total price:", deliveredTotalPrice);
console.log("Delivered orders total amount paid:", deliveredTotalAmountPaid);
console.log("Delivered orders total amount due:", deliveredTotalAmountDue);
reply.send({ status_code: 200, count: booking.length, data: booking,acceptedCount:acceptedCount,pendingRejectedCount:pendingRejectedCount,deliveredCount:deliveredCount,deliveredTotalPrice:deliveredTotalPrice,deliveredTotalAmountPaid:deliveredTotalAmountPaid,deliveredTotalAmountDue:deliveredTotalAmountDue });
} catch (err) {
throw boom.boomify(err);
}
};
exports.supplierAccounts = async (req, reply) => {
try {
const booking = await Tankerbooking.find({supplierId: req.params.supplierId})
// console.log(booking)
let acceptedCount = 0;
let pendingRejectedCount = 0;
let deliveredCount = 0;
let deliveredTotalPrice = 0;
let deliveredTotalAmountPaid = 0;
let deliveredTotalAmountDue = 0;
for (let i = 0; i < booking.length; i++) {
let order = booking[i];
if (order.orderStatus === "accepted") {
acceptedCount++;
} else if (order.orderStatus === "pending" || order.orderStatus === "rejected") {
pendingRejectedCount++;
} else if (order.orderStatus === "delivered") {
deliveredCount++;
deliveredTotalPrice += parseInt(order.price.replace(/,/g, ''), 10)
deliveredTotalAmountPaid += parseInt(order.amount_paid.replace(/,/g, ''), 10)
deliveredTotalAmountDue += parseInt(order.amount_due.replace(/,/g, ''), 10)
}
}
console.log("Accepted orders count:", acceptedCount);
console.log("Pending or rejected orders count:", pendingRejectedCount);
console.log("Delivered orders count:", deliveredCount);
console.log("Delivered orders total price:", deliveredTotalPrice);
console.log("Delivered orders total amount paid:", deliveredTotalAmountPaid);
console.log("Delivered orders total amount due:", deliveredTotalAmountDue);
reply.send({ status_code: 200, count: booking.length, data: booking,acceptedCount:acceptedCount,pendingRejectedCount:pendingRejectedCount,deliveredCount:deliveredCount,deliveredTotalPrice:deliveredTotalPrice,deliveredTotalAmountPaid:deliveredTotalAmountPaid,deliveredTotalAmountDue:deliveredTotalAmountDue });
} catch (err) {
throw boom.boomify(err);
}
};
exports.tankerAccounts = async (req, reply) => {
try {
const booking = await Tankerbooking.find({supplierId: req.params.supplierId,customerId:req.body.customerId,tankerName:req.body.tankerName})
//console.log(booking)
let acceptedCount = 0;
let pendingRejectedCount = 0;
let deliveredCount = 0;
let deliveredTotalPrice = 0;
let deliveredTotalAmountPaid = 0;
let deliveredTotalAmountDue = 0;
for (let i = 0; i < booking.length; i++) {
let order = booking[i];
if (order.orderStatus === "accepted") {
acceptedCount++;
} else if (order.orderStatus === "pending" || order.orderStatus === "rejected") {
pendingRejectedCount++;
} else if (order.orderStatus === "delivered") {
deliveredCount++;
deliveredTotalPrice += parseInt(order.price.replace(/,/g, ''), 10)
deliveredTotalAmountPaid += parseInt(order.amount_paid.replace(/,/g, ''), 10)
deliveredTotalAmountDue += parseInt(order.amount_due.replace(/,/g, ''), 10)
}
}
console.log("Accepted orders count:", acceptedCount);
console.log("Pending or rejected orders count:", pendingRejectedCount);
console.log("Delivered orders count:", deliveredCount);
console.log("Delivered orders total price:", deliveredTotalPrice);
console.log("Delivered orders total amount paid:", deliveredTotalAmountPaid);
console.log("Delivered orders total amount due:", deliveredTotalAmountDue);
reply.send({ status_code: 200, count: booking.length, data: booking,acceptedCount:acceptedCount,pendingRejectedCount:pendingRejectedCount,deliveredCount:deliveredCount,deliveredTotalPrice:deliveredTotalPrice,deliveredTotalAmountPaid:deliveredTotalAmountPaid,deliveredTotalAmountDue:deliveredTotalAmountDue });
} catch (err) {
throw boom.boomify(err);
}
};
exports.getAllOrderaccepted = 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
try {
await Tankerbooking.find({ customerId: customerId, orderStatus: ["accepted"]})
.limit(limit)
.skip(startindex)
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
} catch (err) {
reply.status(400).send({ message: err.message });
}
};
exports.getAllOrderdelivered = 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
try {
await Tankerbooking.find({ customerId: customerId, orderStatus: ["delivered"]})
.limit(limit)
.skip(startindex)
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
} catch (err) {
reply.status(400).send({ message: err.message });
}
};
exports.getAllOrderreject = 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
try {
await Tankerbooking.find({ customerId: customerId, orderStatus: ["rejected"]})
.limit(limit)
.skip(startindex)
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
} catch (err) {
reply.status(400).send({ message: err.message });
}
};
exports.getAllOrderpending = 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
try {
await Tankerbooking.find({ customerId: customerId, orderStatus: ["pending"]})
.limit(limit)
.skip(startindex)
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
} catch (err) {
reply.status(400).send({ message: err.message });
}
};
exports.getBillingInfo = async (req, reply) => {
const limit = parseInt(req.query.limit) || 100;
const page = parseInt(req.query.page) || 1;
const startindex = (page - 1) * limit;
const bookingId = req.params.bookingId;
try {
await Tankerbooking.findOne({ bookingid: bookingId})
.limit(limit)
.skip(startindex)
.exec()
.then((docs) => {
reply.send({ status_code: 200, data: docs, count: docs.length });
})
} catch (err) {
reply.status(400).send({ message: err.message });
}
};