<commit_before>let TelegramBot = require('node-telegram-bot-api');
let token = '<KEY>';
let mysql = require('mysql');
let bot = new TelegramBot(token, {polling: true});
let chat, mainEntry = [], fillings = [], pizzerias = [], bucketList = [], order = [], address, telephone, bill = 0,
    selectedPizzeria;

let con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "<PASSWORD>",
    database: "pizzeria"
});

con.connect(function (err) {
    if (err) throw err;
    console.log("Connected!");

});

bot.onText(/\/выбратьпиццерию/, function (msg) {
    choosePizzeria(msg);
    chat = msg;
});

bot.onText(/\/адресс (.+)/, function (msg, match) {
    address = match[1];
    bot.sendMessage(chat, 'введите телефон')
});

bot.onText(/\/телефон (.+)/, function (msg, match) {
    let resp = match[1];
    telephone = resp;
    saveToBd(msg);
    bot.sendMessage(msg.from.id, 'Ваш заказ принят');
    bucketList.length = 0;
});

bot.on('callback_query', function (msg) {
    if (fillings.includes(msg.data)) {
        saveToBucket(msg.data)
    } else if (pizzerias.includes(msg.data)) {
        mainChoise(msg);
        selectedPizzeria = pizzerias.indexOf(msg.data) + 1;
    } else if (msg.data === 'Да') {
        enterAddress(msg);
    } else if (msg.data === 'Посмотреть заказ') {
        showBucket(msg);
    } else if (msg.data === 'Готовую') {
        choosePizza(msg);
    } else if (msg.data === 'Собрать свою') {
        createPizza(msg);
    }
});

//Work with bd

let getInfo = (sql, col1, col2) => {
    return new Promise(function (resolve, reject) {
        con.query(sql, function (err, result) {
            if (err) throw err;
            let res = JSON.stringify(result);
            let res2 = JSON.parse(res);
            for (let i = 0; i < res2.length; i++) {
                let entry = [];
                if ( pizzerias.includes(res2[i][col1]) || res2[i]['pizzeria_id'] === selectedPizzeria) {
                    if (col2) {
                        entry = [{
                            text: `${res2[i][col1]} ${res2[i][col2]}`,
                            callback_data: `${res2[i][col1]} ${res2[i][col2]}`
                        }];
                        fillings.push(`${res2[i][col1]} ${res2[i][col2]}`);
                    }
                    else {
                        entry = [{text: `${res2[i][col1]}`, callback_data: `${res2[i][col1]}`}];
                        pizzerias.push(`${res2[i][col1]}`);
                    }
                }
                mainEntry.push(entry);
                if (err) {
                    return reject(err);
                }
                resolve(mainEntry);
            }
        });
        mainEntry.length = 0;
    })
};

let mainChoise = (msg) => {
    let text = 'Готовую пиццу или собрать свою?';
    let options = {
        reply_markup: JSON.stringify({
            inline_keyboard: [
                [{text: 'Готовую', callback_data: 'Готовую'}],
                [{text: 'Собрать свою', callback_data: 'Собрать свою'}]
            ],
            parse_mode: 'Markdown',
        })
    };
    chat = msg.hasOwnProperty('chat') ? msg.chat.id : msg.from.id;
    bot.sendMessage(chat, text, options);
};

let choosePizzeria = (msg) => {
    getInfo("SELECT * FROM pizzeria", 'name').then(function () {
        createButtons(mainEntry, msg, 'Выберите пиццу');
    }).then(

    )
};

let createPizza = (msg) => {
    getInfo("SELECT * FROM filter", 'filter', 'cost').then(function () {
        createButtons(mainEntry, msg, 'Выберите начинку');
        saveButton(msg);
    });
};

let choosePizza = (msg) => {
    getInfo("SELECT * FROM pizza", 'pizza_name', 'cost').then(function () {
        createButtons(mainEntry, msg, 'Выберите пиццу');
        saveButton(msg);
    });
};

let enterAddress = (msg) => {
    chat = msg.hasOwnProperty('chat') ? msg.chat.id : msg.from.id;
    bot.sendMessage(chat, 'Введите адресс').then(function () {
        address = msg.data;
    })
};

let showBucket = (msg) => {
    let buttons = [];
    for (let i = 0; i <= bucketList.length - 1; i++) {
        let entry = [{
            text: `${bucketList[i]}`,
            callback_data: `${bucketList[i]}`
        }];
        buttons.push(entry);
    }
    createButtons(buttons, msg, 'Ваша корзина');
    formBill(msg);
    saveButton(msg);
};

let formBill = (msg) => {
    getTotalAmount();
    getOrderInfo();
    bot.sendMessage(msg.from.id, `Ваш заказ ${bill}`)
};

let getTotalAmount = () => {
    for (let i = 0; i <= bucketList.length - 1; i++) {
        bill += parseInt(bucketList[i].split(' ')[1]);
    }
    console.log('bill ' + bill);
};
let getOrderInfo = () => {
    for (let i = 0; i <= bucketList.length - 1; i++) {
        order.push(bucketList[i].split(' ')[0]);
    }
    console.log('order ' + order);
    console.log('bucketList ' + bucketList);

};

// Save to BD

let saveToBd = (msg) => {
    formBill(msg);
    let sql = `INSERT INTO orders (first_name, last_name, list, address, phone, pizzeria_id, amount) VALUES (
        '${msg.from.first_name}',
        '${msg.from.last_name}',
        '${order}', '${address}', '${telephone}' , '${selectedPizzeria}', '${bill}')`;
    console.log(sql);
    con.query(sql, function (err) {
        if (err) throw err;
    });
    console.log(order);
};

let saveButton = (msg) => {
    let text = 'Далее?';
    let options = {
        reply_markup: JSON.stringify({
            inline_keyboard: [<commit_msg>fix bag with ordering pizza<commit_after>let TelegramBot = require('node-telegram-bot-api');
let token = '<KEY>';
let mysql = require('mysql');
let bot = new TelegramBot(token, {polling: true});
let chat, mainEntry = [], fillings = [], pizzerias = [], bucketList = [], order = [], address, telephone, bill = 0,
    selectedPizzeria;

let con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "<PASSWORD>",
    database: "pizzeria"
});

con.connect(function (err) {
    if (err) throw err;
    console.log("Connected!");

});

bot.onText(/\/выбратьпиццерию/, function (msg) {
    choosePizzeria(msg);
    chat = msg;
});

bot.on('callback_query', function (msg) {
    if (fillings.includes(msg.data)) {
        saveToBucket(msg.data)
    } else if (pizzerias.includes(msg.data)) {
        mainChoise(msg);
        selectedPizzeria = pizzerias.indexOf(msg.data) + 1;
    } else if (msg.data === 'Да') {
        enterAddress(msg);
        getTelephone(msg);
    } else if (msg.data === 'Посмотреть заказ') {
        showBucket(msg);
    } else if (msg.data === 'Готовую') {
        choosePizza(msg);
    } else if (msg.data === 'Собрать свою') {
        createPizza(msg);
    }
});

//Work with bd

let getInfo = (sql, col1, col2) => {
    return new Promise(function (resolve, reject) {
        con.query(sql, function (err, result) {
            if (err) throw err;
            let res = JSON.stringify(result);
            let res2 = JSON.parse(res);
            for (let i = 0; i < res2.length; i++) {
                let entry = [];
                if (pizzerias.includes(res2[i][col1]) || res2[i]['pizzeria_id'] === selectedPizzeria) {
                    if (col2) {
                        entry = [{
                            text: `${res2[i][col1]} - ${res2[i][col2]} грн`,
                            callback_data: `${res2[i][col1]} -  ${res2[i][col2]}`
                        }];
                        fillings.push(`${res2[i][col1]} -  ${res2[i][col2]}`);
                    }
                    else {
                        entry = [{text: `${res2[i][col1]}`, callback_data: `${res2[i][col1]}`}];
                        pizzerias.push(`${res2[i][col1]}`);
                    }
                }
                mainEntry.push(entry);
                if (err) {
                    return reject(err);
                }
                resolve(mainEntry);
            }
        });
        mainEntry.length = 0;
    })
};
// choosing

let mainChoise = (msg) => {
    let text = 'Готовую пиццу или собрать свою?';
    let options = {
        reply_markup: JSON.stringify({
            inline_keyboard: [
                [{text: 'Готовую', callback_data: 'Готовую'}],
                [{text: 'Собрать свою', callback_data: 'Собрать свою'}]
            ],
            parse_mode: 'Markdown',
        })
    };
    chat = msg.hasOwnProperty('chat') ? msg.chat.id : msg.from.id;
    bot.sendMessage(chat, text, options);
};


let choosePizzeria = (msg) => {
    getInfo("SELECT * FROM pizzeria", 'name').then(function () {
        createButtons(mainEntry, msg, 'Выберите пиццу');
    })
};

let createPizza = (msg) => {
    getInfo("SELECT * FROM filter", 'filter', 'cost').then(function () {
        createButtons(mainEntry, msg, 'Выберите начинку');
        saveButton(msg);
    });
};

let choosePizza = (msg) => {
    getInfo("SELECT * FROM pizza", 'pizza_name', 'cost').then(function () {
        createButtons(mainEntry, msg, 'Выберите пиццу');
        saveButton(msg);
    });
};

///

let enterAddress = (msg) => {
    chat = msg.hasOwnProperty('chat') ? msg.chat.id : msg.from.id;
    bot.sendMessage(chat, 'Введите адресс').then(function () {
    }).then(ans => {
        bot.on('message', (msg) => {
            address = msg.text;
            console.log(address);
            bot.sendMessage(chat, 'Введите телефон').then(function () {
            }).then(ans => {
                bot.on('message', (msg) => {
                    telephone = msg.text;
                    console.log(telephone);
                    saveToBd(msg);
                    bot.sendMessage(msg.from.id, 'Ваш заказ принят');
                    bucketList.length = 0;
                });
                console.log(msg);
            });
        })
    })
};

let getTelephone = (msg) => {
    bot.sendMessage(chat, 'Введите телефон').then(function () {
    }).then(ans => {
        bot.on('message', (msg) => {
            telephone = msg.text;
            console.log(telephone);
            saveToBd(msg);
            bot.sendMessage(msg.from.id, 'Ваш заказ принят');
            bucketList.length = 0;
        });

    });
};

let showBucket = (msg) => {
    let buttons = [];
    for (let i = 0; i <= bucketList.length - 1; i++) {
        let entry = [{
            text: `${bucketList[i]}`,
            callback_data: `${bucketList[i]}`
        }];
        buttons.push(entry);
    }
    createButtons(buttons, msg, 'Ваша корзина');
    formBill(msg);
    saveButton(msg);
};

// work with bill

let formBill = (msg) => {
    getTotalAmount();
    getOrderInfo();
    bot.sendMessage(msg.from.id, `Ваш заказ ${bill}`)
};

let getTotalAmount = () => {
    for (let i = 0; i <= bucketList.length - 1; i++) {
        bill += parseInt(bucketList[i].split(' - ')[1]);
    }
    console.log('bill ' + bill);
};
let getOrderInfo = () => {
    for (let i = 0; i <= bucketList.length - 1; i++) {
        order.push(bucketList[i].split(' - ')[0]);
    }
    console.log('order ' + order);
    console.log('bucketList ' + bucketList);

};

// Save to BD

let saveToBd = (msg) => {
    formBill(msg);
    let sql = `INSERT INTO orders (first_name, last_name, list, address, phone, pizzeria_id, amount) VALUES (
        '${msg.from.first_name}',
        '${msg.from.last_name}',
        '${order}', '${address}', '${telephone}' , '${selectedPizzeria}', '${bill}')`;
    console.log(sql);
    con.query(sql, function (err) {
        if (err) throw err;
    });
};

let saveButton = (msg) => {
    let text = 'Далее?';
    let options = {
        reply_markup: JSON.stringify({
            inline_keyboard: [
{'fraction_non_alphanumeric': 0.17760950004302556, 'fraction_numerical': 0.00697014026331641, 'mean_word_length': 2.0689199894375494, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 38, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '467020', 'n_tokens_mistral': 3931, 'n_tokens_neox': 3922, 'n_words': 771}