On sending (posting) item to the server the generated UUID is added to the local item.

This commit is contained in:
2026-02-02 16:13:44 +01:00
parent bedf8084d3
commit 63fe96fb2e
16 changed files with 145 additions and 33 deletions

View File

@ -3,7 +3,7 @@
#include <QVariant> #include <QVariant>
typedef QHash<int, QVariant> ModelItemValues; typedef QMap<int, QVariant> ModelItemValues;
class QJsonDocument; class QJsonDocument;
class QString; class QString;

View File

@ -86,7 +86,7 @@ QHash<QString, std::vector<std::string>> CsvParser::extractColumnValues(
const rapidcsv::Document& doc) { const rapidcsv::Document& doc) {
QHash<QString, std::vector<std::string>> columnValueMap; QHash<QString, std::vector<std::string>> columnValueMap;
for (const QString& columnName : headerNames) { for (const QString& columnName : headerNames) {
// NEXT add support for optional columns // TODO add support for optional columns
// if (optionalCsvHeaderNames.contains(columnName)) { // if (optionalCsvHeaderNames.contains(columnName)) {
// const std::vector<std::string> columnNames = doc.GetColumnNames(); // const std::vector<std::string> columnNames = doc.GetColumnNames();
// int columnIdx = doc.GetColumnIdx(columnName.toStdString()); // int columnIdx = doc.GetColumnIdx(columnName.toStdString());
@ -147,7 +147,7 @@ QVariant CsvParser::parseItemValue(const int role, const std::string& valueStrin
result = doubleValue; result = doubleValue;
// } else if (typeColumns.contains(columnName)) { // } else if (typeColumns.contains(columnName)) {
// // NEXT validate string is allowed // // TODO validate string is allowed
// values[role] = QString::fromStdString(columnValueMap.value(columnName).at(row)); // values[role] = QString::fromStdString(columnValueMap.value(columnName).at(row));
} else { } else {
/// no type recognized for column /// no type recognized for column

View File

@ -3,7 +3,7 @@
#include <QString> #include <QString>
typedef QHash<int, QVariant> ModelItemValues; typedef QMap<int, QVariant> ModelItemValues;
namespace rapidcsv { namespace rapidcsv {
class Document; class Document;

View File

@ -6,20 +6,35 @@
#include "../model/metadata.h" #include "../model/metadata.h"
QList<ModelItemValues> JsonParser::toItemValuesList(const QByteArray& jsonData, QList<ModelItemValues> JsonParser::toItemValuesList(const QByteArray& jsonData,
const QString& objectName) { const QString& rootValueName) {
QList<ModelItemValues> result; QList<ModelItemValues> result;
if (jsonData.isEmpty()) { if (jsonData.isEmpty()) {
return result; return result;
} }
QJsonArray itemArray = extractItemArray(jsonData, objectName); // NEXT tidy up the following code and encapsulate into functions;
foreach (QJsonValue value, itemArray) { /// check if there is an array or there is only one object inside the root object;
QJsonObject itemJsonObject = value.toObject(); // TODO ? rename objectName into jsonValueName?
if (rootValueName == ITEMS_KEY_STRING) {
QJsonArray itemArray = extractItemArray(jsonData, rootValueName);
foreach (QJsonValue value, itemArray) {
QJsonObject itemJsonObject = value.toObject();
ModelItemValues values = jsonObjectToItemValues(itemJsonObject);
result.append(values);
}
}
if (rootValueName == ITEM_KEY_STRING) {
// QJsonArray itemArray = extractItemArray(jsonData, objectName);
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
QJsonObject rootObject = doc.object();
QJsonObject itemJsonObject = rootObject.value(rootValueName).toObject();
ModelItemValues values = jsonObjectToItemValues(itemJsonObject); ModelItemValues values = jsonObjectToItemValues(itemJsonObject);
result.append(values); result.append(values);
} }
return result; return result;
} }
@ -28,7 +43,7 @@ QByteArray JsonParser::itemValuesListToJson(const QList<ModelItemValues>& itemVa
QJsonDocument jsonDoc; QJsonDocument jsonDoc;
QJsonObject rootObject; QJsonObject rootObject;
QJsonArray itemArray; QJsonArray itemArray;
for (const QHash<int, QVariant>& itemValues : itemValuesList) { for (const ModelItemValues& itemValues : itemValuesList) {
QJsonObject itemObject; QJsonObject itemObject;
QListIterator<UserRoles> i(USER_FACING_ROLES); QListIterator<UserRoles> i(USER_FACING_ROLES);

View File

@ -8,14 +8,14 @@ class QString;
class QByteArray; class QByteArray;
class QJsonArray; class QJsonArray;
typedef QHash<int, QVariant> ModelItemValues; typedef QMap<int, QVariant> ModelItemValues;
using namespace std; using namespace std;
class JsonParser { class JsonParser {
public: public:
static QList<ModelItemValues> toItemValuesList(const QByteArray& jsonData, static QList<ModelItemValues> toItemValuesList(const QByteArray& jsonData,
const QString& objectName = ""); const QString& rootValueName = "");
static QByteArray itemValuesListToJson(const QList<ModelItemValues>& itemValuesList, static QByteArray itemValuesListToJson(const QList<ModelItemValues>& itemValuesList,
const QString& objectName = ""); const QString& objectName = "");

View File

@ -105,7 +105,7 @@ void GenericCore::saveItems() {
qDebug() << "saving items..."; qDebug() << "saving items...";
const QJsonDocument doc = m_mainModel->getAllItemsAsJsonDoc(); const QJsonDocument doc = m_mainModel->getAllItemsAsJsonDoc();
const bool successfulSave = FileHandler::saveToFile(doc, ITEM_FILE_NAME); const bool successfulSave = FileHandler::saveToFile(doc, ITEMS_FILE_NAME);
if (successfulSave) { if (successfulSave) {
m_modelUndoStack->setClean(); m_modelUndoStack->setClean();
emit displayStatusMessage(QString("Items saved.")); emit displayStatusMessage(QString("Items saved."));
@ -118,7 +118,7 @@ void GenericCore::importCSVFile(const QString& filePath) {
qInfo() << "importing items from CSV..."; qInfo() << "importing items from CSV...";
qDebug() << "filePath:" << filePath; qDebug() << "filePath:" << filePath;
const QList<ModelItemValues> itemValuesList = FileHandler::getItemValuesFromCSVFile(filePath); const QList<ModelItemValues> itemValuesList = FileHandler::getItemValuesFromCSVFile(filePath);
// NEXT inform UI on errors // TODO inform UI on errors
if (itemValuesList.isEmpty()) { if (itemValuesList.isEmpty()) {
qDebug() << "No items found. Doing nothing..."; qDebug() << "No items found. Doing nothing...";
return; return;
@ -149,7 +149,7 @@ void GenericCore::onSendItemTriggered(const QByteArray& jsonData) {
void GenericCore::onItemsFetched(const QByteArray jsonData) { void GenericCore::onItemsFetched(const QByteArray jsonData) {
emit displayStatusMessage("New items fetched."); emit displayStatusMessage("New items fetched.");
// TODO ? check compability of JSON structure beforehand? // TODO ? check compability of JSON structure beforehand?
// TODO check if item already exists? // NEXT check if item already exists ? ;
m_mainModel->appendItems(jsonData); m_mainModel->appendItems(jsonData);
} }
@ -157,8 +157,10 @@ void GenericCore::onItemsFetchFailure(const QString errorString) {
emit displayStatusMessage(QString("Error: %1").arg(errorString)); emit displayStatusMessage(QString("Error: %1").arg(errorString));
} }
void GenericCore::onPostRequestSuccessful(const QString message) { void GenericCore::onPostRequestSuccessful(const QByteArray responseData) {
// NEXT search local item an set server generated UUID // NEXT search local item and set server generated UUID;
const QString message = m_mainModel->updateItemsFromJson(responseData);
emit displayStatusMessage(message); emit displayStatusMessage(message);
} }
@ -193,7 +195,7 @@ void GenericCore::setupModels() {
*/ */
void GenericCore::initModelData() { void GenericCore::initModelData() {
qInfo() << "Trying to read model data from file..."; qInfo() << "Trying to read model data from file...";
const QByteArray jsonDoc = FileHandler::loadJSONDataFromFile(ITEM_FILE_NAME); const QByteArray jsonDoc = FileHandler::loadJSONDataFromFile(ITEMS_FILE_NAME);
// qDebug() << "jsonDoc:" << jsonDoc; // qDebug() << "jsonDoc:" << jsonDoc;
// TODO decide on lack of file(s) (config, data) if example items should be generated // TODO decide on lack of file(s) (config, data) if example items should be generated
// (see welcome wizard) // (see welcome wizard)
@ -228,7 +230,7 @@ void GenericCore::setupServerConfiguration() {
/// request connections /// request connections
connect(this, &GenericCore::fetchItemsFromServer, m_serverCommunicator.get(), connect(this, &GenericCore::fetchItemsFromServer, m_serverCommunicator.get(),
&ServerCommunicator::fetchItems); &ServerCommunicator::fetchItems);
connect(this, &GenericCore::sendItemToServer, this, &GenericCore::onSendItemTriggered); connect(this, &GenericCore::postItemToServer, this, &GenericCore::onSendItemTriggered);
/// response connections /// response connections
connect(m_serverCommunicator.get(), &ServerCommunicator::itemsFetched, this, connect(m_serverCommunicator.get(), &ServerCommunicator::itemsFetched, this,

View File

@ -39,13 +39,13 @@ class GenericCore : public QObject {
void onSendItemTriggered(const QByteArray& jsonData); void onSendItemTriggered(const QByteArray& jsonData);
void onItemsFetched(const QByteArray jsonData); void onItemsFetched(const QByteArray jsonData);
void onItemsFetchFailure(const QString errorString); void onItemsFetchFailure(const QString errorString);
void onPostRequestSuccessful(const QString message); void onPostRequestSuccessful(const QByteArray responseData);
void onPostRequestFailure(const QString errorString); void onPostRequestFailure(const QString errorString);
signals: signals:
void displayStatusMessage(QString message); void displayStatusMessage(QString message);
void fetchItemsFromServer(); void fetchItemsFromServer();
void sendItemToServer(const QByteArray& jsonData); void postItemToServer(const QByteArray& jsonData);
private: private:
QUndoStack* m_modelUndoStack; QUndoStack* m_modelUndoStack;

View File

@ -26,6 +26,11 @@ EditItemCommand::EditItemCommand(TableModel* model,
.arg(roleName) .arg(roleName)
.arg(index.data(DEFAULT_ROLE).toString()) .arg(index.data(DEFAULT_ROLE).toString())
.arg(value.toString()); .arg(value.toString());
} else if (role == IdRole) {
commandText = QString("Setting '%1' of item '%2' to '%3'")
.arg(roleName)
.arg(index.data(DEFAULT_ROLE).toString())
.arg(value.toString());
} else { } else {
qWarning() << "Role didn't match! Using a generic command text..."; qWarning() << "Role didn't match! Using a generic command text...";
commandText = QString("Edit item '%1'").arg(index.data(DEFAULT_ROLE).toString()); commandText = QString("Edit item '%1'").arg(index.data(DEFAULT_ROLE).toString());

View File

@ -3,7 +3,7 @@
#include <QUndoCommand> #include <QUndoCommand>
typedef QHash<int, QVariant> ModelItemValues; typedef QMap<int, QVariant> ModelItemValues;
class TableModel; class TableModel;

View File

@ -5,7 +5,7 @@
class TableModel; class TableModel;
typedef QHash<int, QVariant> ModelItemValues; typedef QMap<int, QVariant> ModelItemValues;
class RemoveRowsCommand : public QUndoCommand { class RemoveRowsCommand : public QUndoCommand {
public: public:

View File

@ -35,10 +35,11 @@ static QList<UserRoles> INT_ROLES = {AmountRole};
static QList<UserRoles> DOUBLE_ROLES = {FactorRole}; static QList<UserRoles> DOUBLE_ROLES = {FactorRole};
/// JSON keys /// JSON keys
static const QString ITEM_KEY_STRING = "items"; static const QString ITEMS_KEY_STRING = "items";
static const QString ITEM_KEY_STRING = "item";
/// file naming /// file naming
static const QString ITEM_FILE_NAME = ITEM_KEY_STRING + ".json"; static const QString ITEMS_FILE_NAME = ITEMS_KEY_STRING + ".json";
/// functions /// functions
static int GET_ROLE_FOR_COLUMN(const int column) { static int GET_ROLE_FOR_COLUMN(const int column) {

View File

@ -3,7 +3,7 @@
#include <QVariant> #include <QVariant>
typedef QHash<int, QVariant> ModelItemValues; typedef QMap<int, QVariant> ModelItemValues;
class ModelItem { class ModelItem {
public: public:
@ -18,7 +18,7 @@ class ModelItem {
QJsonObject toJsonObject() const; QJsonObject toJsonObject() const;
private: private:
QHash<int, QVariant> m_values; ModelItemValues m_values;
}; };
#endif // MODELITEM_H #endif // MODELITEM_H

View File

@ -29,7 +29,7 @@ QByteArray TableModel::generateExampleItems() {
array.append(itemObject); array.append(itemObject);
} }
rootObject.insert(ITEM_KEY_STRING, array); rootObject.insert(ITEMS_KEY_STRING, array);
doc.setObject(rootObject); doc.setObject(rootObject);
return doc.toJson(); return doc.toJson();
@ -83,6 +83,7 @@ QVariant TableModel::data(const QModelIndex& index, int role) const {
case InfoRole: case InfoRole:
case AmountRole: case AmountRole:
case FactorRole: case FactorRole:
case IdRole:
return m_items.at(row)->data(role); return m_items.at(row)->data(role);
case ToStringRole: case ToStringRole:
return m_items.at(row)->toString(); return m_items.at(row)->toString();
@ -152,7 +153,7 @@ QJsonDocument TableModel::getAllItemsAsJsonDoc() const {
QJsonObject itemObject = item->toJsonObject(); QJsonObject itemObject = item->toJsonObject();
array.append(itemObject); array.append(itemObject);
} }
rootObject.insert(ITEM_KEY_STRING, array); rootObject.insert(ITEMS_KEY_STRING, array);
doc.setObject(rootObject); doc.setObject(rootObject);
return doc; return doc;
@ -175,11 +176,37 @@ QList<QStringList> TableModel::getItemsAsStringLists() const {
QByteArray TableModel::jsonDataForServer(const QModelIndex& currentIndex) const { QByteArray TableModel::jsonDataForServer(const QModelIndex& currentIndex) const {
const QJsonObject itemObject = data(currentIndex, ToJsonRole).toJsonObject(); const QJsonObject itemObject = data(currentIndex, ToJsonRole).toJsonObject();
QJsonObject rootObject; QJsonObject rootObject;
rootObject.insert("item", itemObject); rootObject.insert(ITEM_KEY_STRING, itemObject);
const QJsonDocument jsonDoc(rootObject); const QJsonDocument jsonDoc(rootObject);
return jsonDoc.toJson(QJsonDocument::Compact); return jsonDoc.toJson(QJsonDocument::Compact);
} }
QString TableModel::updateItemsFromJson(const QByteArray& jsonData) {
/// convert JSON data into a list of item values
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonData, ITEM_KEY_STRING);
/// for each item values:
// NEXT iterate over all value items in the list (or disable updating multiple items for now)
// for (ModelItemValues itemValues : valueList) {
// }
// NEXT encapsulate into updateItem(const ModelItemValues& itemValues)
QModelIndex foundIndex = searchItemIndex(valueList.first());
qDebug() << "Search done!";
if (foundIndex == QModelIndex()) {
const QString errorMessage = "No matching item found!";
qWarning() << errorMessage;
return errorMessage;
} else {
qInfo() << "Item found!";
/// update existing item
QMap<int, QVariant> roles = valueList.first();
setItemData(foundIndex, roles);
/// return status what happened in this function (i. e. "Created x items, updated y items.")
// return data(foundIndex, ToStringRole).toString();
return QString("Item found at row %1.").arg(foundIndex.row());
}
}
bool TableModel::removeRows(int firstRow, int nRows, const QModelIndex& parentIndex) { bool TableModel::removeRows(int firstRow, int nRows, const QModelIndex& parentIndex) {
if (parentIndex != QModelIndex()) { if (parentIndex != QModelIndex()) {
qWarning() << "Removing of child rows is not supported yet!"; qWarning() << "Removing of child rows is not supported yet!";
@ -203,7 +230,7 @@ void TableModel::appendItems(const QByteArray& jsonDoc) { insertItems(-1, jsonDo
void TableModel::insertItems(int startPosition, void TableModel::insertItems(int startPosition,
const QByteArray& jsonDoc, const QByteArray& jsonDoc,
const QModelIndex& parentIndex) { const QModelIndex& parentIndex) {
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonDoc, ITEM_KEY_STRING); const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonDoc, ITEMS_KEY_STRING);
if (valueList.empty()) { if (valueList.empty()) {
/// don't try inserting if no values to insert /// don't try inserting if no values to insert
@ -302,3 +329,60 @@ bool TableModel::isEmptyValueEqualToZero(const int role) const {
return false; return false;
} }
} }
QModelIndex TableModel::searchItemIndex(const ModelItemValues givenItemValues) const {
// iterate over indexes to search item : see searchItem(...);
// for (const shared_ptr<ModelItem>& item : m_items) {
for (int row = 0; row < rowCount(); ++row) {
qDebug() << "Processing item at row" << row << "...";
QModelIndex itemIndex = index(row, 0);
if (isItemEqualToItemValues(itemIndex, givenItemValues)) {
qInfo() << "Found item at row" << row << "! Returning its index...";
return itemIndex;
}
}
qDebug() << "No matching item found. Returning empty pointer...";
return {};
}
bool TableModel::isItemEqualToItemValues(const QModelIndex& itemIndex,
const ModelItemValues givenItemValues) const {
/// do both have a UUID?
QVariant idOfItem = data(itemIndex, IdRole);
QVariant given = givenItemValues.value(IdRole);
if (idOfItem.isValid() && given.isValid()) {
/// are the UUIDs the same?
if (idOfItem.toString() == given.toString()) {
qInfo() << "UUIDs are the same.";
return true;
} else {
qDebug() << "UUIDs are NOT the same.";
return false;
}
} else {
/// are all other values the same? (for now only USER_FACING_ROLES are checked)
QListIterator<UserRoles> i(USER_FACING_ROLES);
while (i.hasNext()) {
const UserRoles role = i.next();
const QString roleName = ROLE_NAMES.value(role);
const QVariant valueOfItem = data(itemIndex, role);
const QVariant givenValue = givenItemValues.value(role);
if (STRING_ROLES.contains(role)) {
if (valueOfItem.toString() != givenValue.toString()) {
return false;
}
} else if (INT_ROLES.contains(role)) {
if (valueOfItem.toInt() != givenValue.toInt()) {
return false;
}
} else if (DOUBLE_ROLES.contains(role)) {
if (valueOfItem.toDouble() != givenValue.toDouble()) {
return false;
}
} else {
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
}
}
return true;
}
}

View File

@ -8,7 +8,7 @@ class ModelItem;
using namespace std; using namespace std;
typedef QHash<int, QVariant> ModelItemValues; typedef QMap<int, QVariant> ModelItemValues;
class TableModel : public QAbstractTableModel { class TableModel : public QAbstractTableModel {
Q_OBJECT Q_OBJECT
@ -40,6 +40,8 @@ class TableModel : public QAbstractTableModel {
QByteArray jsonDataForServer(const QModelIndex& currentIndex) const; QByteArray jsonDataForServer(const QModelIndex& currentIndex) const;
QString updateItemsFromJson(const QByteArray& jsonData);
public slots: public slots:
// bool insertRows(int position, int rows, const QModelIndex& parentIndex = QModelIndex()) // bool insertRows(int position, int rows, const QModelIndex& parentIndex = QModelIndex())
// override; // override;
@ -68,6 +70,9 @@ class TableModel : public QAbstractTableModel {
QMap<int, QVariant> onlyChangedValues(const QModelIndex& index, QMap<int, QVariant> onlyChangedValues(const QModelIndex& index,
const QMap<int, QVariant>& roleValueMap) const; const QMap<int, QVariant>& roleValueMap) const;
bool isEmptyValueEqualToZero(const int role) const; bool isEmptyValueEqualToZero(const int role) const;
QModelIndex searchItemIndex(const ModelItemValues givenItemValues) const;
bool isItemEqualToItemValues(const QModelIndex& itemIndex,
const ModelItemValues givenItemValues) const;
}; };
#endif // TABLEMODEL_H #endif // TABLEMODEL_H

View File

@ -68,7 +68,7 @@ void ServerCommunicator::postItems(const QByteArray& jsonData) {
QByteArray responseData = reply->readAll(); QByteArray responseData = reply->readAll();
const QString message = QString("POST successful! Response: %1").arg(responseData); const QString message = QString("POST successful! Response: %1").arg(responseData);
qInfo() << message; qInfo() << message;
emit postRequestSuccessful(message); emit postRequestSuccessful(responseData);
} else { } else {
const QString message = QString("Error: %1").arg(reply->errorString()); const QString message = QString("Error: %1").arg(reply->errorString());
qDebug() << message; qDebug() << message;

View File

@ -26,7 +26,7 @@ class ServerCommunicator : public QObject {
void itemsFetched(const QByteArray jsonDoc); void itemsFetched(const QByteArray jsonDoc);
void itemsFetchFailure(const QString errorString); void itemsFetchFailure(const QString errorString);
void postRequestSuccessful(const QString message); void postRequestSuccessful(const QByteArray responseData);
void postRequestFailure(const QString errorString); void postRequestFailure(const QString errorString);
private: private: