From 1fd4a1fe9ce2ec1a7c635dba51817441828ca1ca Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Tue, 9 Apr 2024 07:03:25 +0530 Subject: [PATCH] Added: Update Status to webhook API --- controllers/Bot.js | 59 ++++++++++++++++++++++++---- controllers/ControlCenter.js | 2 + server.js | 8 ++-- services/CronService.js | 76 ------------------------------------ 4 files changed, 56 insertions(+), 89 deletions(-) delete mode 100644 services/CronService.js diff --git a/controllers/Bot.js b/controllers/Bot.js index 7b9580e..74df769 100644 --- a/controllers/Bot.js +++ b/controllers/Bot.js @@ -1,17 +1,12 @@ import ActionsService from '../services/Actions.js' import AI from '../services/AI.js' - import logger from '../utils/logger.js' import {db} from '../server.js' import { v4 as uuidv4 } from 'uuid' import MapsService from '../services/MapService.js' -import { fileURLToPath } from 'url'; -import path from 'path' + const mapService = new MapsService() -const __filename = fileURLToPath(import.meta.url); -const __dirname = path.dirname(__filename); -import CronService from '../services/CronService.js' const actionsService = new ActionsService() /** @@ -105,6 +100,7 @@ async function process_text(req, res) { bookings: [], active_transaction: null, routes:[], + orders:[], selected_route:null } @@ -228,9 +224,10 @@ async function process_text(req, res) { session.bookings = ai.bookings; response = await process_action(ai.action, message, session, sender, format); ai.bookings = response.bookings; - + // update actions if(ai.action?.action === 'confirm') { + session.orders.push(response.raw.responses[0]); session.actions = EMPTY_SESSION.actions; session.text = EMPTY_SESSION.text; } @@ -387,7 +384,53 @@ async function process_action(action, text, session, sender=null, format='applic return response; } + + async function webhookControl (req, res) { + try{ + const sessions = await db.get_all_sessions(); + logger.info(`Got ${sessions.length} sessions.`) + + + for(let session of sessions){ + const orders = session.data.orders; + const index = orders ? orders.findIndex((order)=>order.message.order.id == req.body.orderId) : null; + if(index!==null && orders[index].message.order.fulfillments[0].state.descriptor.name !== req.body.data.data.attributes.state_code) { + // send whatsapp and add to context + try{ + // update session + orders[index].message.order.fulfillments[0].state.descriptor.name = req.body.data.data.attributes.state_code + let reply_message = ''; + if(req.body.data.data.attributes.state_code === "charger-not-working"){ + console.log('here3', session.data.orders); + reply_message ="Hey, looks like the charger is not working, do you want to look for other chargers on the route?" + await actionsService.send_message(session.key, reply_message); + if(!session.data.text) session.data.text=[] + session.data.text.push({role: 'assistant', content: reply_message}); + await db.update_session(session.key, session.data); + } + } + catch(e){ + logger.error(e); + } + + } + } + return res.status(200).json({ + status:true, + message:'Notification Sent' + }) + }catch(error){ + return res.status(400).json({ + status:false, + message:'Some Error Occured' + }) + } + } + + + export default { process_wa_webhook, - process_text, + process_text, + webhookControl, } diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js index be438e2..a747313 100644 --- a/controllers/ControlCenter.js +++ b/controllers/ControlCenter.js @@ -203,6 +203,8 @@ export const updateStatus = async (req, res) => { state_value: DOMAIN_DETAILS.message, }, },{ Authorization: `Bearer ${DOMAIN_DETAILS.token}`}) + const webhookResponse = await action.call_api(`${process.env.BASE_URL}/webhook-ps`, 'POST',{...updateStatusResponse, orderId:orderId}); + logger.info(JSON.stringify(webhookResponse)); return res.status(200).send({ message: `Status Updated to: ${updateStatusResponse.data.data.attributes.state_value}`, status:true }) } diff --git a/server.js b/server.js index fbcfb89..2a55039 100644 --- a/server.js +++ b/server.js @@ -1,7 +1,5 @@ import dotenv from 'dotenv' import cors from 'cors' -import path from 'path' -import { fileURLToPath } from 'url'; dotenv.config() import express from 'express' import bodyParser from 'body-parser' @@ -27,7 +25,7 @@ app.use(cors()) app.use(bodyParser.urlencoded({ extended: false })) app.use('/public', express.static(path.join(__dirname, 'public'))); app.use(bodyParser.json()) -app.use('/static', express.static(path.join(__dirname, 'public'))); + // Define endpoints here // app.post('/act', actions.act) app.post('/webhook', messageController.process_text) @@ -38,11 +36,11 @@ app.post('/trigger-exception', triggerExceptionOnLocation) app.post('/update-status', updateStatus) app.post('/unpublish-item', unpublishItem) app.post('/webhook-ps', messageController.webhookControl) -app.get('/download', messageController.downloadFile); // Reset all sessions export const db = new DBService() -// await db.clear_all_sessions() +await db.clear_all_sessions() + await db.set_data('orderDetails', ORDER_DETAILS) // Start the Express server diff --git a/services/CronService.js b/services/CronService.js deleted file mode 100644 index 5238ed9..0000000 --- a/services/CronService.js +++ /dev/null @@ -1,76 +0,0 @@ -import { - DOMAINS, - BECKN_STATUS_CALL -} from '../utils/constants.js' -import ActionsService from '../services/Actions.js' -import { readFileSync } from 'fs'; -import logger from '../utils/logger.js'; -const action = new ActionsService() -const registry_config = JSON.parse(readFileSync('./config/registry.json')) -class CronService { - constructor() { - - } - async sendStatusUpdatedNotification(db){ - try{ - const data = await db.get_data('orderDetails') - if(data.data.domain){ - - for(let i=0;i