Server part ready

This commit is contained in:
Илья 2024-12-24 18:02:23 +04:00
parent a816ffe839
commit 462357e3c7
40 changed files with 2014 additions and 0 deletions

View File

@ -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

228
apiserver.cpp Normal file
View File

@ -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/<arg>", 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(&currentEntityOk);
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<Device> 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<int, Department> 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<int, DeviceModel> 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<int, DeviceType> 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<int, Location> 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<int, Manufacturer> 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<typename T>
QJsonArray ApiServer::createJsonArray(const QMap<int, T> &items)
{
QJsonArray itemArray;
for (const T &item : items) {
itemArray.append(item.toJson());
}
return itemArray;
}

46
apiserver.h Normal file
View File

@ -0,0 +1,46 @@
#ifndef APISERVER_H
#define APISERVER_H
#include <QCoreApplication>
#include <QHttpServer>
#include <QHttpServerResponse>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#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 <typename T>
QJsonArray createJsonArray(const QMap<int, T> &items);
};
#endif // APISERVER_H

View File

@ -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;

14
data/requestDevices.sql Normal file
View File

@ -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;

12
data/updateDevice.sql Normal file
View File

@ -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';

16
main.cpp Normal file
View File

@ -0,0 +1,16 @@
#include <QCoreApplication>
#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();
}

14
models/baseentity.cpp Normal file
View File

@ -0,0 +1,14 @@
#include "baseentity.h"
BaseEntity::BaseEntity()
{}
int BaseEntity::id() const
{
return _id;
}
void BaseEntity::setId(int newId)
{
_id = newId;
}

21
models/baseentity.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef BASEENTITY_H
#define BASEENTITY_H
#include <QJsonObject>
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

31
models/department.cpp Normal file
View File

@ -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;
}

24
models/department.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef DEPARTMENT_H
#define DEPARTMENT_H
#include <QString>
#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

190
models/device.cpp Normal file
View File

@ -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;
}

78
models/device.h Normal file
View File

@ -0,0 +1,78 @@
#ifndef DEVICE_H
#define DEVICE_H
#include <QString>
#include <QDateTime>
#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

190
models/devicemodel.cpp Normal file
View File

@ -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<DeviceStructureElement> DeviceModel::structureElements() const
{
return _structureElements;
}
void DeviceModel::setStructureElements(const QList<DeviceStructureElement> &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<DeviceStructureElement> 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;
}

75
models/devicemodel.h Normal file
View File

@ -0,0 +1,75 @@
#ifndef DEVICEMODEL_H
#define DEVICEMODEL_H
#include <QString>
#include <QList>
#include <QJsonArray>
#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<DeviceStructureElement> structureElements() const;
void setStructureElements(const QList<DeviceStructureElement> &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<DeviceStructureElement> _structureElements;
};
#endif // DEVICEMODEL_H

View File

@ -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;
}

View File

@ -0,0 +1,40 @@
#ifndef DEVICESTRUCTUREELEMENT_H
#define DEVICESTRUCTUREELEMENT_H
#include <QString>
#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

31
models/devicetype.cpp Normal file
View File

@ -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;
}

24
models/devicetype.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef DEVICETYPE_H
#define DEVICETYPE_H
#include <QString>
#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

54
models/filterparams.cpp Normal file
View File

@ -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;
}

32
models/filterparams.h Normal file
View File

@ -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

31
models/location.cpp Normal file
View File

@ -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;
}

24
models/location.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef LOCATION_H
#define LOCATION_H
#include <QString>
#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

31
models/manufacturer.cpp Normal file
View File

@ -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;
}

24
models/manufacturer.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef MANUFACTURER_H
#define MANUFACTURER_H
#include <QString>
#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

12
models/types.h Normal file
View File

@ -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

View File

@ -0,0 +1,11 @@
#include "departmentlogic.h"
DepartmentLogic::DepartmentLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
}
QMap<int, Department> DepartmentLogic::getAll()
{
return db->loadDepartments();
}

View File

@ -0,0 +1,16 @@
#ifndef DEPARTMENTLOGIC_H
#define DEPARTMENTLOGIC_H
#include "service/serviceloaddb.h"
class DepartmentLogic
{
public:
DepartmentLogic(ServiceLoadDB *serviceDB);
QMap<int, Department> getAll();
private:
ServiceLoadDB *db;
};
#endif // DEPARTMENTLOGIC_H

View File

@ -0,0 +1,142 @@
#include "devicelogic.h"
DeviceLogic::DeviceLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
}
QMap<int, Device> DeviceLogic::getAll()
{
db->loadDeviceModels();
return db->loadDevices();
}
QList<Device> 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<int, Device> DeviceLogic::filterByEntity(const QMap<int, Device> &devices, int entityId, int currentEntity)
{
QMap<int, Device> 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<int, Device> DeviceLogic::searchDevices(const QMap<int, Device> &devices, const QString &searchText)
{
if (searchText.isEmpty())
return devices;
QMap<int, Device> 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<int, Device> DeviceLogic::applyFilters(const QMap<int, Device> &devices, const FilterParams &filterParams)
{
if (!filterParams.getApllyFilters())
return devices;
QMap<int, Device> 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<Device> DeviceLogic::sortDevices(QMap<int, Device> &devices, const QString &sortOrder)
{
QList<Device> 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;
}

View File

@ -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<int, Device> getAll();
QList<Device> getAllByParameters(
int entityId,
int currentEntity,
QString searchText,
const FilterParams &filterParams,
const QString &sortOrder
);
bool updateDevice(const Device &device);
private:
QMap<int, Device> filterByEntity(const QMap<int, Device> &devices, int entityId, int currentEntity);
QMap<int, Device> searchDevices(const QMap<int, Device> &devices, const QString &searchText);
QMap<int, Device> applyFilters(const QMap<int, Device> &devices, const FilterParams &filterParams);
QList<Device> sortDevices(QMap<int, Device> &devices, const QString &sortOrder);
private:
ServiceLoadDB *db;
};
#endif // DEVICELOGIC_H

View File

@ -0,0 +1,11 @@
#include "devicemodellogic.h"
DeviceModelLogic::DeviceModelLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
}
QMap<int, DeviceModel> DeviceModelLogic::getAll()
{
return db->loadDeviceModels();
}

View File

@ -0,0 +1,16 @@
#ifndef DEVICEMODELLOGIC_H
#define DEVICEMODELLOGIC_H
#include "service/serviceloaddb.h"
class DeviceModelLogic
{
public:
DeviceModelLogic(ServiceLoadDB *serviceDB);
QMap<int, DeviceModel> getAll();
private:
ServiceLoadDB *db;
};
#endif // DEVICEMODELLOGIC_H

View File

@ -0,0 +1,11 @@
#include "devicetypelogic.h"
DeviceTypeLogic::DeviceTypeLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
}
QMap<int, DeviceType> DeviceTypeLogic::getAll()
{
return db->loadDeviceTypes();
}

View File

@ -0,0 +1,16 @@
#ifndef DEVICETYPELOGIC_H
#define DEVICETYPELOGIC_H
#include "service/serviceloaddb.h"
class DeviceTypeLogic
{
public:
DeviceTypeLogic(ServiceLoadDB *serviceDB);
QMap<int, DeviceType> getAll();
private:
ServiceLoadDB *db;
};
#endif // DEVICETYPELOGIC_H

View File

@ -0,0 +1,11 @@
#include "locationlogic.h"
LocationLogic::LocationLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
}
QMap<int, Location> LocationLogic::getAll()
{
return db->loadLocations();
}

View File

@ -0,0 +1,16 @@
#ifndef LOCATIONLOGIC_H
#define LOCATIONLOGIC_H
#include "service/serviceloaddb.h"
class LocationLogic
{
public:
LocationLogic(ServiceLoadDB *serviceDB);
QMap<int, Location> getAll();
private:
ServiceLoadDB *db;
};
#endif // LOCATIONLOGIC_H

View File

@ -0,0 +1,11 @@
#include "manufacturerlogic.h"
ManufacturerLogic::ManufacturerLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
}
QMap<int, Manufacturer> ManufacturerLogic::getAll()
{
return db->loadManufacturers();
}

View File

@ -0,0 +1,16 @@
#ifndef MANUFACTURERLOGIC_H
#define MANUFACTURERLOGIC_H
#include "service/serviceloaddb.h"
class ManufacturerLogic
{
public:
ManufacturerLogic(ServiceLoadDB *serviceDB);
QMap<int, Manufacturer> getAll();
private:
ServiceLoadDB *db;
};
#endif // MANUFACTURERLOGIC_H

272
service/serviceloaddb.cpp Normal file
View File

@ -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<int, Location> ServiceLoadDB::loadLocations()
{
QMap<int, Location> 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<int, Department> ServiceLoadDB::loadDepartments()
{
QMap<int, Department> 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<int, Manufacturer> ServiceLoadDB::loadManufacturers()
{
QMap<int, Manufacturer> 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<int, DeviceType> ServiceLoadDB::loadDeviceTypes()
{
QMap<int, DeviceType> 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<int, DeviceModel> ServiceLoadDB::loadDeviceModels()
{
QFile file("../../data/requestDeviceModels.sql");
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "Не получилось открыть файл \"requestDeviceModels.sql\"";
return QMap<int, DeviceModel>();
}
db_input = QString(file.readAll());
if (!query.exec(db_input)) {
qDebug() << "Ошибка запроса при получении информации о моделях устройств: " << query.lastError().text();
return QMap<int, DeviceModel>();
}
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<int, Device> ServiceLoadDB::loadDevices()
{
QMap<int, Device> 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, Device>();
}
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<DeviceStructureElement> 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<DeviceStructureElement>();
}
QSqlRecord rec;
QList<DeviceStructureElement> 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;
}

44
service/serviceloaddb.h Normal file
View File

@ -0,0 +1,44 @@
#ifndef SERVICELOADDB_H
#define SERVICELOADDB_H
#include <QObject>
#include <QSql>
#include <QSqlDatabase>
#include <QSqlRecord>
#include <QSqlQuery>
#include <QSqlError>
#include <QString>
#include <QDebug>
#include <QStringList>
#include <QMap>
#include <QList>
#include <QFile>
#include "models/types.h" // IWYU pragma: keep
class ServiceLoadDB : public QObject
{
Q_OBJECT
public:
explicit ServiceLoadDB(QObject *parent = nullptr);
void start();
QMap<int, Location> loadLocations();
QMap<int, Department> loadDepartments();
QMap<int, Manufacturer> loadManufacturers();
QMap<int, DeviceType> loadDeviceTypes();
QMap<int, DeviceModel> loadDeviceModels();
QMap<int, Device> loadDevices();
bool updateDevice(const Device &device);
private:
QList<DeviceStructureElement> readStructureElements(int modelId);
private:
QSqlDatabase db;
QString db_input;
QSqlQuery query;
QMap<int, DeviceModel> mapDeviceModels;
};
#endif // SERVICELOADDB_H