Add transaction handler, delete transaction and list transactions queries, session methods

This commit is contained in:
Blue 2024-04-15 19:13:22 -03:00
parent c2d4bf5ccb
commit e1d5b6c76c
Signed by: blue
GPG Key ID: 9B203B252A63EE38
9 changed files with 195 additions and 4 deletions

View File

@ -57,8 +57,9 @@ public:
virtual std::vector<Currency> listUsedCurrencies(uint32_t owner) = 0; virtual std::vector<Currency> listUsedCurrencies(uint32_t owner) = 0;
virtual DB::Transaction addTransaction(const DB::Transaction& transaction) = 0; virtual DB::Transaction addTransaction(const DB::Transaction& transaction) = 0;
virtual void updateTransaction(const DB::Transaction& transaction) = 0;
virtual std::vector<DB::Transaction> listTransactions(uint32_t owner) = 0; virtual std::vector<DB::Transaction> listTransactions(uint32_t owner) = 0;
virtual void updateTransaction(const DB::Transaction& transaction) = 0;
virtual void deleteTransaction(uint32_t id) = 0;
protected: protected:
Interface(Type type); Interface(Type type);

View File

@ -39,6 +39,19 @@ constexpr const char* updateTransactionQuery = "UPDATE transactions SET"
" `initiator` = ?, `type` = 1, `asset` = ?," " `initiator` = ?, `type` = 1, `asset` = ?,"
" `parent` = ?, `value` = ?, `performed` = ?" " `parent` = ?, `value` = ?, `performed` = ?"
" WHERE `id` = ?"; " WHERE `id` = ?";
constexpr const char* deleteTransactionQuery = "DELETE FROM transactions where `id` = ? OR `parent` = ?";
constexpr const char* selectAllTransactions = "WITH RECURSIVE AllTransactions AS ("
" SELECT t.id, t.initiator, t.asset, t.parent, t.value, t.modified, t.performed t.notes FROM transactions t"
" JOIN assets a ON t.asset = a.id"
" WHERE a.owner = ?"
" UNION ALL"
" SELECT t.id, t.initiator, t.asset, t.parent, t.value, t.modified, t.performed t.notes FROM transactions t"
" JOIN AllTransactions at ON t.id = at.parent)"
" SELECT DISTINCT id, initiator, asset, parent, value, modified, performed notes FROM AllTransactions"
" ORDER BY performed"
" LIMIT 100 OFFSET 0;";
static const std::filesystem::path buildSQLPath = "database"; static const std::filesystem::path buildSQLPath = "database";
@ -462,6 +475,28 @@ void DB::MySQL::updateTransaction(const DB::Transaction& transaction) {
upd.execute(); upd.execute();
} }
std::vector<DB::Transaction> DB::MySQL::listTransactions(uint32_t owner) { void DB::MySQL::deleteTransaction(uint32_t id) {
return std::vector<DB::Transaction>(); MYSQL* con = &connection;
Statement del(con, deleteTransactionQuery);
del.bind(&id, MYSQL_TYPE_LONG, true); //for actual transactions
del.bind(&id, MYSQL_TYPE_LONG, true); //for potential children
del.execute(); //need to think of a parent with no children transactions...
}
std::vector<DB::Transaction> DB::MySQL::listTransactions(uint32_t owner) {
MYSQL* con = &connection;
Statement get(con, selectAllTransactions);
get.bind(&owner, MYSQL_TYPE_LONG, true);
get.execute();
std::vector<std::vector<std::any>> res = get.fetchResult();
std::size_t size = res.size();
std::vector<DB::Transaction> result(size);
for (std::size_t i = 0; i < size; ++i)
result[i].parse(res[i]);
return result;
} }

View File

@ -44,8 +44,9 @@ public:
std::vector<Currency> listUsedCurrencies(uint32_t owner) override; std::vector<Currency> listUsedCurrencies(uint32_t owner) override;
DB::Transaction addTransaction(const DB::Transaction& transaction) override; DB::Transaction addTransaction(const DB::Transaction& transaction) override;
void updateTransaction(const DB::Transaction& transaction) override;
std::vector<DB::Transaction> listTransactions(uint32_t owner) override; std::vector<DB::Transaction> listTransactions(uint32_t owner) override;
void updateTransaction(const DB::Transaction& transaction) override;
void deleteTransaction(uint32_t id) override;
private: private:
void executeFile (const std::filesystem::path& relativePath); void executeFile (const std::filesystem::path& relativePath);

View File

@ -13,6 +13,7 @@ set(HEADERS
deleteasset.h deleteasset.h
updateasset.h updateasset.h
currencies.h currencies.h
addtransaction.h
) )
set(SOURCES set(SOURCES
@ -27,6 +28,7 @@ set(SOURCES
deleteasset.cpp deleteasset.cpp
updateasset.cpp updateasset.cpp
currencies.cpp currencies.cpp
addtransaction.cpp
) )
target_sources(${PROJECT_NAME} PRIVATE ${SOURCES}) target_sources(${PROJECT_NAME} PRIVATE ${SOURCES})

View File

@ -0,0 +1,78 @@
//SPDX-FileCopyrightText: 2024 Yury Gubich <blue@macaw.me>
//SPDX-License-Identifier: GPL-3.0-or-later
#include "addtransaction.h"
#include <map>
#include "server/server.h"
#include "server/session.h"
#include "database/exceptions.h"
Handler::AddTransaction::AddTransaction (const std::shared_ptr<Server>& server):
Handler("addTransaction", Request::Method::post),
server(server)
{}
void Handler::AddTransaction::handle (Request& request) {
std::string access = request.getAuthorizationToken();
if (access.empty())
return error(request, Response::Status::unauthorized);
if (access.size() != 32)
return error(request, Response::Status::badRequest);
std::shared_ptr<Server> srv = server.lock();
if (!srv)
return error(request, Response::Status::internalError);
std::map form = request.getForm();
std::map<std::string, std::string>::const_iterator itr = form.find("asset");
if (itr == form.end())
return error(request, Response::Status::badRequest);
DB::Transaction txn;
txn.asset = std::stoul(itr->second);
//TODO validate the asset
itr = form.find("value");
if (itr == form.end())
return error(request, Response::Status::badRequest);
txn.value = std::stod(itr->second);
itr = form.find("performed");
if (itr == form.end())
return error(request, Response::Status::badRequest);
txn.performed = std::stoul(itr->second);
itr = form.find("notes");
if (itr != form.end())
txn.notes = itr->second;
itr = form.find("parent");
if (itr != form.end())
txn.parent = std::stoul(itr->second);
try {
Session& session = srv->getSession(access);
txn.initiator = session.owner;
txn = srv->getDatabase()->addTransaction(txn);
Response& res = request.createResponse(Response::Status::ok);
res.send();
session.transactionAdded(txn);
} catch (const DB::NoSession& e) {
return error(request, Response::Status::unauthorized);
} catch (const std::exception& e) {
std::cerr << "Exception on " << path << ":\n\t" << e.what() << std::endl;
return error(request, Response::Status::internalError);
} catch (...) {
std::cerr << "Unknown exception on " << path << std::endl;
return error(request, Response::Status::internalError);
}
}

20
handler/addtransaction.h Normal file
View File

@ -0,0 +1,20 @@
//SPDX-FileCopyrightText: 2024 Yury Gubich <blue@macaw.me>
//SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <memory>
#include "handler.h"
class Server;
namespace Handler {
class AddTransaction : public Handler {
public:
AddTransaction (const std::shared_ptr<Server>& server);
virtual void handle (Request& request) override;
private:
std::weak_ptr<Server> server;
};
}

View File

@ -17,6 +17,7 @@
#include "handler/deleteasset.h" #include "handler/deleteasset.h"
#include "handler/currencies.h" #include "handler/currencies.h"
#include "handler/updateasset.h" #include "handler/updateasset.h"
#include "handler/addtransaction.h"
#include "taskmanager/route.h" #include "taskmanager/route.h"
@ -79,6 +80,7 @@ void Server::run (int socketDescriptor) {
router->addRoute(std::make_unique<Handler::DeleteAsset>(srv)); router->addRoute(std::make_unique<Handler::DeleteAsset>(srv));
router->addRoute(std::make_unique<Handler::Currencies>(srv)); router->addRoute(std::make_unique<Handler::Currencies>(srv));
router->addRoute(std::make_unique<Handler::UpdateAsset>(srv)); router->addRoute(std::make_unique<Handler::UpdateAsset>(srv));
router->addRoute(std::make_unique<Handler::AddTransaction>(srv));
taskManager->start(); taskManager->start();
scheduler->start(); scheduler->start();

View File

@ -144,6 +144,53 @@ void Session::assetRemoved (unsigned int assetId) {
checkUpdates(); checkUpdates();
} }
void Session::transactionAdded(const DB::Transaction& txn) {
std::lock_guard lock(mtx);
std::map<std::string, nlohmann::json>& txns = cache["transactions"];
auto itr = txns.find("changed");
if (itr == txns.end())
itr = txns.emplace("changed", nlohmann::json::array()).first;
removeByID(itr->second, txn.id);
itr->second.push_back(txn.toJSON());
checkUpdates();
}
void Session::transactionChanged(const DB::Transaction& txn) {
std::lock_guard lock(mtx);
std::map<std::string, nlohmann::json>& txns = cache["transactions"];
auto itr = txns.find("changed");
if (itr == txns.end())
itr = txns.emplace("changed", nlohmann::json::array()).first;
removeByID(itr->second, txn.id);
itr->second.push_back(txn.toJSON());
checkUpdates();
}
void Session::transactionRemoved(unsigned int txnId) {
std::lock_guard lock(mtx);
std::map<std::string, nlohmann::json>& txns = cache["transactions"];
auto itr = txns.find("added");
if (itr != txns.end())
removeByID(itr->second, txnId);
else {
itr = txns.find("removed");
if (itr == txns.end())
itr = txns.emplace("removed", nlohmann::json::array()).first;
itr->second.push_back(txnId);
}
itr = txns.find("changed");
if (itr != txns.end())
removeByID(itr->second, txnId);
checkUpdates();
}
void Session::removeByID(nlohmann::json& array, unsigned int id) { void Session::removeByID(nlohmann::json& array, unsigned int id) {
array.erase( array.erase(
std::remove_if( std::remove_if(

View File

@ -13,6 +13,7 @@
#include "taskmanager/scheduler.h" #include "taskmanager/scheduler.h"
#include "database/schema/asset.h" #include "database/schema/asset.h"
#include "database/schema/transaction.h"
class Session : public Accepting { class Session : public Accepting {
public: public:
@ -41,6 +42,10 @@ public:
void assetChanged (const DB::Asset& asset); void assetChanged (const DB::Asset& asset);
void assetRemoved (unsigned int assetId); void assetRemoved (unsigned int assetId);
void transactionAdded(const DB::Transaction& txn);
void transactionChanged(const DB::Transaction& txn);
void transactionRemoved(unsigned int txnId);
private: private:
void onTimeout (); void onTimeout ();
void sendUpdates (std::unique_ptr<Request> request); void sendUpdates (std::unique_ptr<Request> request);