firestore min max function not working in query - javascript

I got this firestore query for filtering data from my database but my min max is not filtering out my max price. I don't understand why.
The else function is not working
but when I test the query in the else if statements then the min max is working without problems.
My body of the GET request:
{
"pageNumber": 1,
"seller": "",
"name": "shirt",
"category": "Shirts",
"min": 0,
"max": 120,
"rating": [ 3, 4 ],
"order": "lowest"
}
My code:
const { admin, db } = require("../util/admin");
const config = require("../util/config");
const firebase = require("firebase");
const { data } = require("../data");
//get all products
let latestDoc = null;
exports.getAllProducts = (req, res) => {
const limit = 4;
const page = Number(req.body.pageNumber) || 1;
const name = req.body.name || "";
const category = req.body.category || "";
const order = req.body.order || "";
const min =
req.body.min && Number(req.body.min) !== 0 ? Number(req.body.min) : 0;
const max =
req.body.max && Number(req.body.max) !== 0 ? Number(req.body.max) : 1000000;
const rating = req.body.rating[0];
const sortOrder =
order === "lowest" ? "asc" : order === "highest" ? "desc" : "asc";
const orderType =
order === "newest"
? "createdAt"
: order === "toprated"
? "rating"
: "price";
console.log(min);
console.log(max);
if (category === "" && rating === 0 && name === "") {
console.log("geen filter");
db.collection("products")
.orderBy(orderType, sortOrder)
.startAfter(latestDoc || 0)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
.then((doc) => {
const sendData = doc.docs.map((data) => data.data());
latestDoc = doc.docs[doc.docs.length - 1];
res.send(sendData);
});
} else if (category === "" && rating > 0 && name === "") {
console.log("products");
db.collection("products")
.where("rating", ">=", rating)
.orderBy("rating")
.startAfter(latestDoc || 0)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
.then((doc) => {
const sendData = doc.docs.map((data) => data.data());
latestDoc = doc.docs[doc.docs.length - 1];
res.send(sendData);
});
} else if (category !== "" && rating === 0 && name === "") {
console.log("category");
db.collection("products")
.where("category", "==", category)
.orderBy(orderType, sortOrder)
.startAfter(latestDoc || 0)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
.then((doc) => {
const sendData = doc.docs.map((data) => data.data());
latestDoc = doc.docs[doc.docs.length - 1];
res.send(sendData);
});
} else if (name !== "" && category === "" && rating === 0) {
console.log("naam");
db.collection("products")
.where("searchName", "array-contains", name)
.orderBy("price")
.startAfter(latestDoc || 0)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
.then((doc) => {
const sendData = doc.docs.map((data) => data.data());
latestDoc = doc.docs[doc.docs.length - 1];
res.send(sendData);
});
} else {
console.log("else");
db.collection("products")
.where("searchName", "array-contains", name)
.where("rating", ">=", rating)
.orderBy("rating")
.where("category", "==", category)
.orderBy(orderType, sortOrder)
.startAfter(latestDoc || 0)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
.then((doc) => {
const sendData = doc.docs.map((data) => data.data());
latestDoc = doc.docs[doc.docs.length - 1];
res.send(sendData);
});
}
};

There are a few problems with your query:
You have a orderBy() between 2 query filters, this is not allowed, so you have to move .orderBy("rating") to after .where("category", "==", category);
You have both a startAfter() and a startAt() clause in your query, you can't do that, you either start after a certain value or at a fixed position;
So say you would change your query to something like this:
db.collection("products")
.where("searchName", "array-contains", name)
.where("category", "==", category)
.where("rating", ">=", rating)
.orderBy("rating")
.orderBy(orderType, sortOrder)
.limit(limit)
.startAt(min)
.endAt(max)
.get()
It should work.

Related

discord.js trying to collect number after a button click

I want my bot to recognize that if my collection equals to 1 then do something but the bot is not getting if it was 1 here is my code
if(button.id === 'policeticket') {
let member = button.clicker.user.id;
button.channel.send("type a number")
const filter = m => m.author.id == button.clicker.user.id;
button.channel.awaitMessages(filter, { max: 1, time: 60000, errors: ['time'] })
.then(async collection => {
let number = collection.first();
if(number === "1") {
button.channel.send("test")
}
})
}
})
I don't no if is correct, but i think do you are comparate a number with a string, and that's comparate always return false if value was number.
in your case i would try this code.
if (button.id === 'policeticket') {
let member = button.clicker.user.id;
button.channel.send("type a number")
const filter = m => m.author.id == button.clicker.user.id;
button.channel.awaitMessages(filter, { max: 1, time: 60000, errors: ['time'] })
.then(async collection => {
let number = collection.first();
if (number === 1) {
button.channel.send("test")
}
})
}
if (button.id === 'policeticket') {
let member = button.clicker.user.id;
button.channel.send("type a number")
const filter = m => m.author.id == button.clicker.user.id;
button.channel.awaitMessages(filter, { max: 1, time: 60000, errors: ['time'] })
.then(async collection => {
let number = parseInt(collection.first());
if (number === 1) {
button.channel.send("test")
}
})
}

How to delete a voice channel when everybody disconnects?

I created a join to create system that creates a channel when a user join and delete it when they leave. However, it only deletes if the last person that's leaving is the user who created the room. Any ideas?
const { Collection } = require("discord.js");
const voiceCollection = new Collection();
module.exports = async (Discord, client, oldState, newState) => {
const user = await client.users.fetch(newState.id);
const member = newState.guild.member(user);
// JOIN
if (!voiceName || voiceName === "") {
if (!oldState.channel && newState.channelID === "898245212541976667") {
const channel = await newState.guild.channels.create(user.tag, {
type: "voice",
parent: newState.channel.parent,
});
member.voice.setChannel(channel);
voiceCollection.set(user.id, channel.id);
await channel.overwritePermissions([
{
id: user.id,
allow: ["MANAGE_CHANNELS", "CONNECT"],
},
{
id: member.guild.id,
deny: ["CONNECT"],
},
]);
} else if (!newState.channel) {
if (oldState.channelID === voiceCollection.get(newState.id)) {
if (oldState.channel.members.size < 1) {
return oldState.channel.delete();
}
}
}
var newchannel_id = config.Channel_id;
var category_id = config.category;
var userchannellist = []
client.login(token);
client.on('voiceStateUpdate', async (oldMember, newMember) => {
if (newMember.channel !== null && oldMember.channel === null && newMember.channel.id === newchannel_id || newMember.channel !== null && oldMember.channel !== null && newMember.channel.id === newchannel_id) {
var current_user = newMember.member.user;
console.log(current_user.username + 'creating the channel');
// Start the creation of the new channel
var server = newMember.guild;
let USERA = newMember.member.nickname || newMember.member.user.username;
var channel = {
type: 'voice', bitrate: 384000, parent: category_id, permissionOverwrites: [{
// permissions
id: server.id, allow: ['VIEW_CHANNEL'],
},
{
id: current_user.id, allow: ['MOVE_MEMBERS', 'MANAGE_CHANNELS']
}
]
};
server.channels.create('🔊' + USERA, channel).then(channel => {
newMember.setChannel(channel).catch(console.error)
userchannellist.push(channel)
//channel region
client.api.channels(channel.id).patch({ data: { rtc_region: "rotterdam" } })
}).catch(console.error);
}
// delete Chaneel
if (oldMember.channel) {
let filter = (ch) =>
(ch.parentID == category_id)
&& (ch.id !== newchannel_id)
&& (oldMember.channel == ch.id)
&& (oldMember.channel.members.size == 0);
return oldMember.guild.channels.cache
.filter(filter)
.forEach((ch) => ch.delete()
.catch(console.error));
}
});

How to cycle through and then save products?

Good afternoon, I am trying to change the remainder of the product in mongoose in a loop. But persistence doesn't work. I would be grateful for your help!
const statusOutOfStock = await ProductStockStatus.findOne({
color: 'danger',
})
for await (const product of Product.find()) {
const orderItems = order.orderItems.filter(
item => String(item.product) === String(product._id)
)
if (orderItems?.length > 0) {
orderItems.forEach(async orderItem => {
if (orderItem.varIdx === 0 && product.stock !== null) {
const stockResult = product.stock - orderItem.count
product.stock = stockResult
if (stockResult === 0) product.status = statusOutOfStock._id
} else {
const stockResult =
product.variations[orderItem.varIdx].stock - orderItem.count
product.variations[orderItem.varIdx].stock = stockResult
if (stockResult === 0)
product.variations[orderItem.varIdx].status = statusOutOfStock
}
})
await product.save()
}
}
I was able to solve this problem.
/* Deduction of stock */
const statusOutOfStock = await ProductStockStatus.findOne({
color: 'danger',
})
for await (const product of Product.find()) {
/* Get order items by productID */
const orderItems = order.orderItems.filter(
item => String(item.product) === String(product._id)
)
/* If order items exists */
if (orderItems?.length > 0) {
/* Run of order items and write new stock */
const proDb = await Product.findById(product._id)
let buffer = []
await Promise.all(
orderItems.map(async orderItem => {
if (orderItem.varIdx === 0 && product?.stock !== null) {
const stockResult = product.stock - orderItem.count
proDb.stock = stockResult < 0 ? 0 : stockResult
if (stockResult === 0) proDb.status = statusOutOfStock._id
} else if (
!!product?.variations[orderItem.varIdx]?.stock !== null &&
orderItem.varIdx !== 0
) {
const stockResult =
product.variations[orderItem.varIdx].stock - orderItem.count
if (buffer?.length === 0) buffer = [...product.variations]
buffer[orderItem.varIdx].stock =
stockResult < 0 ? 0 : stockResult
proDb.variations = buffer
if (stockResult === 0)
proDb.variations[orderItem.varIdx].status = statusOutOfStock
}
})
)
await proDb.save()
}
}

Discord.js limit awaitMessage to 1 channel

I got a issue with a ticket system I made. Currently if the bot has 2 tickets open with questions and is awaiting for a response it takes the response from other channels. Is there a way to only accept the message in the destination channel? The bot has 3 reactions on a message, if you react it makes a new channel and asks you a few questions. These questions interfere with each other
bot.on('messageReactionAdd', (reaction, user) => {
if (user.bot) {
return;
}
reaction.users.remove(user.id)
bot.users.fetch(user.id).then((user) => {
let channelId = "";
let query = `SELECT * FROM ticketMessage`;
db.get(query, (err, row) => {
let ticketMessage = row.MessageId;
if (reaction.emoji.name == "🦖" && reaction.message.id == ticketMessage) {
const startTicket = async (name) => {
reaction.message.channel.guild.channels.create(user.username + name, {
type: 'text'
})
.then(channel => {
let category = "";
category = reaction.message.channel.guild.channels.cache.find(c => c.name.toLowerCase() == "tickets" && c.type == "category");
if (!category) {
user.send("Couldn't Process your ticket since there is no category setup for it!")
} else {
channel.setParent(category.id)
channelId = channel.id
sendQuestions()
}
}).catch(console.error);
}
startTicket(" Dino Lines");
const sendQuestions = async () => {
ticketChannel = bot.channels.cache.get(channelId)
const filter = m => m.author.id === user.id && m.channel === ticketChannel;
ticketChannel.send("What are the names of the dino's you would like to buy, Example => (T-rex, Bronto)?")
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let dinoName = collected.first().content
ticketChannel.send("How many dino's would you like to buy, Example => (Dino1: 5, Dino2: 3)?");
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let amount = collected.first().content
ticketChannel.send("What kind of currency would you like to use, Example => (Money, Items, Recources)?");
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let currencyKind = collected.first().content
ticketChannel.send("Do you want to submit this ticket? => (Yes, No)");
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let yn = collected.first().content
if (yn.toLowerCase() == "yes") {
embed1 = new Discord.MessageEmbed
ticketChannel.bulkDelete(8, true)
embed1
.setTitle(user.username + "'s Ticket")
.addFields({
name: "Buying Dino Lines",
value: "\u200b \n **Dino Names:** " + dinoName + "\n **Dino Count:** " + amount + "\n **Payment Methode:** " + currencyKind,
inline: true
}, )
.setFooter(settings["Embeds"].displayname, settings["Embeds"].image)
.setColor(settings["Embeds"].color)
.setTimestamp()
ticketChannel.send(embed1)
} else {
ticketChannel.send("Okay ticket canceled!");
}
})
})
})
})
}
} else if (reaction.emoji.name == "⚔️" && reaction.message.id == ticketMessage) {
const startTicket = async (name) => {
reaction.message.channel.guild.channels.create(user.username + name, {
type: 'text'
})
.then(channel => {
let category = "";
category = reaction.message.channel.guild.channels.cache.find(c => c.name.toLowerCase() == "tickets" && c.type == "category");
if (!category) {
user.send("Couldn't Process your ticket since there is no category setup for it!")
} else {
channel.setParent(category.id)
channelId = channel.id
sendQuestions()
}
}).catch(console.error);
}
startTicket(" Boss Fights");
const sendQuestions = async () => {
ticketChannel = bot.channels.cache.get(channelId)
const filter = m => m.author.id === user.id && m.channel === ticketChannel;
ticketChannel.send("What are the names of the bossfights you would like to buy, Example => (Dragon, Broodmother)?")
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let bossName = collected.first().content
ticketChannel.send("How many people are joining?, Example => (Fight1: 5, Fight2: 3)?");
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let amount = collected.first().content
ticketChannel.send("What kind of currency would you like to use, Example => (Money, Items, Recources)?");
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let currencyKind = collected.first().content
ticketChannel.send("Do you want to submit this ticket? => (Yes, No)");
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let yn = collected.first().content
if (yn.toLowerCase() == "yes") {
embed1 = new Discord.MessageEmbed
ticketChannel.bulkDelete(8, true)
embed1
.setTitle(user.username + "'s Ticket")
.addFields({
name: "Buying Dino Lines",
value: "\u200b \n **Dino Names:** " + bossName + "\n **Dino Count:** " + amount + "\n **Payment Methode:** " + currencyKind,
inline: true
}, )
.setFooter(settings["Embeds"].displayname, settings["Embeds"].image)
.setColor(settings["Embeds"].color)
.setTimestamp()
ticketChannel.send(embed1)
} else {
ticketChannel.send("Okay ticket canceled!");
}
})
})
})
})
}
} else if (reaction.emoji.name == "🖨️" && reaction.message.id == ticketMessage) {
const startTicket = async (name) => {
reaction.message.channel.guild.channels.create(user.username + name, {
type: 'text'
})
.then(channel => {
let category = "";
category = reaction.message.channel.guild.channels.cache.find(c => c.name.toLowerCase() == "tickets" && c.type == "category");
if (!category) {
user.send("Couldn't Process your ticket since there is no category setup for it!")
} else {
channel.setParent(category.id)
channelId = channel.id
sendQuestions()
}
}).catch(console.error);
}
startTicket(" Blue Prints");
const sendQuestions = async () => {
ticketChannel = bot.channels.cache.get(channelId)
const filter = m => m.author.id === user.id && m.channel === ticketChannel;
ticketChannel.send("Which blueprint would you like to buy?, Example => (Bow, Sadle)?")
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let bluePrint = collected.first().content
ticketChannel.send("What kind of currency would you like to use, Example => (Money, Items, Recources)?");
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let currencyKind = collected.first().content
ticketChannel.send("Do you want to submit this ticket? => (Yes, No)");
ticketChannel.awaitMessages(filter, {
max: 1,
time: 120000
})
.then(collected => {
let yn = collected.first().content
if (yn.toLowerCase() == "yes") {
embed1 = new Discord.MessageEmbed
ticketChannel.bulkDelete(8, true)
embed1
.setTitle(user.username + "'s Ticket")
.addFields({
name: "Buying Dino Lines",
value: "\u200b \n **Dino Names:** " + bluePrint + "\n **Payment Methode:** " + currencyKind,
inline: true
}, )
.setFooter(settings["Embeds"].displayname, settings["Embeds"].image)
.setColor(settings["Embeds"].color)
.setTimestamp()
ticketChannel.send(embed1)
} else {
ticketChannel.send("Okay ticket canceled!");
}
})
})
})
}
} else if (reaction.emoji.name == "❓" && reaction.message.id == ticketMessage) {
const startTicket = async (name) => {
reaction.message.channel.guild.channels.create(user.username + name, {
type: 'text'
})
.then(channel => {
let category = "";
category = reaction.message.channel.guild.channels.cache.find(c => c.name.toLowerCase() == "tickets" && c.type == "category");
if (!category) {
user.send("Couldn't Process your ticket since there is no category setup for it!")
} else {
channel.setParent(category.id)
channelId = channel.id
sendQuestions()
}
}).catch(console.error);
}
startTicket(" Random Things");
const sendQuestions = async () => {
ticketChannel = bot.channels.cache.get(channelId)
ticketChannel.send("How can we help you?")
}
} else if (reaction.emoji.name == "✉️" && reaction.message.id == ticketMessage) {
const startTicket = async (name) => {
reaction.message.channel.guild.channels.create(user.username + name, {
type: 'text'
})
.then(channel => {
let category = "";
category = reaction.message.channel.guild.channels.cache.find(c => c.name.toLowerCase() == "tickets" && c.type == "category");
if (!category) {
user.send("Couldn't Process your ticket since there is no category setup for it!")
} else {
channel.setParent(category.id)
channelId = channel.id
sendQuestions()
}
}).catch(console.error);
}
startTicket(" Support");
const sendQuestions = async () => {
ticketChannel = bot.channels.cache.get(channelId)
ticketChannel.send("How can we help you?")
}
}
})
})
})

Linear flow of multiple intent is not working

I am working on a project of Amazon Alexa of booking a table in a restaurant and I have four intents:
makeReservation
futureOrCurrentLocation
getRestaurantName
selectRestaurants
I am facing one issue that the linear flow of intent is not working. I have stored the previous intent in the session and checked the previous intent from the session and on that basic I am calling the next intent.
But when I say Alexa with the previous intent String in the response of the current intent, it jumps to the new intent we have called, but it throws an exception.
Actually it should work like if I say some intent String in the response of other intent then it should repeat the current intent once again.
And one more issue I am facing is that I need to append the String in the user utterance like e.g.:
Alexa: "Where would you like to go?"
User: "Go to {Restaurant Name}"
I didn't want to append this "Go to" in the restaurant name.
// Lambda Function code for Alexa.
const Alexa = require("ask-sdk");
// Book a table
const makeReservation_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'makeReservation' ;
},
handle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
sessionAttributes.tableTalkType = 1;
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
return responseBuilder
.addDelegateDirective({
name: 'futureOrCurrentLocation',
confirmationStatus: 'NONE',
slots: {}
})
.withShouldEndSession(false)
.getResponse();
},
};
const futureOrCurrentLocation_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'futureOrCurrentLocation' ;
},
async handle(handlerInput) {
const { requestEnvelope, serviceClientFactory, responseBuilder } = handlerInput;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'makeReservation') {
const request = handlerInput.requestEnvelope.request;
// const responseBuilder = handlerInput.responseBuilder;
const slotValues = getSlotValues(request.intent.slots);
const location = slotValues.locationType.heardAs;
const tableTalkType = sessionAttributes.tableTalkType;
let say = '';
// delegate to Alexa to collect all the required slots
const currentIntent = request.intent;
if (request.dialogState && request.dialogState !== 'COMPLETED') {
return handlerInput.responseBuilder
.addDelegateDirective(currentIntent)
.getResponse();
}
if (location == 'future location') {
say = `Future location not available at this moment. Please ask to current location.`;
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
} else if(location == 'current location' && tableTalkType == 1){
return responseBuilder
.addDelegateDirective({
name: 'getRestaurantName',
confirmationStatus: 'NONE',
slots: {}
})
.getResponse();
} else if (location == 'current location' && tableTalkType == 2) {
return userCreatedTableListing_Handler.handle(handlerInput);
} else {
say = `invalid input.Please try again`;
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
},
};
const getRestaurantName_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'getRestaurantName' ;
},
handle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'futureOrCurrentLocation') {
const request = handlerInput.requestEnvelope.request;
let slotValues = getSlotValues(request.intent.slots);
// delegate to Alexa to collect all the required slots
const currentIntent = request.intent;
if (request.dialogState && request.dialogState !== 'COMPLETED') {
return handlerInput.responseBuilder
.addDelegateDirective(currentIntent)
.getResponse();
}
// SLOT: restaurantname
if (request.dialogState && request.dialogState == 'COMPLETED' && slotValues.restaurantname.heardAs) {
return new Promise((resolve) => {
getRestaurants(slotValues, handlerInput).then(say => {
resolve(handlerInput.responseBuilder.speak(say).reprompt(say).withShouldEndSession(false).getResponse());
}).catch(error => {
console.log(error);
});
});
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
}
};
const selectRestaurants_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'selectRestaurants' ;
},
handle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'getRestaurantName') {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let slotValues = getSlotValues(request.intent.slots);
let say = '';
let restaurantListArray = sessionAttributes.sessionrestaurantList ? sessionAttributes.sessionrestaurantList : [];
sessionAttributes.previousIntent = '';
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
let restaurantIndex = slotValues.selectRestaurant.heardAs;
let restaurantData = {
name: '',
address: '',
restaurantlatitude: '',
restaurantlongitude: '',
restaurantID:'',
restaurantImageUrl: '',
date: '',
time:'',
people: '',
};
if (restaurantListArray.length >= restaurantIndex) {
let jsonData = JSON.parse(restaurantListArray[restaurantIndex - 1]);
if ((restaurantIndex) && (jsonData[restaurantIndex].name !== '' && typeof jsonData[restaurantIndex].name !== undefined && jsonData[restaurantIndex].name !== null)) {
let restaurantAddress1 = jsonData[restaurantIndex].location.address1 ? jsonData[restaurantIndex].location.address1: '';
let restaurantAddress2 = jsonData[restaurantIndex].location.address2 ? jsonData[restaurantIndex].location.address2: '';
let restaurantAddress3 = jsonData[restaurantIndex].location.address3 ? jsonData[restaurantIndex].location.address3: '';
restaurantData['name'] = jsonData[restaurantIndex].name;
restaurantData['address'] = restaurantAddress1.concat(restaurantAddress2, restaurantAddress3);
restaurantData['restaurantID'] = jsonData[restaurantIndex].id;
restaurantData['restaurantImageUrl'] = jsonData[restaurantIndex].image_url;
restaurantData['restaurantlatitude'] = jsonData[restaurantIndex].coordinates.latitude;
restaurantData['restaurantlongitude'] = jsonData[restaurantIndex].coordinates.longitude;
sessionAttributes.restaurantData = restaurantData;
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
say = `selected Restaurant name is ${jsonData[restaurantIndex].name} in ${restaurantAddress1} ${restaurantAddress2} ${restaurantAddress3}.`;
return responseBuilder
.addDelegateDirective({
name: 'bookingDate',
confirmationStatus: 'NONE',
slots: {}
})
.speak(say)
// .reprompt('try again, Please provide date')
.withShouldEndSession(false)
.getResponse();
} else {
say = 'Restaurant not available. please say again';
return responseBuilder
.speak(say)
.reprompt('Restaurant not available. please say again')
.withShouldEndSession(false)
.getResponse();
}
} else {
say = 'Please select valid input.';
return responseBuilder
.speak(say)
.reprompt('Please select valid input')
.withShouldEndSession(false)
.getResponse();
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
},
};
const errorIntent_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'errorIntent' ;
},
handle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let say = 'Sorry. There is some problem with the response. Please say again';
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
},
};

Categories

Resources