From 3a95c953440d955e16899acf165314143f779d99 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Fri, 29 Mar 2024 19:59:10 +0530 Subject: [PATCH 01/15] Added:Control Certer Backend APIs --- controllers/ControlCenter.js | 73 +++++++++++++++++++++++++++++++++ controllers/Notification.js | 16 ++++++++ package.json | 1 + server.js | 19 ++++++--- services/Actions.js | 8 ++-- services/notificationService.js | 30 ++++++++++++++ utils/constants.js | 7 ++++ 7 files changed, 144 insertions(+), 10 deletions(-) create mode 100644 controllers/ControlCenter.js create mode 100644 controllers/Notification.js create mode 100644 services/notificationService.js create mode 100644 utils/constants.js diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js new file mode 100644 index 0000000..5e5a8ed --- /dev/null +++ b/controllers/ControlCenter.js @@ -0,0 +1,73 @@ +import axios from 'axios' +import Actions from '../services/Actions.js' +import logger from '../utils/logger.js' +import { + ITEM_ID, + ITEM_NAME, + CAT_ATTR_TAG_RELATIONS, + STRAPI_TOURISM_TOKEN, +} from '../utils/constants.js' +const action = new Actions() +const TOURISM_STRAPI_URL = process.env.TOURISM_STRAPI_URL || '' +export const cancelBookingController = async (req, res) => { + try { + const { recipientNumber, messageBody, orderId } = req.body + console.log(orderId) + const getOrderFulfillmentDetails = await axios.get( + `${TOURISM_STRAPI_URL}/order-fulfillments?order_id=${orderId}`, + { + headers: { + Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`, + }, + } + ) + if (getOrderFulfillmentDetails.data.data.length) { + await axios.put( + `${TOURISM_STRAPI_URL}/order-fulfillments/${getOrderFulfillmentDetails.data.data[0].id}`, + { + data: { + state_code: 'CANCELLED', + state_value: 'CANCELLED BY HOTEL', + }, + }, + { + headers: { + Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`, + }, + } + ) + + await action.send_message(recipientNumber, messageBody) + return res.send({ message: 'Notified' }) + } + + return res.send({ message: 'Cancel Booking Failed' }) + } catch (error) { + logger.error(error.message) + return res.send({ message: error.message }) + } +} + +export const updateCatalog = async (req, res) => { + try { + await axios.put( + `${TOURISM_STRAPI_URL}/items/${ITEM_ID}`, + { + data: { + name: ITEM_NAME, + cat_attr_tag_relations: CAT_ATTR_TAG_RELATIONS, + }, + }, + { + headers: { + Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`, + }, + } + ) + + return res.send({ message: 'Catalog Updated' }) + } catch (error) { + logger.error(error.message) + return res.send({ message: error.message }) + } +} diff --git a/controllers/Notification.js b/controllers/Notification.js new file mode 100644 index 0000000..a57c29b --- /dev/null +++ b/controllers/Notification.js @@ -0,0 +1,16 @@ +import Actions from '../services/Actions.js' +import logger from '../utils/logger.js' +const action = new Actions() +export const notificationController = async (req, res) => { + try { + const { recipientNumber, messageBody } = req.body + const sendWhatsappNotificationResponse = await action.send_message( + recipientNumber, + messageBody + ) + return res.send(sendWhatsappNotificationResponse) + } catch (error) { + logger.error(error.message) + return res.send({ message: error.message }) + } +} diff --git a/package.json b/package.json index 91c36c4..35b4aa5 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "body-parser": "^1.20.2", "chai": "^5.0.0", "config": "^3.3.11", + "cors": "^2.8.5", "dotenv": "^16.3.1", "express": "^4.18.2", "js-yaml": "^4.1.0", diff --git a/server.js b/server.js index b034754..b5ef7b9 100644 --- a/server.js +++ b/server.js @@ -1,13 +1,18 @@ import dotenv from 'dotenv' +import cors from 'cors' dotenv.config() import express from 'express' import bodyParser from 'body-parser' import logger from './utils/logger.js' import messageController from './controllers/Bot.js' import DBService from './services/DBService.js' - +import { notificationController } from './controllers/Notification.js' +import { + cancelBookingController, + updateCatalog, +} from './controllers/ControlCenter.js' const app = express() - +app.use(cors()) // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) @@ -16,11 +21,13 @@ app.use(bodyParser.json()) // Define endpoints here // app.post('/act', actions.act) -app.post('/webhook', messageController.process_text) - +app.post('/webhook', messageController.process_wa_webhook) +app.post('/notify', notificationController) +app.post('/cancel-booking', cancelBookingController) +app.post('/update-catalog', updateCatalog) // Reset all sessions -const db = new DBService(); -await db.clear_all_sessions(); +const db = new DBService() +await db.clear_all_sessions() // Start the Express server app.listen(process.env.SERVER_PORT, () => { diff --git a/services/Actions.js b/services/Actions.js index ea4a4fb..f522929 100644 --- a/services/Actions.js +++ b/services/Actions.js @@ -106,14 +106,14 @@ class Actions { async send_message(recipient, message) { try { - - const response = await client.messages.create({ + const data = await client.messages.create({ body: message, from: `whatsapp:${twilioNumber}`, to: recipient.includes('whatsapp:') ? recipient : `whatsapp:${recipient}`, }) - logger.info(`Message sent: ${JSON.stringify(response)}`) - return true; + const status = await client.messages(data.sid).fetch() + + return { data, status } } catch (error) { logger.error(`Error sending message: ${error.message}`) return false; diff --git a/services/notificationService.js b/services/notificationService.js new file mode 100644 index 0000000..0f101ce --- /dev/null +++ b/services/notificationService.js @@ -0,0 +1,30 @@ +import logger from '../utils/logger.js' +import Twilio from 'twilio' +const TWILIO_NUMBER = process.env.TWILIO_NUMBER +const TWILIO_AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN +const TWILIO_ACCOUNT_SID = process.env.TWILIO_ACCOUNT_SID + +const client = Twilio(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) + +export const sendWhatsappNotification = async ( + recipientNumber, + messageBody +) => { + try { + const data = await client.messages.create({ + body: messageBody, + from: `whatsapp:${TWILIO_NUMBER}`, + to: `whatsapp:${recipientNumber}`, + }) + + const status = await client.messages(data.sid).fetch() + console.log('data===>', data) + console.log('status===>', status) + if(status?.status!=="failed"){ + return {message:'Notification Sent'} + }return {message:'Failed to Send Notification'} + } catch (error) { + logger.error(error.message) + throw new Error(error.message) + } +} diff --git a/utils/constants.js b/utils/constants.js new file mode 100644 index 0000000..f630f0b --- /dev/null +++ b/utils/constants.js @@ -0,0 +1,7 @@ +export const STRAPI_TOURISM_TOKEN = + '82ed7f48afbd0c0605ef36bf4b81259f90c7e6bc357db032a011b1c0ab2bc7db2a753fa84c959f403b256ee66b44174dcc453bd0a40797ce8c22c1b6dab7f416cf3b8a247c19144bc3d019f229612f36b12612223b35f28a1a7fec6ff779228730b45fd93a793399d8f462ba0bada15077725a843d3023cf133838876da3547e' + +export const ITEM_ID = '2' +export const ITEM_NAME = 'MUSEUM' + +export const CAT_ATTR_TAG_RELATIONS = [2, 3, 4, 5] From e561772450c4b365dc66e484f18d9d605a6e6a98 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Fri, 29 Mar 2024 20:37:20 +0530 Subject: [PATCH 02/15] Added:Control Certer Backend APIs --- utils/constants.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/constants.js b/utils/constants.js index f630f0b..acc7287 100644 --- a/utils/constants.js +++ b/utils/constants.js @@ -1,7 +1,7 @@ export const STRAPI_TOURISM_TOKEN = '82ed7f48afbd0c0605ef36bf4b81259f90c7e6bc357db032a011b1c0ab2bc7db2a753fa84c959f403b256ee66b44174dcc453bd0a40797ce8c22c1b6dab7f416cf3b8a247c19144bc3d019f229612f36b12612223b35f28a1a7fec6ff779228730b45fd93a793399d8f462ba0bada15077725a843d3023cf133838876da3547e' -export const ITEM_ID = '2' +export const ITEM_ID = '4' export const ITEM_NAME = 'MUSEUM' export const CAT_ATTR_TAG_RELATIONS = [2, 3, 4, 5] From 6840034dbdc99c92c5daad035c63b6575feb7c72 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Fri, 29 Mar 2024 20:53:24 +0530 Subject: [PATCH 03/15] Added:Control Certer Backend APIs --- controllers/ControlCenter.js | 7 ++++--- controllers/Notification.js | 5 +++-- utils/constants.js | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js index 5e5a8ed..5582af6 100644 --- a/controllers/ControlCenter.js +++ b/controllers/ControlCenter.js @@ -9,9 +9,10 @@ import { } from '../utils/constants.js' const action = new Actions() const TOURISM_STRAPI_URL = process.env.TOURISM_STRAPI_URL || '' +const TWILIO_RECEPIENT_NUMBER = process.env.TOURISM_STRAPI_URL export const cancelBookingController = async (req, res) => { try { - const { recipientNumber, messageBody, orderId } = req.body + const { messageBody, orderId } = req.body console.log(orderId) const getOrderFulfillmentDetails = await axios.get( `${TOURISM_STRAPI_URL}/order-fulfillments?order_id=${orderId}`, @@ -37,7 +38,7 @@ export const cancelBookingController = async (req, res) => { } ) - await action.send_message(recipientNumber, messageBody) + await action.send_message(TWILIO_RECEPIENT_NUMBER, messageBody) return res.send({ message: 'Notified' }) } @@ -64,7 +65,7 @@ export const updateCatalog = async (req, res) => { }, } ) - + await action.send_message(TWILIO_RECEPIENT_NUMBER, messageBody) return res.send({ message: 'Catalog Updated' }) } catch (error) { logger.error(error.message) diff --git a/controllers/Notification.js b/controllers/Notification.js index a57c29b..66fb16d 100644 --- a/controllers/Notification.js +++ b/controllers/Notification.js @@ -1,11 +1,12 @@ import Actions from '../services/Actions.js' import logger from '../utils/logger.js' const action = new Actions() +const TWILIO_RECEPIENT_NUMBER = process.env.TOURISM_STRAPI_URL export const notificationController = async (req, res) => { try { - const { recipientNumber, messageBody } = req.body + const { messageBody } = req.body const sendWhatsappNotificationResponse = await action.send_message( - recipientNumber, + TWILIO_RECEPIENT_NUMBER, messageBody ) return res.send(sendWhatsappNotificationResponse) diff --git a/utils/constants.js b/utils/constants.js index acc7287..761136b 100644 --- a/utils/constants.js +++ b/utils/constants.js @@ -2,6 +2,6 @@ export const STRAPI_TOURISM_TOKEN = '82ed7f48afbd0c0605ef36bf4b81259f90c7e6bc357db032a011b1c0ab2bc7db2a753fa84c959f403b256ee66b44174dcc453bd0a40797ce8c22c1b6dab7f416cf3b8a247c19144bc3d019f229612f36b12612223b35f28a1a7fec6ff779228730b45fd93a793399d8f462ba0bada15077725a843d3023cf133838876da3547e' export const ITEM_ID = '4' -export const ITEM_NAME = 'MUSEUM' +export const ITEM_NAME = 'Ticket Pass-Mueseum' export const CAT_ATTR_TAG_RELATIONS = [2, 3, 4, 5] From a22fdc2c2e86bbb72e262f766d339918ca206b5a Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Fri, 29 Mar 2024 21:00:58 +0530 Subject: [PATCH 04/15] Added:Control Certer Backend APIs --- controllers/ControlCenter.js | 24 ++++++++++++++++++++++-- controllers/Notification.js | 17 ----------------- utils/constants.js | 4 ++++ 3 files changed, 26 insertions(+), 19 deletions(-) delete mode 100644 controllers/Notification.js diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js index 5582af6..914da10 100644 --- a/controllers/ControlCenter.js +++ b/controllers/ControlCenter.js @@ -6,14 +6,18 @@ import { ITEM_NAME, CAT_ATTR_TAG_RELATIONS, STRAPI_TOURISM_TOKEN, + NEW_CATALOG_AVAILABLE, + TRIGGER_BLIZZARD_MESSAGE, + CANCEL_BOOKING_MESSAGE } from '../utils/constants.js' + const action = new Actions() const TOURISM_STRAPI_URL = process.env.TOURISM_STRAPI_URL || '' const TWILIO_RECEPIENT_NUMBER = process.env.TOURISM_STRAPI_URL export const cancelBookingController = async (req, res) => { try { - const { messageBody, orderId } = req.body - console.log(orderId) + const { orderId } = req.body + const messageBody = CANCEL_BOOKING_MESSAGE; const getOrderFulfillmentDetails = await axios.get( `${TOURISM_STRAPI_URL}/order-fulfillments?order_id=${orderId}`, { @@ -51,6 +55,7 @@ export const cancelBookingController = async (req, res) => { export const updateCatalog = async (req, res) => { try { + const messageBody = NEW_CATALOG_AVAILABLE; await axios.put( `${TOURISM_STRAPI_URL}/items/${ITEM_ID}`, { @@ -72,3 +77,18 @@ export const updateCatalog = async (req, res) => { return res.send({ message: error.message }) } } + + +export const notificationController = async (req, res) => { + try { + const messageBody = TRIGGER_BLIZZARD_MESSAGE; + const sendWhatsappNotificationResponse = await action.send_message( + TWILIO_RECEPIENT_NUMBER, + messageBody + ) + return res.send(sendWhatsappNotificationResponse) + } catch (error) { + logger.error(error.message) + return res.send({ message: error.message }) + } +} \ No newline at end of file diff --git a/controllers/Notification.js b/controllers/Notification.js deleted file mode 100644 index 66fb16d..0000000 --- a/controllers/Notification.js +++ /dev/null @@ -1,17 +0,0 @@ -import Actions from '../services/Actions.js' -import logger from '../utils/logger.js' -const action = new Actions() -const TWILIO_RECEPIENT_NUMBER = process.env.TOURISM_STRAPI_URL -export const notificationController = async (req, res) => { - try { - const { messageBody } = req.body - const sendWhatsappNotificationResponse = await action.send_message( - TWILIO_RECEPIENT_NUMBER, - messageBody - ) - return res.send(sendWhatsappNotificationResponse) - } catch (error) { - logger.error(error.message) - return res.send({ message: error.message }) - } -} diff --git a/utils/constants.js b/utils/constants.js index 761136b..af20826 100644 --- a/utils/constants.js +++ b/utils/constants.js @@ -5,3 +5,7 @@ export const ITEM_ID = '4' export const ITEM_NAME = 'Ticket Pass-Mueseum' export const CAT_ATTR_TAG_RELATIONS = [2, 3, 4, 5] +export const TRIGGER_BLIZZARD_MESSAGE = "Hey, Triggering a Blizzard"; +export const CANCEL_BOOKING_MESSAGE = `Dear Guest,\n\nApologies, but your hotel booking with us has been canceled due to unforeseen circumstances. \nWe understand the inconvenience and are here to assist you with any alternative arrangements needed. \n\nPlease contact us for further assistance.`; +export const NEW_CATALOG_AVAILABLE = `Dear Guest,\n\n Checkout this new place to visit.` + From f25fdaa10ae7afdd44afb076d98dc3e8c3566863 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Mon, 1 Apr 2024 19:28:35 +0530 Subject: [PATCH 05/15] Fixed: As per the comment --- .env.sample | 3 +- config/openai.json | 12 ++- controllers/ControlCenter.js | 87 ++++++++++---------- server.js | 8 +- services/Actions.js | 2 +- services/notificationService.js | 30 ------- tests/unit/controllers/controlCenter.test.js | 78 ++++++++++++++++++ utils/constants.js | 3 - 8 files changed, 137 insertions(+), 86 deletions(-) delete mode 100644 services/notificationService.js create mode 100644 tests/unit/controllers/controlCenter.test.js diff --git a/.env.sample b/.env.sample index 29ec50d..dc7d944 100644 --- a/.env.sample +++ b/.env.sample @@ -6,4 +6,5 @@ SERVER_PORT=3001 TWILIO_ACCOUNT_SID= TWILIO_AUTH_TOKEN= TWILIO_NUMBER= -TEST_RECEPIENT_NUMBER= \ No newline at end of file +TEST_RECEPIENT_NUMBER= +STRAPI_TOURISM_TOKEN= \ No newline at end of file diff --git a/config/openai.json b/config/openai.json index 7ca9729..041363b 100644 --- a/config/openai.json +++ b/config/openai.json @@ -11,6 +11,14 @@ { "role": "system", "content": "A typical order flow should be search > select > init > confirm."}, { "role": "system", "content": "Use the response of search from assistant to select items from the list of items provided by the assistant."}, { "role": "system", "content": "Use the response of search request from assistant for filling transaction_id, bpp_id, bpp_uri in the context of all calls except `search`."}, - { "role": "system", "content": "For `select`, `init`, `confirm`, you must use the item `id` as part of the payload for selected item instead of name or any other key."} - ] + { "role": "system", "content": "Use the response from assistant to select items from the list of items provided by the assistant."} + + ], + "PRESETS" : { + "bap_id": "mit-ps-bap.becknprotocol.io", + "bap_uri": "https://mit-ps-bap.becknprotocol.io", + "version": "1.1.0", + "base_url": "https://mit-ps-bap-client.becknprotocol.io", + "TOURISM_STRAPI_URL": "https://mit-bpp-tourism.becknprotocol.io/api" + } } \ No newline at end of file diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js index 914da10..e93120a 100644 --- a/controllers/ControlCenter.js +++ b/controllers/ControlCenter.js @@ -1,49 +1,49 @@ -import axios from 'axios' import Actions from '../services/Actions.js' +import { readFileSync } from 'fs'; import logger from '../utils/logger.js' import { ITEM_ID, ITEM_NAME, CAT_ATTR_TAG_RELATIONS, - STRAPI_TOURISM_TOKEN, NEW_CATALOG_AVAILABLE, TRIGGER_BLIZZARD_MESSAGE, CANCEL_BOOKING_MESSAGE } from '../utils/constants.js' +const config = JSON.parse(readFileSync('./config/openai.json')) const action = new Actions() -const TOURISM_STRAPI_URL = process.env.TOURISM_STRAPI_URL || '' -const TWILIO_RECEPIENT_NUMBER = process.env.TOURISM_STRAPI_URL -export const cancelBookingController = async (req, res) => { +const STRAPI_TOURISM_TOKEN = process.env.STRAPI_TOURISM_TOKEN || '' +const TWILIO_RECEPIENT_NUMBER = process.env.TEST_RECEPIENT_NUMBER +export const cancelBooking = async (req, res) => { try { const { orderId } = req.body + if(!orderId){ + return res.status(500).json({message:"Order Id is Required", status:false}) + } + const validOrderId = await action.call_api(`${config.PRESETS.TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`}) + if(!validOrderId.status){ + return res.send({ message: `Invalid Order Id`, status:false }) + } const messageBody = CANCEL_BOOKING_MESSAGE; - const getOrderFulfillmentDetails = await axios.get( - `${TOURISM_STRAPI_URL}/order-fulfillments?order_id=${orderId}`, - { - headers: { - Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`, - }, - } - ) + const getOrderAddressDetails = await action.call_api(`${config.PRESETS.TOURISM_STRAPI_URL}/order-addresses?order_id=${orderId}`,'GET',{},{ Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`}) + + const getOrderFulfillmentDetails = await action.call_api(`${config.PRESETS.TOURISM_STRAPI_URL}/order-fulfillments?order_id=${orderId}`,'GET',{},{ Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`}) if (getOrderFulfillmentDetails.data.data.length) { - await axios.put( - `${TOURISM_STRAPI_URL}/order-fulfillments/${getOrderFulfillmentDetails.data.data[0].id}`, - { - data: { - state_code: 'CANCELLED', - state_value: 'CANCELLED BY HOTEL', - }, + await action.call_api(`${config.PRESETS.TOURISM_STRAPI_URL}/order-fulfillments/${getOrderFulfillmentDetails.data.data[0].id}`,'PUT',{ + data: { + state_code: 'CANCELLED', + state_value: 'CANCELLED BY HOTEL', }, - { - headers: { - Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`, - }, - } - ) - - await action.send_message(TWILIO_RECEPIENT_NUMBER, messageBody) - return res.send({ message: 'Notified' }) + },{ Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`}) + let statusMessage = ""; + + if(getOrderAddressDetails.data.data[0].attributes.phone){ + statusMessage = (await action.send_message(`+91${getOrderAddressDetails.data.data[0].attributes.phone}`, messageBody)).status.status + } + else{ + statusMessage = (await action.send_message(TWILIO_RECEPIENT_NUMBER, messageBody)).status.status + } + return res.send({ message: `Notification ${statusMessage}` }) } return res.send({ message: 'Cancel Booking Failed' }) @@ -55,22 +55,18 @@ export const cancelBookingController = async (req, res) => { export const updateCatalog = async (req, res) => { try { + const { userNo = TWILIO_RECEPIENT_NUMBER } = req.body; const messageBody = NEW_CATALOG_AVAILABLE; - await axios.put( - `${TOURISM_STRAPI_URL}/items/${ITEM_ID}`, - { - data: { - name: ITEM_NAME, - cat_attr_tag_relations: CAT_ATTR_TAG_RELATIONS, - }, + await action.call_api(`${config.PRESETS.TOURISM_STRAPI_URL}/items/${ITEM_ID}`,'PUT',{ + data: { + name: ITEM_NAME, + cat_attr_tag_relations: CAT_ATTR_TAG_RELATIONS, }, - { - headers: { - Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`, - }, - } - ) - await action.send_message(TWILIO_RECEPIENT_NUMBER, messageBody) + },{ Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`}) + const notifyResponse = await action.send_message(userNo, messageBody) + if(notifyResponse.status.status === "failed"){ + throw new Error('Notification Failed') + } return res.send({ message: 'Catalog Updated' }) } catch (error) { logger.error(error.message) @@ -79,11 +75,12 @@ export const updateCatalog = async (req, res) => { } -export const notificationController = async (req, res) => { +export const notify = async (req, res) => { try { + const { userNo = TWILIO_RECEPIENT_NUMBER } = req.body; const messageBody = TRIGGER_BLIZZARD_MESSAGE; const sendWhatsappNotificationResponse = await action.send_message( - TWILIO_RECEPIENT_NUMBER, + userNo, messageBody ) return res.send(sendWhatsappNotificationResponse) diff --git a/server.js b/server.js index b5ef7b9..e3f73a4 100644 --- a/server.js +++ b/server.js @@ -6,10 +6,10 @@ import bodyParser from 'body-parser' import logger from './utils/logger.js' import messageController from './controllers/Bot.js' import DBService from './services/DBService.js' -import { notificationController } from './controllers/Notification.js' import { - cancelBookingController, + cancelBooking, updateCatalog, + notify } from './controllers/ControlCenter.js' const app = express() app.use(cors()) @@ -22,8 +22,8 @@ app.use(bodyParser.json()) // Define endpoints here // app.post('/act', actions.act) app.post('/webhook', messageController.process_wa_webhook) -app.post('/notify', notificationController) -app.post('/cancel-booking', cancelBookingController) +app.post('/notify', notify) +app.post('/cancel-booking', cancelBooking) app.post('/update-catalog', updateCatalog) // Reset all sessions const db = new DBService() diff --git a/services/Actions.js b/services/Actions.js index f522929..e503d17 100644 --- a/services/Actions.js +++ b/services/Actions.js @@ -44,7 +44,7 @@ class Actions { cookies: response.headers['set-cookie'], } logger.info(`API call was successful: , response.status`) - logger.info(JSON.stringify(response.data, null, 2)) + // logger.info(JSON.stringify(response.data, null, 2)) } catch (error) { logger.error(error) diff --git a/services/notificationService.js b/services/notificationService.js deleted file mode 100644 index 0f101ce..0000000 --- a/services/notificationService.js +++ /dev/null @@ -1,30 +0,0 @@ -import logger from '../utils/logger.js' -import Twilio from 'twilio' -const TWILIO_NUMBER = process.env.TWILIO_NUMBER -const TWILIO_AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN -const TWILIO_ACCOUNT_SID = process.env.TWILIO_ACCOUNT_SID - -const client = Twilio(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) - -export const sendWhatsappNotification = async ( - recipientNumber, - messageBody -) => { - try { - const data = await client.messages.create({ - body: messageBody, - from: `whatsapp:${TWILIO_NUMBER}`, - to: `whatsapp:${recipientNumber}`, - }) - - const status = await client.messages(data.sid).fetch() - console.log('data===>', data) - console.log('status===>', status) - if(status?.status!=="failed"){ - return {message:'Notification Sent'} - }return {message:'Failed to Send Notification'} - } catch (error) { - logger.error(error.message) - throw new Error(error.message) - } -} diff --git a/tests/unit/controllers/controlCenter.test.js b/tests/unit/controllers/controlCenter.test.js new file mode 100644 index 0000000..6a54737 --- /dev/null +++ b/tests/unit/controllers/controlCenter.test.js @@ -0,0 +1,78 @@ +import { describe, it} from 'mocha' +import app from '../../../server.js' +import request from 'supertest' +import * as chai from 'chai' +const expect = chai.expect + + +describe('API tests for /notify endpoint for an end to end Notify Request', () => { + it('Should test unsuccess response for invalid whatsapp number.', async () => { + const response = await request(app).post('/notify').send({ + "userNo":"+919123456789" + }) + expect(response._body.status.status).equal('failed') + }) + + it('Should test success response for no whatsapp number provided in the payload and will sent to TEST_RECEPIENT_NUMBER', async () => { + const response = await request(app).post('/notify').send({ + + }) + expect(response._body.status.status).to.not.equal('failed') + }) + + it('Should test success response for valid whatsapp number', async () => { + const response = await request(app).post('/notify').send({ + "userNo":process.env.TEST_RECEPIENT_NUMBER + }) + expect(response._body.status.status).to.not.equal('failed') + }) + + +}) + + + +describe('API tests for /cancel-booking endpoint for an end to end Notify Message', () => { + it('Should test unsuccess response for invalid order Id.', async () => { + const response = await request(app).post('/cancel-booking').send({ + "orderId":"Abcd" + }) + expect(response._body.status).equal(false) + }) + + it('Should test unsuccess response for no order Id.', async () => { + const response = await request(app).post('/cancel-booking').send({}) + expect(response._body.status).equal(false) + }) + + + it('Should test success response for valid order Id.', async () => { + const response = await request(app).post('/cancel-booking').send({ + "orderId":"1" + }) + expect(response._body.message).equal('Notification delivered') + }) + + +}) + +describe('API tests for /update-catalog endpoint for an end to end Notify Message', () => { + it('Should test success response for invalid whatsapp No.', async () => { + const response = await request(app).post('/update-catalog').send({ + "userNo":"+919123456789" + }) + expect(response._body.message).equal('Notification Failed') + }) + + it('Should test success response for no whatsapp number provided in the payload and will sent to TEST_RECEPIENT_NUMBER', async () => { + const response = await request(app).post('/update-catalog').send({}) + expect(response._body.message).equal('Catalog Updated') + }) + + it('Should test success response for valid whatsapp number', async () => { + const response = await request(app).post('/update-catalog').send({ + "userNo":process.env.TEST_RECEPIENT_NUMBER + }) + expect(response._body.message).equal('Catalog Updated') + }) +}) \ No newline at end of file diff --git a/utils/constants.js b/utils/constants.js index af20826..a2219d2 100644 --- a/utils/constants.js +++ b/utils/constants.js @@ -1,6 +1,3 @@ -export const STRAPI_TOURISM_TOKEN = - '82ed7f48afbd0c0605ef36bf4b81259f90c7e6bc357db032a011b1c0ab2bc7db2a753fa84c959f403b256ee66b44174dcc453bd0a40797ce8c22c1b6dab7f416cf3b8a247c19144bc3d019f229612f36b12612223b35f28a1a7fec6ff779228730b45fd93a793399d8f462ba0bada15077725a843d3023cf133838876da3547e' - export const ITEM_ID = '4' export const ITEM_NAME = 'Ticket Pass-Mueseum' From 7c9d2719585e2578c7ebe3a3432a08a47e3bef46 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Tue, 2 Apr 2024 20:39:28 +0530 Subject: [PATCH 06/15] Added: Chages requested by Mayur --- config/openai.json | 7 ++- controllers/ControlCenter.js | 51 +++++++++++--------- services/Actions.js | 7 ++- tests/unit/controllers/controlCenter.test.js | 35 ++++++++++---- tests/unit/services/actions.test.js | 6 +-- utils/constants.js | 2 +- 6 files changed, 65 insertions(+), 43 deletions(-) diff --git a/config/openai.json b/config/openai.json index 041363b..411d1bd 100644 --- a/config/openai.json +++ b/config/openai.json @@ -11,14 +11,13 @@ { "role": "system", "content": "A typical order flow should be search > select > init > confirm."}, { "role": "system", "content": "Use the response of search from assistant to select items from the list of items provided by the assistant."}, { "role": "system", "content": "Use the response of search request from assistant for filling transaction_id, bpp_id, bpp_uri in the context of all calls except `search`."}, - { "role": "system", "content": "Use the response from assistant to select items from the list of items provided by the assistant."} - + { "role": "system", "content": "Use the response from assistant to select items from the list of items provided by the assistant."}, + { "role": "system", "content": "For `select`, `init`, `confirm`, you must use the item `id` as part of the payload for selected item instead of name or any other key."} ], "PRESETS" : { "bap_id": "mit-ps-bap.becknprotocol.io", "bap_uri": "https://mit-ps-bap.becknprotocol.io", "version": "1.1.0", - "base_url": "https://mit-ps-bap-client.becknprotocol.io", - "TOURISM_STRAPI_URL": "https://mit-bpp-tourism.becknprotocol.io/api" + "base_url": "https://mit-ps-bap-client.becknprotocol.io" } } \ No newline at end of file diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js index e93120a..0deb299 100644 --- a/controllers/ControlCenter.js +++ b/controllers/ControlCenter.js @@ -7,49 +7,51 @@ import { CAT_ATTR_TAG_RELATIONS, NEW_CATALOG_AVAILABLE, TRIGGER_BLIZZARD_MESSAGE, - CANCEL_BOOKING_MESSAGE + CANCEL_BOOKING_MESSAGE, + TOURISM_STRAPI_URL } from '../utils/constants.js' -const config = JSON.parse(readFileSync('./config/openai.json')) const action = new Actions() -const STRAPI_TOURISM_TOKEN = process.env.STRAPI_TOURISM_TOKEN || '' + const TWILIO_RECEPIENT_NUMBER = process.env.TEST_RECEPIENT_NUMBER export const cancelBooking = async (req, res) => { try { const { orderId } = req.body if(!orderId){ - return res.status(500).json({message:"Order Id is Required", status:false}) + return res.status(400).json({message:"Order Id is Required", status:false}) } - const validOrderId = await action.call_api(`${config.PRESETS.TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`}) + + const validOrderId = await action.call_api(`${TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}) + if(!validOrderId.status){ - return res.send({ message: `Invalid Order Id`, status:false }) + return res.status(400).send({ message: `Invalid Order Id`, status:false }) } const messageBody = CANCEL_BOOKING_MESSAGE; - const getOrderAddressDetails = await action.call_api(`${config.PRESETS.TOURISM_STRAPI_URL}/order-addresses?order_id=${orderId}`,'GET',{},{ Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`}) + const getOrderAddressDetails = await action.call_api(`${TOURISM_STRAPI_URL}/order-addresses?order_id=${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}) - const getOrderFulfillmentDetails = await action.call_api(`${config.PRESETS.TOURISM_STRAPI_URL}/order-fulfillments?order_id=${orderId}`,'GET',{},{ Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`}) + const getOrderFulfillmentDetails = await action.call_api(`${TOURISM_STRAPI_URL}/order-fulfillments?order_id=${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}) if (getOrderFulfillmentDetails.data.data.length) { - await action.call_api(`${config.PRESETS.TOURISM_STRAPI_URL}/order-fulfillments/${getOrderFulfillmentDetails.data.data[0].id}`,'PUT',{ + await action.call_api(`${TOURISM_STRAPI_URL}/order-fulfillments/${getOrderFulfillmentDetails.data.data[0].id}`,'PUT',{ data: { state_code: 'CANCELLED', state_value: 'CANCELLED BY HOTEL', }, - },{ Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`}) + },{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}) let statusMessage = ""; if(getOrderAddressDetails.data.data[0].attributes.phone){ - statusMessage = (await action.send_message(`+91${getOrderAddressDetails.data.data[0].attributes.phone}`, messageBody)).status.status + statusMessage = (await action.send_message(`+91${getOrderAddressDetails.data.data[0].attributes.phone}`, messageBody)).deliveryStatus } else{ - statusMessage = (await action.send_message(TWILIO_RECEPIENT_NUMBER, messageBody)).status.status + statusMessage = (await action.send_message(TWILIO_RECEPIENT_NUMBER, messageBody)).deliveryStatus } - return res.send({ message: `Notification ${statusMessage}` }) + return res.status(200).send({ message: `Notification ${statusMessage}`, status:true }) } - return res.send({ message: 'Cancel Booking Failed' }) + return res.status(200).send({ message: 'Cancel Booking Failed', status:false }) } catch (error) { logger.error(error.message) - return res.send({ message: error.message }) + return res.status(400).send({ message: error.message, status:false }) } } @@ -57,20 +59,21 @@ export const updateCatalog = async (req, res) => { try { const { userNo = TWILIO_RECEPIENT_NUMBER } = req.body; const messageBody = NEW_CATALOG_AVAILABLE; - await action.call_api(`${config.PRESETS.TOURISM_STRAPI_URL}/items/${ITEM_ID}`,'PUT',{ + await action.call_api(`${TOURISM_STRAPI_URL}/items/${ITEM_ID}`,'PUT',{ data: { name: ITEM_NAME, cat_attr_tag_relations: CAT_ATTR_TAG_RELATIONS, }, - },{ Authorization: `Bearer ${STRAPI_TOURISM_TOKEN}`}) + },{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}) const notifyResponse = await action.send_message(userNo, messageBody) - if(notifyResponse.status.status === "failed"){ + + if(!notifyResponse || notifyResponse.deliveryStatus === "failed"){ throw new Error('Notification Failed') } - return res.send({ message: 'Catalog Updated' }) + return res.status(200).send({ message: 'Catalog Updated', status:true }) } catch (error) { logger.error(error.message) - return res.send({ message: error.message }) + return res.status(400).send({ message: error.message, status:false }) } } @@ -83,9 +86,13 @@ export const notify = async (req, res) => { userNo, messageBody ) - return res.send(sendWhatsappNotificationResponse) + if(sendWhatsappNotificationResponse.deliveryStatus === "failed"){ + return res.status(400).json({...sendWhatsappNotificationResponse, status:false}) + } + sendWhatsappNotificationResponse.deliveryStatus = 'delivered' + return res.status(200).json({...sendWhatsappNotificationResponse, status:true}) } catch (error) { logger.error(error.message) - return res.send({ message: error.message }) + return res.status(400).send({ message: error.message, status:false }) } } \ No newline at end of file diff --git a/services/Actions.js b/services/Actions.js index e503d17..e7b06c2 100644 --- a/services/Actions.js +++ b/services/Actions.js @@ -33,7 +33,7 @@ class Actions { // optimise search results. // This code will ensure that for search resylts, only the responses with catalog providers are returned and out of them we only take the first resopnse to further reduce the token size. // This should be imlemented by different baps based on their requirements. - if(request.data.context.action==='search'){ + if(request.data.context && request.data.context.action==='search'){ response.data.responses = response.data.responses.filter(res => res.message && res.message.catalog && res.message.catalog.providers && res.message.catalog.providers.length > 0) if(response.data.responses.length > 0) response.data.responses = response.data.responses.slice(0, 1); @@ -44,7 +44,7 @@ class Actions { cookies: response.headers['set-cookie'], } logger.info(`API call was successful: , response.status`) - // logger.info(JSON.stringify(response.data, null, 2)) + logger.info(JSON.stringify(response.data, null, 2)) } catch (error) { logger.error(error) @@ -112,8 +112,7 @@ class Actions { to: recipient.includes('whatsapp:') ? recipient : `whatsapp:${recipient}`, }) const status = await client.messages(data.sid).fetch() - - return { data, status } + return { deliveryStatus: status.status } } catch (error) { logger.error(`Error sending message: ${error.message}`) return false; diff --git a/tests/unit/controllers/controlCenter.test.js b/tests/unit/controllers/controlCenter.test.js index 6a54737..d1bbfce 100644 --- a/tests/unit/controllers/controlCenter.test.js +++ b/tests/unit/controllers/controlCenter.test.js @@ -8,23 +8,26 @@ const expect = chai.expect describe('API tests for /notify endpoint for an end to end Notify Request', () => { it('Should test unsuccess response for invalid whatsapp number.', async () => { const response = await request(app).post('/notify').send({ - "userNo":"+919123456789" + "userNo":"INVALID_NUMBER" }) - expect(response._body.status.status).equal('failed') + expect(response.status).to.equal(400) }) it('Should test success response for no whatsapp number provided in the payload and will sent to TEST_RECEPIENT_NUMBER', async () => { - const response = await request(app).post('/notify').send({ - - }) - expect(response._body.status.status).to.not.equal('failed') + const response = await request(app).post('/notify').send({}) + + expect(response.status).to.equal(200) + expect(response._body.status).to.equal(true) + expect(['sent', 'delivered']).to.include(response._body.deliveryStatus) }) it('Should test success response for valid whatsapp number', async () => { const response = await request(app).post('/notify').send({ "userNo":process.env.TEST_RECEPIENT_NUMBER }) - expect(response._body.status.status).to.not.equal('failed') + expect(response.status).to.equal(200) + expect(response._body.status).to.equal(true) + expect(['sent', 'delivered']).to.include(response._body.deliveryStatus) }) @@ -37,11 +40,15 @@ describe('API tests for /cancel-booking endpoint for an end to end Notify Messag const response = await request(app).post('/cancel-booking').send({ "orderId":"Abcd" }) + expect(response.status).equal(400) + expect(response._body.status).equal(false) expect(response._body.status).equal(false) }) it('Should test unsuccess response for no order Id.', async () => { const response = await request(app).post('/cancel-booking').send({}) + expect(response.status).equal(400) + expect(response._body.status).equal(false) expect(response._body.status).equal(false) }) @@ -50,7 +57,10 @@ describe('API tests for /cancel-booking endpoint for an end to end Notify Messag const response = await request(app).post('/cancel-booking').send({ "orderId":"1" }) - expect(response._body.message).equal('Notification delivered') + + expect(response.status).equal(200) + expect(response._body.status).equal(true) + expect(['Notification delivered' , 'Notification sent']).to.include(response._body.message) }) @@ -59,13 +69,18 @@ describe('API tests for /cancel-booking endpoint for an end to end Notify Messag describe('API tests for /update-catalog endpoint for an end to end Notify Message', () => { it('Should test success response for invalid whatsapp No.', async () => { const response = await request(app).post('/update-catalog').send({ - "userNo":"+919123456789" + "userNo":"INVALID_NUMBER" }) + + expect(response.status).equal(400) + expect(response._body.status).equal(false) expect(response._body.message).equal('Notification Failed') }) it('Should test success response for no whatsapp number provided in the payload and will sent to TEST_RECEPIENT_NUMBER', async () => { const response = await request(app).post('/update-catalog').send({}) + expect(response.status).equal(200) + expect(response._body.status).equal(true) expect(response._body.message).equal('Catalog Updated') }) @@ -73,6 +88,8 @@ describe('API tests for /update-catalog endpoint for an end to end Notify Messag const response = await request(app).post('/update-catalog').send({ "userNo":process.env.TEST_RECEPIENT_NUMBER }) + expect(response.status).equal(200) + expect(response._body.status).equal(true) expect(response._body.message).equal('Catalog Updated') }) }) \ No newline at end of file diff --git a/tests/unit/services/actions.test.js b/tests/unit/services/actions.test.js index 3a85463..35c98b7 100644 --- a/tests/unit/services/actions.test.js +++ b/tests/unit/services/actions.test.js @@ -52,7 +52,8 @@ describe('should test send_message()', () => { const message = "hi, this is a test message"; let status = await actionsService.send_message(recipient, message); - expect(status).to.be.true; + + expect(['delivered', 'sent']).to.include(status.deliveryStatus) }); it('should test send a message via Twilio with a whatsapp prefix', async () => { @@ -60,7 +61,7 @@ describe('should test send_message()', () => { const message = "hi, this is a test message"; let status = await actionsService.send_message(recipient, message); - expect(status).to.be.true; + expect(['delivered', 'sent']).to.include(status.deliveryStatus) }); @@ -85,7 +86,6 @@ describe('should test send_message()', () => { await actionsService.send_message(recipient, message); throw new Error('Expected an error to be thrown'); } catch (error) { - expect(error).to.be.an.instanceOf(Error); } }); diff --git a/utils/constants.js b/utils/constants.js index a2219d2..9d4f394 100644 --- a/utils/constants.js +++ b/utils/constants.js @@ -5,4 +5,4 @@ export const CAT_ATTR_TAG_RELATIONS = [2, 3, 4, 5] export const TRIGGER_BLIZZARD_MESSAGE = "Hey, Triggering a Blizzard"; export const CANCEL_BOOKING_MESSAGE = `Dear Guest,\n\nApologies, but your hotel booking with us has been canceled due to unforeseen circumstances. \nWe understand the inconvenience and are here to assist you with any alternative arrangements needed. \n\nPlease contact us for further assistance.`; export const NEW_CATALOG_AVAILABLE = `Dear Guest,\n\n Checkout this new place to visit.` - +export const TOURISM_STRAPI_URL = "https://mit-bpp-tourism.becknprotocol.io/api" From c690077fda94ca188ea027eb33c8b6f131f1f7f5 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Wed, 3 Apr 2024 18:08:58 +0530 Subject: [PATCH 07/15] Added: Chages requested by Mayur --- controllers/ControlCenter.js | 1 - 1 file changed, 1 deletion(-) diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js index 0deb299..eb67a9d 100644 --- a/controllers/ControlCenter.js +++ b/controllers/ControlCenter.js @@ -1,5 +1,4 @@ import Actions from '../services/Actions.js' -import { readFileSync } from 'fs'; import logger from '../utils/logger.js' import { ITEM_ID, From 6963fec818b519ef9f1a5bb27ce24c6f582f7283 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Wed, 3 Apr 2024 19:11:22 +0530 Subject: [PATCH 08/15] Fixed:Test Cases --- tests/unit/controllers/controlCenter.test.js | 4 ++-- tests/unit/services/actions.test.js | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/unit/controllers/controlCenter.test.js b/tests/unit/controllers/controlCenter.test.js index d1bbfce..9d805a6 100644 --- a/tests/unit/controllers/controlCenter.test.js +++ b/tests/unit/controllers/controlCenter.test.js @@ -18,7 +18,7 @@ describe('API tests for /notify endpoint for an end to end Notify Request', () = expect(response.status).to.equal(200) expect(response._body.status).to.equal(true) - expect(['sent', 'delivered']).to.include(response._body.deliveryStatus) + expect(response._body.deliveryStatus).to.not.equal('failed') }) it('Should test success response for valid whatsapp number', async () => { @@ -27,7 +27,7 @@ describe('API tests for /notify endpoint for an end to end Notify Request', () = }) expect(response.status).to.equal(200) expect(response._body.status).to.equal(true) - expect(['sent', 'delivered']).to.include(response._body.deliveryStatus) + expect(response._body.deliveryStatus).to.not.equal('failed') }) diff --git a/tests/unit/services/actions.test.js b/tests/unit/services/actions.test.js index 35c98b7..dc46345 100644 --- a/tests/unit/services/actions.test.js +++ b/tests/unit/services/actions.test.js @@ -46,14 +46,14 @@ describe.skip('Test cases for process_instruction function', ()=> { }) }) -describe('should test send_message()', () => { +describe.only('should test send_message()', () => { it('should test send a message via Twilio', async () => { const recipient = process.env.TEST_RECEPIENT_NUMBER; const message = "hi, this is a test message"; let status = await actionsService.send_message(recipient, message); - expect(['delivered', 'sent']).to.include(status.deliveryStatus) + expect(status.deliveryStatus).to.not.equal('failed') }); it('should test send a message via Twilio with a whatsapp prefix', async () => { @@ -61,7 +61,7 @@ describe('should test send_message()', () => { const message = "hi, this is a test message"; let status = await actionsService.send_message(recipient, message); - expect(['delivered', 'sent']).to.include(status.deliveryStatus) + expect(status.deliveryStatus).to.not.equal('failed') }); From 1518a84a0cdc04ea6785a7740b83c8f93f349c66 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Wed, 3 Apr 2024 21:12:06 +0530 Subject: [PATCH 09/15] Fixed:Test Cases --- config/openai.json | 9 +-------- tests/unit/services/actions.test.js | 5 +---- 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/config/openai.json b/config/openai.json index 411d1bd..7ca9729 100644 --- a/config/openai.json +++ b/config/openai.json @@ -11,13 +11,6 @@ { "role": "system", "content": "A typical order flow should be search > select > init > confirm."}, { "role": "system", "content": "Use the response of search from assistant to select items from the list of items provided by the assistant."}, { "role": "system", "content": "Use the response of search request from assistant for filling transaction_id, bpp_id, bpp_uri in the context of all calls except `search`."}, - { "role": "system", "content": "Use the response from assistant to select items from the list of items provided by the assistant."}, { "role": "system", "content": "For `select`, `init`, `confirm`, you must use the item `id` as part of the payload for selected item instead of name or any other key."} - ], - "PRESETS" : { - "bap_id": "mit-ps-bap.becknprotocol.io", - "bap_uri": "https://mit-ps-bap.becknprotocol.io", - "version": "1.1.0", - "base_url": "https://mit-ps-bap-client.becknprotocol.io" - } + ] } \ No newline at end of file diff --git a/tests/unit/services/actions.test.js b/tests/unit/services/actions.test.js index dc46345..45994c5 100644 --- a/tests/unit/services/actions.test.js +++ b/tests/unit/services/actions.test.js @@ -46,7 +46,7 @@ describe.skip('Test cases for process_instruction function', ()=> { }) }) -describe.only('should test send_message()', () => { +describe('should test send_message()', () => { it('should test send a message via Twilio', async () => { const recipient = process.env.TEST_RECEPIENT_NUMBER; const message = "hi, this is a test message"; @@ -68,12 +68,10 @@ describe.only('should test send_message()', () => { it('should throw an error for invalid recipient', async () => { const recipient = ''; const message = 'Test message'; - try { await actionsService.send_message(recipient, message); throw new Error('Expected an error to be thrown'); } catch (error) { - expect(error).to.be.an.instanceOf(Error); } }); @@ -81,7 +79,6 @@ describe.only('should test send_message()', () => { it('should throw an error for empty message', async () => { const recipient = process.env.TEST_RECEPIENT_NUMBER; const message = ''; - try { await actionsService.send_message(recipient, message); throw new Error('Expected an error to be thrown'); From 81c3edec2db3f347b67e4b1126e3e960814cce49 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Wed, 3 Apr 2024 21:27:55 +0530 Subject: [PATCH 10/15] Fixed:Test Cases --- tests/unit/services/ai.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/services/ai.test.js b/tests/unit/services/ai.test.js index f55a51c..02e8efc 100644 --- a/tests/unit/services/ai.test.js +++ b/tests/unit/services/ai.test.js @@ -148,7 +148,7 @@ describe('Test cases for get_context_by_instruction()', async () => { expect(config.bap_url).to.equal(registry_config[0].bpp_subscriber_uri); }) - it('Should return right config for search action in retail contect', async () => { + it('Should return right config for search action in retail context', async () => { ai.action = {action: 'search'}; const config = await ai.get_context_by_instruction("I'm looking for some pet food");; expect(config).to.have.property('action') From 009e2518daf9c1a32bae00fd7fab6141fe0cbba8 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Wed, 3 Apr 2024 21:39:36 +0530 Subject: [PATCH 11/15] Fixed:Test Cases --- controllers/ControlCenter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js index eb67a9d..173f69d 100644 --- a/controllers/ControlCenter.js +++ b/controllers/ControlCenter.js @@ -21,7 +21,7 @@ export const cancelBooking = async (req, res) => { } const validOrderId = await action.call_api(`${TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}) - + logger.info(`OrderDetails: ${JSON.stringify(validOrderId)}`) if(!validOrderId.status){ return res.status(400).send({ message: `Invalid Order Id`, status:false }) } From 08e51c703dae5a88085928c5062caababd5f4d00 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Wed, 3 Apr 2024 21:50:44 +0530 Subject: [PATCH 12/15] Fixed:Test Cases --- controllers/ControlCenter.js | 1 + 1 file changed, 1 insertion(+) diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js index 173f69d..b135a57 100644 --- a/controllers/ControlCenter.js +++ b/controllers/ControlCenter.js @@ -21,6 +21,7 @@ export const cancelBooking = async (req, res) => { } const validOrderId = await action.call_api(`${TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}) + logger.info(`${[`${TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}]}`) logger.info(`OrderDetails: ${JSON.stringify(validOrderId)}`) if(!validOrderId.status){ return res.status(400).send({ message: `Invalid Order Id`, status:false }) From b3c02821062ad9a33507107eb0482e56fff4d930 Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Wed, 3 Apr 2024 21:57:26 +0530 Subject: [PATCH 13/15] Fixed:Test Cases --- controllers/ControlCenter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js index b135a57..daf74c2 100644 --- a/controllers/ControlCenter.js +++ b/controllers/ControlCenter.js @@ -21,7 +21,7 @@ export const cancelBooking = async (req, res) => { } const validOrderId = await action.call_api(`${TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}) - logger.info(`${[`${TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}]}`) + logger.info(`${JSON.stringify([`${TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}])}`) logger.info(`OrderDetails: ${JSON.stringify(validOrderId)}`) if(!validOrderId.status){ return res.status(400).send({ message: `Invalid Order Id`, status:false }) From a817650f4e13cf7c08d327a5cb052d534d53153a Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Wed, 3 Apr 2024 22:08:23 +0530 Subject: [PATCH 14/15] Fixed:Test Cases --- .github/workflows/api_tests.yml | 1 + .github/workflows/deploy.yml | 2 +- .github/workflows/lint_checks.yml | 2 +- .github/workflows/unit_tests.yml | 2 +- controllers/ControlCenter.js | 1 - 5 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/api_tests.yml b/.github/workflows/api_tests.yml index 6f41203..c57dad4 100644 --- a/.github/workflows/api_tests.yml +++ b/.github/workflows/api_tests.yml @@ -23,6 +23,7 @@ jobs: echo "TWILIO_AUTH_TOKEN=${{secrets.TWILIO_AUTH_TOKEN}}" >> .env echo "TWILIO_NUMBER=${{secrets.TWILIO_NUMBER}}" >> .env echo "TEST_RECEPIENT_NUMBER=${{secrets.TEST_RECEPIENT_NUMBER}}" >> .env + echo "STRAPI_TOURISM_TOKEN=${{secrets.STRAPI_TOURISM_TOKEN}}" >> .env - name: Set up Node.js uses: actions/setup-node@v2 diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index c7db779..70bdba2 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -24,7 +24,7 @@ jobs: echo "TWILIO_AUTH_TOKEN=${{secrets.TWILIO_AUTH_TOKEN}}" >> .env echo "TWILIO_NUMBER=${{secrets.TWILIO_NUMBER}}" >> .env echo "TEST_RECEPIENT_NUMBER=${{secrets.TEST_RECEPIENT_NUMBER}}" >> .env - + echo "STRAPI_TOURISM_TOKEN=${{secrets.STRAPI_TOURISM_TOKEN}}" >> .env - name: Create SSH key file run: echo -e "${{ secrets.EC2_SSH_KEY }}" > ~/ec2_key env: diff --git a/.github/workflows/lint_checks.yml b/.github/workflows/lint_checks.yml index cdba9ff..212b69e 100644 --- a/.github/workflows/lint_checks.yml +++ b/.github/workflows/lint_checks.yml @@ -23,7 +23,7 @@ jobs: echo "TWILIO_AUTH_TOKEN=${{secrets.TWILIO_AUTH_TOKEN}}" >> .env echo "TWILIO_NUMBER=${{secrets.TWILIO_NUMBER}}" >> .env echo "TEST_RECEPIENT_NUMBER=${{secrets.TEST_RECEPIENT_NUMBER}}" >> .env - + echo "STRAPI_TOURISM_TOKEN=${{secrets.STRAPI_TOURISM_TOKEN}}" >> .env - name: Set up Node.js uses: actions/setup-node@v2 with: diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index adc4635..27f1df7 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -23,7 +23,7 @@ jobs: echo "TWILIO_AUTH_TOKEN=${{secrets.TWILIO_AUTH_TOKEN}}" >> .env echo "TWILIO_NUMBER=${{secrets.TWILIO_NUMBER}}" >> .env echo "TEST_RECEPIENT_NUMBER=${{secrets.TEST_RECEPIENT_NUMBER}}" >> .env - + echo "STRAPI_TOURISM_TOKEN=${{secrets.STRAPI_TOURISM_TOKEN}}" >> .env - name: Set up Node.js uses: actions/setup-node@v2 with: diff --git a/controllers/ControlCenter.js b/controllers/ControlCenter.js index daf74c2..173f69d 100644 --- a/controllers/ControlCenter.js +++ b/controllers/ControlCenter.js @@ -21,7 +21,6 @@ export const cancelBooking = async (req, res) => { } const validOrderId = await action.call_api(`${TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}) - logger.info(`${JSON.stringify([`${TOURISM_STRAPI_URL}/orders/${orderId}`,'GET',{},{ Authorization: `Bearer ${process.env.STRAPI_TOURISM_TOKEN}`}])}`) logger.info(`OrderDetails: ${JSON.stringify(validOrderId)}`) if(!validOrderId.status){ return res.status(400).send({ message: `Invalid Order Id`, status:false }) From a8f156f764caa02f65141de1558372b6b51a408e Mon Sep 17 00:00:00 2001 From: shreyvishal Date: Wed, 3 Apr 2024 22:21:30 +0530 Subject: [PATCH 15/15] Fixed:Test Cases --- tests/unit/controllers/controlCenter.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/controllers/controlCenter.test.js b/tests/unit/controllers/controlCenter.test.js index 9d805a6..e45c314 100644 --- a/tests/unit/controllers/controlCenter.test.js +++ b/tests/unit/controllers/controlCenter.test.js @@ -60,7 +60,7 @@ describe('API tests for /cancel-booking endpoint for an end to end Notify Messag expect(response.status).equal(200) expect(response._body.status).equal(true) - expect(['Notification delivered' , 'Notification sent']).to.include(response._body.message) + expect(response._body.message).to.not.equal('Notification failed') })