From 0345c38fb68285c0744db201acd0ef07079081e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=BB=D1=8C=D1=8F?= <Илья@WIN-RANNDDD> Date: Tue, 14 Jan 2025 21:28:06 +0400 Subject: [PATCH] Final version --- HardwareAccountingServer.pro | 2 + apiserver.cpp | 117 +++++++------ apiserver.h | 24 ++- data/requestDevices.sql | 8 +- main.cpp | 1 + models/baseentity.h | 2 +- models/device.cpp | 4 +- models/enums/entitytype.h | 13 ++ models/filterparams.cpp | 12 +- models/filterparams.h | 8 +- service/businesslogic/departmentlogic.cpp | 4 +- service/businesslogic/departmentlogic.h | 2 +- service/businesslogic/devicelogic.cpp | 83 +++++---- service/businesslogic/devicelogic.h | 7 +- service/businesslogic/devicemodellogic.cpp | 4 +- service/businesslogic/devicemodellogic.h | 2 +- service/businesslogic/devicetypelogic.cpp | 4 +- service/businesslogic/devicetypelogic.h | 2 +- service/businesslogic/locationlogic.cpp | 4 +- service/businesslogic/locationlogic.h | 2 +- service/businesslogic/manufacturerlogic.cpp | 4 +- service/businesslogic/manufacturerlogic.h | 2 +- service/serviceloaddb.cpp | 183 ++++++++++---------- service/serviceloaddb.h | 14 +- 24 files changed, 281 insertions(+), 227 deletions(-) create mode 100644 models/enums/entitytype.h diff --git a/HardwareAccountingServer.pro b/HardwareAccountingServer.pro index ccad961..b66b39d 100644 --- a/HardwareAccountingServer.pro +++ b/HardwareAccountingServer.pro @@ -46,6 +46,8 @@ HEADERS += \ models/devicemodel.h \ models/devicestructureelement.h \ models/devicetype.h \ + models/entitytype.h \ + models/enums/entitytype.h \ models/filterparams.h \ models/location.h \ models/manufacturer.h \ diff --git a/apiserver.cpp b/apiserver.cpp index 51ff1fd..5513453 100644 --- a/apiserver.cpp +++ b/apiserver.cpp @@ -1,37 +1,37 @@ #include "apiserver.h" ApiServer::ApiServer() { - server.route("/api/devices", QHttpServerRequest::Method::Get, + _server.route("/api/devices", QHttpServerRequest::Method::Get, [this](const QHttpServerRequest &request) { return handleGetFilteredDevices(request); }); - server.route("/api/departments", QHttpServerRequest::Method::Get, + _server.route("/api/departments", QHttpServerRequest::Method::Get, [this](const QHttpServerRequest &request) { return handleGetAllDepartments(request); }); - server.route("/api/devicemodels", QHttpServerRequest::Method::Get, + _server.route("/api/devicemodels", QHttpServerRequest::Method::Get, [this](const QHttpServerRequest &request) { return handleGetAllDeviceModels(request); }); - server.route("/api/devicetypes", QHttpServerRequest::Method::Get, + _server.route("/api/devicetypes", QHttpServerRequest::Method::Get, [this](const QHttpServerRequest &request) { return handleGetAllDeviceTypes(request); }); - server.route("/api/locations", QHttpServerRequest::Method::Get, + _server.route("/api/locations", QHttpServerRequest::Method::Get, [this](const QHttpServerRequest &request) { return handleGetAllLocations(request); }); - server.route("/api/manufacturers", QHttpServerRequest::Method::Get, + _server.route("/api/manufacturers", QHttpServerRequest::Method::Get, [this](const QHttpServerRequest &request) { return handleGetAllManufacturers(request); }); - server.route("/api/devices/", QHttpServerRequest::Method::Put, + _server.route("/api/devices/", QHttpServerRequest::Method::Put, [this](int id, const QHttpServerRequest &request) { return handleUpdateDevice(id, request); }); @@ -39,54 +39,34 @@ ApiServer::ApiServer() { void ApiServer::start(ServiceLoadDB *serviceDB) { - server.listen(QHostAddress::LocalHost, 8080); - deviceLogic = new DeviceLogic(serviceDB); - departmentLogic = new DepartmentLogic(serviceDB); - deviceModelLogic = new DeviceModelLogic(serviceDB); - locationLogic = new LocationLogic(serviceDB); - manufacturerLogic = new ManufacturerLogic(serviceDB); - deviceTypeLogic = new DeviceTypeLogic(serviceDB); + _server.listen(QHostAddress::LocalHost, 8080); + _deviceLogic = new DeviceLogic(serviceDB); + _departmentLogic = new DepartmentLogic(serviceDB); + _deviceModelLogic = new DeviceModelLogic(serviceDB); + _locationLogic = new LocationLogic(serviceDB); + _manufacturerLogic = new ManufacturerLogic(serviceDB); + _deviceTypeLogic = new DeviceTypeLogic(serviceDB); } QHttpServerResponse ApiServer::handleGetFilteredDevices(const QHttpServerRequest &request) { QUrlQuery query = request.query(); - bool isWorking = query.queryItemValue("isWorking") == "true"; + bool isWorking = getQueryParamWithDefault(query, "isWorking", true); + double priceFrom = getQueryParamWithDefault(query, "priceFrom", 0.00); + double priceTo = getQueryParamWithDefault(query, "priceTo", std::numeric_limits::max()); + bool applyFilters = getQueryParamWithDefault(query, "applyFilters", false); + bool disregardState = getQueryParamWithDefault(query, "disregardState", true); + int entityId = getQueryParamWithDefault(query, "entityId", -1); + int currentEntity = getQueryParamWithDefault(query, "currentEntity", 0); + QString searchText = getQueryParamWithDefault(query, "searchText", QString()); + QString sortOrder = getQueryParamWithDefault(query, "sortOrder", QString("Сначала новые")); - bool priceFromOk; - double priceFrom = query.queryItemValue("priceFrom").toDouble(&priceFromOk); - if (!priceFromOk) { - return QHttpServerResponse("Invalid priceFrom value", QHttpServerResponse::StatusCode::BadRequest); + if (!validEntityTypeNumbers.contains(currentEntity)) { + currentEntity = 0; } - - bool priceToOk; - double priceTo = query.queryItemValue("priceTo").toDouble(&priceToOk); - if (!priceToOk) { - return QHttpServerResponse("Invalid priceTo value", QHttpServerResponse::StatusCode::BadRequest); - } - - bool applyFilters = query.queryItemValue("applyFilters") == "true"; - bool disregardState = query.queryItemValue("disregardState") == "true"; - - bool entityIdOk; - int entityId = query.queryItemValue("entityId").toInt(&entityIdOk); - if (!entityIdOk) { - return QHttpServerResponse("Invalid entityId value", QHttpServerResponse::StatusCode::BadRequest); - } - - bool currentEntityOk; - int currentEntity = query.queryItemValue("currentEntity").toInt(¤tEntityOk); - if (!currentEntityOk) { - return QHttpServerResponse("Invalid currentEntity value", QHttpServerResponse::StatusCode::BadRequest); - } - - QString searchText = query.queryItemValue("searchText"); - - QStringList validSortOrders = {"Сначала новые", "Сначала старые", "Сначала дешевые", "Сначала дорогие", "Сначала с лайком"}; - QString sortOrder = query.queryItemValue("sortOrder"); if (!validSortOrders.contains(sortOrder)) { - return QHttpServerResponse("Invalid sortOrder value", QHttpServerResponse::StatusCode::BadRequest); + sortOrder = "Сначала новые"; } FilterParams filterParams; @@ -96,9 +76,9 @@ QHttpServerResponse ApiServer::handleGetFilteredDevices(const QHttpServerRequest filterParams.setApllyFilters(applyFilters); filterParams.setDisregardState(disregardState); - QList filteredDevices = deviceLogic->getAllByParameters( + QList filteredDevices = _deviceLogic->getAllByParameters( entityId, - currentEntity, + static_cast(currentEntity), searchText, filterParams, sortOrder @@ -117,7 +97,7 @@ QHttpServerResponse ApiServer::handleGetFilteredDevices(const QHttpServerRequest QHttpServerResponse ApiServer::handleGetAllDepartments(const QHttpServerRequest &request) { - QMap departments = departmentLogic->getAll(); + QMap departments = _departmentLogic->getAll(); if (departments.isEmpty()) { return QHttpServerResponse("Failed to retrieve departments", QHttpServerResponse::StatusCode::InternalServerError); @@ -133,7 +113,7 @@ QHttpServerResponse ApiServer::handleGetAllDepartments(const QHttpServerRequest QHttpServerResponse ApiServer::handleGetAllDeviceModels(const QHttpServerRequest &request) { - QMap deviceModels = deviceModelLogic->getAll(); + QMap deviceModels = _deviceModelLogic->getAll(); if (deviceModels.isEmpty()) { return QHttpServerResponse("Failed to retrieve device models", QHttpServerResponse::StatusCode::InternalServerError); @@ -149,7 +129,7 @@ QHttpServerResponse ApiServer::handleGetAllDeviceModels(const QHttpServerRequest QHttpServerResponse ApiServer::handleGetAllDeviceTypes(const QHttpServerRequest &request) { - QMap deviceTypes = deviceTypeLogic->getAll(); + QMap deviceTypes = _deviceTypeLogic->getAll(); if (deviceTypes.isEmpty()) { return QHttpServerResponse("Failed to retrieve device types", QHttpServerResponse::StatusCode::InternalServerError); @@ -165,7 +145,7 @@ QHttpServerResponse ApiServer::handleGetAllDeviceTypes(const QHttpServerRequest QHttpServerResponse ApiServer::handleGetAllLocations(const QHttpServerRequest &request) { - QMap locations = locationLogic->getAll(); + QMap locations = _locationLogic->getAll(); if (locations.isEmpty()) { return QHttpServerResponse("Failed to retrieve locations", QHttpServerResponse::StatusCode::InternalServerError); @@ -181,7 +161,7 @@ QHttpServerResponse ApiServer::handleGetAllLocations(const QHttpServerRequest &r QHttpServerResponse ApiServer::handleGetAllManufacturers(const QHttpServerRequest &request) { - QMap manufacturers = manufacturerLogic->getAll(); + QMap manufacturers = _manufacturerLogic->getAll(); if (manufacturers.isEmpty()) { return QHttpServerResponse("Failed to retrieve manufacturers", QHttpServerResponse::StatusCode::InternalServerError); @@ -210,7 +190,7 @@ QHttpServerResponse ApiServer::handleUpdateDevice(int id, const QHttpServerReque device.fromJson(jsonObject); device.setId(id); - if (!deviceLogic->updateDevice(device)) { + if (!_deviceLogic->updateDevice(device)) { return QHttpServerResponse("Failed to update device", QHttpServerResponse::StatusCode::InternalServerError); } @@ -226,3 +206,32 @@ QJsonArray ApiServer::createJsonArray(const QMap &items) } return itemArray; } + +template +T ApiServer::getQueryParamWithDefault(const QUrlQuery &query, const QString ¶mName, const T &defaultValue) +{ + QString value = query.queryItemValue(paramName); + if (value.isEmpty()) { + return defaultValue; + } + + if constexpr (std::is_same::value) { + return value == "true"; + } + if constexpr (std::is_same::value) { + bool ok; + int result = value.toInt(&ok); + return ok ? result : defaultValue; + } + if constexpr (std::is_same::value) { + + bool ok; + double result = value.toDouble(&ok); + return ok ? result : defaultValue; + } + if constexpr (std::is_same::value) { + return value; + } + + return defaultValue; +} diff --git a/apiserver.h b/apiserver.h index d65c52c..ae4fb57 100644 --- a/apiserver.h +++ b/apiserver.h @@ -22,15 +22,6 @@ public: void start(ServiceLoadDB *serviceDB); private: - QHttpServer server; - - DeviceLogic *deviceLogic; - DepartmentLogic *departmentLogic; - DeviceModelLogic *deviceModelLogic; - DeviceTypeLogic *deviceTypeLogic; - LocationLogic *locationLogic; - ManufacturerLogic *manufacturerLogic; - QHttpServerResponse handleGetFilteredDevices(const QHttpServerRequest &request); QHttpServerResponse handleGetAllDepartments(const QHttpServerRequest &request); QHttpServerResponse handleGetAllDeviceModels(const QHttpServerRequest &request); @@ -41,6 +32,21 @@ private: template QJsonArray createJsonArray(const QMap &items); + template + T getQueryParamWithDefault(const QUrlQuery &query, const QString ¶mName, const T &defaultValue); + +private: + const QSet validSortOrders = {"Сначала новые", "Сначала старые", "Сначала дешевые", "Сначала дорогие", "Сначала с лайком"}; + const QSet validEntityTypeNumbers = {0, 1, 2, 3, 4, 5}; + + QHttpServer _server; + + DeviceLogic *_deviceLogic; + DepartmentLogic *_departmentLogic; + DeviceModelLogic *_deviceModelLogic; + DeviceTypeLogic *_deviceTypeLogic; + LocationLogic *_locationLogic; + ManufacturerLogic *_manufacturerLogic; }; #endif // APISERVER_H diff --git a/data/requestDevices.sql b/data/requestDevices.sql index 80abb1d..fe106c2 100644 --- a/data/requestDevices.sql +++ b/data/requestDevices.sql @@ -1,14 +1,14 @@ SELECT d.*, l.name AS location_name, - CONCAT(e.last_name, ' ', e.first_name, ' ', e.patronymic) AS employee_full_name, + TRIM(CONCAT(e.last_name, ' ', e.first_name, ' ', e.patronymic)) AS employee_full_name, e.fk_id_department AS department_id, - dep.name AS department_name + dep.name AS department_name FROM device d JOIN location l ON d.fk_id_location = l.id -JOIN +LEFT JOIN employee e ON d.fk_id_employee = e.id -JOIN +LEFT JOIN department dep ON e.fk_id_department = dep.id; diff --git a/main.cpp b/main.cpp index e28d6f2..45ae1a2 100644 --- a/main.cpp +++ b/main.cpp @@ -1,4 +1,5 @@ #include + #include "service/serviceloaddb.h" #include "apiserver.h" diff --git a/models/baseentity.h b/models/baseentity.h index beebd43..7c24ec5 100644 --- a/models/baseentity.h +++ b/models/baseentity.h @@ -11,7 +11,7 @@ public: int id() const; void setId(int newId); - virtual void fromJson(const QJsonObject &) {} + virtual void fromJson(const QJsonObject &) = 0; virtual QJsonObject toJson() const = 0; private: diff --git a/models/device.cpp b/models/device.cpp index a834707..a2d3584 100644 --- a/models/device.cpp +++ b/models/device.cpp @@ -164,7 +164,7 @@ void Device::fromJson(const QJsonObject &json) setIsLiked(json["isLiked"].toBool()); DeviceModel model; - model.setId(json["idDeviceModel"].toInt()); + model.fromJson(json["deviceModel"].toObject()); setDeviceModel(model); } @@ -184,7 +184,7 @@ QJsonObject Device::toJson() const obj["nameEmployee"] = nameEmployee(); obj["idDepartment"] = idDepartment(); obj["nameDepartment"] = nameDepartment(); - obj["idDeviceModel"] = deviceModel().id(); + obj["deviceModel"] = deviceModel().toJson(); obj["isLiked"] = isLiked(); return obj; } diff --git a/models/enums/entitytype.h b/models/enums/entitytype.h new file mode 100644 index 0000000..9674d7b --- /dev/null +++ b/models/enums/entitytype.h @@ -0,0 +1,13 @@ +#ifndef ENTITYTYPE_H +#define ENTITYTYPE_H + +enum class EntityType : int { + All = 0, + DeviceTypes = 1, + Locations = 2, + Departments = 3, + Manufacturers = 4, + DeviceModels = 5 +}; + +#endif // ENTITYTYPE_H diff --git a/models/filterparams.cpp b/models/filterparams.cpp index 6fe84aa..9a4a83a 100644 --- a/models/filterparams.cpp +++ b/models/filterparams.cpp @@ -33,22 +33,22 @@ void FilterParams::setPriceTo(double newPriceTo) _priceTo = newPriceTo; } -bool FilterParams::getDisregardState() const +bool FilterParams::disregardState() const { - return disregardState; + return _disregardState; } void FilterParams::setDisregardState(bool newDisregardState) { - disregardState = newDisregardState; + _disregardState = newDisregardState; } -bool FilterParams::getApllyFilters() const +bool FilterParams::apllyFilters() const { - return apllyFilters; + return _apllyFilters; } void FilterParams::setApllyFilters(bool newApllyFilters) { - apllyFilters = newApllyFilters; + _apllyFilters = newApllyFilters; } diff --git a/models/filterparams.h b/models/filterparams.h index 5267e90..3ebea6e 100644 --- a/models/filterparams.h +++ b/models/filterparams.h @@ -15,18 +15,18 @@ public: double priceTo() const; void setPriceTo(double newPriceTo); - bool getDisregardState() const; + bool disregardState() const; void setDisregardState(bool newDisregardState); - bool getApllyFilters() const; + bool apllyFilters() const; void setApllyFilters(bool newApllyFilters); private: bool _isWorking = true; double _priceFrom = -1; double _priceTo = -1; - bool disregardState = false; - bool apllyFilters = false; + bool _disregardState = false; + bool _apllyFilters = false; }; #endif // FILTERPARAMS_H diff --git a/service/businesslogic/departmentlogic.cpp b/service/businesslogic/departmentlogic.cpp index 9515494..92c4053 100644 --- a/service/businesslogic/departmentlogic.cpp +++ b/service/businesslogic/departmentlogic.cpp @@ -2,10 +2,10 @@ DepartmentLogic::DepartmentLogic(ServiceLoadDB *serviceDB) { - db = serviceDB; + _db = serviceDB; } QMap DepartmentLogic::getAll() { - return db->loadDepartments(); + return _db->loadDepartments(); } diff --git a/service/businesslogic/departmentlogic.h b/service/businesslogic/departmentlogic.h index f0fc150..2f73a98 100644 --- a/service/businesslogic/departmentlogic.h +++ b/service/businesslogic/departmentlogic.h @@ -10,7 +10,7 @@ public: QMap getAll(); private: - ServiceLoadDB *db; + ServiceLoadDB *_db; }; #endif // DEPARTMENTLOGIC_H diff --git a/service/businesslogic/devicelogic.cpp b/service/businesslogic/devicelogic.cpp index 6e3b0e5..ccc70c7 100644 --- a/service/businesslogic/devicelogic.cpp +++ b/service/businesslogic/devicelogic.cpp @@ -2,25 +2,25 @@ DeviceLogic::DeviceLogic(ServiceLoadDB *serviceDB) { - db = serviceDB; + _db = serviceDB; } QMap DeviceLogic::getAll() { - db->loadDeviceModels(); - return db->loadDevices(); + _db->loadDeviceModels(); + return _db->loadDevices(); } QList DeviceLogic::getAllByParameters( - int entityId, int currentEntity, + int entityId, EntityType entityType, QString searchText, const FilterParams &filterParams, const QString &sortOrder ) { - db->loadDeviceModels(); - auto devices = db->loadDevices(); - auto filteredDevices = filterByEntity(devices, entityId, currentEntity); + _db->loadDeviceModels(); + auto devices = _db->loadDevices(); + auto filteredDevices = filterByEntity(devices, entityId, entityType); filteredDevices = searchDevices(filteredDevices, searchText); filteredDevices = applyFilters(filteredDevices, filterParams); return sortDevices(filteredDevices, sortOrder); @@ -28,38 +28,50 @@ QList DeviceLogic::getAllByParameters( bool DeviceLogic::updateDevice(const Device &device) { - return db->updateDevice(device); + if (device.serialNumber().isEmpty()) { + qDebug() << "Неверный серийный номер устройства, переданного для обновления" << device.serialNumber(); + return false; + } + if (device.price() <= 0) { + qDebug() << "Неверная цена устройства, переданного для обновления" << device.price(); + return false; + } + if (device.purchaseDate() > device.warrantyExpireDate()) { + qDebug() << "Для корректного обновления устройства необходимо учитывать, что дата покупки не может быть позже даты истечения гарантии"; + return false; + } + return _db->updateDevice(device); } -QMap DeviceLogic::filterByEntity(const QMap &devices, int entityId, int currentEntity) +QMap DeviceLogic::filterByEntity(const QMap &devices, int entityId, EntityType entityType) { QMap result; - if (entityId == -1 || currentEntity == 0) - return devices; // "Все устройства" + if (entityId == -1 || entityType == EntityType::All) + return devices; for (auto &device : devices) { - switch (currentEntity) { - case 1: // Типы устройств - if (device.deviceModel().idType() == entityId) - result.insert(device.id(), device); - break; - case 2: // Помещения - if (device.idLocation() == entityId) - result.insert(device.id(), device); - break; - case 3: // Отделы - if (device.idDepartment() == entityId) - result.insert(device.id(), device); - break; - case 4: // Производители - if (device.deviceModel().idManuf() == entityId) - result.insert(device.id(), device); - break; - case 5: // Модели устройств - if (device.deviceModel().id() == entityId) - result.insert(device.id(), device); - break; - default: break; + switch (entityType) { + case EntityType::DeviceTypes: + if (device.deviceModel().idType() == entityId) + result.insert(device.id(), device); + break; + case EntityType::Locations: + if (device.idLocation() == entityId) + result.insert(device.id(), device); + break; + case EntityType::Departments: + if (device.idDepartment() == entityId) + result.insert(device.id(), device); + break; + case EntityType::Manufacturers: + if (device.deviceModel().idManuf() == entityId) + result.insert(device.id(), device); + break; + case EntityType::DeviceModels: + if (device.deviceModel().id() == entityId) + result.insert(device.id(), device); + break; + default: break; } } return result; @@ -83,10 +95,11 @@ QMap DeviceLogic::searchDevices(const QMap &devices, c QMap DeviceLogic::applyFilters(const QMap &devices, const FilterParams &filterParams) { - if (!filterParams.getApllyFilters()) + if (!filterParams.apllyFilters()) return devices; + QMap result; - if (filterParams.getDisregardState()) + if (filterParams.disregardState()) { for (auto &device : devices) { if (device.price() < filterParams.priceFrom() || device.price() > filterParams.priceTo()) diff --git a/service/businesslogic/devicelogic.h b/service/businesslogic/devicelogic.h index 3ca53f7..e66a071 100644 --- a/service/businesslogic/devicelogic.h +++ b/service/businesslogic/devicelogic.h @@ -3,6 +3,7 @@ #include "service/serviceloaddb.h" #include "models/filterparams.h" +#include "models/enums/entitytype.h" class DeviceLogic { @@ -11,7 +12,7 @@ public: QMap getAll(); QList getAllByParameters( int entityId, - int currentEntity, + EntityType entityType, QString searchText, const FilterParams &filterParams, const QString &sortOrder @@ -19,13 +20,13 @@ public: bool updateDevice(const Device &device); private: - QMap filterByEntity(const QMap &devices, int entityId, int currentEntity); + QMap filterByEntity(const QMap &devices, int entityId, EntityType entityType); QMap searchDevices(const QMap &devices, const QString &searchText); QMap applyFilters(const QMap &devices, const FilterParams &filterParams); QList sortDevices(QMap &devices, const QString &sortOrder); private: - ServiceLoadDB *db; + ServiceLoadDB *_db; }; #endif // DEVICELOGIC_H diff --git a/service/businesslogic/devicemodellogic.cpp b/service/businesslogic/devicemodellogic.cpp index 6d78713..1d1c923 100644 --- a/service/businesslogic/devicemodellogic.cpp +++ b/service/businesslogic/devicemodellogic.cpp @@ -2,10 +2,10 @@ DeviceModelLogic::DeviceModelLogic(ServiceLoadDB *serviceDB) { - db = serviceDB; + _db = serviceDB; } QMap DeviceModelLogic::getAll() { - return db->loadDeviceModels(); + return _db->loadDeviceModels(); } diff --git a/service/businesslogic/devicemodellogic.h b/service/businesslogic/devicemodellogic.h index 76a5354..179fdd7 100644 --- a/service/businesslogic/devicemodellogic.h +++ b/service/businesslogic/devicemodellogic.h @@ -10,7 +10,7 @@ public: QMap getAll(); private: - ServiceLoadDB *db; + ServiceLoadDB *_db; }; #endif // DEVICEMODELLOGIC_H diff --git a/service/businesslogic/devicetypelogic.cpp b/service/businesslogic/devicetypelogic.cpp index 9ceec04..e52aa5b 100644 --- a/service/businesslogic/devicetypelogic.cpp +++ b/service/businesslogic/devicetypelogic.cpp @@ -2,10 +2,10 @@ DeviceTypeLogic::DeviceTypeLogic(ServiceLoadDB *serviceDB) { - db = serviceDB; + _db = serviceDB; } QMap DeviceTypeLogic::getAll() { - return db->loadDeviceTypes(); + return _db->loadDeviceTypes(); } diff --git a/service/businesslogic/devicetypelogic.h b/service/businesslogic/devicetypelogic.h index d42b34a..7687c8f 100644 --- a/service/businesslogic/devicetypelogic.h +++ b/service/businesslogic/devicetypelogic.h @@ -10,7 +10,7 @@ public: QMap getAll(); private: - ServiceLoadDB *db; + ServiceLoadDB *_db; }; #endif // DEVICETYPELOGIC_H diff --git a/service/businesslogic/locationlogic.cpp b/service/businesslogic/locationlogic.cpp index 561b47f..3048676 100644 --- a/service/businesslogic/locationlogic.cpp +++ b/service/businesslogic/locationlogic.cpp @@ -2,10 +2,10 @@ LocationLogic::LocationLogic(ServiceLoadDB *serviceDB) { - db = serviceDB; + _db = serviceDB; } QMap LocationLogic::getAll() { - return db->loadLocations(); + return _db->loadLocations(); } diff --git a/service/businesslogic/locationlogic.h b/service/businesslogic/locationlogic.h index e5eaf2e..b2ff564 100644 --- a/service/businesslogic/locationlogic.h +++ b/service/businesslogic/locationlogic.h @@ -10,7 +10,7 @@ public: QMap getAll(); private: - ServiceLoadDB *db; + ServiceLoadDB *_db; }; #endif // LOCATIONLOGIC_H diff --git a/service/businesslogic/manufacturerlogic.cpp b/service/businesslogic/manufacturerlogic.cpp index d786381..0941791 100644 --- a/service/businesslogic/manufacturerlogic.cpp +++ b/service/businesslogic/manufacturerlogic.cpp @@ -2,10 +2,10 @@ ManufacturerLogic::ManufacturerLogic(ServiceLoadDB *serviceDB) { - db = serviceDB; + _db = serviceDB; } QMap ManufacturerLogic::getAll() { - return db->loadManufacturers(); + return _db->loadManufacturers(); } diff --git a/service/businesslogic/manufacturerlogic.h b/service/businesslogic/manufacturerlogic.h index 6fcd0ab..a13e4bc 100644 --- a/service/businesslogic/manufacturerlogic.h +++ b/service/businesslogic/manufacturerlogic.h @@ -10,7 +10,7 @@ public: QMap getAll(); private: - ServiceLoadDB *db; + ServiceLoadDB *_db; }; #endif // MANUFACTURERLOGIC_H diff --git a/service/serviceloaddb.cpp b/service/serviceloaddb.cpp index 2b2be47..cbd1152 100644 --- a/service/serviceloaddb.cpp +++ b/service/serviceloaddb.cpp @@ -5,35 +5,35 @@ ServiceLoadDB::ServiceLoadDB(QObject *parent) : QObject(parent) void ServiceLoadDB::start() { - db = QSqlDatabase::addDatabase("QPSQL"); - db.setHostName("127.0.0.1"); - db.setDatabaseName("hardware_accounting_db"); - db.setUserName("postgres"); - db.setPassword("pass"); - if(!db.open()){ + _db = QSqlDatabase::addDatabase("QPSQL"); + _db.setHostName("127.0.0.1"); + _db.setDatabaseName("hardware_accounting_db"); + _db.setUserName("postgres"); + _db.setPassword("pass"); + if(!_db.open()){ qDebug() << "Не удалось открыть БД"; return; } - query = QSqlQuery(db); + _query = QSqlQuery(_db); } QMap ServiceLoadDB::loadLocations() { QMap mapLocations; - db_input = "SELECT * FROM public.location"; - if (!query.exec(db_input)) { - qDebug() << "Ошибка запроса к таблице location: " << query.lastError().text(); + _dbInput = "SELECT * FROM public.location"; + if (!_query.exec(_dbInput)) { + qDebug() << "Ошибка запроса к таблице location: " << _query.lastError().text(); return mapLocations; } QSqlRecord rec; - while (query.next()) { - rec = query.record(); + while (_query.next()) { + rec = _query.record(); Location location; - location.setId(query.value(rec.indexOf("id")).toInt()); - location.setName(query.value(rec.indexOf("name")).toString()); + location.setId(_query.value(rec.indexOf("id")).toInt()); + location.setName(_query.value(rec.indexOf("name")).toString()); mapLocations.insert(location.id(), location); } @@ -45,19 +45,19 @@ QMap ServiceLoadDB::loadDepartments() { QMap mapDepartments; - db_input = "SELECT * FROM public.department"; - if (!query.exec(db_input)) { - qDebug() << "Ошибка запроса к таблице department: " << query.lastError().text(); + _dbInput = "SELECT * FROM public.department"; + if (!_query.exec(_dbInput)) { + qDebug() << "Ошибка запроса к таблице department: " << _query.lastError().text(); return mapDepartments; } QSqlRecord rec; - while (query.next()) { - rec = query.record(); + while (_query.next()) { + rec = _query.record(); Department department; - department.setId(query.value(rec.indexOf("id")).toInt()); - department.setName(query.value(rec.indexOf("name")).toString()); + department.setId(_query.value(rec.indexOf("id")).toInt()); + department.setName(_query.value(rec.indexOf("name")).toString()); mapDepartments.insert(department.id(), department); } @@ -69,19 +69,19 @@ QMap ServiceLoadDB::loadManufacturers() { QMap mapManufacturers; - db_input = "SELECT * FROM public.manufacturer"; - if (!query.exec(db_input)) { - qDebug() << "Ошибка запроса к таблице manufacturer: " << query.lastError().text(); + _dbInput = "SELECT * FROM public.manufacturer"; + if (!_query.exec(_dbInput)) { + qDebug() << "Ошибка запроса к таблице manufacturer: " << _query.lastError().text(); return mapManufacturers; } QSqlRecord rec; - while (query.next()) { - rec = query.record(); + while (_query.next()) { + rec = _query.record(); Manufacturer manufacturer; - manufacturer.setId(query.value(rec.indexOf("id")).toInt()); - manufacturer.setName(query.value(rec.indexOf("name")).toString()); + manufacturer.setId(_query.value(rec.indexOf("id")).toInt()); + manufacturer.setName(_query.value(rec.indexOf("name")).toString()); mapManufacturers.insert(manufacturer.id(), manufacturer); } @@ -93,19 +93,19 @@ QMap ServiceLoadDB::loadDeviceTypes() { QMap mapDeviceTypes; - db_input = "SELECT * FROM public.device_type"; - if (!query.exec(db_input)) { - qDebug() << "Ошибка запроса к таблице device_type: " << query.lastError().text(); + _dbInput = "SELECT * FROM public.device_type"; + if (!_query.exec(_dbInput)) { + qDebug() << "Ошибка запроса к таблице device_type: " << _query.lastError().text(); return mapDeviceTypes; } QSqlRecord rec; - while (query.next()) { - rec = query.record(); + while (_query.next()) { + rec = _query.record(); DeviceType deviceType; - deviceType.setId(query.value(rec.indexOf("id")).toInt()); - deviceType.setName(query.value(rec.indexOf("name")).toString()); + deviceType.setId(_query.value(rec.indexOf("id")).toInt()); + deviceType.setName(_query.value(rec.indexOf("name")).toString()); mapDeviceTypes.insert(deviceType.id(), deviceType); } @@ -121,38 +121,38 @@ QMap ServiceLoadDB::loadDeviceModels() return QMap(); } - db_input = QString(file.readAll()); + _dbInput = QString(file.readAll()); - if (!query.exec(db_input)) { - qDebug() << "Ошибка запроса при получении информации о моделях устройств: " << query.lastError().text(); + if (!_query.exec(_dbInput)) { + qDebug() << "Ошибка запроса при получении информации о моделях устройств: " << _query.lastError().text(); return QMap(); } QSqlRecord rec; - while (query.next()) { - rec = query.record(); + while (_query.next()) { + rec = _query.record(); DeviceModel deviceModel; - int id = query.value(rec.indexOf("id")).toInt(); + int id = _query.value(rec.indexOf("id")).toInt(); deviceModel.setId(id); - deviceModel.setName(query.value(rec.indexOf("name")).toString()); - deviceModel.setDescription(query.value(rec.indexOf("description")).toString()); - deviceModel.setWorkEfficiency(query.value(rec.indexOf("work_efficiency")).toInt()); - deviceModel.setReliability(query.value(rec.indexOf("reliability")).toInt()); - deviceModel.setEnergyEfficiency(query.value(rec.indexOf("energy_efficiency")).toInt()); - deviceModel.setUserFriendliness(query.value(rec.indexOf("user_friendliness")).toInt()); - deviceModel.setDurability(query.value(rec.indexOf("durability")).toInt()); - deviceModel.setAestheticQualities(query.value(rec.indexOf("aesthetic_qualities")).toInt()); - deviceModel.setIdType(query.value(rec.indexOf("fk_id_type")).toInt()); - deviceModel.setNameType(query.value(rec.indexOf("device_type_name")).toString()); - deviceModel.setIdManuf(query.value(rec.indexOf("fk_id_manuf")).toInt()); - deviceModel.setNameManuf(query.value(rec.indexOf("manufacturer_name")).toString()); + deviceModel.setName(_query.value(rec.indexOf("name")).toString()); + deviceModel.setDescription(getValueOrDefault(_query, rec, "description", QString("Описание отсутствует"))); + deviceModel.setWorkEfficiency(_query.value(rec.indexOf("work_efficiency")).toInt()); + deviceModel.setReliability(_query.value(rec.indexOf("reliability")).toInt()); + deviceModel.setEnergyEfficiency(_query.value(rec.indexOf("energy_efficiency")).toInt()); + deviceModel.setUserFriendliness(_query.value(rec.indexOf("user_friendliness")).toInt()); + deviceModel.setDurability(_query.value(rec.indexOf("durability")).toInt()); + deviceModel.setAestheticQualities(_query.value(rec.indexOf("aesthetic_qualities")).toInt()); + deviceModel.setIdType(_query.value(rec.indexOf("fk_id_type")).toInt()); + deviceModel.setNameType(_query.value(rec.indexOf("device_type_name")).toString()); + deviceModel.setIdManuf(_query.value(rec.indexOf("fk_id_manuf")).toInt()); + deviceModel.setNameManuf(_query.value(rec.indexOf("manufacturer_name")).toString()); deviceModel.setStructureElements(readStructureElements(id)); - mapDeviceModels.insert(deviceModel.id(), deviceModel); + _mapDeviceModels.insert(deviceModel.id(), deviceModel); } - return mapDeviceModels; + return _mapDeviceModels; } QMap ServiceLoadDB::loadDevices() @@ -160,50 +160,45 @@ QMap ServiceLoadDB::loadDevices() QMap mapDevices; QFile file("../../data/requestDevices.sql"); - if (!file.open(QIODevice::ReadOnly)) + if (!file.open(QIODevice::ReadOnly)) { + qDebug() << "Не получилось открыть файл \"requestDevices.sql\""; return mapDevices; + } - db_input = QString(file.readAll()); + _dbInput = QString(file.readAll()); - if (!query.exec(db_input)) { - qDebug() << "Ошибка запроса при получении информации о устройствах: " << query.lastError().text(); + if (!_query.exec(_dbInput)) { + qDebug() << "Ошибка запроса при получении информации о устройствах: " << _query.lastError().text(); return mapDevices; } QSqlRecord rec; - while (query.next()) { - rec = query.record(); + while (_query.next()) { + rec = _query.record(); Device device; - int id = query.value(rec.indexOf("id")).toInt(); - int idModel = query.value(rec.indexOf("fk_id_model")).toInt(); - if (!mapDeviceModels.contains(idModel)) { + int id = _query.value(rec.indexOf("id")).toInt(); + int idModel = _query.value(rec.indexOf("fk_id_model")).toInt(); + if (!_mapDeviceModels.contains(idModel)) { qDebug() << "Не загружена модель устройства. Идентификатор устройства: " << id; return QMap(); } - int idDepartment = 0; - QString nameDepartment = "Не относится к отделу"; - if (!query.value(rec.indexOf("department_id")).isNull()) { - idDepartment = query.value(rec.indexOf("department_id")).toInt(); - nameDepartment = query.value(rec.indexOf("department_name")).toString(); - } - device.setId(id); - device.setSerialNumber(query.value(rec.indexOf("serial_number")).toString()); - device.setPurchaseDate(query.value(rec.indexOf("purchase_date")).toDateTime()); - device.setPrice(query.value(rec.indexOf("price")).toDouble()); - device.setWarrantyExpireDate(query.value(rec.indexOf("warranty_expire_date")).toDateTime()); - device.setIsWorking(query.value(rec.indexOf("is_working")).toBool()); - device.setFurtherInformation(query.value(rec.indexOf("further_information")).toString()); - device.setIdLocation(query.value(rec.indexOf("fk_id_location")).toInt()); - device.setNameLocation(query.value(rec.indexOf("location_name")).toString()); - device.setIdEmployee(query.value(rec.indexOf("fk_id_employee")).toInt()); - device.setNameEmployee(query.value(rec.indexOf("employee_full_name")).toString()); - device.setIdDepartment(idDepartment); - device.setNameDepartment(nameDepartment); - device.setDeviceModel(mapDeviceModels[idModel]); - device.setIsLiked(query.value(rec.indexOf("is_liked")).toBool()); + device.setSerialNumber(_query.value(rec.indexOf("serial_number")).toString()); + device.setPurchaseDate(_query.value(rec.indexOf("purchase_date")).toDateTime()); + device.setPrice(_query.value(rec.indexOf("price")).toDouble()); + device.setWarrantyExpireDate(_query.value(rec.indexOf("warranty_expire_date")).toDateTime()); + device.setIsWorking(_query.value(rec.indexOf("is_working")).toBool()); + device.setFurtherInformation(getValueOrDefault(_query, rec, "further_information", QString(""))); + device.setIdLocation(_query.value(rec.indexOf("fk_id_location")).toInt()); + device.setNameLocation(_query.value(rec.indexOf("location_name")).toString()); + device.setIdEmployee(getValueOrDefault(_query, rec, "fk_id_employee", 0)); + device.setNameEmployee(getValueOrDefault(_query, rec, "employee_full_name", QString("Не назначен"))); + device.setIdDepartment(getValueOrDefault(_query, rec, "department_id", 0)); + device.setNameDepartment(getValueOrDefault(_query, rec, "department_name", QString("Не относится к отделу"))); + device.setDeviceModel(_mapDeviceModels[idModel]); + device.setIsLiked(_query.value(rec.indexOf("is_liked")).toBool()); mapDevices.insert(device.id(), device); } @@ -233,8 +228,8 @@ bool ServiceLoadDB::updateDevice(const Device &device) .arg(device.isLiked() ? "TRUE" : "FALSE") .arg(device.id()); - if (!query.exec(db_input)) { - qDebug() << "Ошибка обновления устройства с id = " << device.id() << ": " << query.lastError().text(); + if (!_query.exec(db_input)) { + qDebug() << "Ошибка обновления устройства с id = " << device.id() << ": " << _query.lastError().text(); return false; } @@ -244,8 +239,8 @@ bool ServiceLoadDB::updateDevice(const Device &device) QList ServiceLoadDB::readStructureElements(int modelId) { QSqlQuery secondQuery; - db_input = "SELECT * FROM get_model_structure(:model_id)"; - secondQuery.prepare(db_input); + _dbInput = "SELECT * FROM get_model_structure(:model_id)"; + secondQuery.prepare(_dbInput); secondQuery.bindValue(":model_id", modelId); if (!secondQuery.exec()) { qDebug() << "Ошибка при выполнении запроса для получения элементов структуры: " << secondQuery.lastError().text(); @@ -270,3 +265,13 @@ QList ServiceLoadDB::readStructureElements(int modelId) return elements; } + +template +T ServiceLoadDB::getValueOrDefault(const QSqlQuery &query, const QSqlRecord &record, const QString &fieldName, const T &defaultValue) +{ + int index = record.indexOf(fieldName); + if (index == -1 || query.value(index).isNull()) { + return defaultValue; + } + return query.value(index).value(); +} diff --git a/service/serviceloaddb.h b/service/serviceloaddb.h index 39f35ab..f1ca7aa 100644 --- a/service/serviceloaddb.h +++ b/service/serviceloaddb.h @@ -19,6 +19,7 @@ class ServiceLoadDB : public QObject { Q_OBJECT + public: explicit ServiceLoadDB(QObject *parent = nullptr); void start(); @@ -33,12 +34,15 @@ public: private: QList readStructureElements(int modelId); -private: - QSqlDatabase db; - QString db_input; - QSqlQuery query; + template + T getValueOrDefault(const QSqlQuery &query, const QSqlRecord &record, const QString &fieldName, const T &defaultValue); - QMap mapDeviceModels; +private: + QSqlDatabase _db; + QString _dbInput; + QSqlQuery _query; + + QMap _mapDeviceModels; }; #endif // SERVICELOADDB_H