Added payment and basic deduction and increase of cash
This commit is contained in:
@@ -1,20 +1,67 @@
|
||||
#include "Base/SQL.hpp"
|
||||
#include "Commands.hpp"
|
||||
#include <cstdint>
|
||||
#include <dpp/dispatcher.h>
|
||||
#include <dpp/snowflake.h>
|
||||
#include <string>
|
||||
|
||||
void commandPing(const dpp::slashcommand_t &event) { event.reply("Pong"); }
|
||||
void commandBalance(const dpp::slashcommand_t &event) {
|
||||
dpp::snowflake userid = event.command.get_issuing_user().id;
|
||||
std::string balance = getUserBalance(event.command.get_issuing_user().id);
|
||||
event.reply(COMMAND_BALANCE_RESPONSE(balance));
|
||||
}
|
||||
|
||||
void commandPay(const dpp::slashcommand_t &event) {
|
||||
std::string recipient =
|
||||
std::get<dpp::snowflake>(event.get_parameter("recipient")).str();
|
||||
std::uint64_t amount = std::get<std::int64_t>(event.get_parameter("amount"));
|
||||
|
||||
// See if we can deduct the payment first
|
||||
if (!deductFromUsersBalance(event.command.get_issuing_user().id, amount)) {
|
||||
event.reply(COMMAND_PAY_FAIL_INSUFFICIENT_AMOUNT(recipient,
|
||||
std::to_string(amount)));
|
||||
return;
|
||||
}
|
||||
|
||||
// Lets pay them
|
||||
increaseFromUsersBalance(recipient, amount);
|
||||
event.reply(COMMAND_PAY_SUCCESS(recipient, std::to_string(amount)));
|
||||
}
|
||||
|
||||
inline void increaseFromUsersBalance(const dpp::snowflake userid,
|
||||
std::uint64_t amount) {
|
||||
std::uint64_t balance = std::stoi(getUserBalance(userid));
|
||||
execSQL("UPDATE MONEY SET CASH=" + std::to_string(balance + amount) +
|
||||
" WHERE UID=" + userid.str());
|
||||
}
|
||||
|
||||
inline bool deductFromUsersBalance(const dpp::snowflake userid,
|
||||
std::uint64_t amount) {
|
||||
std::uint64_t balance = std::stoi(getUserBalance(userid));
|
||||
if (balance < amount) {
|
||||
return false;
|
||||
}
|
||||
|
||||
execSQL("UPDATE MONEY SET CASH=" + std::to_string(balance - amount) +
|
||||
" WHERE UID=" + userid.str());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
inline std::string getUserBalance(const dpp::snowflake userid) {
|
||||
std::string balance;
|
||||
execSQL("SELECT CASH FROM MONEY WHERE UID=" + userid.str(), &balance);
|
||||
|
||||
if (balance.empty()) {
|
||||
execSQL("INSERT INTO MONEY (UID) VALUES (" + userid.str() + ");");
|
||||
addUserToDatabase(userid);
|
||||
balance = "0";
|
||||
} else {
|
||||
std::uint8_t begining = balance.find(':') + 1;
|
||||
balance = balance.substr(begining, balance.find(';') - begining);
|
||||
}
|
||||
|
||||
event.reply(COMMAND_BALANCE_RESPONSE(balance));
|
||||
return balance;
|
||||
}
|
||||
|
||||
inline void addUserToDatabase(const dpp::snowflake userid) {
|
||||
execSQL("INSERT INTO MONEY (UID) VALUES (" + userid.str() + ");");
|
||||
}
|
||||
|
Reference in New Issue
Block a user