Добавьте файлы проекта.
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using Newtonsoft.Json;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Calculators
|
||||
{
|
||||
public class SelectCalcCcalResultCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectCalcCcalResult-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
int age = 0;
|
||||
int genderCoef = 0;
|
||||
double kkalResult = 0;
|
||||
double kkalResultLow = 0;
|
||||
double kkalResultHigh = 0;
|
||||
double colorPercent = 0;
|
||||
double dayCoef = 0;
|
||||
double curDayKkal = 0;
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int curColor = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
Dictionary<int, string> days = new Dictionary<int, string>(7);
|
||||
days.Add(1, "Понедельник");
|
||||
days.Add(2, "Вторник");
|
||||
days.Add(3, "Среда");
|
||||
days.Add(4, "Четверг");
|
||||
days.Add(5, "Пятница");
|
||||
days.Add(6, "Суббота");
|
||||
days.Add(7, "Воскресенье");
|
||||
|
||||
int curDay = (int)DateTime.Now.DayOfWeek;
|
||||
if (curDay == 0) curDay = 7;
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(user.sportDays);
|
||||
|
||||
string cons = "✅Прошёл консультацию";
|
||||
|
||||
if ((DateTime.Now.Month >= user.birthday.Month) && (DateTime.Now.Day >= user.birthday.Day))
|
||||
age = DateTime.Now.Year - user.birthday.Year;
|
||||
else
|
||||
age = DateTime.Now.Year - user.birthday.Year - 1;
|
||||
|
||||
if (user.weight == 0 || user.height == 0)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Message = "Для подсчёта калорий не хватает данных о росте/весе.\n" +
|
||||
"Нажмите \"📝Редактировать данные\" и заполните показатели.";
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (user.gender == 1)
|
||||
{
|
||||
genderCoef = 5;
|
||||
//cons = "✅Прошёл консультацию";
|
||||
}
|
||||
else
|
||||
{
|
||||
genderCoef = -161;
|
||||
//cons = "✅Прошла консультацию";
|
||||
}
|
||||
switch (user.track)
|
||||
{
|
||||
case 1: //не изменяя веса
|
||||
colorPercent = 1;
|
||||
break;
|
||||
case 2:
|
||||
colorPercent = 0.75; //1 - 15%
|
||||
break;
|
||||
case 3:
|
||||
colorPercent = 1.2; //1 - 15%
|
||||
break;
|
||||
default:
|
||||
colorPercent = 1;
|
||||
break;
|
||||
}
|
||||
@params.Message = "Ваш результат:\n\n";
|
||||
|
||||
for (int i = 1; i <= 7; i++)
|
||||
{
|
||||
switch (i)
|
||||
{
|
||||
case 2:
|
||||
dayCoef = 0.8;
|
||||
break;
|
||||
|
||||
case 3:
|
||||
dayCoef = 1.2;
|
||||
break;
|
||||
|
||||
case 5:
|
||||
dayCoef = 0.9;
|
||||
break;
|
||||
|
||||
case 6:
|
||||
dayCoef = 1.1;
|
||||
break;
|
||||
|
||||
default:
|
||||
dayCoef = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
kkalResult = Math.Round((((10 * user.weight) + (6.25 * user.height) - (5 * age) + genderCoef) * user.activityCoef) * colorPercent * dayCoef);
|
||||
kkalResultHigh = Math.Round(kkalResult * 1.2);
|
||||
kkalResultLow = Math.Round(kkalResult * 0.9);
|
||||
|
||||
if (i == curDay)
|
||||
{
|
||||
@params.Message += $"⭐ {days[i]}: {kkalResultLow}-{kkalResultHigh} ккал\n";
|
||||
curDayKkal = kkalResult;
|
||||
}
|
||||
else
|
||||
@params.Message += $"{days[i]}: {kkalResultLow}-{kkalResultHigh} ккал\n";
|
||||
}
|
||||
//kkalResult = Math.Round((((10 * weight) + (6.25 * height) - (5 * age) + genderCoef) * activityCoef) * colorPercent);
|
||||
|
||||
keyboardBuilder.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
user.kkal = Convert.ToInt32(curDayKkal);
|
||||
db.SaveChanges();
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectCalcCcalResultCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Calculators
|
||||
{
|
||||
public class SelectCalculatorCcalCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectCalculatorCcal\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
@params.Message = "🚦Выберите на клавиатуре комфортный для Вас режим сохранения/потери веса.\n";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("🟥Не изменяя вес", "selectCalcCcalResult-1", KeyboardButtonColor.Primary) //К
|
||||
.AddLine()
|
||||
.AddButton("🟨Снижение веса", "selectCalcCcalResult-2", KeyboardButtonColor.Primary) //Ж
|
||||
.AddLine()
|
||||
.AddButton("🟩Быстрое снижение веса", "selectCalcCcalResult-3", KeyboardButtonColor.Primary) //З
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectCalculatorCcalCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Calculators
|
||||
{
|
||||
public class SelectIdealWeightCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectIdealWeight\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
double indexMT = 23;
|
||||
double indexMTLow = 18.5;
|
||||
double indexMTHigh = 25;
|
||||
string IMT = "";
|
||||
double idealWeight = 0;
|
||||
double normWeightLow = 0;
|
||||
double normWeightHigh = 0;
|
||||
int age = 0;
|
||||
try
|
||||
{
|
||||
Data.Users user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
|
||||
age = DateTime.Today.Year - user.birthday.Year;
|
||||
|
||||
idealWeight = Math.Round(indexMT * user.height / 100.0 * user.height / 100.0, 1);
|
||||
normWeightLow = Math.Round(indexMTLow * user.height / 100.0 * user.height / 100.0, 1);
|
||||
normWeightHigh = Math.Round(indexMTHigh * user.height / 100.0 * user.height / 100.0, 1);
|
||||
//indexMT = Math.Round(weight / (double)(height / 100.0 * height / 100.0), 1);
|
||||
@params.Message = "⭐Ваш идеальный вес: " + idealWeight + " кг.\n" +
|
||||
"✅Диапазон нормального веса: " + normWeightLow + " - " + normWeightHigh + " кг.\n\n" +
|
||||
"Идеальный для здоровья вес рассчитывается, исходя из ИМТ равного 23.";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectIdealWeightCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
163
SvetoforVKBot/Models/Commands/LK/Cart/SelectAddToCartCommand.cs
Normal file
163
SvetoforVKBot/Models/Commands/LK/Cart/SelectAddToCartCommand.cs
Normal file
@@ -0,0 +1,163 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Model.RequestParams;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using SvetoforVKBot.Models.Commands.LK.Menu;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Cart
|
||||
{
|
||||
public class SelectAddToCartCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectAddToCart-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
string msg = "";
|
||||
double sum = 0;
|
||||
string backPL = "startPL";
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
List<ProductsDostavka> products = new List<ProductsDostavka>();
|
||||
List<ProductsDostavka> souses = new List<ProductsDostavka>();
|
||||
ShowPersonalMenuCarusel showProductCaruselMain = new ShowPersonalMenuCarusel();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
int kkals = 0;
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int curCategory = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
int curProduct = Convert.ToInt32(regex.Replace(payload[2], ""));
|
||||
int curDayKkal = Convert.ToInt32(regex.Replace(payload[3], ""));
|
||||
int curDay = (int)DateTime.Now.DayOfWeek;
|
||||
if (curDay == 0) curDay = 7;
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
|
||||
|
||||
var prodDb = db.ProductsDostavkas.Where(p =>
|
||||
p.id == curProduct &&
|
||||
JsonConvert.DeserializeObject<List<int>>(p.weekDays).Exists(e => e == curDay));
|
||||
products = prodDb.ToList().ConvertAll<ProductsDostavka>(el => new ProductsDostavka()
|
||||
{
|
||||
id = el.id,
|
||||
idIiko = el.idIiko,
|
||||
article = el.article,
|
||||
categoryId = el.categoryId,
|
||||
name = el.name,
|
||||
fullName = el.fullName,
|
||||
description = el.description,
|
||||
price = Convert.ToDouble( el.price),
|
||||
photo = el.photo,
|
||||
additions = JsonConvert.DeserializeObject<List<string>>(el.additions),
|
||||
recommends = JsonConvert.DeserializeObject<List<string>>(el.recommends),
|
||||
kkal = el.kkal,
|
||||
});
|
||||
|
||||
var orderPizza = new Order();
|
||||
var orderSous = new Order();
|
||||
if (cartObject.orders.Exists(o => o.id.Equals(curCategory + "-" + curProduct)))
|
||||
cartObject.orders.Find(o => o.id.Equals(curCategory + "-" + curProduct)).number++;
|
||||
else
|
||||
{
|
||||
var order = new Order()
|
||||
{
|
||||
id = curCategory + "-" + curProduct,
|
||||
idIiko = products[0].idIiko,
|
||||
fullname = products[0].fullName,
|
||||
name = products[0].name,
|
||||
price = products[0].price,
|
||||
number = 1,
|
||||
article = products[0].article,
|
||||
kkal = products[0].kkal,
|
||||
};
|
||||
cartObject.orders.Add(order);
|
||||
|
||||
}
|
||||
|
||||
user.cart = JsonConvert.SerializeObject(cartObject);
|
||||
db.SaveChanges();
|
||||
|
||||
foreach (var o in cartObject.orders)
|
||||
{
|
||||
sum += o.price * o.number;
|
||||
kkals += o.kkal * o.number;
|
||||
}
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton($"Завтрак (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-1-" + curDayKkal, KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton($"Обед (до {Math.Round(curDayKkal * 1.2 * 0.4)} ккал)", "selectPersonalMenu-2-" + curDayKkal, KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton($"Перекус (до {Math.Round(curDayKkal * 1.2 * 0.1)} ккал)", "selectPersonalMenu-3-" + curDayKkal, KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton($"Ужин (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-4-" + curDayKkal, KeyboardButtonColor.Primary)
|
||||
.AddLine();
|
||||
|
||||
if (cartObject.orders.Count > 0)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default)
|
||||
.AddButton("Корзина: " + sum + " р", "selectCart-0", KeyboardButtonColor.Negative);
|
||||
}
|
||||
else
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
|
||||
}
|
||||
if (update.@object.client_info.carousel == true)
|
||||
{
|
||||
msg = "✅ " + products.Find(p => p.id == curProduct).fullName + " добавлен в корзину.";
|
||||
|
||||
}
|
||||
|
||||
//@params.Template = templateBuilder.Build();
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.Message = msg;
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
//else
|
||||
//{
|
||||
// switch (curCategory)
|
||||
// {
|
||||
// case 1:
|
||||
// if (update.@object.client_info.carousel == true)
|
||||
// showProductCaruselDouble.Execute(update, client, Con, curCategory, curProduct);
|
||||
// else
|
||||
// showProductDouble.Execute(update, client, Con, curCategory, curProduct, 2);
|
||||
// break;
|
||||
|
||||
// default:
|
||||
// if (update.@object.client_info.carousel == true)
|
||||
// showProductCaruselMain.Execute(update, client, Con, curCategory, curProduct, 1);
|
||||
// else
|
||||
// showProductMain.Execute(update, client, Con, curCategory, curProduct, 0, 2);
|
||||
// break;
|
||||
// }
|
||||
//}
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectAddToCartCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
49
SvetoforVKBot/Models/Commands/LK/Cart/SelectCartCommand.cs
Normal file
49
SvetoforVKBot/Models/Commands/LK/Cart/SelectCartCommand.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Text.RegularExpressions;
|
||||
using SvetoforVKBot.Models.Commands.LK.Cart;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Model;
|
||||
using VkNet.Model.RequestParams;
|
||||
using Newtonsoft.Json;
|
||||
using VkNet.Model.Keyboard;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Cart
|
||||
{
|
||||
public class SelectCartCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectCart-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db){ }
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
List<ProductsDostavka> products = new List<ProductsDostavka>();
|
||||
List<Button> buttons = new List<Button>();
|
||||
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int curCart = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
ShowCart showCart = new ShowCart();
|
||||
showCart.Execute(update, client, db, curCart);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectCartCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Commands.LK.Menu.Products;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Model.RequestParams;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using Newtonsoft.Json;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Cart
|
||||
{
|
||||
public class SelectConfirmClearCartCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectConfirmClearCart\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
var jsCart = JsonConvert.DeserializeObject<CartObject>(user.cart);
|
||||
jsCart.orders.RemoveAll(o => o.id.StartsWith("0-") == false);
|
||||
user.cart = JsonConvert.SerializeObject(jsCart);
|
||||
db.SaveChanges();
|
||||
|
||||
msg = "✅Корзина очищена.\nВозвращаю в Личный кабинет.\n";
|
||||
|
||||
ShowLKCommand showLK = new ShowLKCommand();
|
||||
showLK.Execute(update, client, db);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectConfirmClearCartCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using System.Text.RegularExpressions;
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Commands.LK.Cart;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Model.RequestParams;
|
||||
using SvetoforVKBot.Models.Commands.LK.Menu.Products;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Cart
|
||||
{
|
||||
public class SelectEditCartCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectEditCart-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
string msg = "";
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int action = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
int curCart = Convert.ToInt32(regex.Replace(payload[2], ""));
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
|
||||
|
||||
|
||||
if (cartObject.orders[curCart].id.StartsWith("0-")) return;
|
||||
|
||||
switch (action)
|
||||
{
|
||||
case 1: // -
|
||||
if (cartObject.orders[curCart].number == 1)
|
||||
cartObject.orders.RemoveAt(curCart);
|
||||
else
|
||||
cartObject.orders[curCart].number--;
|
||||
break;
|
||||
case 2: // +
|
||||
cartObject.orders[curCart].number++;
|
||||
break;
|
||||
};
|
||||
|
||||
if (action > 2)
|
||||
{
|
||||
int count = action - 3;
|
||||
if (count == 0)
|
||||
cartObject.orders.RemoveAt(curCart);
|
||||
else
|
||||
cartObject.orders[curCart].number = count;
|
||||
}
|
||||
|
||||
user.cart = JsonConvert.SerializeObject(cartObject);
|
||||
db.SaveChanges();
|
||||
|
||||
if (cartObject.orders.Count > 0)
|
||||
{
|
||||
if (curCart >= cartObject.orders.Count)
|
||||
curCart = cartObject.orders.Count - 1;
|
||||
ShowCart showCart = new ShowCart();
|
||||
showCart.Execute(update, client, db, curCart);
|
||||
}
|
||||
else
|
||||
{
|
||||
msg = "Корзина оказалась пустой. \n" +
|
||||
"\n" +
|
||||
"Возвращаю в Личный кабинет";
|
||||
ShowLKCommand showLK = new ShowLKCommand();
|
||||
showLK.Execute(update, client, db);
|
||||
}
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectEditCartCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
192
SvetoforVKBot/Models/Commands/LK/Cart/ShowCart.cs
Normal file
192
SvetoforVKBot/Models/Commands/LK/Cart/ShowCart.cs
Normal file
@@ -0,0 +1,192 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Cart
|
||||
{
|
||||
public class ShowCart
|
||||
{
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCart) //curCart - порядковый номер в массиве корзины
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
int cartCount = 0;
|
||||
var chatId = update.@object.message.from_id;
|
||||
string msg = "";
|
||||
//string voronka = "";
|
||||
List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
|
||||
List<ProductsDostavka> products = new List<ProductsDostavka>();
|
||||
int i = 0;
|
||||
int j = 0;
|
||||
int prevCart = 0, nextCart = 0;
|
||||
double sum = 0;
|
||||
double fullSum = 0;
|
||||
string label = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
int kkals = 0;
|
||||
try
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
|
||||
|
||||
|
||||
//SqlCommand getCart = new SqlCommand("SELECT cart, voronka FROM Users WHERE chatId = @chatId;", Con);
|
||||
//getCart.Parameters.AddWithValue("@chatId", chatId);
|
||||
//SqlDataReader rgetCart = getCart.ExecuteReader();
|
||||
//rgetCart.Read();
|
||||
//var cartObject = JsonConvert.DeserializeObject<CartObject>(rgetCart["cart"].ToString());
|
||||
//voronka = rgetCart["voronka"].ToString();
|
||||
//rgetCart.Close();
|
||||
|
||||
//cartObject.orders.RemoveAll(o => o.article.StartsWith("00-"));
|
||||
cartObject.dostavkaCost = 100;
|
||||
|
||||
//if (cartObject.orders.Count == 0)
|
||||
//{
|
||||
// msg = "Корзина пуста.\n📋Возвращаю в основное меню";
|
||||
// ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
|
||||
// showMenuDostavka.Execute(update, client, Con, msg, 1, 0);
|
||||
// return;
|
||||
//}
|
||||
|
||||
if (curCart >= cartObject.orders.Count)
|
||||
{
|
||||
curCart = cartObject.orders.Count - 1;
|
||||
prevCart = curCart - 1;
|
||||
nextCart = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
prevCart = curCart - 1;
|
||||
nextCart = curCart + 1;
|
||||
}
|
||||
if ((curCart + 1) == cartObject.orders.Count)
|
||||
{
|
||||
prevCart = curCart - 1;
|
||||
nextCart = 0;
|
||||
}
|
||||
if (curCart == 0)
|
||||
{
|
||||
prevCart = cartObject.orders.Count - 1;
|
||||
nextCart = curCart + 1;
|
||||
}
|
||||
string promo = "";
|
||||
msg = "Ваша корзина: \n";
|
||||
|
||||
double sumCheck = 0;
|
||||
foreach (var o in cartObject.orders)
|
||||
{
|
||||
sumCheck += o.price * o.number;
|
||||
}
|
||||
|
||||
for (i = 0; i < cartObject.orders.Count; i++)
|
||||
{
|
||||
cartCount++;
|
||||
switch (cartObject.orders[i].id)
|
||||
{
|
||||
|
||||
default:
|
||||
msg += (i + 1).ToString() + ". " +
|
||||
cartObject.orders[i].fullname + " - " + cartObject.orders[i].kkal + " ккал. " +
|
||||
cartObject.orders[i].number + " шт. " +
|
||||
(cartObject.orders[i].price * cartObject.orders[i].number).ToString() + " ₽ \n";
|
||||
sum += cartObject.orders[i].price * cartObject.orders[i].number;
|
||||
kkals += cartObject.orders[i].kkal * cartObject.orders[i].number;
|
||||
break;
|
||||
}
|
||||
//msg += (i + 1).ToString() + ". " +
|
||||
// cartObject.orders[i].fullname + " - " +
|
||||
// cartObject.orders[i].number + " шт. " +
|
||||
// (cartObject.orders[i].price * cartObject.orders[i].number).ToString() + " ₽ \n";
|
||||
|
||||
|
||||
/*cartCount++;
|
||||
for (j = 0; j < cartObject.orders.Count; j++)
|
||||
{
|
||||
msg += " " + cartCount.ToString() + "." + (j + 1).ToString() + " Доп - " +
|
||||
cartObject.orders[i].addition[j].fullname + " - " +
|
||||
cartObject.orders[i].addition[j].number + " шт. " +
|
||||
(cartObject.orders[i].addition[j].price * cartObject.orders[i].addition[j].number).ToString() + " ₽ \n";
|
||||
}
|
||||
*/
|
||||
|
||||
}
|
||||
|
||||
|
||||
fullSum = sum;
|
||||
|
||||
user.cart = JsonConvert.SerializeObject(cartObject);
|
||||
db.SaveChanges();
|
||||
|
||||
//SqlCommand updCart = new SqlCommand("UPDATE Users SET cart = @cart WHERE chatId = @chatId;", Con);
|
||||
//updCart.Parameters.AddWithValue("@chatId", chatId);
|
||||
//updCart.Parameters.AddWithValue("@cart", JsonConvert.SerializeObject(cartObject));
|
||||
//updCart.ExecuteNonQuery();
|
||||
|
||||
msg += "\n" +
|
||||
"Итого: " + fullSum + " ₽ | " + kkals + " ккал.";
|
||||
|
||||
label = cartObject.orders[curCart].name + " " +
|
||||
cartObject.orders[curCart].price + " ₽ * " +
|
||||
cartObject.orders[curCart].number + " = " +
|
||||
(cartObject.orders[curCart].price * cartObject.orders[curCart].number).ToString() + " ₽";
|
||||
|
||||
if (label.Length > 40)
|
||||
label = cartObject.orders[curCart].name + " " +
|
||||
(cartObject.orders[curCart].price * cartObject.orders[curCart].number).ToString() + " ₽";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton(label, "selectCart-" + curCart, KeyboardButtonColor.Default)
|
||||
.AddLine()
|
||||
.AddButton("-", "selectEditCart-1-" + curCart, KeyboardButtonColor.Default)
|
||||
.AddButton(cartObject.orders[curCart].number + " шт", "selectCartCount-" + curCart, KeyboardButtonColor.Default)
|
||||
.AddButton("+", "selectEditCart-2-" + curCart, KeyboardButtonColor.Default)
|
||||
.AddButton("🗑Очистить", "selectConfirmClearCart", KeyboardButtonColor.Default)
|
||||
.AddLine()
|
||||
.AddButton("<<", "selectCart-" + prevCart, KeyboardButtonColor.Primary)
|
||||
.AddButton((curCart + 1).ToString() + "/" + cartObject.orders.Count, "selectCart-" + curCart, KeyboardButtonColor.Default)
|
||||
.AddButton(">>", "selectCart-" + nextCart, KeyboardButtonColor.Primary);
|
||||
|
||||
keyboardBuilder
|
||||
.AddLine()
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
|
||||
@params.Message = msg;
|
||||
@params.UserId = chatId;
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.DontParseLinks = true;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в ShowCart: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
private int GetRandomId()
|
||||
{
|
||||
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using SvetoforVKBot.App_Start;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Consultation
|
||||
{
|
||||
public class GetConsultationCommand
|
||||
{
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
MessagesSendParams @params2 = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
if (update.@object.message.text.Length > 0)
|
||||
{
|
||||
var ids = new long[] { chatId };
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.question = update.@object.message.text.Trim();
|
||||
user.tag = "Личный кабинет";
|
||||
db.SaveChanges();
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.Message = "✅Вопрос принят. Менеджер ответит Вам в ближайшее время!\n";
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
@params2.Message = "❓Вопрос. \nСсылка на диалог: " + ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).GroupDialogsLink + chatId;
|
||||
|
||||
List<long> listFrwMsg = new List<long>() { update.@object.message.id };
|
||||
@params2.PeerId = 2000000002;
|
||||
//@params2.UserId = 59111081;
|
||||
@params2.ForwardMessages = listFrwMsg;
|
||||
@params2.RandomId = GetRandomId();
|
||||
client.Messages.Send(@params2);
|
||||
}
|
||||
else
|
||||
{
|
||||
@params.Message = "Не распознал сообщение 😕 Попробуйте, пожалуйста, ещё раз";
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в GetReportCommentCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
public int GetRandomId()
|
||||
{
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.RegularExpressions;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Attachments;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Consultation
|
||||
{
|
||||
public class SelectConsultationCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectConsultation\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.tag = "Консультация - Вопрос";
|
||||
db.SaveChanges();
|
||||
|
||||
@params.Message = //"Вы можете записаться на онлайн-консультацию к специалисту.\n" +
|
||||
"Напишите свой вопрос сюда одним сообщением. " + //Это будет служить Вашей заявкой.\n" +
|
||||
"Менеджер свяжется с Вами для ответа и уточнения информации."; //"Мы оповестим Вас о ближайшей консультации, к которой Вы сможете присоединиться.\n\n";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectExpertLKCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Consultation
|
||||
{
|
||||
public class SelectLiveConsultationCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectLiveConsultation\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
@params.Message = "-----Информация о приёме на консультации.-----\n\n" +
|
||||
"Вы можете оформить заявку на запись. Для этого нажмите кнопку \"Оставить заявку\".\n" +
|
||||
"Ваши данные будут отправлены менеджеру, с Вами свяжутся для уточнения даты и времени консультации.";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Оставить заявку", "selectSubmitConsultation", KeyboardButtonColor.Positive) //К
|
||||
.AddLine()
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в selectLiveConsultation: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Threading;
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Attachments;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Consultation
|
||||
{
|
||||
public class SelectMoreAboutSpecCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectMoreAboutSpec\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
//{"id": 457239276, "owner_id": -194717824, "access_key": "3f83861845f644622f"}
|
||||
|
||||
List<MediaAttachment> listPhoto = new List<MediaAttachment>()
|
||||
{
|
||||
new VkNet.Model.Attachments.Photo() { Id = 457239276, OwnerId = -194717824, AccessKey = "3f83861845f644622f"}
|
||||
};
|
||||
|
||||
@params.Message =
|
||||
"📌Кадочникова Наталья Ивановна\n" +
|
||||
"Кандидат биологических наук, доцент кафедры медико-биологических дисциплин факультета физической культуры и спорта ВятГУ." +
|
||||
"\n\n" +
|
||||
"⭐Стаж работы более 20 лет, автор более 100 научных публикаций в области физиологии." +
|
||||
"\n\n" +
|
||||
"⭐Участник Международных и Всероссийских научно-практических конференций по спортивной науке." +
|
||||
"\n\n" +
|
||||
"🎓Прошла обучение по программам:" +
|
||||
"\n" +
|
||||
"✅По использованию анализатора состава тела АВС-01 «Медасс» в практике спортивной медицины " +
|
||||
"и реабилитологии (г. Москва АО НТЦ «Медасс», март 2016)" +
|
||||
"\n\n" +
|
||||
"✅«Оптимальное питание» (г. Москва, ФНМО РУДН, март 2019)" +
|
||||
"\n\n" +
|
||||
"✅«Питание в фитнесе» (г. Москва, ФНМО РУДН, апрель 2019)" +
|
||||
"\n\n" +
|
||||
"✅ «Современное диетическое и персонализированное питание» (г. Москва, МГУТУ им. К.Г. Разумовского, март 2021)." +
|
||||
"\n\n";
|
||||
|
||||
|
||||
@params.Message += "📍Консультации проводятся по субботам по адресу: г. Киров, ул. Молодой Гвардии, д.13.\n" +
|
||||
"☎Тел. 70-81-22.\n" +
|
||||
"Стоимость и условия по телефону.";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Оставить заявку", "selectSubmitConsultation", KeyboardButtonColor.Positive) //К
|
||||
.AddLine()
|
||||
.AddButton("Назад", "selectTrack-4", KeyboardButtonColor.Default);
|
||||
@params.Attachments = listPhoto;
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectMoreAboutSpecCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Threading;
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Attachments;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Linq;
|
||||
using System.Configuration;
|
||||
using SvetoforVKBot.App_Start;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Consultation
|
||||
{
|
||||
public class SelectSubmitConsultationCommand : Command
|
||||
{
|
||||
public const int MODER = 59111081;
|
||||
public override string Name => "{\"button\":\"selectSubmitConsultation\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
MessagesSendParams @params2 = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
string msg = "";
|
||||
DateTime dt = DateTime.Now;
|
||||
string msgManager = "";
|
||||
List<int> ids = new List<int>();
|
||||
try
|
||||
{
|
||||
if (db.PersonalConsultations.Where(c => c.chatId == chatId).Count() > 0)
|
||||
{
|
||||
@params.Message = "Ваша заявка уже на рассмотрении. Чтобы вернуться назад, нажмите кнопку \"Личный кабинет\".";
|
||||
keyboardBuilder
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Positive);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
return;
|
||||
}
|
||||
|
||||
//https://vk.com/doc59111081_594730049
|
||||
List<MediaAttachment> listDoc = new List<MediaAttachment>()
|
||||
{
|
||||
new Document() { Id = 594730049, OwnerId = 59111081 }
|
||||
};
|
||||
|
||||
|
||||
db.PersonalConsultations.Add(new Data.PersonalConsultation()
|
||||
{
|
||||
chatId = chatId,
|
||||
datetime = dt,
|
||||
state = 1,
|
||||
});
|
||||
db.SaveChanges();
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
|
||||
|
||||
@params.Message = "📌Ваша заявка:\n\n";
|
||||
|
||||
msg = "ФИО: " + user.fio +
|
||||
"\n" +
|
||||
"Телефон: " + jsPhones[0] +
|
||||
"\n" +
|
||||
"Дата рождения: " + user.birthday.ToShortDateString() +
|
||||
"\n\n" +
|
||||
"Дата заявки: " + dt.ToString("dd.MM.yyyy HH:mm");
|
||||
|
||||
@params.Message += msg +
|
||||
"\n\n" +
|
||||
"Заявка отправлена! Менеджер свяжется с Вами в ближайшее время. Чтобы вернуться назад, нажмите кнопку \"Личный кабинет\".\n\n" +
|
||||
"Квитанция на оплату 👇🏻";
|
||||
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Positive);
|
||||
@params.Attachments = listDoc;
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
Thread.Sleep(1000);
|
||||
|
||||
@params2.Message = "✅Новая заявка на консультацию:\n\n" +
|
||||
"ФИО: " + user.fio +
|
||||
"\n" +
|
||||
"Телефон: " + jsPhones[0] +
|
||||
"\n" +
|
||||
"Дата рождения: " + user.birthday.ToShortDateString() +
|
||||
"\n" +
|
||||
"Рост: " + user.height +
|
||||
"\n" +
|
||||
"Вес: " + user.weight +
|
||||
"\n\n" +
|
||||
"Дата заявки: " + dt.ToString("dd.MM.yyyy HH:mm") +
|
||||
"\n" +
|
||||
"Диалог с пользователем: " + ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).GroupDialogsLink + chatId;
|
||||
//https://vk.com/gim194717824?sel=
|
||||
@params2.PeerId = 2000000002;
|
||||
@params2.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params2);
|
||||
|
||||
Thread.Sleep(1500);
|
||||
|
||||
ids = db.PersonalConsultations.Where(c => c.state == 2).ToList().ConvertAll<int>(el => el.chatId);
|
||||
|
||||
string strIds = "Участники, записавшиеся на консультацию:\n";
|
||||
|
||||
if (ids.Count >= 6)
|
||||
{
|
||||
foreach (var id in ids)
|
||||
{
|
||||
strIds += ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).GroupDialogsLink + id + " \n";
|
||||
|
||||
//Проверить как записывает
|
||||
var con = db.PersonalConsultations.Where(el => el.chatId == chatId);
|
||||
db.Entry(con).Property("state").CurrentValue = 3;
|
||||
db.SaveChanges();
|
||||
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
|
||||
@params2.Message = "🔔 Набралась группа на консультацию! Оповестите их о подробностях." +
|
||||
"\n\n" +
|
||||
strIds;
|
||||
@params2.PeerId = 2000000002;
|
||||
@params2.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params2);
|
||||
}
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectSubmitConsultationCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.EditData
|
||||
{
|
||||
public class GetEditFIOCommand
|
||||
{
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
|
||||
try
|
||||
{
|
||||
if (update.@object.message.text.Length > 0 && update.@object.message.text.Length <= 50)
|
||||
{
|
||||
var ids = new long[] { chatId };
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.fio = update.@object.message.text.Trim();
|
||||
user.tag = "Личный кабинет - Данные";
|
||||
db.SaveChanges();
|
||||
|
||||
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
|
||||
selectEditData.Execute(update, client, db);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
@params.Message = "Данные введены некорректно 😕 Напишите, пожалуйста, текст длиной до 50 символов.";
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в GetEditFIOCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
public int GetRandomId()
|
||||
{
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
111
SvetoforVKBot/Models/Commands/LK/EditData/GetEditPhoneCommand.cs
Normal file
111
SvetoforVKBot/Models/Commands/LK/EditData/GetEditPhoneCommand.cs
Normal file
@@ -0,0 +1,111 @@
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using VkNet;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Security.Cryptography;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.Attachments;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Threading;
|
||||
using System.Text.RegularExpressions;
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Commands.LK;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.EditData
|
||||
{
|
||||
public class GetEditPhoneCommand
|
||||
{
|
||||
public bool Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
MessagesSendParams @params2 = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
int i = 0;
|
||||
var row = new List<MessageKeyboardButton>();
|
||||
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
string phone = regex.Replace(update.@object.message.text, "");
|
||||
|
||||
if (phone.Length == 11)
|
||||
if (phone.StartsWith("8") || phone.StartsWith("7"))
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
|
||||
|
||||
if (jsPhones.Contains(phone))
|
||||
{
|
||||
jsPhones[jsPhones.FindIndex(p => p.Equals(phone))] = jsPhones[0];
|
||||
jsPhones[0] = phone;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (jsPhones.Count > 0)
|
||||
{
|
||||
for (i = jsPhones.Count; i > 0; i--)
|
||||
{
|
||||
if (i != 4)
|
||||
{
|
||||
if (i == jsPhones.Count)
|
||||
jsPhones.Add("");
|
||||
|
||||
jsPhones[i] = jsPhones[i - 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
jsPhones.Add("");
|
||||
|
||||
jsPhones[0] = phone;
|
||||
}
|
||||
|
||||
user.tag = "Личный кабинет - Данные";
|
||||
user.phone = JsonConvert.SerializeObject(jsPhones);
|
||||
|
||||
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
|
||||
selectEditData.Execute(update, client, db);
|
||||
|
||||
}
|
||||
else
|
||||
@params.Message = "Контактный телефон в формате 89123456789 (11 цифр, без плюса и через \"8\" или \"7\" обязательно).";
|
||||
else
|
||||
@params.Message = "Контактный телефон в формате 89123456789 (11 цифр, без плюса и через \"8\" или \"7\" обязательно).";
|
||||
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в GetEditPhoneCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
public int GetRandomId()
|
||||
{
|
||||
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using Newtonsoft.Json;
|
||||
using VkNet.Enums.Filters;
|
||||
using System.Text.RegularExpressions;
|
||||
using SvetoforVKBot.Models.Commands.LK;
|
||||
using System.Collections.Generic;
|
||||
using SvetoforVKBot.Models.Commands.LK.SportsLK;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.EditData
|
||||
{
|
||||
public class SelectEditNotifyCount : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectEditNotifyCount-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
double activityCoef = 0;
|
||||
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int notifyCount = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.notifyCount = notifyCount;
|
||||
user.tag = "Личный кабинет - Данные";
|
||||
db.SaveChanges();
|
||||
|
||||
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
|
||||
selectEditData.Execute(update, client, db);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectEditNotifyCountCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Commands.Registration;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Attachments;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.EditData
|
||||
{
|
||||
public class SelectUpdateSportDaysCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectUpdateSportDays\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
MessagesSendParams @params2 = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
string msg = "";
|
||||
DateTime dt = DateTime.Now;
|
||||
string msgManager = "";
|
||||
List<int> ids = new List<int>();
|
||||
try
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.sportDays = "[]";
|
||||
db.SaveChanges();
|
||||
|
||||
ShowSportDays showSportDays = new ShowSportDays();
|
||||
showSportDays.Execute(update, client, db);
|
||||
return;
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectUpdateSportDaysCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
70
SvetoforVKBot/Models/Commands/LK/GetHeightCommand.cs
Normal file
70
SvetoforVKBot/Models/Commands/LK/GetHeightCommand.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Text.RegularExpressions;
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Model.RequestParams;
|
||||
using VkNet.Model.Keyboard;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Security.Cryptography;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using SvetoforVKBot.Models.Dop;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK
|
||||
{
|
||||
public class GetHeightCommand
|
||||
{
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
int i = 0;
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
if (int.TryParse(update.@object.message.text.Trim(), out int height))
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.height = height;
|
||||
user.tag = "Личный кабинет - Данные";
|
||||
db.SaveChanges();
|
||||
|
||||
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
|
||||
selectEditData.Execute(update, client, db);
|
||||
}
|
||||
else
|
||||
{
|
||||
@params.UserId = chatId;
|
||||
@params.Message = "Вы некорректно ввели рост 🤔 Введите, пожалуйста, число (до 3 символов).";
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в GetHeightCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
public int GetRandomId()
|
||||
{
|
||||
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
76
SvetoforVKBot/Models/Commands/LK/GetWeightCommand.cs
Normal file
76
SvetoforVKBot/Models/Commands/LK/GetWeightCommand.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Text.RegularExpressions;
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Model.RequestParams;
|
||||
using VkNet.Model.Keyboard;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Security.Cryptography;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using SvetoforVKBot.Models.Dop;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK
|
||||
{
|
||||
public class GetWeightCommand
|
||||
{
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
int i = 0;
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
if (int.TryParse(update.@object.message.text.Trim(), out int weight))
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.weight = weight;
|
||||
user.tag = "Личный кабинет - Данные";
|
||||
db.SaveChanges();
|
||||
|
||||
/*SqlCommand editUser = new SqlCommand("UPDATE Users SET tag = @tag, weight = @weight WHERE chatId = @chatId;", Con);
|
||||
editUser.Parameters.AddWithValue("@chatId", chatId);
|
||||
editUser.Parameters.AddWithValue("@tag", "Личный кабинет - Данные");
|
||||
editUser.Parameters.AddWithValue("@weight", weight);
|
||||
editUser.ExecuteNonQuery();*/
|
||||
|
||||
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
|
||||
selectEditData.Execute(update, client, db);
|
||||
}
|
||||
else
|
||||
{
|
||||
@params.UserId = chatId;
|
||||
@params.Message = "Вы некорректно ввели вес 🤔 Введите, пожалуйста, число (до 3 символов).";
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в GetWeightCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
public int GetRandomId()
|
||||
{
|
||||
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using System.Text.RegularExpressions;
|
||||
using SvetoforVKBot.Models.Commands.LK.Menu.Products;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Model.RequestParams;
|
||||
using Newtonsoft.Json;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Menu.Products
|
||||
{
|
||||
public class SelectProductCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectProduct-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
string msg = "";
|
||||
string voronka = "";
|
||||
double sum = 0;
|
||||
string backPL = "startPL";
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
ShowProductCaruselMain showProductCaruselMain = new ShowProductCaruselMain();
|
||||
ShowProductMain showProductMain = new ShowProductMain();
|
||||
CategoriesDostavka categories = new CategoriesDostavka();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int curCategory = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
int curProduct = Convert.ToInt32(regex.Replace(payload[2], ""));
|
||||
int curWay = Convert.ToInt32(regex.Replace(payload[3], "")); //для ShowProductCaruselMain направление навигации, 1 по умолчанию
|
||||
|
||||
var cats = db.CategoriesDostavkas.Where(e => e.subMenu == curCategory);
|
||||
if(cats.Count() > 0)
|
||||
{
|
||||
ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
|
||||
showMenuDostavka.Execute(update, client, db, msg, 2, categories.subMenu); //1
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (curCategory)
|
||||
{
|
||||
default:
|
||||
if (update.@object.client_info.carousel == true)
|
||||
showProductCaruselMain.Execute(update, client, db, curCategory, curProduct, curWay);
|
||||
else
|
||||
showProductMain.Execute(update, client, db, curCategory, curProduct, 0, 1);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectProductCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Security.Cryptography;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using VkNet.Utils;
|
||||
using VkNet.Model.Template;
|
||||
using VkNet.Model.Template.Carousel;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Menu.Products
|
||||
{
|
||||
public class ShowProductCaruselMain
|
||||
{
|
||||
private const string PHOTOIDNEXT = "-194717824_457239273_446146426236760985";
|
||||
//{"id": 457239273, "owner_id": -194717824, "access_key": "446146426236760985"}
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCategory, int curProduct, int curWay)
|
||||
//curCategory - id Categories, curProduct - порядковый номер в массиве продуктов, curWay - для showProductCarusel направление навигации
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
int i = 0;
|
||||
int prevCatalog = 0, nextCatalog = 0;
|
||||
int naviState = 0;
|
||||
double sum = 0;
|
||||
string desc = "";
|
||||
//int curDay = (int)DateTime.Now.DayOfWeek;
|
||||
//if (curDay == 0) curDay = 7;
|
||||
|
||||
List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
|
||||
List<ProductsDostavka> products = new List<ProductsDostavka>();
|
||||
var row = new List<MessageKeyboardButton>();
|
||||
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
|
||||
TemplateBuilder templateBuilder = new TemplateBuilder();
|
||||
CarouselElementAction carouselElementAction = new CarouselElementAction();
|
||||
carouselElementAction.Type = CarouselElementActionType.OpenPhoto;
|
||||
|
||||
try
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
|
||||
int curDay = user.day;
|
||||
|
||||
//SqlCommand getCart = new SqlCommand("SELECT cart, day, colorId FROM Users WHERE chatId = @chatId;", Con);
|
||||
//getCart.Parameters.AddWithValue("@chatId", chatId);
|
||||
//SqlDataReader rgetCart = getCart.ExecuteReader();
|
||||
//rgetCart.Read();
|
||||
//var cartObject = JsonConvert.DeserializeObject<CartObject>(rgetCart["cart"].ToString());
|
||||
//int curDay = Convert.ToInt32(rgetCart["day"]);
|
||||
//int colorId = Convert.ToInt32(rgetCart["colorId"]);
|
||||
//rgetCart.Close();
|
||||
|
||||
if (curDay == 8) curDay = (int)DateTime.Now.DayOfWeek;
|
||||
|
||||
foreach (var o in cartObject.orders)
|
||||
{
|
||||
sum += o.price * o.number;
|
||||
}
|
||||
|
||||
categories = db.CategoriesDostavkas.ToList().ConvertAll<CategoriesDostavka>(c =>
|
||||
new CategoriesDostavka()
|
||||
{
|
||||
categoryId = c.categoryId,
|
||||
name = c.name,
|
||||
btnName = c.btnName,
|
||||
kbColor = c.kbColor,
|
||||
});
|
||||
|
||||
|
||||
//SqlCommand getCategories = new SqlCommand("SELECT * FROM CategoriesDostavka;", Con);
|
||||
//getCategories.Parameters.AddWithValue("@chatId", chatId);
|
||||
//SqlDataReader rgetCategories = getCategories.ExecuteReader();
|
||||
//while (rgetCategories.Read())
|
||||
// categories.Add(new CategoriesDostavka()
|
||||
// {
|
||||
// categoryId = Convert.ToInt32(rgetCategories["categoryId"]),
|
||||
// name = rgetCategories["name"].ToString(),
|
||||
// btnName = rgetCategories["btnName"].ToString(),
|
||||
// kbColor = rgetCategories["kbColor"].ToString(),
|
||||
// });
|
||||
//rgetCategories.Close();
|
||||
|
||||
|
||||
products = db.ProductsDostavkas.Where(p => p.categoryId == curCategory &&
|
||||
JsonConvert.DeserializeObject<List<int>>(p.weekDays).Exists(day => day == curDay)).
|
||||
ToList().ConvertAll<ProductsDostavka>(e => new ProductsDostavka()
|
||||
{
|
||||
id = e.id,
|
||||
article = e.article,
|
||||
colorId = e.colorId,
|
||||
categoryId = e.categoryId,
|
||||
name = e.name,
|
||||
fullName = e.fullName,
|
||||
description = e.description,
|
||||
descriptionCarousel = e.descriptionCarousel,
|
||||
price = Convert.ToDouble(e.price),
|
||||
photo = e.photo,
|
||||
photoCarousel = e.photoCarousel,
|
||||
additions = JsonConvert.DeserializeObject<List<string>>(e.additions),
|
||||
recommends = JsonConvert.DeserializeObject<List<string>>(e.recommends),
|
||||
});
|
||||
|
||||
//SqlCommand getProducts = new SqlCommand("SELECT * FROM ProductsDostavka WHERE categoryId = @categoryId;", Con);
|
||||
//getProducts.Parameters.AddWithValue("@categoryId", curCategory);
|
||||
////getProducts.Parameters.AddWithValue("@colorId", colorId);
|
||||
//SqlDataReader rgetProducts = getProducts.ExecuteReader();
|
||||
//while (rgetProducts.Read())
|
||||
//{
|
||||
// var weekDays = JsonConvert.DeserializeObject<List<int>>(rgetProducts["weekDays"].ToString());
|
||||
// foreach (int weekDay in weekDays)
|
||||
// {
|
||||
// if (weekDay == curDay)
|
||||
// {
|
||||
// products.Add(new ProductsDostavka()
|
||||
// {
|
||||
// id = Convert.ToInt32(rgetProducts["id"]),
|
||||
// article = rgetProducts["article"].ToString(),
|
||||
// colorId = Convert.ToInt32(rgetProducts["colorId"]),
|
||||
// categoryId = Convert.ToInt32(rgetProducts["categoryId"]),
|
||||
// name = rgetProducts["name"].ToString(),
|
||||
// fullName = rgetProducts["fullName"].ToString(),
|
||||
// descriptionCarousel = rgetProducts["descriptionCarousel"].ToString(),
|
||||
// price = Convert.ToInt32(rgetProducts["price"]),
|
||||
// photo = rgetProducts["photo"].ToString(),
|
||||
// photoCarousel = rgetProducts["photoCarousel"].ToString(),
|
||||
// //weight = rgetProducts["weight"].ToString(),
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
//rgetProducts.Close();
|
||||
|
||||
nextCatalog = curProduct + 9;
|
||||
prevCatalog = curProduct - 9;
|
||||
|
||||
if (curProduct > 0 && products.Count > 6)
|
||||
{
|
||||
if (nextCatalog > products.Count) nextCatalog = products.Count - (products.Count - curProduct);
|
||||
|
||||
if (prevCatalog < 0) prevCatalog = 0;
|
||||
}
|
||||
|
||||
for (i = curProduct; i < products.Count; i++)
|
||||
{
|
||||
var jsPhoto = JsonConvert.DeserializeObject<CatalogPhotoObject>(products[i].photoCarousel);
|
||||
|
||||
desc = products[i].descriptionCarousel; //+ " " + products[i].weight;
|
||||
if (desc.Length > 80) desc = desc.Substring(0, 77) + "..."; //desc.Substring(0, 77)
|
||||
|
||||
templateBuilder.AddTemplateElement(new CarouselElement()
|
||||
{
|
||||
Title = products[i].fullName,
|
||||
Description = desc,
|
||||
PhotoId = jsPhoto.owner_id + "_" + jsPhoto.id + "_" + jsPhoto.access_key,
|
||||
Buttons = new List<MessageKeyboardButton>()
|
||||
{
|
||||
new MessageKeyboardButton(){
|
||||
Action = new MessageKeyboardButtonAction(){ Label = "Подробнее",
|
||||
Payload = "{\"button\":\"selectAddToCart-" + curCategory + "-" + i + "\"}",
|
||||
Type = KeyboardButtonActionType.Text },
|
||||
Color = KeyboardButtonColor.Default
|
||||
},
|
||||
},
|
||||
Action = carouselElementAction,
|
||||
});
|
||||
|
||||
if (templateBuilder.Elements.Count == 9 && products.Count > 10)
|
||||
break;
|
||||
}
|
||||
|
||||
if (products.Count > 10)
|
||||
{
|
||||
switch (curWay)
|
||||
{
|
||||
case 1:
|
||||
if (curProduct < (products.Count - 9))
|
||||
naviState = 1;
|
||||
else
|
||||
naviState = 2;
|
||||
break;
|
||||
case 2:
|
||||
if (curProduct == 0)
|
||||
naviState = 1;
|
||||
else
|
||||
naviState = 2;
|
||||
break;
|
||||
default:
|
||||
naviState = 2;
|
||||
break;
|
||||
}
|
||||
|
||||
switch (naviState)
|
||||
{
|
||||
case 1:
|
||||
templateBuilder.AddTemplateElement(new CarouselElement()
|
||||
{
|
||||
Title = ".",
|
||||
Description = ".",
|
||||
PhotoId = PHOTOIDNEXT,
|
||||
Buttons = new List<MessageKeyboardButton>()
|
||||
{
|
||||
new MessageKeyboardButton() {
|
||||
Action = new MessageKeyboardButtonAction(){ Label = ">> Следующие " + (products.Count - nextCatalog).ToString(),
|
||||
Payload = "{\"button\":\"selectProduct-" + products[nextCatalog].categoryId + "-" + nextCatalog + "-1\"}",
|
||||
Type = KeyboardButtonActionType.Text },
|
||||
Color = KeyboardButtonColor.Primary
|
||||
},
|
||||
},
|
||||
Action = carouselElementAction,
|
||||
});
|
||||
break;
|
||||
|
||||
case 2:
|
||||
templateBuilder.AddTemplateElement(new CarouselElement()
|
||||
{
|
||||
Title = ".",
|
||||
Description = ".",
|
||||
PhotoId = PHOTOIDNEXT,
|
||||
Buttons = new List<MessageKeyboardButton>()
|
||||
{
|
||||
new MessageKeyboardButton() {
|
||||
Action = new MessageKeyboardButtonAction(){ Label = "<< Предыдущие " + curProduct,
|
||||
Payload = "{\"button\":\"selectProduct-" + products[prevCatalog].categoryId + "-" + prevCatalog + "-2\"}",
|
||||
Type = KeyboardButtonActionType.Text },
|
||||
Color = KeyboardButtonColor.Primary
|
||||
},
|
||||
},
|
||||
Action = carouselElementAction,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@params.Template = templateBuilder.Build();
|
||||
@params.Message = "😍";
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в ShowProductCaruselMain: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
private int GetRandomId()
|
||||
{
|
||||
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.RegularExpressions;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Attachments;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Menu.Products
|
||||
{
|
||||
public class ShowProductMain
|
||||
{
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCategory, int curProduct, int curAddition, int plAction)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
int i = 0;
|
||||
int index = 0;
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
int prevCatalog = 0, nextCatalog = 0;
|
||||
//double sumCart = 0;
|
||||
double sum = 0;
|
||||
Additions addition = new Additions();
|
||||
//DateTime startDate = new DateTime(2020, 09, 14);
|
||||
//DateTime currentDate = DateTime.Now;
|
||||
//TimeSpan offset = currentDate - startDate;
|
||||
//int curDay = offset.Days % 14 + 1;
|
||||
|
||||
string backPL = "selectMenu-0";
|
||||
|
||||
List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
|
||||
List<ProductsDostavka> products = new List<ProductsDostavka>();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
|
||||
int curDay = user.day;
|
||||
|
||||
//int curDay = (int)DateTime.Now.DayOfWeek;
|
||||
//if (curDay == 0) curDay = 7;
|
||||
|
||||
if (curDay == 8) curDay = (int)DateTime.Now.DayOfWeek;
|
||||
|
||||
/*
|
||||
* foreach (var o in cartObject.orders)
|
||||
sum += o.price * o.number;
|
||||
*/
|
||||
|
||||
|
||||
categories = db.CategoriesDostavkas.ToList().ConvertAll<CategoriesDostavka>(c =>
|
||||
new CategoriesDostavka()
|
||||
{
|
||||
categoryId = c.categoryId,
|
||||
name = c.name,
|
||||
btnName = c.btnName,
|
||||
kbColor = c.kbColor,
|
||||
});
|
||||
|
||||
|
||||
products = db.ProductsDostavkas.Where(p => p.categoryId == curCategory &&
|
||||
JsonConvert.DeserializeObject<List<int>>(p.weekDays).Exists(day => day == curDay)).
|
||||
ToList().ConvertAll<ProductsDostavka>(e => new ProductsDostavka()
|
||||
{
|
||||
id = e.id,
|
||||
article = e.article,
|
||||
colorId = e.colorId,
|
||||
categoryId = e.categoryId,
|
||||
name = e.name,
|
||||
fullName = e.fullName,
|
||||
description = e.description,
|
||||
descriptionCarousel = e.descriptionCarousel,
|
||||
price = Convert.ToDouble(e.price),
|
||||
photo = e.photo,
|
||||
photoCarousel = e.photoCarousel,
|
||||
additions = JsonConvert.DeserializeObject<List<string>>(e.additions),
|
||||
recommends = JsonConvert.DeserializeObject<List<string>>(e.recommends),
|
||||
});
|
||||
|
||||
|
||||
switch (plAction)
|
||||
{
|
||||
case 1:
|
||||
var jsPhoto = JsonConvert.DeserializeObject<CatalogPhotoObject>(products[curProduct].photo);
|
||||
List<MediaAttachment> listPhoto = new List<MediaAttachment>()
|
||||
{
|
||||
new VkNet.Model.Attachments.Photo() { Id = jsPhoto.id, OwnerId = jsPhoto.owner_id, AccessKey = jsPhoto.access_key}
|
||||
};
|
||||
@params.Attachments = listPhoto;
|
||||
@params.Message = products[curProduct].fullName + "\n" +
|
||||
products[curProduct].description + "\n"; // + " " + products[curProduct].weight
|
||||
break;
|
||||
case 2:
|
||||
if (curAddition == 0)
|
||||
@params.Message = "✅ " + products[curProduct].fullName + " добавлен в корзину.";
|
||||
else
|
||||
{
|
||||
// Нет таблицы с модификаторами
|
||||
|
||||
//SqlCommand getAddition = new SqlCommand("SELECT * FROM Modifiers WHERE article = @article;", Con);
|
||||
//getAddition.Parameters.AddWithValue("@article", curAddition);
|
||||
//SqlDataReader rgetAddition = getAddition.ExecuteReader();
|
||||
//if (rgetAddition.HasRows)
|
||||
//{
|
||||
// rgetAddition.Read();
|
||||
// addition = new Additions()
|
||||
// {
|
||||
// name = rgetAddition["name"].ToString(),
|
||||
// price = Convert.ToInt32(rgetAddition["price"]),
|
||||
// fullName = rgetAddition["fullName"].ToString(),
|
||||
// article = rgetAddition["article"].ToString(),
|
||||
// };
|
||||
//}
|
||||
//rgetAddition.Close();
|
||||
|
||||
@params.Message = "✅ " + products[curProduct].fullName + " с " + addition.fullName + " добавлен в корзину.";
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (curProduct >= products.Count)
|
||||
{
|
||||
curProduct = products.Count - 1;
|
||||
prevCatalog = curProduct - 1;
|
||||
nextCatalog = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
prevCatalog = curProduct - 1;
|
||||
nextCatalog = curProduct + 1;
|
||||
}
|
||||
|
||||
if ((curProduct + 1) == products.Count)
|
||||
{
|
||||
prevCatalog = curProduct - 1;
|
||||
nextCatalog = 0;
|
||||
}
|
||||
if (curProduct == 0)
|
||||
{
|
||||
prevCatalog = products.Count - 1;
|
||||
nextCatalog = curProduct + 1;
|
||||
}
|
||||
if (products.Count == 1)
|
||||
{
|
||||
prevCatalog = 0;
|
||||
nextCatalog = 0;
|
||||
}
|
||||
|
||||
#region keyboard
|
||||
//keyboardBuilder
|
||||
// .AddButton("Подробнее", "selectAddToCart-" + curCategory + "-" + curProduct, KeyboardButtonColor.Primary)
|
||||
// .AddLine();
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("<<", "selectProduct-" + curCategory + "-" + prevCatalog + "-1", KeyboardButtonColor.Primary)
|
||||
.AddButton((curProduct + 1) + "/" + products.Count, "selectProduct-" + curCategory + "-" + curProduct + "-1", KeyboardButtonColor.Default)
|
||||
.AddButton(">>", "selectProduct-" + curCategory + "-" + nextCatalog + "-1", KeyboardButtonColor.Primary)
|
||||
.AddLine();
|
||||
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Вернуться в меню", "selectDayMenu-" + curDay, KeyboardButtonColor.Default)
|
||||
//.AddButton("Корзина: " + sum + " р", "selectCart-0", KeyboardButtonColor.Negative)
|
||||
.AddLine()
|
||||
.AddButton("День недели", "selectMenu-0", KeyboardButtonColor.Default);
|
||||
//.AddLine();
|
||||
|
||||
|
||||
#endregion keyboard
|
||||
/*
|
||||
if (products.Count > 10) //14
|
||||
{
|
||||
if (curProduct < (products.Count - 10)) index = curProduct + 1;
|
||||
else index = products.Count - 10;
|
||||
}
|
||||
else index = 0;
|
||||
|
||||
int rowCount = 3;
|
||||
|
||||
for (i = index; i < products.Count; i += 2)
|
||||
{
|
||||
if (i + 1 < products.Count)
|
||||
keyboardBuilder
|
||||
.AddButton(products[i].name, "selectProduct-" + curCategory + "-" + i.ToString() + "-1", KeyboardButtonColor.Default)
|
||||
.AddButton(products[i + 1].name, "selectProduct-" + curCategory + "-" + (i + 1).ToString() + "-1", KeyboardButtonColor.Default)
|
||||
.AddLine();
|
||||
else
|
||||
keyboardBuilder
|
||||
.AddButton(products[i].name, "selectProduct-" + curCategory + "-" + i.ToString() + "-1", KeyboardButtonColor.Default)
|
||||
.AddLine();
|
||||
rowCount += 1;
|
||||
|
||||
if (rowCount == 8) break;
|
||||
}
|
||||
*/
|
||||
|
||||
@params.UserId = chatId;
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в ShowProductMain: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
private int GetRandomId()
|
||||
{
|
||||
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
60
SvetoforVKBot/Models/Commands/LK/Menu/SelectColorCommand.cs
Normal file
60
SvetoforVKBot/Models/Commands/LK/Menu/SelectColorCommand.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Menu
|
||||
{
|
||||
public class SelectColorCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectColor-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
List<Data.Svetofor> categories = new List<Data.Svetofor>();
|
||||
var row = new List<MessageKeyboardButton>();
|
||||
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
|
||||
var kbColor = KeyboardButtonColor.Positive;
|
||||
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int colorId = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.colorId = colorId;
|
||||
db.SaveChanges();
|
||||
|
||||
msg = "📋Основное меню\n";
|
||||
|
||||
ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
|
||||
showMenuDostavka.Execute(update, client, db, msg, 2, 0);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectColorCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Menu
|
||||
{
|
||||
public class SelectDayMenuCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectDayMenu-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
List<Data.Svetofor> categories = new List<Data.Svetofor>();
|
||||
var row = new List<MessageKeyboardButton>();
|
||||
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
|
||||
var kbColor = KeyboardButtonColor.Positive;
|
||||
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int curDay = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.tag = "Меню";
|
||||
user.day = curDay;
|
||||
db.SaveChanges();
|
||||
|
||||
keyboardBuilder.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
msg = "📋Основное меню\n";
|
||||
|
||||
ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
|
||||
showMenuDostavka.Execute(update, client, db, msg, 2, 0);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectDayMenuCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
65
SvetoforVKBot/Models/Commands/LK/Menu/SelectMenuCommand.cs
Normal file
65
SvetoforVKBot/Models/Commands/LK/Menu/SelectMenuCommand.cs
Normal file
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Menu
|
||||
{
|
||||
public class SelectMenuCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectMenu-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int curSubMenu = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
@params.Message = "📅На какой день показать меню? Выберите на клавиатуре\n";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Сегодня", "selectDayMenu-8", KeyboardButtonColor.Positive)
|
||||
.AddLine()
|
||||
.AddButton("Пн", "selectDayMenu-1", KeyboardButtonColor.Primary)
|
||||
.AddButton("Вт", "selectDayMenu-2", KeyboardButtonColor.Primary)
|
||||
.AddButton("Ср", "selectDayMenu-3", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Чт", "selectDayMenu-4", KeyboardButtonColor.Primary)
|
||||
.AddButton("Пт", "selectDayMenu-5", KeyboardButtonColor.Primary)
|
||||
.AddButton("Сб", "selectDayMenu-6", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
//ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
|
||||
//showMenuDostavka.Execute(update, client, Con, msg, 2, curSubMenu);
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectMenuCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
using Newtonsoft.Json;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Menu
|
||||
{
|
||||
public class SelectPersonalMenuCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectPersonalMenu-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
double sum = 0;
|
||||
string backPL = "startPL";
|
||||
int kkals = 0;
|
||||
|
||||
try
|
||||
{
|
||||
switch (DateTime.Now.DayOfWeek)
|
||||
{
|
||||
case DayOfWeek.Saturday:
|
||||
case DayOfWeek.Sunday:
|
||||
keyboardBuilder
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
@params.Message = "Рекомендации по дневному меню доступны с понедельника по пятницу.\n" +
|
||||
"Чтобы вернуться в Личный кабинет, нажмите кнопку \"Назад\"";
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
return;
|
||||
}
|
||||
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int foodType = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
int curDayKkal = Convert.ToInt32(regex.Replace(payload[2], ""));
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
|
||||
|
||||
foreach (var o in cartObject.orders)
|
||||
{
|
||||
sum += o.price * o.number;
|
||||
kkals += o.kkal * o.number;
|
||||
}
|
||||
|
||||
//keyboardBuilder
|
||||
// .AddButton($"Завтрак (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-1-" + curDayKkal, KeyboardButtonColor.Primary)
|
||||
// .AddLine()
|
||||
// .AddButton($"Обед (до {Math.Round(curDayKkal * 1.2 * 0.4)} ккал)", "selectPersonalMenu-2-" + curDayKkal, KeyboardButtonColor.Primary)
|
||||
// .AddLine()
|
||||
// .AddButton($"Перекус (до {Math.Round(curDayKkal * 1.2 * 0.1)} ккал)", "selectPersonalMenu-3-" + curDayKkal, KeyboardButtonColor.Primary)
|
||||
// .AddLine()
|
||||
// .AddButton($"Ужин (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-4-" + curDayKkal, KeyboardButtonColor.Primary)
|
||||
// .AddLine();
|
||||
|
||||
//if (cartObject.orders.Count > 0)
|
||||
//{
|
||||
// keyboardBuilder
|
||||
// .AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default)
|
||||
// .AddButton("Корзина: " + sum + " р", "selectCart-0", KeyboardButtonColor.Negative);
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// keyboardBuilder
|
||||
// .AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
|
||||
//}
|
||||
|
||||
////@params.Template = templateBuilder.Build();
|
||||
//@params.Keyboard = keyboardBuilder.Build();
|
||||
//@params.Message = "Если хотите подобрать блюда ещё раз, нажмите кнопку повторно😉";
|
||||
//@params.UserId = chatId;
|
||||
//@params.RandomId = GetRandomId();
|
||||
//client.Messages.SendAsync(@params);
|
||||
|
||||
ShowPersonalMenuCarusel showPersonalMenu = new ShowPersonalMenuCarusel();
|
||||
showPersonalMenu.Execute(update, client, db, foodType, 0, 1, curDayKkal);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectMenuCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
139
SvetoforVKBot/Models/Commands/LK/Menu/ShowMenuDostavka.cs
Normal file
139
SvetoforVKBot/Models/Commands/LK/Menu/ShowMenuDostavka.cs
Normal file
@@ -0,0 +1,139 @@
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Attachments;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Menu
|
||||
{
|
||||
public class ShowMenuDostavka
|
||||
{
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, string msg, int plAction, int subMenu)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
var ids = new long[] { chatId };
|
||||
var user = client.Users.Get(ids);
|
||||
string voronka = "";
|
||||
double sum = 0;
|
||||
string backPL = "";
|
||||
List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
|
||||
var row = new List<MessageKeyboardButton>();
|
||||
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
|
||||
var kbColor = KeyboardButtonColor.Positive;
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
categories = db.CategoriesDostavkas.Where(c=>c.subMenu == subMenu).ToList().ConvertAll<CategoriesDostavka>(c =>
|
||||
new CategoriesDostavka()
|
||||
{
|
||||
categoryId = c.categoryId,
|
||||
inTheOrder = c.inTheOrder,
|
||||
name = c.name,
|
||||
btnName = c.btnName,
|
||||
kbColor = c.kbColor,
|
||||
});
|
||||
|
||||
//SqlCommand getCategories = new SqlCommand("SELECT * FROM CategoriesDostavka WHERE subMenu = @subMenu;", Con);
|
||||
//getCategories.Parameters.AddWithValue("@subMenu", subMenu);
|
||||
//SqlDataReader rgetCategories = getCategories.ExecuteReader();
|
||||
//while (rgetCategories.Read())
|
||||
// categories.Add(new CategoriesDostavka()
|
||||
// {
|
||||
// categoryId = Convert.ToInt32(rgetCategories["categoryId"]),
|
||||
// inTheOrder = Convert.ToInt32(rgetCategories["inTheOrder"]),
|
||||
// name = rgetCategories["name"].ToString(),
|
||||
// btnName = rgetCategories["btnName"].ToString(),
|
||||
// kbColor = rgetCategories["kbColor"].ToString(),
|
||||
// });
|
||||
//rgetCategories.Close();
|
||||
|
||||
categories.RemoveAll(c => c.inTheOrder.Equals(0));
|
||||
categories.Sort((x, y) => x.inTheOrder.CompareTo(y.inTheOrder));
|
||||
|
||||
int btnCount = 0;
|
||||
foreach (var c in categories)
|
||||
{
|
||||
switch (c.kbColor)
|
||||
{
|
||||
case "Default":
|
||||
kbColor = KeyboardButtonColor.Default;
|
||||
break;
|
||||
case "Positive":
|
||||
kbColor = KeyboardButtonColor.Positive;
|
||||
break;
|
||||
case "Negative":
|
||||
kbColor = KeyboardButtonColor.Negative;
|
||||
break;
|
||||
case "Primary":
|
||||
kbColor = KeyboardButtonColor.Primary;
|
||||
break;
|
||||
}
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton(c.btnName, "selectProduct-" + c.categoryId + "-0-1", kbColor);
|
||||
|
||||
btnCount += 1;
|
||||
|
||||
if (btnCount % 2 == 0)
|
||||
{
|
||||
keyboardBuilder.AddLine();
|
||||
}
|
||||
}
|
||||
if (btnCount % 2 != 0)
|
||||
{
|
||||
keyboardBuilder.AddLine();
|
||||
}
|
||||
|
||||
if (subMenu == 0)
|
||||
{
|
||||
backPL = "startPL";
|
||||
}
|
||||
else
|
||||
backPL = "selectMenu-0";
|
||||
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Назад", "selectMenu-0", KeyboardButtonColor.Default)
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
|
||||
@params.UserId = chatId;
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.Message = msg;
|
||||
@params.DontParseLinks = true;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в ShowMenuDostavka: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
private int GetRandomId()
|
||||
{
|
||||
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
430
SvetoforVKBot/Models/Commands/LK/Menu/ShowPersonalMenuCarusel.cs
Normal file
430
SvetoforVKBot/Models/Commands/LK/Menu/ShowPersonalMenuCarusel.cs
Normal file
@@ -0,0 +1,430 @@
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Security.Cryptography;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using VkNet.Utils;
|
||||
using VkNet.Model.Template;
|
||||
using VkNet.Model.Template.Carousel;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Menu
|
||||
{
|
||||
public class ShowPersonalMenuCarusel
|
||||
{
|
||||
private const string PHOTOIDNEXT = "-194717824_457239273_446146426236760985";
|
||||
//{"id": 457239273, "owner_id": -194717824, "access_key": "446146426236760985"}
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCategory, int curProduct, int curWay, double curDayKkal)
|
||||
//curCategory - id Categories, curProduct - порядковый номер в массиве продуктов, curWay - для showProductCarusel направление навигации
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
int i = 0;
|
||||
int prevCatalog = 0, nextCatalog = 0;
|
||||
int naviState = 0;
|
||||
double sum = 0;
|
||||
string desc = "";
|
||||
int curDay = (int)DateTime.Now.DayOfWeek;
|
||||
if (curDay == 0) curDay = 7;
|
||||
|
||||
List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
|
||||
List<ProductsDostavka> products = new List<ProductsDostavka>();
|
||||
List<ProductsDostavka> allProducts = new List<ProductsDostavka>();
|
||||
List<ProductsDostavka> randomFood = new List<ProductsDostavka>();
|
||||
//List<ProductsDostavka> personalProducts = new List<ProductsDostavka>();
|
||||
var row = new List<MessageKeyboardButton>();
|
||||
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
|
||||
TemplateBuilder templateBuilder = new TemplateBuilder();
|
||||
CarouselElementAction carouselElementAction = new CarouselElementAction();
|
||||
carouselElementAction.Type = CarouselElementActionType.OpenPhoto;
|
||||
double belkiLow = 0, zhiryLow = 0, uglevodyLow = 0, belkiHigh = 0, zhiryHigh = 0, uglevodyHigh = 0;
|
||||
double curBelki = 0, curZhiry = 0, curUglevody = 0;
|
||||
double foodPercent = 0;
|
||||
double belkiPercent = 0, zhiryPercent = 0, uglevodyPercent = 0;
|
||||
double dayKkal = 0;
|
||||
string foodTime = "";
|
||||
try
|
||||
{
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
|
||||
var choosenProducts = JsonConvert.DeserializeObject<List<int>>(user.choosenProducts);
|
||||
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(user.sportDays);
|
||||
|
||||
//if (curDay == 8) curDay = (int)DateTime.Now.DayOfWeek;
|
||||
int nextDay = curDay + 1;
|
||||
|
||||
if (nextDay == 8)
|
||||
nextDay = 1;
|
||||
|
||||
foreach (var o in cartObject.orders)
|
||||
{
|
||||
sum += o.price * o.number;
|
||||
}
|
||||
|
||||
|
||||
categories = db.CategoriesDostavkas.ToList().ConvertAll<CategoriesDostavka>(c =>
|
||||
new CategoriesDostavka()
|
||||
{
|
||||
categoryId = c.categoryId,
|
||||
name = c.name,
|
||||
btnName = c.btnName,
|
||||
kbColor = c.kbColor,
|
||||
});
|
||||
|
||||
allProducts = db.ProductsDostavkas.Where(p => p.categoryId != 0 &&
|
||||
JsonConvert.DeserializeObject<List<int>>(p.weekDays).Exists(day => day == curDay)).
|
||||
ToList().ConvertAll<ProductsDostavka>(e=>new ProductsDostavka()
|
||||
{
|
||||
id = e.id,
|
||||
article = e.article,
|
||||
colorId = e.colorId,
|
||||
categoryId = e.categoryId,
|
||||
name = e.name,
|
||||
fullName = e.fullName,
|
||||
descriptionCarousel = e.descriptionCarousel,
|
||||
price = Convert.ToDouble(e.price),
|
||||
photo = e.photo,
|
||||
photoCarousel = e.photoCarousel,
|
||||
kkal = e.kkal,
|
||||
foodType = JsonConvert.DeserializeObject<List<int>>(e.foodType),
|
||||
belki = Convert.ToDouble(e.belki),
|
||||
zhiry = Convert.ToDouble(e.zhiry),
|
||||
uglevody = Convert.ToDouble(e.uglevody),
|
||||
});
|
||||
|
||||
ProductsDostavka water = new ProductsDostavka();
|
||||
water = allProducts.Find(p => p.article.Equals("55"));
|
||||
allProducts.Remove(water);
|
||||
//allProducts.RemoveAll(p => !p.foodType.Contains(curCategory));
|
||||
if (choosenProducts.Count > 0)
|
||||
allProducts.RemoveAll(p => choosenProducts.Contains(p.id));
|
||||
|
||||
switch (user.track)
|
||||
{
|
||||
case 1:
|
||||
belkiLow = 1.4;
|
||||
belkiHigh = 2;
|
||||
|
||||
zhiryLow = 1;
|
||||
zhiryHigh = 1.1;
|
||||
|
||||
uglevodyLow = 2.4;
|
||||
uglevodyHigh = 3;
|
||||
break;
|
||||
|
||||
case 2:
|
||||
belkiLow = 1.2;
|
||||
belkiHigh = 1.7;
|
||||
|
||||
zhiryLow = 0.9;
|
||||
zhiryHigh = 1;
|
||||
|
||||
uglevodyLow = 2;
|
||||
uglevodyHigh = 2.6;
|
||||
break;
|
||||
|
||||
case 3:
|
||||
belkiLow = 1.6;
|
||||
belkiHigh = 2.2;
|
||||
|
||||
zhiryLow = 1.1;
|
||||
zhiryHigh = 1.2;
|
||||
|
||||
uglevodyLow = 2.8;
|
||||
uglevodyHigh = 3.4;
|
||||
break;
|
||||
}
|
||||
|
||||
switch (curCategory)
|
||||
{
|
||||
case 1:
|
||||
allProducts.RemoveAll(p => p.categoryId == 1);
|
||||
|
||||
foodPercent = 0.3;
|
||||
belkiPercent = 0.3;
|
||||
uglevodyPercent = 0.4;
|
||||
zhiryPercent = 0.2;
|
||||
foodTime = "🥐Завтрак";
|
||||
randomFood = allProducts.FindAll(ap => (ap.categoryId != 1) && ap.zhiry <= zhiryLow * user.weight * zhiryPercent && ap.uglevody <= uglevodyLow * user.weight * uglevodyPercent);
|
||||
|
||||
//Углеводы - 0.4
|
||||
//Белки - 0.3
|
||||
//Жиры - 0.2
|
||||
//Кнопка ещё один вариант
|
||||
//web
|
||||
break;
|
||||
|
||||
case 2:
|
||||
foodPercent = 0.4;
|
||||
belkiPercent = 0.3;
|
||||
uglevodyPercent = 0.3;
|
||||
zhiryPercent = 0.4;
|
||||
foodTime = "🍲Обед";
|
||||
randomFood = allProducts.FindAll(ap => ap.categoryId == 1 && ap.zhiry <= zhiryLow * user.weight * zhiryPercent && ap.uglevody <= uglevodyLow * user.weight * uglevodyPercent);
|
||||
break;
|
||||
|
||||
case 3:
|
||||
allProducts.RemoveAll(p => p.categoryId == 1);
|
||||
|
||||
foodPercent = 0.1;
|
||||
belkiPercent = 0.2;
|
||||
uglevodyPercent = 0.2;
|
||||
zhiryPercent = 0.2;
|
||||
foodTime = "🥪Перекус";
|
||||
//ap.categoryId == 5 || ap.categoryId == 4
|
||||
randomFood = allProducts.FindAll(ap => (ap.categoryId != 1) && ap.zhiry <= zhiryLow * user.weight * zhiryPercent && ap.uglevody <= uglevodyLow * user.weight * uglevodyPercent);
|
||||
break;
|
||||
|
||||
case 4:
|
||||
allProducts.RemoveAll(p => p.categoryId == 1);
|
||||
|
||||
foodPercent = 0.3;
|
||||
belkiPercent = 0.2;
|
||||
uglevodyPercent = 0.2;
|
||||
zhiryPercent = 0.2;
|
||||
randomFood = allProducts.FindAll(ap => (ap.categoryId != 1) && ap.zhiry <= zhiryLow * user.weight * zhiryPercent && ap.uglevody <= uglevodyLow * user.weight * uglevodyPercent);
|
||||
foodTime = "🥗Ужин";
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
double maxKkal = Math.Round(curDayKkal * 1.2 * foodPercent);
|
||||
double minKkal = Math.Round(curDayKkal * 0.9 * foodPercent);
|
||||
|
||||
Random rand = new Random();
|
||||
if (choosenProducts.Count > 0)
|
||||
randomFood.RemoveAll(p => choosenProducts.Contains(p.id));
|
||||
|
||||
int randomBludo = rand.Next(0, randomFood.Count);
|
||||
|
||||
if (curCategory == 3)
|
||||
{
|
||||
products.Add(randomFood.Find(rf => rf.kkal <= maxKkal));
|
||||
}
|
||||
else
|
||||
{
|
||||
products.Add(randomFood[randomBludo]);
|
||||
}
|
||||
|
||||
curBelki = products[0].belki;
|
||||
curZhiry = products[0].zhiry;
|
||||
curUglevody = products[0].uglevody;
|
||||
dayKkal = products[0].kkal;
|
||||
choosenProducts.Add(products[0].id);
|
||||
ProductsDostavka tmp = new ProductsDostavka();
|
||||
for (i = 0; i < allProducts.Count; i++)
|
||||
{
|
||||
tmp = allProducts[i];
|
||||
allProducts.RemoveAt(i);
|
||||
allProducts.Insert(rand.Next(allProducts.Count), tmp);
|
||||
}
|
||||
|
||||
|
||||
|
||||
foreach (var ap in allProducts)
|
||||
{
|
||||
//if (dayKkal + ap.kkal <= maxKkal) //curBelki <= belkiLow * weight * foodPercent && curUglevody + ap.uglevody < uglevodyHigh * weight * foodPercent)
|
||||
if (curBelki + ap.belki <= belkiHigh * user.weight * belkiPercent &&
|
||||
curUglevody + ap.uglevody <= uglevodyHigh * user.weight * uglevodyPercent)// &&
|
||||
//curZhiry + ap.zhiry <= zhiryHigh * weight * zhiryPercent)
|
||||
{
|
||||
if (!products.Exists(p => p.categoryId == ap.categoryId))
|
||||
{
|
||||
if (true)//curUglevody + ap.uglevody < uglevodyHigh * weight * foodPercent curBelki < belkiHigh * weight * foodPercent && curZhiry < zhiryHigh * weight * foodPercent && curUglevody < uglevodyHigh * weight * foodPercent)
|
||||
{
|
||||
|
||||
curBelki += ap.belki;
|
||||
curZhiry += ap.zhiry;
|
||||
curUglevody += ap.uglevody;
|
||||
dayKkal += ap.kkal;
|
||||
products.Add(ap);
|
||||
choosenProducts.Add(ap.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
//else break;
|
||||
}
|
||||
|
||||
//if (dayKkal < minKkal)
|
||||
//{
|
||||
// if (curCategory != 3)
|
||||
// {
|
||||
// products.Add(allProducts.Find(ap => !choosenProducts.Contains(ap.id) && ap.zhiry <= zhiryLow * weight * zhiryPercent && ap.uglevody <= uglevodyLow * weight * uglevodyPercent && ap.categoryId != 7));
|
||||
// curBelki += products[products.Count - 1].belki;
|
||||
// curZhiry += products[products.Count - 1].zhiry;
|
||||
// curUglevody += products[products.Count - 1].uglevody;
|
||||
// dayKkal += products[products.Count - 1].kkal;
|
||||
// choosenProducts.Add(products[products.Count - 1].id);
|
||||
// }
|
||||
// //else
|
||||
// // products.Add(allProducts.Find(ap => !choosenProducts.Contains(ap.id) && ap.kkal <= maxKkal - minKkal));
|
||||
// //choosenProducts.Add(products[products.Count - 1].id);
|
||||
//}
|
||||
|
||||
if (!products.Exists(p => p.categoryId == 7))
|
||||
products.Add(water);
|
||||
//(p => p.article.Equals("55")))
|
||||
|
||||
//if (curCategory != 4)
|
||||
//{
|
||||
// SqlCommand updCart = new SqlCommand("UPDATE Users SET choosenProducts = @choosenProducts WHERE chatId = @chatId;", Con);
|
||||
// updCart.Parameters.AddWithValue("@chatId", chatId);
|
||||
// updCart.Parameters.AddWithValue("@choosenProducts", JsonConvert.SerializeObject(choosenProducts));
|
||||
// updCart.ExecuteNonQuery();
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// SqlCommand updCart = new SqlCommand("UPDATE Users SET choosenProducts = @choosenProducts WHERE chatId = @chatId;", Con);
|
||||
// updCart.Parameters.AddWithValue("@chatId", chatId);
|
||||
// updCart.Parameters.AddWithValue("@choosenProducts", "[]");
|
||||
// updCart.ExecuteNonQuery();
|
||||
//}
|
||||
|
||||
nextCatalog = curProduct + 9;
|
||||
prevCatalog = curProduct - 9;
|
||||
|
||||
if (curProduct > 0 && products.Count > 6)
|
||||
{
|
||||
if (nextCatalog > products.Count) nextCatalog = products.Count - (products.Count - curProduct);
|
||||
|
||||
if (prevCatalog < 0) prevCatalog = 0;
|
||||
}
|
||||
|
||||
for (i = curProduct; i < products.Count; i++)
|
||||
{
|
||||
var jsPhoto = JsonConvert.DeserializeObject<CatalogPhotoObject>(products[i].photoCarousel);
|
||||
|
||||
desc = products[i].descriptionCarousel; //+ " " + products[i].weight;
|
||||
if (desc.Length > 80) desc = desc.Substring(0, 77) + "..."; //desc.Substring(0, 77)
|
||||
|
||||
templateBuilder.AddTemplateElement(new CarouselElement()
|
||||
{
|
||||
Title = products[i].fullName,
|
||||
Description = desc + " | " + products[i].kkal + " ккал\n" +
|
||||
$"Б\\Ж\\У: {products[i].belki}г\\{products[i].zhiry}г\\{products[i].uglevody}г",
|
||||
PhotoId = jsPhoto.owner_id + "_" + jsPhoto.id + "_" + jsPhoto.access_key,
|
||||
Buttons = new List<MessageKeyboardButton>()
|
||||
{
|
||||
new MessageKeyboardButton(){
|
||||
Action = new MessageKeyboardButtonAction(){ Label = "Добавить в корзину " + products[i].price + "р",
|
||||
Payload = "{\"button\":\"selectAddToCart-" + products[i].categoryId + "-" + products[i].id + "-" + curDayKkal + "\"}",
|
||||
Type = KeyboardButtonActionType.Text },
|
||||
Color = KeyboardButtonColor.Positive
|
||||
},
|
||||
//new MessageKeyboardButton(){
|
||||
// Action = new MessageKeyboardButtonAction(){ Label = "Подробнее",
|
||||
// Payload = "{\"button\":\"selectAddToCart-" + curCategory + "-" + i + "\"}",
|
||||
// Type = KeyboardButtonActionType.Text },
|
||||
// Color = KeyboardButtonColor.Default
|
||||
//},
|
||||
},
|
||||
Action = carouselElementAction,
|
||||
});
|
||||
|
||||
if (templateBuilder.Elements.Count == 9 && products.Count > 10)
|
||||
break;
|
||||
}
|
||||
|
||||
if (products.Count > 10)
|
||||
{
|
||||
switch (curWay)
|
||||
{
|
||||
case 1:
|
||||
if (curProduct < (products.Count - 9))
|
||||
naviState = 1;
|
||||
else
|
||||
naviState = 2;
|
||||
break;
|
||||
case 2:
|
||||
if (curProduct == 0)
|
||||
naviState = 1;
|
||||
else
|
||||
naviState = 2;
|
||||
break;
|
||||
default:
|
||||
naviState = 2;
|
||||
break;
|
||||
}
|
||||
|
||||
switch (naviState)
|
||||
{
|
||||
case 1:
|
||||
templateBuilder.AddTemplateElement(new CarouselElement()
|
||||
{
|
||||
Title = ".",
|
||||
Description = ".",
|
||||
PhotoId = PHOTOIDNEXT,
|
||||
Buttons = new List<MessageKeyboardButton>()
|
||||
{
|
||||
new MessageKeyboardButton() {
|
||||
Action = new MessageKeyboardButtonAction(){ Label = ">> Следующие " + (products.Count - nextCatalog).ToString(),
|
||||
Payload = "{\"button\":\"selectProduct-" + products[nextCatalog].categoryId + "-" + nextCatalog + "-1\"}",
|
||||
Type = KeyboardButtonActionType.Text },
|
||||
Color = KeyboardButtonColor.Primary
|
||||
},
|
||||
},
|
||||
Action = carouselElementAction,
|
||||
});
|
||||
break;
|
||||
|
||||
case 2:
|
||||
templateBuilder.AddTemplateElement(new CarouselElement()
|
||||
{
|
||||
Title = ".",
|
||||
Description = ".",
|
||||
PhotoId = PHOTOIDNEXT,
|
||||
Buttons = new List<MessageKeyboardButton>()
|
||||
{
|
||||
new MessageKeyboardButton() {
|
||||
Action = new MessageKeyboardButtonAction(){ Label = "<< Предыдущие " + curProduct,
|
||||
Payload = "{\"button\":\"selectProduct-" + products[prevCatalog].categoryId + "-" + prevCatalog + "-2\"}",
|
||||
Type = KeyboardButtonActionType.Text },
|
||||
Color = KeyboardButtonColor.Primary
|
||||
},
|
||||
},
|
||||
Action = carouselElementAction,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@params.Message = foodTime + "\n" +
|
||||
"Калории: " + dayKkal + " ккал \n" +
|
||||
$"Б\\Ж\\У: {curBelki}г\\{curZhiry}г\\{curUglevody}г \n\n" +
|
||||
$"Если хотите подобрать блюда ещё раз, нажмите кнопку повторно😉";
|
||||
@params.Template = templateBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в ShowProductCaruselMain: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
private int GetRandomId()
|
||||
{
|
||||
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
15
SvetoforVKBot/Models/Commands/LK/Reports/CompareReport.cs
Normal file
15
SvetoforVKBot/Models/Commands/LK/Reports/CompareReport.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
|
||||
namespace SvetoforVKBot.Data
|
||||
{
|
||||
public partial class Reports : IComparable<Reports>
|
||||
{
|
||||
public int CompareTo(Reports other) // Сделаем сравнение по максимальному id
|
||||
{
|
||||
return (id < other.id) ? -1 : (id > other.id) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Reports
|
||||
{
|
||||
public class GetReportCommentCommand
|
||||
{
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
if (update.@object.message.text.Length > 0)
|
||||
{
|
||||
var ids = new long[] { chatId };
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.tag = "Личный кабинет";
|
||||
db.SaveChanges();
|
||||
|
||||
var report = db.Reports.Where(r=>r.chatId == chatId).Max();
|
||||
report.comment = update.@object.message.text.Trim();
|
||||
report.datetime = DateTime.Now;
|
||||
report.state = 1;
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.Message = "✅Отчет сохранён. Увидимся завтра!\n";
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
else
|
||||
{
|
||||
@params.Message = "Не распознал сообщение 😕 Попробуйте, пожалуйста, ещё раз";
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в GetReportCommentCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
public int GetRandomId()
|
||||
{
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Reports
|
||||
{
|
||||
public class SelectCreateReportCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectCreateReport\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
|
||||
@params.Message = "✏Отчёт за " + DateTime.Now.ToShortDateString() + "\n\n" +
|
||||
user.firstName + ", как Вы себя чувствуете?";
|
||||
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("😀", "selectReportRate-10", KeyboardButtonColor.Primary)
|
||||
.AddButton("😐", "selectReportRate-5", KeyboardButtonColor.Primary)
|
||||
.AddButton("🙁", "selectReportRate-1", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectCreateReportCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Reports
|
||||
{
|
||||
public class SelectReportCcalCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectReportCcal-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int result = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.tag = "Отчет - Комменнт";
|
||||
db.SaveChanges();
|
||||
|
||||
var report = db.Reports.Where(r => r.chatId == chatId).Max();
|
||||
report.result = result;
|
||||
db.SaveChanges();
|
||||
|
||||
@params.Message = "Оставьте несколько слов о прошедшем дне😌";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Пропустить", "Пропустить", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectReportCcalCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Reports
|
||||
{
|
||||
public class SelectReportRateCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectReportRate-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int rate = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
|
||||
db.Reports.Add(new Data.Reports()
|
||||
{
|
||||
chatId = chatId,
|
||||
rate = rate,
|
||||
datetime = DateTime.Now
|
||||
});
|
||||
db.SaveChanges();
|
||||
|
||||
@params.Message = "Ваша дневная норма: " + user.kkal + " ккал.\n" +
|
||||
"Справились?";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Меньше", "selectReportCcal-2", KeyboardButtonColor.Primary)
|
||||
.AddButton("Норма", "selectReportCcal-1", KeyboardButtonColor.Positive)
|
||||
.AddButton("Больше", "selectReportCcal-3", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectReportRateCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
229
SvetoforVKBot/Models/Commands/LK/SelectDayFoodCommand.cs
Normal file
229
SvetoforVKBot/Models/Commands/LK/SelectDayFoodCommand.cs
Normal file
@@ -0,0 +1,229 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using Newtonsoft.Json;
|
||||
using VkNet.Enums.Filters;
|
||||
using VkNet.Model.Attachments;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using SvetoforVKBot.Models.Dop;
|
||||
using SvetoforVKBot.Models.Commands;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK
|
||||
{
|
||||
public class SelectDayFoodCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectDayFood\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
var keyboardBuilder2 = new KeyboardBuilder().Clear();
|
||||
DateTime dt = DateTime.Now.AddHours(0);
|
||||
List<OrderLog> orders = new List<OrderLog>();
|
||||
string highWorkload = "0";
|
||||
List<int> ids = new List<int>();
|
||||
List<int> ids2 = new List<int>();
|
||||
List<int> idsFood = new List<int>();
|
||||
List<UserObject> waterNotifiesList = new List<UserObject>();
|
||||
string msg = "";
|
||||
|
||||
string name = "";
|
||||
int age = 0;
|
||||
int genderCoef = 0;
|
||||
double kkalResult = 0;
|
||||
double colorPercent = 0;
|
||||
double dayCoef = 0;
|
||||
double curDayKkal = 0;
|
||||
double kkalResultLow = 0;
|
||||
double kkalResultHigh = 0;
|
||||
try
|
||||
{
|
||||
switch (DateTime.Now.DayOfWeek)
|
||||
{
|
||||
case DayOfWeek.Saturday:
|
||||
case DayOfWeek.Sunday:
|
||||
keyboardBuilder
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
@params.Message = "Рекомендации по дневному меню доступны с понедельника по пятницу.\n" +
|
||||
"Чтобы вернуться в Личный кабинет, нажмите кнопку \"Назад\"";
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
return;
|
||||
}
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.choosenProducts = "[]";
|
||||
user.cart = "{\"orders\":[]}";
|
||||
db.SaveChanges();
|
||||
|
||||
|
||||
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
|
||||
tracks.Add(1, "Оптимизация питания");
|
||||
tracks.Add(2, "Снижение жировой массы");
|
||||
tracks.Add(3, "Увеличение мышечной массы");
|
||||
tracks.Add(4, "Персональный режим");
|
||||
|
||||
keyboardBuilder.Clear();
|
||||
|
||||
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
|
||||
|
||||
if ((DateTime.Now.Month >= user.birthday.Month) && (DateTime.Now.Day >= user.birthday.Day))
|
||||
age = DateTime.Now.Year - user.birthday.Year;
|
||||
else
|
||||
age = DateTime.Now.Year - user.birthday.Year - 1;
|
||||
|
||||
#region ccalCalculator
|
||||
Dictionary<int, string> days = new Dictionary<int, string>(7);
|
||||
days.Add(1, "Понедельник");
|
||||
days.Add(2, "Вторник");
|
||||
days.Add(3, "Среда");
|
||||
days.Add(4, "Четверг");
|
||||
days.Add(5, "Пятница");
|
||||
days.Add(6, "Суббота");
|
||||
days.Add(7, "Воскресенье");
|
||||
|
||||
Dictionary<int, string> gend = new Dictionary<int, string>(3);
|
||||
gend.Add(0, "Мужской");
|
||||
gend.Add(1, "Мужской");
|
||||
gend.Add(2, "Женский");
|
||||
|
||||
int curDay = (int)DateTime.Now.DayOfWeek;
|
||||
if (curDay == 0) curDay = 7;
|
||||
|
||||
int nextDay = curDay + 1;
|
||||
|
||||
if (nextDay == 8)
|
||||
nextDay = 1;
|
||||
|
||||
//if (weight == 0 || height == 0)
|
||||
//{
|
||||
// keyboardBuilder
|
||||
// .AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
|
||||
// .AddLine()
|
||||
// .AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
// @params.Message = "Не хватает данных о росте/весе.\n" +
|
||||
// "Нажмите \"📝Редактировать данные\" и заполните показатели.";
|
||||
|
||||
// @params.Keyboard = keyboardBuilder.Build();
|
||||
// @params.UserId = chatId;
|
||||
// @params.RandomId = GetRandomId();
|
||||
// client.Messages.SendAsync(@params);
|
||||
// return;
|
||||
//}
|
||||
|
||||
|
||||
if (user.gender == 1)
|
||||
{
|
||||
genderCoef = 5;
|
||||
}
|
||||
else
|
||||
{
|
||||
genderCoef = -161;
|
||||
}
|
||||
switch (user.track)
|
||||
{
|
||||
case 1: //не изменяя веса
|
||||
colorPercent = 1;
|
||||
break;
|
||||
case 2:
|
||||
colorPercent = 0.75; //1 - 15%
|
||||
break;
|
||||
case 3:
|
||||
colorPercent = 1.2; //1 - 15%
|
||||
break;
|
||||
default:
|
||||
colorPercent = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
for (int i = 1; i <= 7; i++)
|
||||
{
|
||||
switch (i)
|
||||
{
|
||||
case 2:
|
||||
dayCoef = 0.8;
|
||||
break;
|
||||
|
||||
case 3:
|
||||
dayCoef = 1.2;
|
||||
break;
|
||||
|
||||
case 5:
|
||||
dayCoef = 0.9;
|
||||
break;
|
||||
|
||||
case 6:
|
||||
dayCoef = 1.1;
|
||||
break;
|
||||
|
||||
default:
|
||||
dayCoef = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
kkalResult = Math.Round((((10 * user.weight) + (6.25 * user.height) - (5 * age) + genderCoef) * user.activityCoef) * colorPercent * dayCoef);
|
||||
kkalResultHigh = Math.Round(kkalResult * 1.2);
|
||||
kkalResultLow = Math.Round(kkalResult * 0.9);
|
||||
|
||||
if (i == curDay)
|
||||
//if (i == curDay)
|
||||
{
|
||||
curDayKkal = kkalResult;
|
||||
}
|
||||
}
|
||||
#endregion ccalCalculator
|
||||
|
||||
|
||||
//@params.Message = "🌙Добрый вечер!\n" +
|
||||
// $"Ваша норма калорий на завтра: {Math.Round(curDayKkal * 0.9)} - {Math.Round(curDayKkal * 1.2)}\n" +
|
||||
// "Мы подготовили для Вас блюда👇🏻";
|
||||
@params.Message = //"☀Доброе утро!\n" +
|
||||
$"Ваша норма калорий на сегодня: {Math.Round(curDayKkal * 0.9)} - {Math.Round(curDayKkal * 1.2)}\n" +
|
||||
$"Мы подготовили для Вас блюда👇🏻\n\n";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton($"Завтрак (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-1-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton($"Обед (до {Math.Round(curDayKkal * 1.2 * 0.4)} ккал)", "selectPersonalMenu-2-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton($"Перекус (до {Math.Round(curDayKkal * 1.2 * 0.1)} ккал)", "selectPersonalMenu-3-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton($"Ужин (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-4-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
|
||||
//.SetInline();
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
Thread.Sleep(1500);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectParticipateCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
453
SvetoforVKBot/Models/Commands/LK/SelectEditDataCommand.cs
Normal file
453
SvetoforVKBot/Models/Commands/LK/SelectEditDataCommand.cs
Normal file
@@ -0,0 +1,453 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using Newtonsoft.Json;
|
||||
using VkNet.Enums.Filters;
|
||||
using VkNet.Model.Attachments;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using SvetoforVKBot.Models.Dop;
|
||||
using SvetoforVKBot.Models.Commands;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK
|
||||
{
|
||||
public class SelectEditDataCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectEditData-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string tag = "";
|
||||
string msgSports = "";
|
||||
string strSportKind = "";
|
||||
string sportName = "";
|
||||
try
|
||||
{
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.tag = "Личный кабинет - Данные";
|
||||
db.SaveChanges();
|
||||
|
||||
Dictionary<int, string> colors = new Dictionary<int, string>(3);
|
||||
colors.Add(1, "🟩"); //З
|
||||
colors.Add(2, "🟦"); //C
|
||||
colors.Add(3, "🟨"); //Ж
|
||||
|
||||
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
|
||||
tracks.Add(1, "Оптимизация питания");
|
||||
tracks.Add(2, "Снижение жировой массы");
|
||||
tracks.Add(3, "Увеличение мышечной массы");
|
||||
tracks.Add(4, "Персональный режим");
|
||||
|
||||
Dictionary<int, string> notifies = new Dictionary<int, string>(4);
|
||||
notifies.Add(1, "1 раз в день");
|
||||
notifies.Add(3, "3 раза в день");
|
||||
notifies.Add(4, "Более 3х раз в день");
|
||||
notifies.Add(0, "Никогда");
|
||||
|
||||
int weight = user.weight;
|
||||
int height = user.height;
|
||||
int gender = user.gender;
|
||||
int notifyCount = user.notifyCount;
|
||||
string fio = user.fio;
|
||||
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
|
||||
var birthday = user.birthday;
|
||||
int track = user.track;
|
||||
int waterNotify = user.waterNotify;
|
||||
int activityKind = user.activityKind;
|
||||
int sportId = user.sportId;
|
||||
|
||||
|
||||
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("⚖Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
|
||||
.AddButton("📐Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("🔔Уведомления", "selectEditData-3", KeyboardButtonColor.Primary)
|
||||
.AddButton("✏ФИО", "selectEditData-4", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("📅Дата рождения", "selectEditData-5", KeyboardButtonColor.Primary)
|
||||
.AddButton("📞Телефон", "selectEditData-6", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Режим питания", "selectEditData-7", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Вид спорта/активности", "selectEditData-8", KeyboardButtonColor.Primary)
|
||||
.AddLine();
|
||||
|
||||
if (activityKind == 0 || activityKind == 3)
|
||||
msgSports = "Ничем не занимаюсь";
|
||||
else
|
||||
{
|
||||
msgSports = "";
|
||||
|
||||
var sport = db.SportKinds.Single(s => s.id == sportId);
|
||||
sportName = sport.name;
|
||||
int sportKind = sport.kind;
|
||||
|
||||
if (sportKind == 1) strSportKind = sportName + " (Спорт)";
|
||||
else strSportKind = sportName + " (Физ. активность)";
|
||||
|
||||
}
|
||||
|
||||
if (waterNotify == 1)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton("✅Напоминания о воде", "selectOffWaterNotify", KeyboardButtonColor.Positive);
|
||||
}
|
||||
else
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton("⛔Напоминания о воде", "selectGoWaterNotify", KeyboardButtonColor.Negative);
|
||||
}
|
||||
|
||||
keyboardBuilder
|
||||
.AddLine()
|
||||
.AddButton("Готово", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Message = "РЕДАКТИРОВАНИЕ ДАННЫХ" +
|
||||
"\n\n" +
|
||||
"ФИО: " + fio +
|
||||
"\n" +
|
||||
"Телефон: " + jsPhones[0] +
|
||||
"\n" +
|
||||
"Дата рождения: " + birthday.ToShortDateString() +
|
||||
"\n" +
|
||||
"Рост: " + height + " см" +
|
||||
"\n" +
|
||||
"Вес: " + weight + " кг" +
|
||||
"\n" +
|
||||
colors[track] + "Выбранный трек: " + tracks[track] +
|
||||
"\n" +
|
||||
"Уведомления: " + notifies[notifyCount] +
|
||||
"\n" +
|
||||
$"Вид спорта/активности: {msgSports}{strSportKind}" +
|
||||
"\n\n" +
|
||||
"Выберите на клавиатуре показатель, который хотите изменить или нажмите \"Готово\"👇🏻";
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectEditDataCommand.Execute: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string tag = "";
|
||||
int startYear = DateTime.Now.Year - 18;
|
||||
int i = 0;
|
||||
int btnCount = 0;
|
||||
int btnLines = 0;
|
||||
string msgSports = "";
|
||||
string strSportKind = "";
|
||||
string sportName = "";
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int curOption = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
Dictionary<int, string> notifies = new Dictionary<int, string>(4);
|
||||
notifies.Add(1, "1 раз в день");
|
||||
notifies.Add(3, "3 раза в день");
|
||||
notifies.Add(4, "Более 3х раз в день");
|
||||
notifies.Add(0, "Никогда");
|
||||
|
||||
Dictionary<int, string> colors = new Dictionary<int, string>(3);
|
||||
colors.Add(1, "🟩"); //З
|
||||
colors.Add(2, "🟦"); //C
|
||||
colors.Add(3, "🟨"); //Ж
|
||||
|
||||
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
|
||||
tracks.Add(1, "Оптимизация питания");
|
||||
tracks.Add(2, "Снижение жировой массы");
|
||||
tracks.Add(3, "Увеличение мышечной массы");
|
||||
tracks.Add(4, "Персональный режим");
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
int weight = user.weight;
|
||||
int height = user.height;
|
||||
int gender = user.gender;
|
||||
int notifyCount = user.notifyCount;
|
||||
string fio = user.fio;
|
||||
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
|
||||
var birthday = user.birthday;
|
||||
int track = user.track;
|
||||
int waterNotify = user.waterNotify;
|
||||
int activityKind = user.activityKind;
|
||||
int sportId = user.sportId;
|
||||
|
||||
|
||||
switch (curOption)
|
||||
{
|
||||
case 0:
|
||||
tag = "Личный кабинет - Данные";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("⚖Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
|
||||
.AddButton("📐Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("🔔Уведомления", "selectEditData-3", KeyboardButtonColor.Primary)
|
||||
.AddButton("✏ФИО", "selectEditData-4", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("📅Дата рождения", "selectEditData-5", KeyboardButtonColor.Primary)
|
||||
.AddButton("📞Телефон", "selectEditData-6", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Режим питания", "selectEditData-7", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Вид спорта/активности", "selectEditData-8", KeyboardButtonColor.Primary)
|
||||
.AddLine();
|
||||
|
||||
if (activityKind == 0)
|
||||
msgSports = "Ничем не занимаюсь";
|
||||
else
|
||||
{
|
||||
msgSports = "";
|
||||
|
||||
var sport = db.SportKinds.Single(s => s.id == sportId);
|
||||
sportName = sport.name;
|
||||
int sportKind = sport.kind;
|
||||
|
||||
if (sportKind == 1) strSportKind = sportName + " (Спорт)";
|
||||
else strSportKind = sportName + " (Физ. активность)";
|
||||
|
||||
}
|
||||
|
||||
if (waterNotify >= 1 && waterNotify != 10)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton("✅Напоминания о воде", "selectOffWaterNotify", KeyboardButtonColor.Positive);
|
||||
}
|
||||
else
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton("⛔Напоминания о воде", "selectGoWaterNotify", KeyboardButtonColor.Negative);
|
||||
}
|
||||
|
||||
keyboardBuilder
|
||||
.AddLine()
|
||||
.AddButton("Готово", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Message = "РЕДАКТИРОВАНИЕ ДАННЫХ" +
|
||||
"\n\n" +
|
||||
"ФИО: " + fio +
|
||||
"\n" +
|
||||
"Телефон: " + jsPhones[0] +
|
||||
"\n" +
|
||||
"Дата рождения: " + birthday.ToShortDateString() +
|
||||
"\n" +
|
||||
"Рост: " + height + " см" +
|
||||
"\n" +
|
||||
"Вес: " + weight + " кг" +
|
||||
"\n" +
|
||||
colors[track] + "Выбранный трек: " + tracks[track] +
|
||||
"\n" +
|
||||
"Уведомления: " + notifies[notifyCount] +
|
||||
"\n" +
|
||||
$"Вид спорта/активности: {msgSports}{strSportKind}" +
|
||||
"\n\n" +
|
||||
"Выберите на клавиатуре показатель, который хотите изменить или нажмите \"Готово\"👇🏻";
|
||||
|
||||
break;
|
||||
|
||||
case 1:
|
||||
tag = "Личный кабинет - Изменить вес";
|
||||
|
||||
keyboardBuilder
|
||||
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Message = "Введите свой вес в кг. Например, 65.\n\n" +
|
||||
"⚠ Лучшее время для измерения веса - утро. Взвешиваться следует после утренних процедур и до приёма пищи."; //❕
|
||||
|
||||
break;
|
||||
|
||||
case 2:
|
||||
tag = "Личный кабинет - Изменить рост";
|
||||
|
||||
keyboardBuilder
|
||||
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Message = "Введите свой рост в см. Например, 168.";
|
||||
|
||||
break;
|
||||
|
||||
case 3:
|
||||
tag = "Личный кабинет - Уведомления";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Раз в день", "selectEditNotifyCount-1", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Три раза в день", "selectEditNotifyCount-3", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Более 3х раз", "selectEditNotifyCount-4", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Никогда", "selectEditNotifyCount-0", KeyboardButtonColor.Default)
|
||||
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Message = "Как часто Вы готовы получать напоминания от чат-бота?\n\n" +
|
||||
"Вы будете получать уведомления о приёмах пищи и воды. Если Вы хотите сформировать привычку " +
|
||||
"по режиму питания или употреблению достаточного количества воды, выберите вариант \"Более 3х раз\".\n" +
|
||||
"Наш чат-бот не будет рассылать рекламу или спам. Только персональные уведомления и рекомендации по здоровому питанию.";
|
||||
|
||||
break;
|
||||
|
||||
case 4:
|
||||
tag = "Личный кабинет - ФИО";
|
||||
|
||||
keyboardBuilder
|
||||
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Message = "Введите фамилию, имя и отчество одним сообщением.\n\nНапример: Иванов Иван Иванович";
|
||||
|
||||
break;
|
||||
|
||||
case 5:
|
||||
tag = "Личный кабинет - ДР - Год";
|
||||
@params.Message = "Выберите на клавиатуре внизу или введите свой год рождения, например 1993. \n";
|
||||
|
||||
for (i = startYear; i > startYear - 20; i--)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton(i.ToString(), i.ToString(), KeyboardButtonColor.Primary);
|
||||
|
||||
btnCount++;
|
||||
|
||||
if (btnCount % 4 == 0)
|
||||
{
|
||||
btnLines++;
|
||||
keyboardBuilder.AddLine();
|
||||
}
|
||||
}
|
||||
|
||||
if (btnCount % 4 != 0)
|
||||
{
|
||||
keyboardBuilder.AddLine();
|
||||
}
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder
|
||||
.Build();
|
||||
break;
|
||||
|
||||
case 6:
|
||||
tag = "Личный кабинет - Телефон";
|
||||
|
||||
|
||||
keyboardBuilder
|
||||
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Message = "Напишите номер телефона в формате 11 цифр через \"8\" или \"7\" \n";
|
||||
|
||||
break;
|
||||
|
||||
case 7:
|
||||
tag = "Личный кабинет - Режим питания";
|
||||
|
||||
//SqlCommand editTrack = new SqlCommand("UPDATE Users SET track = @track WHERE chatId = @chatId;", Con);
|
||||
//editTrack.Parameters.AddWithValue("@chatId", chatId);
|
||||
//editTrack.Parameters.AddWithValue("@track", 0);
|
||||
//editTrack.ExecuteNonQuery();
|
||||
|
||||
@params.Message = "Выберите желаемый трек оптимизации питания👇🏻";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("🟩Оптимизация питания", "selectTrack-1", KeyboardButtonColor.Primary) //З🟩
|
||||
.AddLine()
|
||||
.AddButton("🟦Снижение жировой массы", "selectTrack-2", KeyboardButtonColor.Primary) //С🟦
|
||||
.AddLine()
|
||||
.AddButton("🟨Увеличение мыш. массы", "selectTrack-3", KeyboardButtonColor.Primary) //Ж🟨
|
||||
.AddLine()
|
||||
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
|
||||
//keyboardBuilder
|
||||
// //.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
|
||||
// //.AddLine()
|
||||
// //.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
|
||||
// //.AddLine()
|
||||
// .AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
|
||||
|
||||
|
||||
break;
|
||||
|
||||
case 8:
|
||||
tag = "Личный кабинет - Вид спорта";
|
||||
|
||||
@params.Message = "Вы заниматесь спортом или физкультурой?\n" +
|
||||
"Выберите на клавиатуре вариант, который наиболее точно описывает Ваш образ жизни.\n\n" +
|
||||
"👉🏻 Если Вы профессионально занимаетесь спортом или Ваша работа связана с тяжёлым физическим трудом, выберите вариант \"Занимаюсь спортом\"\n" +
|
||||
"👉🏻 Если Вы не занимаетесь спортом профессионально, но регулярно поддерживаете физическую активность (занятия физкультурой), выберите вариант \"Занимаюсь физкультурой\"\n" +
|
||||
"👉🏻 Если у Вас сидячая работа или нерегулярная физическая активность (менее одного раза в неделю), выберите вариант \"Ничем не занимаюсь\".\n";
|
||||
keyboardBuilder
|
||||
.AddButton("Занимаюсь спортом", "selectActivityKind-1", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Занимаюсь физкультурой", "selectActivityKind-2", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Ничем не занимаюсь", "selectActivityKind-3", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
|
||||
|
||||
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
user.tag = tag;
|
||||
db.SaveChanges();
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectEditDataCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.RegularExpressions;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Attachments;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK
|
||||
{
|
||||
public class SelectPersonalPlanCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectPersonalPlan\"}";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
List<UserObject> users = new List<UserObject>();
|
||||
List<int> chatIds = new List<int>();
|
||||
string name = "";
|
||||
try
|
||||
{
|
||||
@params.Message = "Ваш персональный план:\n";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "Ошибка в SelectPersonalPlanCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
214
SvetoforVKBot/Models/Commands/LK/ShowLKCommand.cs
Normal file
214
SvetoforVKBot/Models/Commands/LK/ShowLKCommand.cs
Normal file
@@ -0,0 +1,214 @@
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.RegularExpressions;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Attachments;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK
|
||||
{
|
||||
public class ShowLKCommand
|
||||
{
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
List<StackObject> techStack = new List<StackObject>();
|
||||
string msg = "";
|
||||
int age = 0;
|
||||
string genderStr = "";
|
||||
double indexMT = 0;
|
||||
string IMT = "";
|
||||
double kkalLow = 0;
|
||||
double kkalHigh = 0;
|
||||
try
|
||||
{
|
||||
msg = "📌Личный кабинет\n";
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.tag = "Личный кабинет";
|
||||
user.day = 0;
|
||||
user.colorId = 0;
|
||||
db.SaveChanges();
|
||||
|
||||
msg += user.fio + "\n\n";
|
||||
|
||||
if ((DateTime.Now.Month >= user.birthday.Month) && (DateTime.Now.Day >= user.birthday.Day))
|
||||
age = DateTime.Now.Year - user.birthday.Year;
|
||||
else
|
||||
age = DateTime.Now.Year - user.birthday.Year - 1;
|
||||
|
||||
Dictionary<int, string> colors = new Dictionary<int, string>(3);
|
||||
colors.Add(1, "🟩"); //З
|
||||
colors.Add(2, "🟦"); //C
|
||||
colors.Add(3, "🟨"); //Ж
|
||||
|
||||
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
|
||||
tracks.Add(1, "Оптимизация питания");
|
||||
tracks.Add(2, "Снижение жировой массы");
|
||||
tracks.Add(3, "Увеличение мышечной массы");
|
||||
tracks.Add(4, "Персональный режим");
|
||||
|
||||
//if (personal == 1)
|
||||
//{
|
||||
// keyboardBuilder
|
||||
// .AddButton("✅Персональный режим", "selectPersonalPlan", KeyboardButtonColor.Positive)
|
||||
// .AddLine();
|
||||
//}
|
||||
|
||||
if (user.track == 0)
|
||||
{
|
||||
msg += "Выберите желаемый трек оптимизации питания👇🏻";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("🟩Оптимизация питания", "selectTrack-1", KeyboardButtonColor.Primary) //З🟩
|
||||
.AddLine()
|
||||
.AddButton("🟦Снижение жировой массы", "selectTrack-2", KeyboardButtonColor.Primary) //С🟦
|
||||
.AddLine()
|
||||
.AddButton("🟨Увеличение мыш. массы", "selectTrack-3", KeyboardButtonColor.Primary) //Ж🟨
|
||||
.AddLine()
|
||||
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (user.gender == 1)
|
||||
genderStr = "Мужчина";
|
||||
else
|
||||
genderStr = "Женщина";
|
||||
|
||||
if (user.weight != 0 && user.height != 0)
|
||||
{
|
||||
indexMT = Math.Round(user.weight / (double)(user.height / 100.0 * user.height / 100.0), 1);
|
||||
IMT = "Индекс массы тела: " + indexMT + " кг/м2 \n";
|
||||
if (indexMT < 18.5)
|
||||
IMT += "🔴 Дефицит" + "\n" +
|
||||
"Риск сопутствующих заболеваний: Низкий (повышен риск других заболеваний)";
|
||||
else if (indexMT >= 18.5 && indexMT < 25)
|
||||
IMT += "✅ Норма" + "\n" +
|
||||
"Риск сопутствующих заболеваний: Обычный";
|
||||
else if (indexMT >= 25 && indexMT < 30)
|
||||
IMT += "⚠ Избыточная масса тела" + "\n" +
|
||||
"Риск сопутствующих заболеваний: Повышенный";
|
||||
else if (indexMT >= 30 && indexMT < 35)
|
||||
IMT += "🔴 Ожирение I степени" + "\n" +
|
||||
"Риск сопутствующих заболеваний: Высокий";
|
||||
else if (indexMT >= 35 && indexMT < 40)
|
||||
IMT += "🔴 Ожирение II степени" + "\n" +
|
||||
"Риск сопутствующих заболеваний: Очень высокий";
|
||||
else
|
||||
IMT += "🔴 Ожирение III степени" + "\n" +
|
||||
"Риск сопутствующих заболеваний: Чрезвычайно высокий";
|
||||
}
|
||||
else
|
||||
{
|
||||
IMT = "⚠Индекс массы тела: не рассчитан (укажите рост и вес в разделе \"Редактировать данные\").";
|
||||
}
|
||||
msg += "🧬Показатели здоровья\n" +
|
||||
"Вес: " + user.weight + " кг" +
|
||||
"\n" +
|
||||
"Рост: " + user.height + " см" +
|
||||
"\n" +
|
||||
"Возраст: " + age +
|
||||
"\n" +
|
||||
"Пол: " + genderStr +
|
||||
"\n\n" +
|
||||
IMT +
|
||||
"\n\n";
|
||||
if (user.kkal != 0)
|
||||
{
|
||||
kkalLow = Math.Round(user.kkal * 0.9);
|
||||
kkalHigh = Math.Round(user.kkal * 1.2);
|
||||
msg += $"Норма на сегодня: {kkalLow}-{kkalHigh} ккал";
|
||||
}
|
||||
else
|
||||
msg += "⚠Норма ккал на сегодня: не рассчитана (воспользуйтесь калькулятором калорий).";
|
||||
|
||||
if (user.kkal == 0 || user.height == 0 || user.weight == 0)
|
||||
{
|
||||
keyboardBuilder
|
||||
//.AddButton("📊Отправить отчёт", "selectCreateReport", KeyboardButtonColor.Positive)
|
||||
//.AddLine()
|
||||
.AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Positive)
|
||||
.AddLine()
|
||||
.AddButton("🧮Калькулятор калорий", "selectCalcCcalResult-" + user.track, KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("⭐Рекомендации", "selectTrack-" + user.track, KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
//.AddButton("⭐Идеальный вес", "selectIdealWeight", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
//.AddButton("📈Набор мышечной массы", "selectCalculatorCcal", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
//.AddButton("📋Меню", "selectMenu-0", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
.AddButton("💬Есть вопрос?", "selectConsultation", KeyboardButtonColor.Primary); //✏
|
||||
}
|
||||
else
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton("📊Отправить отчёт", "selectCreateReport", KeyboardButtonColor.Positive)
|
||||
.AddLine()
|
||||
.AddButton("🥗Дневной рацион", "selectDayFood", KeyboardButtonColor.Positive)
|
||||
.AddLine()
|
||||
.AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("🧮Калькулятор калорий", "selectCalcCcalResult-" + user.track, KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("⭐Рекомендации", "selectTrack-" + user.track, KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
//.AddButton("⭐Идеальный вес", "selectIdealWeight", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
//.AddButton("📈Набор мышечной массы", "selectCalculatorCcal", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
//.AddButton("📋Меню", "selectMenu-0", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
.AddButton("💬Есть вопрос?", "selectConsultation", KeyboardButtonColor.Primary); //✏
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (chatId == 59111081 || chatId == 10160301 || chatId == 369217524 || chatId == 178385801)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddLine()
|
||||
.AddButton("Администратору", "selectAdminMenu", KeyboardButtonColor.Default);
|
||||
}
|
||||
|
||||
@params.Message = msg;
|
||||
@params.UserId = chatId;
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в ShowLKCommnad: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
private int GetRandomId()
|
||||
{
|
||||
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
126
SvetoforVKBot/Models/Commands/LK/SportsLK/ShowSportsLKCommand.cs
Normal file
126
SvetoforVKBot/Models/Commands/LK/SportsLK/ShowSportsLKCommand.cs
Normal file
@@ -0,0 +1,126 @@
|
||||
using Newtonsoft.Json;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.RegularExpressions;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Attachments;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.SportsLK
|
||||
{
|
||||
public class ShowSportsLKCommand
|
||||
{
|
||||
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
var chatId = update.@object.message.from_id;
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
List<StackObject> techStack = new List<StackObject>();
|
||||
string msg = "";
|
||||
int age = 0;
|
||||
string genderStr = "";
|
||||
double indexMT = 0;
|
||||
string IMT = "";
|
||||
try
|
||||
{
|
||||
msg = "📌Личный кабинет\n";
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.tag = "Личный кабинет";
|
||||
user.day = 0;
|
||||
user.colorId = 0;
|
||||
db.SaveChanges();
|
||||
|
||||
//SqlCommand getUser = new SqlCommand("SELECT * FROM Users WHERE chatId = @chatId;", Con);
|
||||
//getUser.Parameters.AddWithValue("@chatId", chatId);
|
||||
//SqlDataReader rgetUser = getUser.ExecuteReader();
|
||||
//rgetUser.Read();
|
||||
//string fio = rgetUser["fio"].ToString();
|
||||
//int weight = Convert.ToInt32(rgetUser["weight"]);
|
||||
//int height = Convert.ToInt32(rgetUser["height"]);
|
||||
//int gender = Convert.ToInt32(rgetUser["gender"]);
|
||||
//var birthday = DateTime.Parse(rgetUser["birthday"].ToString());
|
||||
//int kkal = Convert.ToInt32(rgetUser["kkal"]);
|
||||
//rgetUser.Close();
|
||||
|
||||
msg += user.fio + "\n\n";
|
||||
|
||||
age = (DateTime.Today.Year - user.birthday.Year);
|
||||
|
||||
if (user.gender == 1)
|
||||
genderStr = "Мужчина";
|
||||
else
|
||||
genderStr = "Женщина";
|
||||
|
||||
msg += "🧬Показатели здоровья\n" +
|
||||
"Вес: " + user.weight + " кг" +
|
||||
"\n" +
|
||||
"Рост: " + user.height + " см" +
|
||||
"\n" +
|
||||
"Возраст: " + age +
|
||||
"\n" +
|
||||
"Пол: " + genderStr +
|
||||
"\n\n" +
|
||||
IMT +
|
||||
"\n\n";
|
||||
|
||||
if (user.kkal != 0)
|
||||
msg += "Норма ккал на сегодня: " + user.kkal;
|
||||
else
|
||||
msg += "Норма ккал на сегодня: не рассчитана";
|
||||
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("📊Отправить отчёт", "selectCreateReport", KeyboardButtonColor.Positive)
|
||||
.AddLine()
|
||||
.AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("📈Набор мышечной массы", "selectCalculatorCcal", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("📋Меню", "selectMenu-0", KeyboardButtonColor.Primary)
|
||||
//.AddLine()
|
||||
.AddButton("💬Консультация", "selectConsultation", KeyboardButtonColor.Primary); //✏
|
||||
|
||||
if (chatId == 59111081)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddLine()
|
||||
.AddButton("Администратору", "selectAdminMenu", KeyboardButtonColor.Default);
|
||||
}
|
||||
|
||||
@params.Message = msg;
|
||||
@params.UserId = chatId;
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в ShowSportsLKCommnad: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
|
||||
private int GetRandomId()
|
||||
{
|
||||
|
||||
var intBytes = new byte[4];
|
||||
|
||||
Rng.GetBytes(intBytes);
|
||||
|
||||
return BitConverter.ToInt32(intBytes, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using Newtonsoft.Json;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Tracks
|
||||
{
|
||||
public class SelectChooseTrackCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectChooseTrack-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
int age = 0;
|
||||
int genderCoef = 0;
|
||||
double kkalResult = 0;
|
||||
double colorPercent = 0;
|
||||
double dayCoef = 0;
|
||||
double curDayKkal = 0;
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int track = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
Dictionary<int, string> colors = new Dictionary<int, string>(3);
|
||||
colors.Add(1, "🟩"); //З
|
||||
colors.Add(2, "🟦"); //C
|
||||
colors.Add(3, "🟨"); //Ж
|
||||
|
||||
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
|
||||
tracks.Add(1, "Оптимизация питания");
|
||||
tracks.Add(2, "Снижение жировой массы");
|
||||
tracks.Add(3, "Увеличение мышечной массы");
|
||||
tracks.Add(4, "Персональный режим");
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
user.track = track;
|
||||
db.SaveChanges();
|
||||
|
||||
/*
|
||||
SqlCommand getUser = new SqlCommand("SELECT * FROM Users WHERE chatId = @chatId;", Con);
|
||||
getUser.Parameters.AddWithValue("@chatId", chatId);
|
||||
SqlDataReader rgetUser = getUser.ExecuteReader();
|
||||
rgetUser.Read();
|
||||
string fio = rgetUser["fio"].ToString();
|
||||
int weight = Convert.ToInt32(rgetUser["weight"]);
|
||||
int height = Convert.ToInt32(rgetUser["height"]);
|
||||
int gender = Convert.ToInt32(rgetUser["gender"]);
|
||||
var birthday = DateTime.Parse(rgetUser["birthday"].ToString());
|
||||
var activityCoef = Convert.ToDouble(rgetUser["activityCoef"]);
|
||||
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(rgetUser["sportDays"].ToString());
|
||||
rgetUser.Close();
|
||||
age = (DateTime.Today.Year - birthday.Year);
|
||||
*/
|
||||
|
||||
|
||||
@params.Message = $"{colors[track]} Вы выбрали трек {tracks[track]}! В личном кабинете для Вас доступны рекомендации и калькулятор калорий.";
|
||||
|
||||
//keyboardBuilder
|
||||
// .AddButton("💬Консультация", "selectLiveConsultation", KeyboardButtonColor.Primary)
|
||||
// .AddLine()
|
||||
// //.AddButton(cons, "selectGotConsultation", KeyboardButtonColor.Primary)
|
||||
// //.AddLine()
|
||||
// .AddButton("Назад", "selectCalculatorCcal", KeyboardButtonColor.Default);
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Positive);
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectChooseTrackCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using Newtonsoft.Json;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Tracks
|
||||
{
|
||||
public class SelectExampleMenuCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectExampleMenu-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
int age = 0;
|
||||
int genderCoef = 0;
|
||||
double kkalResult = 0;
|
||||
double colorPercent = 0;
|
||||
double dayCoef = 0;
|
||||
double curDayKkal = 0;
|
||||
double kkalResultLow = 0;
|
||||
double kkalResultHigh = 0;
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int track = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
Dictionary<int, string> colors = new Dictionary<int, string>(3);
|
||||
colors.Add(1, "🟩"); //З
|
||||
colors.Add(2, "🟦"); //C
|
||||
colors.Add(3, "🟨"); //Ж
|
||||
|
||||
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
|
||||
tracks.Add(1, "Оптимизация питания");
|
||||
tracks.Add(2, "Снижение жировой массы");
|
||||
tracks.Add(3, "Увеличение мышечной массы");
|
||||
tracks.Add(4, "Персональный режим");
|
||||
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(user.sportDays);
|
||||
|
||||
//SqlCommand getUser = new SqlCommand("SELECT * FROM Users WHERE chatId = @chatId;", Con);
|
||||
//getUser.Parameters.AddWithValue("@chatId", chatId);
|
||||
//SqlDataReader rgetUser = getUser.ExecuteReader();
|
||||
//rgetUser.Read();
|
||||
////string fio = rgetUser["fio"].ToString();
|
||||
//int choosenTrack = Convert.ToInt32(rgetUser["track"]);
|
||||
//int height = Convert.ToInt32(rgetUser["height"]);
|
||||
//int weight = Convert.ToInt32(rgetUser["weight"]);
|
||||
//int gender = Convert.ToInt32(rgetUser["gender"]); // 1 - М / 2 - Ж
|
||||
//var birthday = DateTime.Parse(rgetUser["birthday"].ToString());
|
||||
//var activityCoef = Convert.ToDouble(rgetUser["activityCoef"]);
|
||||
//List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(rgetUser["sportDays"].ToString());
|
||||
//rgetUser.Close();
|
||||
|
||||
//age = (DateTime.Today.Year - birthday.Year);
|
||||
|
||||
if ((DateTime.Now.Month >= user.birthday.Month) && (DateTime.Now.Day >= user.birthday.Day))
|
||||
age = DateTime.Now.Year - user.birthday.Year;
|
||||
else
|
||||
age = DateTime.Now.Year - user.birthday.Year - 1;
|
||||
|
||||
#region ccalCalculator
|
||||
Dictionary<int, string> days = new Dictionary<int, string>(7);
|
||||
days.Add(1, "Понедельник");
|
||||
days.Add(2, "Вторник");
|
||||
days.Add(3, "Среда");
|
||||
days.Add(4, "Четверг");
|
||||
days.Add(5, "Пятница");
|
||||
days.Add(6, "Суббота");
|
||||
days.Add(7, "Воскресенье");
|
||||
|
||||
Dictionary<int, string> gend = new Dictionary<int, string>(3);
|
||||
gend.Add(0, "Мужской");
|
||||
gend.Add(1, "Мужской");
|
||||
gend.Add(2, "Женский");
|
||||
|
||||
int curDay = (int)DateTime.Now.DayOfWeek;
|
||||
if (curDay == 0) curDay = 7;
|
||||
|
||||
if (user.weight == 0 || user.height == 0)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Message = "Не хватает данных о росте/весе.\n" +
|
||||
"Нажмите \"📝Редактировать данные\" и заполните показатели.";
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (user.gender == 1)
|
||||
{
|
||||
genderCoef = 5;
|
||||
}
|
||||
else
|
||||
{
|
||||
genderCoef = -161;
|
||||
}
|
||||
switch (track)
|
||||
{
|
||||
case 1: //не изменяя веса
|
||||
colorPercent = 1;
|
||||
break;
|
||||
case 2:
|
||||
colorPercent = 0.75; //1 - 15%
|
||||
break;
|
||||
case 3:
|
||||
colorPercent = 1.2; //1 - 15%
|
||||
break;
|
||||
default:
|
||||
colorPercent = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
for (int i = 1; i <= 7; i++)
|
||||
{
|
||||
switch (i)
|
||||
{
|
||||
case 2:
|
||||
dayCoef = 0.8;
|
||||
break;
|
||||
|
||||
case 3:
|
||||
dayCoef = 1.2;
|
||||
break;
|
||||
|
||||
case 5:
|
||||
dayCoef = 0.9;
|
||||
break;
|
||||
|
||||
case 6:
|
||||
dayCoef = 1.1;
|
||||
break;
|
||||
|
||||
default:
|
||||
dayCoef = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
kkalResult = Math.Round((((10 * user.weight) + (6.25 * user.height) - (5 * age) + genderCoef) * user.activityCoef) * colorPercent * dayCoef);
|
||||
kkalResultHigh = Math.Round(kkalResult * 1.2);
|
||||
kkalResultLow = Math.Round(kkalResult * 0.9);
|
||||
|
||||
if (i == curDay)
|
||||
{
|
||||
//@params.Message += $"⭐ {days[i]}: {kkalResultLow}-{kkalResultHigh} ккал\n";
|
||||
curDayKkal = kkalResult;
|
||||
}
|
||||
//else
|
||||
//@params.Message += $"{days[i]}: {kkalResultLow}-{kkalResultHigh} ккал\n";
|
||||
}
|
||||
#endregion ccalCalculator
|
||||
double belki_opt = 0;
|
||||
double zhiry_opt = 0;
|
||||
double uglevody_opt = 0;
|
||||
|
||||
switch (track)
|
||||
{
|
||||
case 1:
|
||||
//Распределение объема пищи в течение дня должно быть следующим: завтрак – 20-30%, обед – 30-40%, полдник – 5-10%, ужин – 20-30%.
|
||||
//В рационе питания должно быть на килограмм массы тела: белков 1,4-2,0 грамма, жиров 1,0-1,1 грамма и углеводов 2,4-3,0 грамма.
|
||||
@params.Message =
|
||||
"Примерное меню" +
|
||||
"\n\n" +
|
||||
$"Пол: {gend[user.gender]} | Возраст: {age}\n" +
|
||||
$"Рост: {user.height} см | Масса тела: {user.weight} кг\n\n" +
|
||||
//"Активность: низкая (1-3 тренировки в неделю)\n" +
|
||||
$"Рекомендуемая норма КБЖУ:\n" +
|
||||
$"Калории {curDayKkal*0.9} - {curDayKkal*1.2}\n" +
|
||||
$"Белки {user.weight *1.4}-{user.weight *2} грамм\n" +
|
||||
$"Жиры {user.weight}-{user.weight *1.1} грамм\n" +
|
||||
$"Углеводы {user.weight *2.4}-{user.weight *3} грамм\n\n" +
|
||||
$"Завтрак (Максимальное количество калорий {curDayKkal*0.3})\n" +
|
||||
$"Белки – {user.weight * 2 * 0.3}, Жиры - {user.weight * 1.1 * 0.3}, Углеводы – {user.weight *3 * 0.3}.\n" +
|
||||
$"Рисовая каша на молоке 310 грамм, яблоко 340 грамм, черный кофе без сахара 400 грамм\n\n" +
|
||||
$"Обед (Максимальное количество калорий {curDayKkal * 0.4})\n" +
|
||||
$"Белки – {user.weight * 2 * 0.4}, Жиры - {user.weight * 1.1 * 0.4}, Углеводы – {user.weight * 3 * 0.4}.\n" +
|
||||
$"Борщ 380 грамм, бифштекс классический 90 грамм, картофельное пюре 120 грамм, винегрет 140 грамм, морс 220 грамм\n\n" +
|
||||
$"Полдник (Максимальное количество калорий {curDayKkal * 0.1})\n" +
|
||||
$"Белки – {user.weight * 2 * 0.1}, Жиры - {user.weight * 1.1 * 0.1}, Углеводы – {user.weight * 3 * 0.1}.\n" +
|
||||
$"Творожная запеканка 130 грамм, сметана 20% 10 грамм, яйцо 80 грамм, апельсиновый сок 270 грамм\n\n" +
|
||||
$"Ужин (Максимальное количество калорий {curDayKkal * 0.2})\n" +
|
||||
$"Белки – {user.weight * 2 * 0.2}, Жиры - {user.weight * 1.1 * 0.2}, Углеводы – {user.weight * 3 * 0.2}.\n" +
|
||||
$"Минтай отварной 290 грамм, рис белый вареный 80 грамм, салат из белокочанной капусты с морковью 120 грамм, чай зеленый без сахара 150 грамм\n" +
|
||||
$"\n" +
|
||||
//$"Всего: Калории 2083, Белки 124, Жиры 75, Углеводы 208\n\n" +
|
||||
$"Блюда, рекомендованные для оптимизации питания, в комбинате общественного питания промаркированы зеленым цветом." +
|
||||
$"\n\n" +
|
||||
$"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
|
||||
break;
|
||||
|
||||
case 2:
|
||||
//Распределение объема пищи в течение дня должно быть следующим: завтрак – 20-30%, обед – 30-40%, полдник – 5-10%, ужин – 20-30%, второй завтрак (5-10%) и второй ужин (до 5%).
|
||||
//В рационе питания должно быть на килограмм массы тела: белков 1,2 - 1,7 грамма, жиров 0,9 - 1,0 грамма и углеводов 2,0 - 2,6 грамма.
|
||||
@params.Message =
|
||||
"Примерное меню" +
|
||||
"\n\n" +
|
||||
$"Пол: {gend[user.gender]} | Возраст: {age}\n" +
|
||||
$"Рост: {user.height} см | Масса тела: {user.weight} кг\n\n" +
|
||||
//"Активность: низкая (1-3 тренировки в неделю)\n" +
|
||||
$"Рекомендуемая норма КБЖУ:\n" +
|
||||
$"Калории {curDayKkal * 0.9} - {curDayKkal * 1.2}\n" +
|
||||
$"Белки {user.weight * 1.2}-{user.weight * 1.7} грамм\n" +
|
||||
$"Жиры {user.weight *0.9}-{user.weight} грамм\n" +
|
||||
$"Углеводы {user.weight * 2}-{user.weight * 2.6} грамм\n\n" +
|
||||
$"Первый завтрак (Максимальное количество калорий {curDayKkal * 0.3})\n" +
|
||||
$"Белки – {user.weight * 1.7 * 0.3}, Жиры - {user.weight * 0.3}, Углеводы – {user.weight * 2.6 * 0.3}.\n" +
|
||||
$"Омлет 230 грамм, яблоко 300 грамм, черный кофе без сахара 400 грамм\n" +
|
||||
$"Второй завтрак (Максимальное количество калорий {curDayKkal * 0.1}) " +
|
||||
$"Белки – {user.weight * 1.7 * 0.3}, Жиры - {user.weight * 0.3}, Углеводы – {user.weight * 2.6 * 0.3}.\n" +
|
||||
$"Сырники 110 грамм, сметана 20% 10 грамм, яйцо 70 грамм, апельсиновый сок 240 грамм\n\n" +
|
||||
$"Обед (Максимальное количество калорий {curDayKkal * 0.4})\n" +
|
||||
$"Белки – {user.weight * 1.7 * 0.4}, Жиры - {user.weight * 0.4}, Углеводы – {user.weight * 2.6 * 0.4}.\n" +
|
||||
$"Борщ 340 грамм, семга стейк на гриле 120 грамм, рис белый вареный 80 грамм, салат из белокочанной капусты с морковью 180 грамм, хлеб зерновой 25 грамм, морс 200 грамм\n\n" +
|
||||
$"Полдник (Максимальное количество калорий {curDayKkal * 0.05})\n" +
|
||||
$"Белки – {user.weight * 1.7 * 0.1}, Жиры - {user.weight * 0.1}, Углеводы – {user.weight * 2.6 * 0.1}.\n" +
|
||||
$"Творожная запеканка 130 грамм, сметана 20% 10 грамм, яйцо 80 грамм, апельсиновый сок 270 грамм\n\n" +
|
||||
$"Ужин (Максимальное количество калорий {curDayKkal * 0.3})\n" +
|
||||
$"Белки – {user.weight * 1.7 * 0.2}, Жиры - {user.weight * 0.2}, Углеводы – {user.weight * 2.6 * 0.2}.\n" +
|
||||
"Говядина вареная 80 грамм, картофель вареный 90 грамм, салат цезарь с креветками 80 грамм, хлеб зерновой 25 грамм, чай черный без сахара 150 грамм\n\n" +
|
||||
//"Всего: Калории 1904, Белки 101, Жиры 78, Углеводы 170" +
|
||||
//"\n\n" +
|
||||
"Блюда, рекомендованные для оптимизации питания, в комбинате общественного питания промаркированы зеленым цветом." +
|
||||
"\n\n" +
|
||||
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
|
||||
break;
|
||||
|
||||
case 3:
|
||||
@params.Message =
|
||||
"Примерное меню" +
|
||||
"\n\n" +
|
||||
$"Пол: {gend[user.gender]} | Возраст: {age}\n" +
|
||||
$"Рост: {user.height} см | Масса тела: {user.weight} кг\n\n" +
|
||||
//"Активность: низкая (1-3 тренировки в неделю)\n" +
|
||||
"Рекомендуемая норма КБЖУ: Калории 2474-2824 Белки 112-156 грамм, Жиры 77-84 грамм, Углеводы 196-238 грамм\n" +
|
||||
"Первый завтрак (Максимальное количество калорий 677) Калории - 554, Белки – 24, Жиры -24, Углеводы – 60.\n" +
|
||||
"Рисовая каша на молоке 370 грамм, яйцо 120 грамм, черный кофе без сахара 400 грамм\n" +
|
||||
"Второй завтрак (Максимальное количество калорий 649) Калории - 618, Белки - 35, Жиры - 19, Углеводы – 70\n" +
|
||||
"Сырники 240 грамм, сметана 20% 10 грамм, апельсиновый сок 320 грамм\n" +
|
||||
"Обед (Максимальное количество калорий 931) Калории - 837, Белки - 41, Жиры - 35, Углеводы - 84\n" +
|
||||
"Борщ 400 грамм, стейк из филе куриного 120 грамм, гречневая каша 80 грамм, кетчуп 30 грамм, салат овощной 350 грамм, чай черный без сахара 150 грамм\n" +
|
||||
"Ужин (Максимальное количество калорий 564) Калории - 447, Белки - 65, Жиры - 7, Углеводы – 25\n" +
|
||||
"Треска отварная 350 грамм, рис белый вареный 90 грамм, салат греческий 80 грамм, чай зеленый 150 грамм\n" +
|
||||
"\n" +
|
||||
"Всего: Калории 2456, Белки 165, Жиры 85, Углеводы 239" +
|
||||
"\n\n" +
|
||||
"Блюда, рекомендованные для оптимизации питания, в комбинате общественного питания промаркированы зеленым цветом." +
|
||||
"\n\n" +
|
||||
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
|
||||
break;
|
||||
}
|
||||
|
||||
if (track != 4 && user.track == 0)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton(colors[track] + "Выбрать этот трек", "selectChooseTrack-" + track, KeyboardButtonColor.Positive)
|
||||
.AddLine()
|
||||
.AddButton("Рацион питания", "selectRation-" + track, KeyboardButtonColor.Primary)
|
||||
//.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "selectTrack-" + track, KeyboardButtonColor.Default);
|
||||
}
|
||||
else if (track != 0 && user.track != 0)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton("Рацион питания", "selectRation-" + track, KeyboardButtonColor.Primary)
|
||||
//.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
}
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectExampleMenuCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
197
SvetoforVKBot/Models/Commands/LK/Tracks/SelectRationCommand.cs
Normal file
197
SvetoforVKBot/Models/Commands/LK/Tracks/SelectRationCommand.cs
Normal file
@@ -0,0 +1,197 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using Newtonsoft.Json;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Tracks
|
||||
{
|
||||
public class SelectRationCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectRation-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
int age = 0;
|
||||
int genderCoef = 0;
|
||||
double kkalResult = 0;
|
||||
double colorPercent = 0;
|
||||
double dayCoef = 0;
|
||||
double curDayKkal = 0;
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int track = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
|
||||
Dictionary<int, string> colors = new Dictionary<int, string>(3);
|
||||
colors.Add(1, "🟩"); //З
|
||||
colors.Add(2, "🟦"); //C
|
||||
colors.Add(3, "🟨"); //Ж
|
||||
|
||||
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
|
||||
tracks.Add(1, "Оптимизация питания");
|
||||
tracks.Add(2, "Снижение жировой массы");
|
||||
tracks.Add(3, "Увеличение мышечной массы");
|
||||
tracks.Add(4, "Персональный режим");
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
|
||||
switch (track)
|
||||
{
|
||||
case 1:
|
||||
@params.Message =
|
||||
"Необходимо свести к минимуму в рационе питания:" +
|
||||
"\n" +
|
||||
"• жирное мясо;\n" +
|
||||
"• майонез, сливочные соусы;\n" +
|
||||
"• консервы и соления;\n" +
|
||||
"• копчености;\n" +
|
||||
"• фастфуд;\n" +
|
||||
"• белый хлеб и выпечку;\n" +
|
||||
"• кондитерские изделия;\n" +
|
||||
"• пакетированные соки;\n" +
|
||||
"• газированную воду;\n" +
|
||||
"• лакомства из пакетов (чипсы, снеки, сухарики с добавками). " +
|
||||
"\n\n" +
|
||||
"Как можно чаще на столе должны быть:" +
|
||||
"\n" +
|
||||
"• свежие фрукты и овощи,\n" +
|
||||
"• молочные продукты,\n" +
|
||||
"• цельнозерновой хлеб,\n" +
|
||||
"• белое мясо,\n" +
|
||||
"• рыба и морепродукты,\n" +
|
||||
"• каши,\n" +
|
||||
"• свежевыжатые соки,\n" +
|
||||
"• орехи и семечки, \n" +
|
||||
"• сухофрукты,\n" +
|
||||
"• яйца,\n" +
|
||||
"• твердый сыр,\n" +
|
||||
"• растительные масла (оливковое, льняное и т.д.)" +
|
||||
"\n\n" +
|
||||
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
|
||||
|
||||
break;
|
||||
|
||||
case 2:
|
||||
@params.Message =
|
||||
"Необходимо свести к минимуму в рационе питания:" +
|
||||
"\n" +
|
||||
"• жирное мясо;\n" +
|
||||
"• майонез, сливочные соусы;\n" +
|
||||
"• консервы и соления;\n" +
|
||||
"• копчености;\n" +
|
||||
"• фастфуд;\n" +
|
||||
"• белый хлеб и выпечку;\n" +
|
||||
"• кондитерские изделия;\n" +
|
||||
"• пакетированные соки;\n" +
|
||||
"• газированную воду;\n" +
|
||||
"• лакомства из пакетов (чипсы, снеки, сухарики с добавками). " +
|
||||
"\n\n" +
|
||||
"Как можно чаще на столе должны быть:" +
|
||||
"\n" +
|
||||
"• свежие фрукты и овощи,\n" +
|
||||
"• молочные продукты,\n" +
|
||||
"• цельнозерновой хлеб,\n" +
|
||||
"• белое мясо,\n" +
|
||||
"• рыба и морепродукты,\n" +
|
||||
"• каши,\n" +
|
||||
"• свежевыжатые соки,\n" +
|
||||
"• орехи и семечки, \n" +
|
||||
"• сухофрукты,\n" +
|
||||
"• яйца,\n" +
|
||||
"• твердый сыр,\n" +
|
||||
"• растительные масла (оливковое, льняное и т.д.)" +
|
||||
"\n\n" +
|
||||
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
|
||||
|
||||
break;
|
||||
|
||||
case 3:
|
||||
@params.Message =
|
||||
"Необходимо свести к минимуму в рационе питания:" +
|
||||
"\n" +
|
||||
"• жирное мясо;\n" +
|
||||
"• майонез, сливочные соусы;\n" +
|
||||
"• консервы и соления;\n" +
|
||||
"• копчености;\n" +
|
||||
"• фастфуд;\n" +
|
||||
"• белый хлеб и выпечку;\n" +
|
||||
"• кондитерские изделия;\n" +
|
||||
"• пакетированные соки;\n" +
|
||||
"• газированную воду;\n" +
|
||||
"• лакомства из пакетов (чипсы, снеки, сухарики с добавками). " +
|
||||
"\n\n" +
|
||||
"Как можно чаще на столе должны быть:" +
|
||||
"\n" +
|
||||
"• свежие фрукты и овощи,\n" +
|
||||
"• молочные продукты,\n" +
|
||||
"• цельнозерновой хлеб,\n" +
|
||||
"• белое мясо,\n" +
|
||||
"• рыба и морепродукты,\n" +
|
||||
"• каши,\n" +
|
||||
"• свежевыжатые соки,\n" +
|
||||
"• орехи и семечки, \n" +
|
||||
"• сухофрукты,\n" +
|
||||
"• яйца,\n" +
|
||||
"• твердый сыр,\n" +
|
||||
"• растительные масла (оливковое, льняное и т.д.)" +
|
||||
"\n\n" +
|
||||
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (track != 4 && user.track == 0)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton(colors[track] + "Выбрать этот трек", "selectChooseTrack-" + track, KeyboardButtonColor.Positive)
|
||||
.AddLine()
|
||||
.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "selectTrack-" + track, KeyboardButtonColor.Default);
|
||||
}
|
||||
else if (track != 0 && user.track != 0)
|
||||
{
|
||||
keyboardBuilder
|
||||
//.AddButton("Рацион питания", "selectRation-" + track, KeyboardButtonColor.Primary)
|
||||
.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
}
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectRationCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
199
SvetoforVKBot/Models/Commands/LK/Tracks/SelectTrackCommand.cs
Normal file
199
SvetoforVKBot/Models/Commands/LK/Tracks/SelectTrackCommand.cs
Normal file
@@ -0,0 +1,199 @@
|
||||
using System;
|
||||
using System.Data.SqlClient;
|
||||
using SvetoforVKBot.Models.Updates;
|
||||
using VkNet;
|
||||
using VkNet.Enums.SafetyEnums;
|
||||
using VkNet.Model.Keyboard;
|
||||
using VkNet.Model.RequestParams;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using Newtonsoft.Json;
|
||||
using System.Linq;
|
||||
|
||||
namespace SvetoforVKBot.Models.Commands.LK.Tracks
|
||||
{
|
||||
public class SelectTrackCommand : Command
|
||||
{
|
||||
public override string Name => "{\"button\":\"selectTrack-";
|
||||
|
||||
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
}
|
||||
|
||||
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
|
||||
{
|
||||
var chatId = update.@object.message.from_id;
|
||||
MessagesSendParams @params = new MessagesSendParams();
|
||||
Regex regex = new Regex("[^0-9]");
|
||||
string msg = "";
|
||||
var keyboardBuilder = new KeyboardBuilder().Clear();
|
||||
int age = 0;
|
||||
int genderCoef = 0;
|
||||
double kkalResult = 0;
|
||||
double colorPercent = 0;
|
||||
double dayCoef = 0;
|
||||
double curDayKkal = 0;
|
||||
try
|
||||
{
|
||||
string[] payload = update.@object.message.payload.Split('-');
|
||||
int track = Convert.ToInt32(regex.Replace(payload[1], ""));
|
||||
Dictionary<int, string> colors = new Dictionary<int, string>(3);
|
||||
colors.Add(1, "🟩"); //З
|
||||
colors.Add(2, "🟦"); //C
|
||||
colors.Add(3, "🟨"); //Ж
|
||||
|
||||
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
|
||||
tracks.Add(1, "Оптимизация питания");
|
||||
tracks.Add(2, "Снижение жировой массы");
|
||||
tracks.Add(3, "Увеличение мышечной массы");
|
||||
tracks.Add(4, "Персональный режим");
|
||||
|
||||
//SqlCommand updTag = new SqlCommand("UPDATE Users SET track = @track WHERE chatId = @chatId;", Con);
|
||||
//updTag.Parameters.AddWithValue("@chatId", chatId);
|
||||
//updTag.Parameters.AddWithValue("@track", track);
|
||||
//updTag.ExecuteNonQuery();
|
||||
|
||||
|
||||
var user = db.Users.Single(usr => usr.chatId == chatId);
|
||||
|
||||
//SqlCommand getUser = new SqlCommand("SELECT * FROM Users WHERE chatId = @chatId;", Con);
|
||||
//getUser.Parameters.AddWithValue("@chatId", chatId);
|
||||
//SqlDataReader rgetUser = getUser.ExecuteReader();
|
||||
//rgetUser.Read();
|
||||
//int choosenTrack = Convert.ToInt32(rgetUser["track"]);
|
||||
//rgetUser.Close();
|
||||
////age = (DateTime.Today.Year - birthday.Year);
|
||||
|
||||
|
||||
|
||||
switch (track)
|
||||
{
|
||||
case 1:
|
||||
@params.Message =
|
||||
"Рекомендации для поддержания массы тела:" +
|
||||
"\n\n" +
|
||||
"Режим питания: 3 - 4 разовое питание, из них 3 основных приема пищи (завтрак, обед и ужин) и 1 дополнительный прием.\n" +
|
||||
"Распределение объема пищи в течение дня должно быть следующим: завтрак – 20-30%, обед – 30-40%, полдник – 5-10%, ужин – 20-30%.\n" +
|
||||
"В рационе питания должно быть на килограмм массы тела: белков 1,4-2,0 грамма, жиров 1,0-1,1 грамма и углеводов 2,4-3,0 грамма." +
|
||||
"\n\n" +
|
||||
"Жмите \"Рацион питания\", чтобы увидеть список рекомендуемых и нерекомендуемых продуктов.\n" +
|
||||
"\"Примерное меню\" поможет Вам составить персональное меню." +
|
||||
"\n\n" +
|
||||
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
|
||||
|
||||
break;
|
||||
|
||||
case 2:
|
||||
@params.Message =
|
||||
"Рекомендации для снижения жировой массы тела:" +
|
||||
"\n\n" +
|
||||
"Режим питания: 4 - 5 разового питание, из них 3 основных приема пищи (завтрак, обед и ужин) и 1-2 дополнительных приема.\n" +
|
||||
"Распределение объема пищи в течение дня должно быть следующим: завтрак – 20-30%, обед – 30-40%, полдник – 5-10%, ужин – 20-30%, второй завтрак (5-10%) и второй ужин (до 5%).\n" +
|
||||
"В рационе питания должно быть на килограмм массы тела: белков 1,2-1,7 грамма, жиров 0,9-1,0 грамма и углеводов 2,0-2,6 грамма." +
|
||||
"\n\n" +
|
||||
"Жмите \"Рацион питания\", чтобы увидеть список рекомендуемых и нерекомендуемых продуктов.\n" +
|
||||
"\"Примерное меню\" поможет Вам составить персональное меню." +
|
||||
"\n\n" +
|
||||
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
|
||||
|
||||
break;
|
||||
|
||||
case 3:
|
||||
@params.Message =
|
||||
"Рекомендации для набора мышечной массы тела:" +
|
||||
"\n\n" +
|
||||
"Режим питания: 4 - 5 разового питание, из них 3 основных приема пищи (завтрак, обед и ужин) и 1-2 дополнительных приема.\n" +
|
||||
"Распределение объема пищи в течение дня должно быть следующим: завтрак – 20-30%, обед – 30-40%, полдник – 5-10%, ужин – 20-30%, второй завтрак (5-10%) и второй ужин (до 5%).\n" +
|
||||
"В рационе питания должно быть на килограмм массы тела: белков 1,6-2,2 грамма, жиров 1,1-1,2 грамма и углеводов 2,8-3,4 грамма." +
|
||||
"\n\n" +
|
||||
"Жмите \"Рацион питания\", чтобы увидеть список рекомендуемых и нерекомендуемых продуктов.\n" +
|
||||
"\"Примерное меню\" поможет Вам составить персональное меню." +
|
||||
"\n\n" +
|
||||
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
|
||||
|
||||
break;
|
||||
|
||||
case 4:
|
||||
@params.Message =
|
||||
"⚠Персональный режим определяется после консультации со специалистом.\n\n" +
|
||||
"Консультация включает: \n\n" +
|
||||
"- определение и оценка состава тела\n" +
|
||||
"- коррекция рациона питания\n" +
|
||||
"- оценка функционального состояния\n" +
|
||||
"- психофизиологическое тестирование\n\n" +
|
||||
"📍Консультации проводятся по субботам по адресу: г. Киров, ул. Молодой Гвардии, д.13.\n" +
|
||||
"☎Тел. 70-81-22.\n" +
|
||||
"Стоимость и условия по телефону. \n\n" +
|
||||
"Специалист: Кадочникова Наталья Ивановна.\n\n" +
|
||||
"Чтобы узнать подробнее, нажмите кнопку \"О специалисте\"\n\n" +
|
||||
"Вы можете оформить заявку на запись. Для этого нажмите кнопку \"Оставить заявку\".\n" +
|
||||
"Ваши данные будут отправлены менеджеру, с Вами свяжутся для уточнения даты и времени консультации.";
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Оставить заявку", "selectSubmitConsultation", KeyboardButtonColor.Positive)
|
||||
.AddLine()
|
||||
.AddButton("О специалисте", "selectMoreAboutSpec", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
//keyboardBuilder
|
||||
// .AddButton("💬Консультация", "selectLiveConsultation", KeyboardButtonColor.Primary)
|
||||
// .AddLine()
|
||||
// //.AddButton(cons, "selectGotConsultation", KeyboardButtonColor.Primary)
|
||||
// //.AddLine()
|
||||
// .AddButton("Назад", "selectCalculatorCcal", KeyboardButtonColor.Default);
|
||||
|
||||
if (track != 4) // && choosenTrack == 0)
|
||||
{
|
||||
if (user.track != track)
|
||||
{
|
||||
keyboardBuilder
|
||||
.AddButton(colors[track] + "Выбрать этот трек", "selectChooseTrack-" + track, KeyboardButtonColor.Positive)
|
||||
.AddLine();
|
||||
}
|
||||
|
||||
keyboardBuilder
|
||||
.AddButton("Рацион питания", "selectRation-" + track, KeyboardButtonColor.Primary)
|
||||
//.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
|
||||
.AddLine()
|
||||
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
}
|
||||
//else if (track != 0 && choosenTrack != 0)
|
||||
//{
|
||||
// keyboardBuilder
|
||||
// .AddButton("Рацион питания", "selectRation-" + track, KeyboardButtonColor.Primary)
|
||||
// //.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
|
||||
// .AddLine()
|
||||
// .AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
|
||||
// .AddLine()
|
||||
// .AddButton("Назад", "startPL", KeyboardButtonColor.Default);
|
||||
//}
|
||||
|
||||
@params.Keyboard = keyboardBuilder.Build();
|
||||
@params.UserId = chatId;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
@params.Message = "‼Ошибка в SelectTrackCommand: " + ee.Message;
|
||||
@params.Attachments = null;
|
||||
@params.Keyboard = null;
|
||||
@params.UserId = 59111081;
|
||||
@params.RandomId = GetRandomId();
|
||||
client.Messages.SendAsync(@params);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user