1
0
forked from blue/pica
pica/handler/updatetransaction.cpp

85 lines
2.5 KiB
C++
Raw Permalink Normal View History

//SPDX-FileCopyrightText: 2024 Yury Gubich <blue@macaw.me>
//SPDX-License-Identifier: GPL-3.0-or-later
#include "updatetransaction.h"
#include <map>
#include "server/server.h"
#include "server/session.h"
#include "database/exceptions.h"
Handler::UpdateTransaction::UpdateTransaction (const std::shared_ptr<Server>& server):
Handler("updateTransaction", Request::Method::post),
server(server)
{}
void Handler::UpdateTransaction::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("id");
if (itr == form.end())
return error(request, Response::Status::badRequest);
DB::Transaction txn;
txn.id = std::stoul(itr->second);
itr = form.find("asset");
if (itr == form.end())
return error(request, Response::Status::badRequest);
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;
srv->getDatabase()->updateTransaction(txn);
Response& res = request.createResponse(Response::Status::ok);
res.send();
session.transactionChanged(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);
}
}