From 462357e3c779f262f7a7300fac84bf007b75e9d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=BB=D1=8C=D1=8F?= <Илья@WIN-RANNDDD> Date: Tue, 24 Dec 2024 18:02:23 +0400 Subject: [PATCH] Server part ready --- HardwareAccountingServer.pro | 59 +++++ apiserver.cpp | 228 ++++++++++++++++ apiserver.h | 46 ++++ data/requestDeviceModels.sql | 10 + data/requestDevices.sql | 14 + data/updateDevice.sql | 12 + main.cpp | 16 ++ models/baseentity.cpp | 14 + models/baseentity.h | 21 ++ models/department.cpp | 31 +++ models/department.h | 24 ++ models/device.cpp | 190 ++++++++++++++ models/device.h | 78 ++++++ models/devicemodel.cpp | 190 ++++++++++++++ models/devicemodel.h | 75 ++++++ models/devicestructureelement.cpp | 79 ++++++ models/devicestructureelement.h | 40 +++ models/devicetype.cpp | 31 +++ models/devicetype.h | 24 ++ models/filterparams.cpp | 54 ++++ models/filterparams.h | 32 +++ models/location.cpp | 31 +++ models/location.h | 24 ++ models/manufacturer.cpp | 31 +++ models/manufacturer.h | 24 ++ models/types.h | 12 + service/businesslogic/departmentlogic.cpp | 11 + service/businesslogic/departmentlogic.h | 16 ++ service/businesslogic/devicelogic.cpp | 142 ++++++++++ service/businesslogic/devicelogic.h | 31 +++ service/businesslogic/devicemodellogic.cpp | 11 + service/businesslogic/devicemodellogic.h | 16 ++ service/businesslogic/devicetypelogic.cpp | 11 + service/businesslogic/devicetypelogic.h | 16 ++ service/businesslogic/locationlogic.cpp | 11 + service/businesslogic/locationlogic.h | 16 ++ service/businesslogic/manufacturerlogic.cpp | 11 + service/businesslogic/manufacturerlogic.h | 16 ++ service/serviceloaddb.cpp | 272 ++++++++++++++++++++ service/serviceloaddb.h | 44 ++++ 40 files changed, 2014 insertions(+) create mode 100644 HardwareAccountingServer.pro create mode 100644 apiserver.cpp create mode 100644 apiserver.h create mode 100644 data/requestDeviceModels.sql create mode 100644 data/requestDevices.sql create mode 100644 data/updateDevice.sql create mode 100644 main.cpp create mode 100644 models/baseentity.cpp create mode 100644 models/baseentity.h create mode 100644 models/department.cpp create mode 100644 models/department.h create mode 100644 models/device.cpp create mode 100644 models/device.h create mode 100644 models/devicemodel.cpp create mode 100644 models/devicemodel.h create mode 100644 models/devicestructureelement.cpp create mode 100644 models/devicestructureelement.h create mode 100644 models/devicetype.cpp create mode 100644 models/devicetype.h create mode 100644 models/filterparams.cpp create mode 100644 models/filterparams.h create mode 100644 models/location.cpp create mode 100644 models/location.h create mode 100644 models/manufacturer.cpp create mode 100644 models/manufacturer.h create mode 100644 models/types.h create mode 100644 service/businesslogic/departmentlogic.cpp create mode 100644 service/businesslogic/departmentlogic.h create mode 100644 service/businesslogic/devicelogic.cpp create mode 100644 service/businesslogic/devicelogic.h create mode 100644 service/businesslogic/devicemodellogic.cpp create mode 100644 service/businesslogic/devicemodellogic.h create mode 100644 service/businesslogic/devicetypelogic.cpp create mode 100644 service/businesslogic/devicetypelogic.h create mode 100644 service/businesslogic/locationlogic.cpp create mode 100644 service/businesslogic/locationlogic.h create mode 100644 service/businesslogic/manufacturerlogic.cpp create mode 100644 service/businesslogic/manufacturerlogic.h create mode 100644 service/serviceloaddb.cpp create mode 100644 service/serviceloaddb.h diff --git a/HardwareAccountingServer.pro b/HardwareAccountingServer.pro new file mode 100644 index 0000000..ccad961 --- /dev/null +++ b/HardwareAccountingServer.pro @@ -0,0 +1,59 @@ +QT += core sql httpserver + +CONFIG += c++17 cmdline + +QMAKE_CXXFLAGS_WARN_ON += -Wno-unused-parameter + +# You can make your code fail to compile if it uses deprecated APIs. +# In order to do so, uncomment the following line. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +SOURCES += \ + apiserver.cpp \ + main.cpp \ + models/baseentity.cpp \ + models/department.cpp \ + models/device.cpp \ + models/devicemodel.cpp \ + models/devicestructureelement.cpp \ + models/devicetype.cpp \ + models/filterparams.cpp \ + models/location.cpp \ + models/manufacturer.cpp \ + service/businesslogic/departmentlogic.cpp \ + service/businesslogic/devicelogic.cpp \ + service/businesslogic/devicemodellogic.cpp \ + service/businesslogic/devicetypelogic.cpp \ + service/businesslogic/locationlogic.cpp \ + service/businesslogic/manufacturerlogic.cpp \ + service/serviceloaddb.cpp + +# Default rules for deployment. +qnx: target.path = /tmp/$${TARGET}/bin +else: unix:!android: target.path = /opt/$${TARGET}/bin +!isEmpty(target.path): INSTALLS += target + +DISTFILES += \ + data/requestDeviceModels.sql \ + data/requestDevices.sql \ + data/updateDevice.sql + +HEADERS += \ + apiserver.h \ + models/baseentity.h \ + models/department.h \ + models/device.h \ + models/devicemodel.h \ + models/devicestructureelement.h \ + models/devicetype.h \ + models/filterparams.h \ + models/location.h \ + models/manufacturer.h \ + models/types.h \ + service/businesslogic/departmentlogic.h \ + service/businesslogic/devicelogic.h \ + service/businesslogic/devicemodellogic.h \ + service/businesslogic/devicetypelogic.h \ + service/businesslogic/locationlogic.h \ + service/businesslogic/manufacturerlogic.h \ + service/serviceloaddb.h diff --git a/apiserver.cpp b/apiserver.cpp new file mode 100644 index 0000000..51ff1fd --- /dev/null +++ b/apiserver.cpp @@ -0,0 +1,228 @@ +#include "apiserver.h" + +ApiServer::ApiServer() { + server.route("/api/devices", QHttpServerRequest::Method::Get, + [this](const QHttpServerRequest &request) { + return handleGetFilteredDevices(request); + }); + + server.route("/api/departments", QHttpServerRequest::Method::Get, + [this](const QHttpServerRequest &request) { + return handleGetAllDepartments(request); + }); + + server.route("/api/devicemodels", QHttpServerRequest::Method::Get, + [this](const QHttpServerRequest &request) { + return handleGetAllDeviceModels(request); + }); + + server.route("/api/devicetypes", QHttpServerRequest::Method::Get, + [this](const QHttpServerRequest &request) { + return handleGetAllDeviceTypes(request); + }); + + server.route("/api/locations", QHttpServerRequest::Method::Get, + [this](const QHttpServerRequest &request) { + return handleGetAllLocations(request); + }); + + server.route("/api/manufacturers", QHttpServerRequest::Method::Get, + [this](const QHttpServerRequest &request) { + return handleGetAllManufacturers(request); + }); + + server.route("/api/devices/", QHttpServerRequest::Method::Put, + [this](int id, const QHttpServerRequest &request) { + return handleUpdateDevice(id, request); + }); +} + +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); +} + +QHttpServerResponse ApiServer::handleGetFilteredDevices(const QHttpServerRequest &request) +{ + QUrlQuery query = request.query(); + + bool isWorking = query.queryItemValue("isWorking") == "true"; + + bool priceFromOk; + double priceFrom = query.queryItemValue("priceFrom").toDouble(&priceFromOk); + if (!priceFromOk) { + return QHttpServerResponse("Invalid priceFrom value", QHttpServerResponse::StatusCode::BadRequest); + } + + 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); + } + + FilterParams filterParams; + filterParams.setIsWorking(isWorking); + filterParams.setPriceFrom(priceFrom); + filterParams.setPriceTo(priceTo); + filterParams.setApllyFilters(applyFilters); + filterParams.setDisregardState(disregardState); + + QList filteredDevices = deviceLogic->getAllByParameters( + entityId, + currentEntity, + searchText, + filterParams, + sortOrder + ); + + QJsonArray deviceArray; + for (const Device &device : filteredDevices) { + deviceArray.append(device.toJson()); + } + + QJsonObject responseObject; + responseObject["devices"] = deviceArray; + + return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok); +} + +QHttpServerResponse ApiServer::handleGetAllDepartments(const QHttpServerRequest &request) +{ + QMap departments = departmentLogic->getAll(); + + if (departments.isEmpty()) { + return QHttpServerResponse("Failed to retrieve departments", QHttpServerResponse::StatusCode::InternalServerError); + } + + QJsonArray departmentArray = createJsonArray(departments); + + QJsonObject responseObject; + responseObject["departments"] = departmentArray; + + return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok); +} + +QHttpServerResponse ApiServer::handleGetAllDeviceModels(const QHttpServerRequest &request) +{ + QMap deviceModels = deviceModelLogic->getAll(); + + if (deviceModels.isEmpty()) { + return QHttpServerResponse("Failed to retrieve device models", QHttpServerResponse::StatusCode::InternalServerError); + } + + QJsonArray deviceModelArray = createJsonArray(deviceModels); + + QJsonObject responseObject; + responseObject["deviceModels"] = deviceModelArray; + + return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok); +} + +QHttpServerResponse ApiServer::handleGetAllDeviceTypes(const QHttpServerRequest &request) +{ + QMap deviceTypes = deviceTypeLogic->getAll(); + + if (deviceTypes.isEmpty()) { + return QHttpServerResponse("Failed to retrieve device types", QHttpServerResponse::StatusCode::InternalServerError); + } + + QJsonArray deviceTypeArray = createJsonArray(deviceTypes); + + QJsonObject responseObject; + responseObject["deviceTypes"] = deviceTypeArray; + + return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok); +} + +QHttpServerResponse ApiServer::handleGetAllLocations(const QHttpServerRequest &request) +{ + QMap locations = locationLogic->getAll(); + + if (locations.isEmpty()) { + return QHttpServerResponse("Failed to retrieve locations", QHttpServerResponse::StatusCode::InternalServerError); + } + + QJsonArray locationArray = createJsonArray(locations); + + QJsonObject responseObject; + responseObject["locations"] = locationArray; + + return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok); +} + +QHttpServerResponse ApiServer::handleGetAllManufacturers(const QHttpServerRequest &request) +{ + QMap manufacturers = manufacturerLogic->getAll(); + + if (manufacturers.isEmpty()) { + return QHttpServerResponse("Failed to retrieve manufacturers", QHttpServerResponse::StatusCode::InternalServerError); + } + + QJsonArray manufacturerArray = createJsonArray(manufacturers); + + QJsonObject responseObject; + responseObject["manufacturers"] = manufacturerArray; + + return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok); +} + +QHttpServerResponse ApiServer::handleUpdateDevice(int id, const QHttpServerRequest &request) +{ + QByteArray body = request.body(); + QJsonDocument doc = QJsonDocument::fromJson(body); + + if (!doc.isObject()) { + return QHttpServerResponse("Invalid JSON", QHttpServerResponse::StatusCode::BadRequest); + } + + QJsonObject jsonObject = doc.object(); + + Device device; + device.fromJson(jsonObject); + device.setId(id); + + if (!deviceLogic->updateDevice(device)) { + return QHttpServerResponse("Failed to update device", QHttpServerResponse::StatusCode::InternalServerError); + } + + return QHttpServerResponse("Device updated successfully", QHttpServerResponse::StatusCode::Ok); +} + +template +QJsonArray ApiServer::createJsonArray(const QMap &items) +{ + QJsonArray itemArray; + for (const T &item : items) { + itemArray.append(item.toJson()); + } + return itemArray; +} diff --git a/apiserver.h b/apiserver.h new file mode 100644 index 0000000..d65c52c --- /dev/null +++ b/apiserver.h @@ -0,0 +1,46 @@ +#ifndef APISERVER_H +#define APISERVER_H + +#include +#include +#include +#include +#include +#include + +#include "service/businesslogic/devicelogic.h" +#include "service/businesslogic/departmentlogic.h" +#include "service/businesslogic/devicemodellogic.h" +#include "service/businesslogic/devicetypelogic.h" +#include "service/businesslogic/locationlogic.h" +#include "service/businesslogic/manufacturerlogic.h" + +class ApiServer +{ +public: + ApiServer(); + 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); + QHttpServerResponse handleGetAllDeviceTypes(const QHttpServerRequest &request); + QHttpServerResponse handleGetAllLocations(const QHttpServerRequest &request); + QHttpServerResponse handleGetAllManufacturers(const QHttpServerRequest &request); + QHttpServerResponse handleUpdateDevice(int id, const QHttpServerRequest &request); + + template + QJsonArray createJsonArray(const QMap &items); +}; + +#endif // APISERVER_H diff --git a/data/requestDeviceModels.sql b/data/requestDeviceModels.sql new file mode 100644 index 0000000..ae5c57f --- /dev/null +++ b/data/requestDeviceModels.sql @@ -0,0 +1,10 @@ +SELECT + dm.*, + dt.name AS device_type_name, + m.name AS manufacturer_name +FROM + device_model dm +JOIN + device_type dt ON dm.fk_id_type = dt.id +JOIN + manufacturer m ON dm.fk_id_manuf = m.id; diff --git a/data/requestDevices.sql b/data/requestDevices.sql new file mode 100644 index 0000000..80abb1d --- /dev/null +++ b/data/requestDevices.sql @@ -0,0 +1,14 @@ +SELECT + d.*, + l.name AS location_name, + 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 +FROM + device d +JOIN + location l ON d.fk_id_location = l.id +JOIN + employee e ON d.fk_id_employee = e.id +JOIN + department dep ON e.fk_id_department = dep.id; diff --git a/data/updateDevice.sql b/data/updateDevice.sql new file mode 100644 index 0000000..3b88b7a --- /dev/null +++ b/data/updateDevice.sql @@ -0,0 +1,12 @@ +UPDATE device +SET serial_number = '%1', + purchase_date = '%2', + price = '%3', + warranty_expire_date = '%4', + is_working = '%5', + further_information = '%6', + fk_id_location = '%7', + fk_id_employee = '%8', + fk_id_model = '%9', + is_liked = '%10' +WHERE id = '%11'; diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..e28d6f2 --- /dev/null +++ b/main.cpp @@ -0,0 +1,16 @@ +#include +#include "service/serviceloaddb.h" +#include "apiserver.h" + +int main(int argc, char *argv[]) +{ + QCoreApplication a(argc, argv); + + ServiceLoadDB *db = new ServiceLoadDB(); + ApiServer *server = new ApiServer(); + + db->start(); + server->start(db); + + return a.exec(); +} diff --git a/models/baseentity.cpp b/models/baseentity.cpp new file mode 100644 index 0000000..db5aa17 --- /dev/null +++ b/models/baseentity.cpp @@ -0,0 +1,14 @@ +#include "baseentity.h" + +BaseEntity::BaseEntity() +{} + +int BaseEntity::id() const +{ + return _id; +} + +void BaseEntity::setId(int newId) +{ + _id = newId; +} diff --git a/models/baseentity.h b/models/baseentity.h new file mode 100644 index 0000000..beebd43 --- /dev/null +++ b/models/baseentity.h @@ -0,0 +1,21 @@ +#ifndef BASEENTITY_H +#define BASEENTITY_H + +#include + +class BaseEntity +{ +public: + BaseEntity(); + + int id() const; + void setId(int newId); + + virtual void fromJson(const QJsonObject &) {} + virtual QJsonObject toJson() const = 0; + +private: + int _id = 0; +}; + +#endif // BASEENTITY_H diff --git a/models/department.cpp b/models/department.cpp new file mode 100644 index 0000000..2456e90 --- /dev/null +++ b/models/department.cpp @@ -0,0 +1,31 @@ +#include "department.h" + +Department::Department() +{} + +Department::~Department() +{} + +QString Department::name() const +{ + return _name; +} + +void Department::setName(const QString &newName) +{ + _name = newName; +} + +void Department::fromJson(const QJsonObject &json) +{ + setId(json["id"].toInt()); + setName(json["name"].toString()); +} + +QJsonObject Department::toJson() const +{ + QJsonObject obj; + obj["id"] = id(); + obj["name"] = name(); + return obj; +} diff --git a/models/department.h b/models/department.h new file mode 100644 index 0000000..5b39401 --- /dev/null +++ b/models/department.h @@ -0,0 +1,24 @@ +#ifndef DEPARTMENT_H +#define DEPARTMENT_H + +#include + +#include "baseentity.h" + +class Department : public BaseEntity +{ +public: + Department(); + virtual ~Department(); + + QString name() const; + void setName(const QString &newName); + + void fromJson(const QJsonObject &json) override; + QJsonObject toJson() const override; + +private: + QString _name = ""; +}; + +#endif // DEPARTMENT_H diff --git a/models/device.cpp b/models/device.cpp new file mode 100644 index 0000000..a834707 --- /dev/null +++ b/models/device.cpp @@ -0,0 +1,190 @@ +#include "device.h" + +Device::Device() +{} + +Device::~Device() +{} + +QString Device::serialNumber() const +{ + return _serialNumber; +} + +void Device::setSerialNumber(const QString &newSerialNumber) +{ + _serialNumber = newSerialNumber; +} + +QDateTime Device::purchaseDate() const +{ + return _purchaseDate; +} + +void Device::setPurchaseDate(const QDateTime &newPurchaseDate) +{ + _purchaseDate = newPurchaseDate; +} + +double Device::price() const +{ + return _price; +} + +void Device::setPrice(double newPrice) +{ + _price = newPrice; +} + +QDateTime Device::warrantyExpireDate() const +{ + return _warrantyExpireDate; +} + +void Device::setWarrantyExpireDate(const QDateTime &newWarrantyExpireDate) +{ + _warrantyExpireDate = newWarrantyExpireDate; +} + +bool Device::isWorking() const +{ + return _isWorking; +} + +void Device::setIsWorking(bool newIsWorking) +{ + _isWorking = newIsWorking; +} + +QString Device::furtherInformation() const +{ + return _furtherInformation; +} + +void Device::setFurtherInformation(const QString &newFurtherInformation) +{ + _furtherInformation = newFurtherInformation; +} + +int Device::idLocation() const +{ + return _idLocation; +} + +void Device::setIdLocation(int newIdLocation) +{ + _idLocation = newIdLocation; +} + +QString Device::nameLocation() const +{ + return _nameLocation; +} + +void Device::setNameLocation(const QString &newNameLocation) +{ + _nameLocation = newNameLocation; +} + +int Device::idEmployee() const +{ + return _idEmployee; +} + +void Device::setIdEmployee(int newIdEmployee) +{ + _idEmployee = newIdEmployee; +} + +QString Device::nameEmployee() const +{ + return _nameEmployee; +} + +void Device::setNameEmployee(const QString &newNameEmployee) +{ + _nameEmployee = newNameEmployee; +} + +int Device::idDepartment() const +{ + return _idDepartment; +} + +void Device::setIdDepartment(int newIdDepartment) +{ + _idDepartment = newIdDepartment; +} + +QString Device::nameDepartment() const +{ + return _nameDepartment; +} + +void Device::setNameDepartment(const QString &newNameDepartment) +{ + _nameDepartment = newNameDepartment; +} + +DeviceModel Device::deviceModel() const +{ + return _deviceModel; +} + +void Device::setDeviceModel(const DeviceModel &newDeviceModel) +{ + _deviceModel = newDeviceModel; +} + +bool Device::isLiked() const +{ + return _isLiked; +} + +void Device::setIsLiked(bool newIsLiked) +{ + _isLiked = newIsLiked; +} + +void Device::fromJson(const QJsonObject &json) +{ + setId(json["id"].toInt()); + setSerialNumber(json["serialNumber"].toString()); + setPurchaseDate(QDateTime::fromString(json["purchaseDate"].toString(), Qt::ISODate)); + setPrice(json["price"].toDouble()); + setWarrantyExpireDate(QDateTime::fromString(json["warrantyExpireDate"].toString(), Qt::ISODate)); + setIsWorking(json["isWorking"].toBool()); + setFurtherInformation(json["furtherInformation"].toString()); + setIdLocation(json["idLocation"].toInt()); + setNameLocation(json["nameLocation"].toString()); + setIdEmployee(json["idEmployee"].toInt()); + setNameEmployee(json["nameEmployee"].toString()); + setIdDepartment(json["idDepartment"].toInt()); + setNameDepartment(json["nameDepartment"].toString()); + setIsLiked(json["isLiked"].toBool()); + + DeviceModel model; + model.setId(json["idDeviceModel"].toInt()); + setDeviceModel(model); +} + +QJsonObject Device::toJson() const +{ + QJsonObject obj; + obj["id"] = id(); + obj["serialNumber"] = serialNumber(); + obj["purchaseDate"] = purchaseDate().toString(Qt::ISODate); + obj["price"] = price(); + obj["warrantyExpireDate"] = warrantyExpireDate().toString(Qt::ISODate); + obj["isWorking"] = isWorking(); + obj["furtherInformation"] = furtherInformation(); + obj["idLocation"] = idLocation(); + obj["nameLocation"] = nameLocation(); + obj["idEmployee"] = idEmployee(); + obj["nameEmployee"] = nameEmployee(); + obj["idDepartment"] = idDepartment(); + obj["nameDepartment"] = nameDepartment(); + obj["idDeviceModel"] = deviceModel().id(); + obj["isLiked"] = isLiked(); + return obj; +} diff --git a/models/device.h b/models/device.h new file mode 100644 index 0000000..590611e --- /dev/null +++ b/models/device.h @@ -0,0 +1,78 @@ +#ifndef DEVICE_H +#define DEVICE_H + +#include +#include + +#include "devicemodel.h" +#include "baseentity.h" + +class Device : public BaseEntity +{ +public: + Device(); + virtual ~Device(); + + QString serialNumber() const; + void setSerialNumber(const QString &newSerialNumber); + + QDateTime purchaseDate() const; + void setPurchaseDate(const QDateTime &newPurchaseDate); + + double price() const; + void setPrice(double newPrice); + + QDateTime warrantyExpireDate() const; + void setWarrantyExpireDate(const QDateTime &newWarrantyExpireDate); + + bool isWorking() const; + void setIsWorking(bool newIsWorking); + + QString furtherInformation() const; + void setFurtherInformation(const QString &newFurtherInformation); + + int idLocation() const; + void setIdLocation(int newIdLocation); + + QString nameLocation() const; + void setNameLocation(const QString &newNameLocation); + + int idEmployee() const; + void setIdEmployee(int newIdEmployee); + + QString nameEmployee() const; + void setNameEmployee(const QString &newNameEmployee); + + int idDepartment() const; + void setIdDepartment(int newIdDepartment); + + QString nameDepartment() const; + void setNameDepartment(const QString &newNameDepartment); + + DeviceModel deviceModel() const; + void setDeviceModel(const DeviceModel &newDeviceModel); + + bool isLiked() const; + void setIsLiked(bool newIsLiked); + + void fromJson(const QJsonObject &json) override; + QJsonObject toJson() const override; + +private: + QString _serialNumber = ""; + QDateTime _purchaseDate = QDateTime(); + double _price = 1; + QDateTime _warrantyExpireDate = QDateTime(); + bool _isWorking = true; + QString _furtherInformation = ""; + int _idLocation = 0; + QString _nameLocation = ""; + int _idEmployee = 0; + QString _nameEmployee = ""; + int _idDepartment = 0; + QString _nameDepartment = ""; + DeviceModel _deviceModel; + bool _isLiked = false; +}; + +#endif // DEVICE_H diff --git a/models/devicemodel.cpp b/models/devicemodel.cpp new file mode 100644 index 0000000..d132f9f --- /dev/null +++ b/models/devicemodel.cpp @@ -0,0 +1,190 @@ +#include "devicemodel.h" + +DeviceModel::DeviceModel() +{} + +DeviceModel::~DeviceModel() +{} + +QString DeviceModel::name() const +{ + return _name; +} + +void DeviceModel::setName(const QString &newName) +{ + _name = newName; +} + +QString DeviceModel::description() const +{ + return _description; +} + +void DeviceModel::setDescription(const QString &newDescription) +{ + _description = newDescription; +} + +int DeviceModel::workEfficiency() const +{ + return _workEfficiency; +} + +void DeviceModel::setWorkEfficiency(int newWorkEfficiency) +{ + _workEfficiency = newWorkEfficiency; +} + +int DeviceModel::reliability() const +{ + return _reliability; +} + +void DeviceModel::setReliability(int newReliability) +{ + _reliability = newReliability; +} + +int DeviceModel::energyEfficiency() const +{ + return _energyEfficiency; +} + +void DeviceModel::setEnergyEfficiency(int newEnergyEfficiency) +{ + _energyEfficiency = newEnergyEfficiency; +} + +int DeviceModel::userFriendliness() const +{ + return _userFriendliness; +} + +void DeviceModel::setUserFriendliness(int newUserFriendliness) +{ + _userFriendliness = newUserFriendliness; +} + +int DeviceModel::durability() const +{ + return _durability; +} + +void DeviceModel::setDurability(int newDurability) +{ + _durability = newDurability; +} + +int DeviceModel::aestheticQualities() const +{ + return _aestheticQualities; +} + +void DeviceModel::setAestheticQualities(int newAestheticQualities) +{ + _aestheticQualities = newAestheticQualities; +} + +int DeviceModel::idType() const +{ + return _idType; +} + +void DeviceModel::setIdType(int newIdType) +{ + _idType = newIdType; +} + +QString DeviceModel::nameType() const +{ + return _nameType; +} + +void DeviceModel::setNameType(const QString &newNameType) +{ + _nameType = newNameType; +} + +int DeviceModel::idManuf() const +{ + return _idManuf; +} + +void DeviceModel::setIdManuf(int newIdManuf) +{ + _idManuf = newIdManuf; +} + +QString DeviceModel::nameManuf() const +{ + return _nameManuf; +} + +void DeviceModel::setNameManuf(const QString &newNameManuf) +{ + _nameManuf = newNameManuf; +} + +QList DeviceModel::structureElements() const +{ + return _structureElements; +} + +void DeviceModel::setStructureElements(const QList &newStructureElements) +{ + _structureElements = newStructureElements; +} + +void DeviceModel::fromJson(const QJsonObject &json) +{ + setId(json["id"].toInt()); + setName(json["name"].toString()); + setDescription(json["description"].toString()); + setWorkEfficiency(json["workEfficiency"].toInt()); + setReliability(json["reliability"].toInt()); + setEnergyEfficiency(json["energyEfficiency"].toInt()); + setUserFriendliness(json["userFriendliness"].toInt()); + setDurability(json["durability"].toInt()); + setAestheticQualities(json["aestheticQualities"].toInt()); + setIdType(json["idType"].toInt()); + setNameType(json["nameType"].toString()); + setIdManuf(json["idManuf"].toInt()); + setNameManuf(json["nameManuf"].toString()); + + QJsonArray structureElementsArray = json["structureElements"].toArray(); + QList elements; + for (const QJsonValue &value : structureElementsArray) { + DeviceStructureElement element; + element.fromJson(value.toObject()); + elements.append(element); + } + setStructureElements(elements); +} + +QJsonObject DeviceModel::toJson() const +{ + QJsonObject obj; + + obj["id"] = id(); + obj["name"] = name(); + obj["description"] = description(); + obj["workEfficiency"] = workEfficiency(); + obj["reliability"] = reliability(); + obj["energyEfficiency"] = energyEfficiency(); + obj["userFriendliness"] = userFriendliness(); + obj["durability"] = durability(); + obj["aestheticQualities"] = aestheticQualities(); + obj["idType"] = idType(); + obj["nameType"] = nameType(); + obj["idManuf"] = idManuf(); + obj["nameManuf"] = nameManuf(); + + QJsonArray structureElementsArray; + for (const DeviceStructureElement &element : structureElements()) { + structureElementsArray.append(element.toJson()); + } + obj["structureElements"] = structureElementsArray; + + return obj; +} diff --git a/models/devicemodel.h b/models/devicemodel.h new file mode 100644 index 0000000..8b860b9 --- /dev/null +++ b/models/devicemodel.h @@ -0,0 +1,75 @@ +#ifndef DEVICEMODEL_H +#define DEVICEMODEL_H + +#include +#include +#include + +#include "baseentity.h" +#include "devicestructureelement.h" + +class DeviceModel : public BaseEntity +{ +public: + DeviceModel(); + virtual ~DeviceModel(); + + QString name() const; + void setName(const QString &newName); + + QString description() const; + void setDescription(const QString &newDescription); + + int workEfficiency() const; + void setWorkEfficiency(int newWorkEfficiency); + + int reliability() const; + void setReliability(int newReliability); + + int energyEfficiency() const; + void setEnergyEfficiency(int newEnergyEfficiency); + + int userFriendliness() const; + void setUserFriendliness(int newUserFriendliness); + + int durability() const; + void setDurability(int newDurability); + + int aestheticQualities() const; + void setAestheticQualities(int newAestheticQualities); + + int idType() const; + void setIdType(int newIdType); + + QString nameType() const; + void setNameType(const QString &newNameType); + + int idManuf() const; + void setIdManuf(int newIdManuf); + + QString nameManuf() const; + void setNameManuf(const QString &newNameManuf); + + QList structureElements() const; + void setStructureElements(const QList &newStructureElements); + + void fromJson(const QJsonObject &json) override; + QJsonObject toJson() const override; + +private: + QString _name = ""; + QString _description = ""; + int _workEfficiency = 0; + int _reliability = 0; + int _energyEfficiency = 0; + int _userFriendliness = 0; + int _durability = 0; + int _aestheticQualities = 0; + int _idType = 0; + QString _nameType = ""; + int _idManuf = 0; + QString _nameManuf = ""; + QList _structureElements; +}; + +#endif // DEVICEMODEL_H diff --git a/models/devicestructureelement.cpp b/models/devicestructureelement.cpp new file mode 100644 index 0000000..52fcfb8 --- /dev/null +++ b/models/devicestructureelement.cpp @@ -0,0 +1,79 @@ +#include "devicestructureelement.h" + +DeviceStructureElement::DeviceStructureElement() +{} + +DeviceStructureElement::~DeviceStructureElement() +{} + +QString DeviceStructureElement::nameModel() const +{ + return _nameModel; +} + +void DeviceStructureElement::setNameModel(const QString &newNameModel) +{ + _nameModel = newNameModel; +} + +QString DeviceStructureElement::nameManuf() const +{ + return _nameManuf; +} + +void DeviceStructureElement::setNameManuf(const QString &newNameManuf) +{ + _nameManuf = newNameManuf; +} + +QString DeviceStructureElement::description() const +{ + return _description; +} + +void DeviceStructureElement::setDescription(const QString &newDescription) +{ + _description = newDescription; +} + +QString DeviceStructureElement::nameType() const +{ + return _nameType; +} + +void DeviceStructureElement::setNameType(const QString &newNameType) +{ + _nameType = newNameType; +} + +int DeviceStructureElement::count() const +{ + return _count; +} + +void DeviceStructureElement::setCount(int newCount) +{ + _count = newCount; +} + +void DeviceStructureElement::fromJson(const QJsonObject &json) +{ + setId(json["id"].toInt()); + setNameModel(json["nameModel"].toString()); + setNameManuf(json["nameManuf"].toString()); + setDescription(json["description"].toString()); + setNameType(json["nameType"].toString()); + setCount(json["count"].toInt()); +} + +QJsonObject DeviceStructureElement::toJson() const +{ + QJsonObject obj; + obj["id"] = id(); + obj["nameModel"] = nameModel(); + obj["nameManuf"] = nameManuf(); + obj["description"] = description(); + obj["nameType"] = nameType(); + obj["count"] = count(); + return obj; +} diff --git a/models/devicestructureelement.h b/models/devicestructureelement.h new file mode 100644 index 0000000..dfb2c2b --- /dev/null +++ b/models/devicestructureelement.h @@ -0,0 +1,40 @@ +#ifndef DEVICESTRUCTUREELEMENT_H +#define DEVICESTRUCTUREELEMENT_H + +#include + +#include "baseentity.h" + +class DeviceStructureElement : public BaseEntity +{ +public: + DeviceStructureElement(); + virtual ~DeviceStructureElement(); + + QString nameModel() const; + void setNameModel(const QString &newNameModel); + + QString nameManuf() const; + void setNameManuf(const QString &newNameManuf); + + QString description() const; + void setDescription(const QString &newDescription); + + QString nameType() const; + void setNameType(const QString &newNameType); + + int count() const; + void setCount(int newCount); + + void fromJson(const QJsonObject &json) override; + QJsonObject toJson() const override; + +private: + QString _nameModel = ""; + QString _nameManuf = ""; + QString _description = ""; + QString _nameType = ""; + int _count = 1; +}; + +#endif // DEVICESTRUCTUREELEMENT_H diff --git a/models/devicetype.cpp b/models/devicetype.cpp new file mode 100644 index 0000000..5985e77 --- /dev/null +++ b/models/devicetype.cpp @@ -0,0 +1,31 @@ +#include "devicetype.h" + +DeviceType::DeviceType() +{} + +DeviceType::~DeviceType() +{} + +QString DeviceType::name() const +{ + return _name; +} + +void DeviceType::setName(const QString &newName) +{ + _name = newName; +} + +void DeviceType::fromJson(const QJsonObject &json) +{ + setId(json["id"].toInt()); + setName(json["name"].toString()); +} + +QJsonObject DeviceType::toJson() const +{ + QJsonObject obj; + obj["id"] = id(); + obj["name"] = name(); + return obj; +} diff --git a/models/devicetype.h b/models/devicetype.h new file mode 100644 index 0000000..f655cc7 --- /dev/null +++ b/models/devicetype.h @@ -0,0 +1,24 @@ +#ifndef DEVICETYPE_H +#define DEVICETYPE_H + +#include + +#include "baseentity.h" + +class DeviceType : public BaseEntity +{ +public: + DeviceType(); + virtual ~DeviceType(); + + QString name() const; + void setName(const QString &newName); + + void fromJson(const QJsonObject &json) override; + QJsonObject toJson() const override; + +private: + QString _name = ""; +}; + +#endif // DEVICETYPE_H diff --git a/models/filterparams.cpp b/models/filterparams.cpp new file mode 100644 index 0000000..6fe84aa --- /dev/null +++ b/models/filterparams.cpp @@ -0,0 +1,54 @@ +#include "filterparams.h" + +FilterParams::FilterParams() +{} + +bool FilterParams::isWorking() const +{ + return _isWorking; +} + +void FilterParams::setIsWorking(bool newIsWorking) +{ + _isWorking = newIsWorking; +} + +double FilterParams::priceFrom() const +{ + return _priceFrom; +} + +void FilterParams::setPriceFrom(double newPriceFrom) +{ + _priceFrom = newPriceFrom; +} + +double FilterParams::priceTo() const +{ + return _priceTo; +} + +void FilterParams::setPriceTo(double newPriceTo) +{ + _priceTo = newPriceTo; +} + +bool FilterParams::getDisregardState() const +{ + return disregardState; +} + +void FilterParams::setDisregardState(bool newDisregardState) +{ + disregardState = newDisregardState; +} + +bool FilterParams::getApllyFilters() const +{ + return apllyFilters; +} + +void FilterParams::setApllyFilters(bool newApllyFilters) +{ + apllyFilters = newApllyFilters; +} diff --git a/models/filterparams.h b/models/filterparams.h new file mode 100644 index 0000000..5267e90 --- /dev/null +++ b/models/filterparams.h @@ -0,0 +1,32 @@ +#ifndef FILTERPARAMS_H +#define FILTERPARAMS_H + +class FilterParams +{ +public: + FilterParams(); + + bool isWorking() const; + void setIsWorking(bool newIsWorking); + + double priceFrom() const; + void setPriceFrom(double newPriceFrom); + + double priceTo() const; + void setPriceTo(double newPriceTo); + + bool getDisregardState() const; + void setDisregardState(bool newDisregardState); + + bool getApllyFilters() const; + void setApllyFilters(bool newApllyFilters); + +private: + bool _isWorking = true; + double _priceFrom = -1; + double _priceTo = -1; + bool disregardState = false; + bool apllyFilters = false; +}; + +#endif // FILTERPARAMS_H diff --git a/models/location.cpp b/models/location.cpp new file mode 100644 index 0000000..0928550 --- /dev/null +++ b/models/location.cpp @@ -0,0 +1,31 @@ +#include "location.h" + +Location::Location() +{} + +Location::~Location() +{} + +QString Location::name() const +{ + return _name; +} + +void Location::setName(const QString &newName) +{ + _name = newName; +} + +void Location::fromJson(const QJsonObject &json) +{ + setId(json["id"].toInt()); + setName(json["name"].toString()); +} + +QJsonObject Location::toJson() const +{ + QJsonObject obj; + obj["id"] = id(); + obj["name"] = name(); + return obj; +} diff --git a/models/location.h b/models/location.h new file mode 100644 index 0000000..98e3772 --- /dev/null +++ b/models/location.h @@ -0,0 +1,24 @@ +#ifndef LOCATION_H +#define LOCATION_H + +#include + +#include "baseentity.h" + +class Location : public BaseEntity +{ +public: + Location(); + virtual ~Location(); + + QString name() const; + void setName(const QString &newName); + + void fromJson(const QJsonObject &json) override; + QJsonObject toJson() const override; + +private: + QString _name = ""; +}; + +#endif // LOCATION_H diff --git a/models/manufacturer.cpp b/models/manufacturer.cpp new file mode 100644 index 0000000..6d9df58 --- /dev/null +++ b/models/manufacturer.cpp @@ -0,0 +1,31 @@ +#include "manufacturer.h" + +Manufacturer::Manufacturer() +{} + +Manufacturer::~Manufacturer() +{} + +QString Manufacturer::name() const +{ + return _name; +} + +void Manufacturer::setName(const QString &newName) +{ + _name = newName; +} + +void Manufacturer::fromJson(const QJsonObject &json) +{ + setId(json["id"].toInt()); + setName(json["name"].toString()); +} + +QJsonObject Manufacturer::toJson() const +{ + QJsonObject obj; + obj["id"] = id(); + obj["name"] = name(); + return obj; +} diff --git a/models/manufacturer.h b/models/manufacturer.h new file mode 100644 index 0000000..6106671 --- /dev/null +++ b/models/manufacturer.h @@ -0,0 +1,24 @@ +#ifndef MANUFACTURER_H +#define MANUFACTURER_H + +#include + +#include "baseentity.h" + +class Manufacturer : public BaseEntity +{ +public: + Manufacturer(); + virtual ~Manufacturer(); + + QString name() const; + void setName(const QString &newName); + + void fromJson(const QJsonObject &json) override; + QJsonObject toJson() const override; + +private: + QString _name = ""; +}; + +#endif // MANUFACTURER_H diff --git a/models/types.h b/models/types.h new file mode 100644 index 0000000..669460b --- /dev/null +++ b/models/types.h @@ -0,0 +1,12 @@ +#ifndef TYPES_H +#define TYPES_H + +#include "location.h" // IWYU pragma: keep +#include "department.h" // IWYU pragma: keep +#include "manufacturer.h" // IWYU pragma: keep +#include "devicetype.h" // IWYU pragma: keep +#include "devicestructureelement.h" // IWYU pragma: keep +#include "devicemodel.h" // IWYU pragma: keep +#include "device.h" // IWYU pragma: keep + +#endif // TYPES_H diff --git a/service/businesslogic/departmentlogic.cpp b/service/businesslogic/departmentlogic.cpp new file mode 100644 index 0000000..9515494 --- /dev/null +++ b/service/businesslogic/departmentlogic.cpp @@ -0,0 +1,11 @@ +#include "departmentlogic.h" + +DepartmentLogic::DepartmentLogic(ServiceLoadDB *serviceDB) +{ + db = serviceDB; +} + +QMap DepartmentLogic::getAll() +{ + return db->loadDepartments(); +} diff --git a/service/businesslogic/departmentlogic.h b/service/businesslogic/departmentlogic.h new file mode 100644 index 0000000..f0fc150 --- /dev/null +++ b/service/businesslogic/departmentlogic.h @@ -0,0 +1,16 @@ +#ifndef DEPARTMENTLOGIC_H +#define DEPARTMENTLOGIC_H + +#include "service/serviceloaddb.h" + +class DepartmentLogic +{ +public: + DepartmentLogic(ServiceLoadDB *serviceDB); + QMap getAll(); + +private: + ServiceLoadDB *db; +}; + +#endif // DEPARTMENTLOGIC_H diff --git a/service/businesslogic/devicelogic.cpp b/service/businesslogic/devicelogic.cpp new file mode 100644 index 0000000..6e3b0e5 --- /dev/null +++ b/service/businesslogic/devicelogic.cpp @@ -0,0 +1,142 @@ +#include "devicelogic.h" + +DeviceLogic::DeviceLogic(ServiceLoadDB *serviceDB) +{ + db = serviceDB; +} + +QMap DeviceLogic::getAll() +{ + db->loadDeviceModels(); + return db->loadDevices(); +} + +QList DeviceLogic::getAllByParameters( + int entityId, int currentEntity, + QString searchText, + const FilterParams &filterParams, + const QString &sortOrder +) +{ + db->loadDeviceModels(); + auto devices = db->loadDevices(); + auto filteredDevices = filterByEntity(devices, entityId, currentEntity); + filteredDevices = searchDevices(filteredDevices, searchText); + filteredDevices = applyFilters(filteredDevices, filterParams); + return sortDevices(filteredDevices, sortOrder); +} + +bool DeviceLogic::updateDevice(const Device &device) +{ + return db->updateDevice(device); +} + +QMap DeviceLogic::filterByEntity(const QMap &devices, int entityId, int currentEntity) +{ + QMap result; + if (entityId == -1 || currentEntity == 0) + 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; + } + } + return result; +} + +QMap DeviceLogic::searchDevices(const QMap &devices, const QString &searchText) +{ + if (searchText.isEmpty()) + return devices; + + QMap result; + for (auto &device : devices) { + if (device.deviceModel().name().contains(searchText, Qt::CaseInsensitive) || + device.deviceModel().nameType().contains(searchText, Qt::CaseInsensitive) || + device.serialNumber().contains(searchText, Qt::CaseInsensitive)) { + result.insert(device.id(), device); + } + } + return result; +} + +QMap DeviceLogic::applyFilters(const QMap &devices, const FilterParams &filterParams) +{ + if (!filterParams.getApllyFilters()) + return devices; + QMap result; + if (filterParams.getDisregardState()) + { + for (auto &device : devices) { + if (device.price() < filterParams.priceFrom() || device.price() > filterParams.priceTo()) + continue; + result.insert(device.id(), device); + } + } + else + { + for (auto &device : devices) { + if (device.isWorking() != filterParams.isWorking()) + continue; + if (device.price() < filterParams.priceFrom() || device.price() > filterParams.priceTo()) + continue; + result.insert(device.id(), device); + } + } + + return result; +} + +QList DeviceLogic::sortDevices(QMap &devices, const QString &sortOrder) +{ + QList deviceList = devices.values(); + + if (sortOrder == "Сначала новые") { + std::sort(deviceList.begin(), deviceList.end(), [](const Device &a, const Device &b) { + return a.purchaseDate() > b.purchaseDate(); + }); + } + if (sortOrder == "Сначала старые") { + std::sort(deviceList.begin(), deviceList.end(), [](const Device &a, const Device &b) { + return a.purchaseDate() < b.purchaseDate(); + }); + } + if (sortOrder == "Сначала дешевые") { + std::sort(deviceList.begin(), deviceList.end(), [](const Device &a, const Device &b) { + return a.price() < b.price(); + }); + } + if (sortOrder == "Сначала дорогие") { + std::sort(deviceList.begin(), deviceList.end(), [](const Device &a, const Device &b) { + return a.price() > b.price(); + }); + } + if (sortOrder == "Сначала с лайком") { + std::sort(deviceList.begin(), deviceList.end(), [](const Device &a, const Device &b) { + return a.isLiked() > b.isLiked(); + }); + } + + return deviceList; +} diff --git a/service/businesslogic/devicelogic.h b/service/businesslogic/devicelogic.h new file mode 100644 index 0000000..3ca53f7 --- /dev/null +++ b/service/businesslogic/devicelogic.h @@ -0,0 +1,31 @@ +#ifndef DEVICELOGIC_H +#define DEVICELOGIC_H + +#include "service/serviceloaddb.h" +#include "models/filterparams.h" + +class DeviceLogic +{ +public: + DeviceLogic(ServiceLoadDB *serviceDB); + QMap getAll(); + QList getAllByParameters( + int entityId, + int currentEntity, + QString searchText, + const FilterParams &filterParams, + const QString &sortOrder + ); + bool updateDevice(const Device &device); + +private: + QMap filterByEntity(const QMap &devices, int entityId, int currentEntity); + 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; +}; + +#endif // DEVICELOGIC_H diff --git a/service/businesslogic/devicemodellogic.cpp b/service/businesslogic/devicemodellogic.cpp new file mode 100644 index 0000000..6d78713 --- /dev/null +++ b/service/businesslogic/devicemodellogic.cpp @@ -0,0 +1,11 @@ +#include "devicemodellogic.h" + +DeviceModelLogic::DeviceModelLogic(ServiceLoadDB *serviceDB) +{ + db = serviceDB; +} + +QMap DeviceModelLogic::getAll() +{ + return db->loadDeviceModels(); +} diff --git a/service/businesslogic/devicemodellogic.h b/service/businesslogic/devicemodellogic.h new file mode 100644 index 0000000..76a5354 --- /dev/null +++ b/service/businesslogic/devicemodellogic.h @@ -0,0 +1,16 @@ +#ifndef DEVICEMODELLOGIC_H +#define DEVICEMODELLOGIC_H + +#include "service/serviceloaddb.h" + +class DeviceModelLogic +{ +public: + DeviceModelLogic(ServiceLoadDB *serviceDB); + QMap getAll(); + +private: + ServiceLoadDB *db; +}; + +#endif // DEVICEMODELLOGIC_H diff --git a/service/businesslogic/devicetypelogic.cpp b/service/businesslogic/devicetypelogic.cpp new file mode 100644 index 0000000..9ceec04 --- /dev/null +++ b/service/businesslogic/devicetypelogic.cpp @@ -0,0 +1,11 @@ +#include "devicetypelogic.h" + +DeviceTypeLogic::DeviceTypeLogic(ServiceLoadDB *serviceDB) +{ + db = serviceDB; +} + +QMap DeviceTypeLogic::getAll() +{ + return db->loadDeviceTypes(); +} diff --git a/service/businesslogic/devicetypelogic.h b/service/businesslogic/devicetypelogic.h new file mode 100644 index 0000000..d42b34a --- /dev/null +++ b/service/businesslogic/devicetypelogic.h @@ -0,0 +1,16 @@ +#ifndef DEVICETYPELOGIC_H +#define DEVICETYPELOGIC_H + +#include "service/serviceloaddb.h" + +class DeviceTypeLogic +{ +public: + DeviceTypeLogic(ServiceLoadDB *serviceDB); + QMap getAll(); + +private: + ServiceLoadDB *db; +}; + +#endif // DEVICETYPELOGIC_H diff --git a/service/businesslogic/locationlogic.cpp b/service/businesslogic/locationlogic.cpp new file mode 100644 index 0000000..561b47f --- /dev/null +++ b/service/businesslogic/locationlogic.cpp @@ -0,0 +1,11 @@ +#include "locationlogic.h" + +LocationLogic::LocationLogic(ServiceLoadDB *serviceDB) +{ + db = serviceDB; +} + +QMap LocationLogic::getAll() +{ + return db->loadLocations(); +} diff --git a/service/businesslogic/locationlogic.h b/service/businesslogic/locationlogic.h new file mode 100644 index 0000000..e5eaf2e --- /dev/null +++ b/service/businesslogic/locationlogic.h @@ -0,0 +1,16 @@ +#ifndef LOCATIONLOGIC_H +#define LOCATIONLOGIC_H + +#include "service/serviceloaddb.h" + +class LocationLogic +{ +public: + LocationLogic(ServiceLoadDB *serviceDB); + QMap getAll(); + +private: + ServiceLoadDB *db; +}; + +#endif // LOCATIONLOGIC_H diff --git a/service/businesslogic/manufacturerlogic.cpp b/service/businesslogic/manufacturerlogic.cpp new file mode 100644 index 0000000..d786381 --- /dev/null +++ b/service/businesslogic/manufacturerlogic.cpp @@ -0,0 +1,11 @@ +#include "manufacturerlogic.h" + +ManufacturerLogic::ManufacturerLogic(ServiceLoadDB *serviceDB) +{ + db = serviceDB; +} + +QMap ManufacturerLogic::getAll() +{ + return db->loadManufacturers(); +} diff --git a/service/businesslogic/manufacturerlogic.h b/service/businesslogic/manufacturerlogic.h new file mode 100644 index 0000000..6fcd0ab --- /dev/null +++ b/service/businesslogic/manufacturerlogic.h @@ -0,0 +1,16 @@ +#ifndef MANUFACTURERLOGIC_H +#define MANUFACTURERLOGIC_H + +#include "service/serviceloaddb.h" + +class ManufacturerLogic +{ +public: + ManufacturerLogic(ServiceLoadDB *serviceDB); + QMap getAll(); + +private: + ServiceLoadDB *db; +}; + +#endif // MANUFACTURERLOGIC_H diff --git a/service/serviceloaddb.cpp b/service/serviceloaddb.cpp new file mode 100644 index 0000000..2b2be47 --- /dev/null +++ b/service/serviceloaddb.cpp @@ -0,0 +1,272 @@ +#include "serviceloaddb.h" + +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()){ + qDebug() << "Не удалось открыть БД"; + return; + } + query = QSqlQuery(db); +} + +QMap ServiceLoadDB::loadLocations() +{ + QMap mapLocations; + + db_input = "SELECT * FROM public.location"; + if (!query.exec(db_input)) { + qDebug() << "Ошибка запроса к таблице location: " << query.lastError().text(); + return mapLocations; + } + + QSqlRecord rec; + while (query.next()) { + rec = query.record(); + + Location location; + location.setId(query.value(rec.indexOf("id")).toInt()); + location.setName(query.value(rec.indexOf("name")).toString()); + + mapLocations.insert(location.id(), location); + } + + return mapLocations; +} + +QMap ServiceLoadDB::loadDepartments() +{ + QMap mapDepartments; + + db_input = "SELECT * FROM public.department"; + if (!query.exec(db_input)) { + qDebug() << "Ошибка запроса к таблице department: " << query.lastError().text(); + return mapDepartments; + } + + QSqlRecord rec; + while (query.next()) { + rec = query.record(); + + Department department; + department.setId(query.value(rec.indexOf("id")).toInt()); + department.setName(query.value(rec.indexOf("name")).toString()); + + mapDepartments.insert(department.id(), department); + } + + return mapDepartments; +} + +QMap ServiceLoadDB::loadManufacturers() +{ + QMap mapManufacturers; + + db_input = "SELECT * FROM public.manufacturer"; + if (!query.exec(db_input)) { + qDebug() << "Ошибка запроса к таблице manufacturer: " << query.lastError().text(); + return mapManufacturers; + } + + QSqlRecord rec; + while (query.next()) { + rec = query.record(); + + Manufacturer manufacturer; + manufacturer.setId(query.value(rec.indexOf("id")).toInt()); + manufacturer.setName(query.value(rec.indexOf("name")).toString()); + + mapManufacturers.insert(manufacturer.id(), manufacturer); + } + + return mapManufacturers; +} + +QMap ServiceLoadDB::loadDeviceTypes() +{ + QMap mapDeviceTypes; + + db_input = "SELECT * FROM public.device_type"; + if (!query.exec(db_input)) { + qDebug() << "Ошибка запроса к таблице device_type: " << query.lastError().text(); + return mapDeviceTypes; + } + + QSqlRecord rec; + while (query.next()) { + rec = query.record(); + + DeviceType deviceType; + deviceType.setId(query.value(rec.indexOf("id")).toInt()); + deviceType.setName(query.value(rec.indexOf("name")).toString()); + + mapDeviceTypes.insert(deviceType.id(), deviceType); + } + + return mapDeviceTypes; +} + +QMap ServiceLoadDB::loadDeviceModels() +{ + QFile file("../../data/requestDeviceModels.sql"); + if (!file.open(QIODevice::ReadOnly)) { + qDebug() << "Не получилось открыть файл \"requestDeviceModels.sql\""; + return QMap(); + } + + db_input = QString(file.readAll()); + + if (!query.exec(db_input)) { + qDebug() << "Ошибка запроса при получении информации о моделях устройств: " << query.lastError().text(); + return QMap(); + } + + QSqlRecord rec; + while (query.next()) { + rec = query.record(); + + DeviceModel deviceModel; + 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.setStructureElements(readStructureElements(id)); + + mapDeviceModels.insert(deviceModel.id(), deviceModel); + } + + return mapDeviceModels; +} + +QMap ServiceLoadDB::loadDevices() +{ + QMap mapDevices; + + QFile file("../../data/requestDevices.sql"); + if (!file.open(QIODevice::ReadOnly)) + return mapDevices; + + db_input = QString(file.readAll()); + + if (!query.exec(db_input)) { + qDebug() << "Ошибка запроса при получении информации о устройствах: " << query.lastError().text(); + return mapDevices; + } + + QSqlRecord rec; + 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)) { + 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()); + + mapDevices.insert(device.id(), device); + } + + return mapDevices; +} + +bool ServiceLoadDB::updateDevice(const Device &device) +{ + QFile file("../../data/updateDevice.sql"); + if (!file.open(QIODevice::ReadOnly)) { + qDebug() << "Не удалось открыть файл с запросом для обновления устройства"; + return false; + } + + QString db_input = QString(file.readAll()); + + db_input = db_input.arg(device.serialNumber()) + .arg(device.purchaseDate().toString("yyyy-MM-dd HH:mm:ss")) + .arg(device.price()) + .arg(device.warrantyExpireDate().toString("yyyy-MM-dd HH:mm:ss")) + .arg(device.isWorking() ? "TRUE" : "FALSE") + .arg(device.furtherInformation()) + .arg(device.idLocation()) + .arg(device.idEmployee()) + .arg(device.deviceModel().id()) + .arg(device.isLiked() ? "TRUE" : "FALSE") + .arg(device.id()); + + if (!query.exec(db_input)) { + qDebug() << "Ошибка обновления устройства с id = " << device.id() << ": " << query.lastError().text(); + return false; + } + + return true; +} + +QList ServiceLoadDB::readStructureElements(int modelId) +{ + QSqlQuery secondQuery; + db_input = "SELECT * FROM get_model_structure(:model_id)"; + secondQuery.prepare(db_input); + secondQuery.bindValue(":model_id", modelId); + if (!secondQuery.exec()) { + qDebug() << "Ошибка при выполнении запроса для получения элементов структуры: " << secondQuery.lastError().text(); + return QList(); + } + + QSqlRecord rec; + QList elements; + while (secondQuery.next()) { + rec = secondQuery.record(); + + DeviceStructureElement element; + element.setId(secondQuery.value(rec.indexOf("Идентификатор элемента")).toInt()); + element.setNameModel(secondQuery.value(rec.indexOf("Модель")).toString()); + element.setNameManuf(secondQuery.value(rec.indexOf("Производитель")).toString()); + element.setDescription(secondQuery.value(rec.indexOf("Описание элемента")).toString()); + element.setNameType(secondQuery.value(rec.indexOf("Тип элемента")).toString()); + element.setCount(secondQuery.value(rec.indexOf("Количество")).toInt()); + + elements.append(element); + } + + return elements; +} diff --git a/service/serviceloaddb.h b/service/serviceloaddb.h new file mode 100644 index 0000000..39f35ab --- /dev/null +++ b/service/serviceloaddb.h @@ -0,0 +1,44 @@ +#ifndef SERVICELOADDB_H +#define SERVICELOADDB_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "models/types.h" // IWYU pragma: keep + +class ServiceLoadDB : public QObject +{ + Q_OBJECT +public: + explicit ServiceLoadDB(QObject *parent = nullptr); + void start(); + QMap loadLocations(); + QMap loadDepartments(); + QMap loadManufacturers(); + QMap loadDeviceTypes(); + QMap loadDeviceModels(); + QMap loadDevices(); + bool updateDevice(const Device &device); + +private: + QList readStructureElements(int modelId); + +private: + QSqlDatabase db; + QString db_input; + QSqlQuery query; + + QMap mapDeviceModels; +}; + +#endif // SERVICELOADDB_H