Final version

This commit is contained in:
Илья 2025-01-14 21:28:06 +04:00
parent 462357e3c7
commit 0345c38fb6
24 changed files with 281 additions and 227 deletions

View File

@ -46,6 +46,8 @@ HEADERS += \
models/devicemodel.h \
models/devicestructureelement.h \
models/devicetype.h \
models/entitytype.h \
models/enums/entitytype.h \
models/filterparams.h \
models/location.h \
models/manufacturer.h \

View File

@ -1,37 +1,37 @@
#include "apiserver.h"
ApiServer::ApiServer() {
server.route("/api/devices", QHttpServerRequest::Method::Get,
_server.route("/api/devices", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetFilteredDevices(request);
});
server.route("/api/departments", QHttpServerRequest::Method::Get,
_server.route("/api/departments", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetAllDepartments(request);
});
server.route("/api/devicemodels", QHttpServerRequest::Method::Get,
_server.route("/api/devicemodels", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetAllDeviceModels(request);
});
server.route("/api/devicetypes", QHttpServerRequest::Method::Get,
_server.route("/api/devicetypes", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetAllDeviceTypes(request);
});
server.route("/api/locations", QHttpServerRequest::Method::Get,
_server.route("/api/locations", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetAllLocations(request);
});
server.route("/api/manufacturers", QHttpServerRequest::Method::Get,
_server.route("/api/manufacturers", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetAllManufacturers(request);
});
server.route("/api/devices/<arg>", QHttpServerRequest::Method::Put,
_server.route("/api/devices/<arg>", QHttpServerRequest::Method::Put,
[this](int id, const QHttpServerRequest &request) {
return handleUpdateDevice(id, request);
});
@ -39,54 +39,34 @@ ApiServer::ApiServer() {
void ApiServer::start(ServiceLoadDB *serviceDB)
{
server.listen(QHostAddress::LocalHost, 8080);
deviceLogic = new DeviceLogic(serviceDB);
departmentLogic = new DepartmentLogic(serviceDB);
deviceModelLogic = new DeviceModelLogic(serviceDB);
locationLogic = new LocationLogic(serviceDB);
manufacturerLogic = new ManufacturerLogic(serviceDB);
deviceTypeLogic = new DeviceTypeLogic(serviceDB);
_server.listen(QHostAddress::LocalHost, 8080);
_deviceLogic = new DeviceLogic(serviceDB);
_departmentLogic = new DepartmentLogic(serviceDB);
_deviceModelLogic = new DeviceModelLogic(serviceDB);
_locationLogic = new LocationLogic(serviceDB);
_manufacturerLogic = new ManufacturerLogic(serviceDB);
_deviceTypeLogic = new DeviceTypeLogic(serviceDB);
}
QHttpServerResponse ApiServer::handleGetFilteredDevices(const QHttpServerRequest &request)
{
QUrlQuery query = request.query();
bool isWorking = query.queryItemValue("isWorking") == "true";
bool isWorking = getQueryParamWithDefault(query, "isWorking", true);
double priceFrom = getQueryParamWithDefault(query, "priceFrom", 0.00);
double priceTo = getQueryParamWithDefault(query, "priceTo", std::numeric_limits<double>::max());
bool applyFilters = getQueryParamWithDefault(query, "applyFilters", false);
bool disregardState = getQueryParamWithDefault(query, "disregardState", true);
int entityId = getQueryParamWithDefault(query, "entityId", -1);
int currentEntity = getQueryParamWithDefault(query, "currentEntity", 0);
QString searchText = getQueryParamWithDefault(query, "searchText", QString());
QString sortOrder = getQueryParamWithDefault(query, "sortOrder", QString("Сначала новые"));
bool priceFromOk;
double priceFrom = query.queryItemValue("priceFrom").toDouble(&priceFromOk);
if (!priceFromOk) {
return QHttpServerResponse("Invalid priceFrom value", QHttpServerResponse::StatusCode::BadRequest);
if (!validEntityTypeNumbers.contains(currentEntity)) {
currentEntity = 0;
}
bool priceToOk;
double priceTo = query.queryItemValue("priceTo").toDouble(&priceToOk);
if (!priceToOk) {
return QHttpServerResponse("Invalid priceTo value", QHttpServerResponse::StatusCode::BadRequest);
}
bool applyFilters = query.queryItemValue("applyFilters") == "true";
bool disregardState = query.queryItemValue("disregardState") == "true";
bool entityIdOk;
int entityId = query.queryItemValue("entityId").toInt(&entityIdOk);
if (!entityIdOk) {
return QHttpServerResponse("Invalid entityId value", QHttpServerResponse::StatusCode::BadRequest);
}
bool currentEntityOk;
int currentEntity = query.queryItemValue("currentEntity").toInt(&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);
sortOrder = "Сначала новые";
}
FilterParams filterParams;
@ -96,9 +76,9 @@ QHttpServerResponse ApiServer::handleGetFilteredDevices(const QHttpServerRequest
filterParams.setApllyFilters(applyFilters);
filterParams.setDisregardState(disregardState);
QList<Device> filteredDevices = deviceLogic->getAllByParameters(
QList<Device> filteredDevices = _deviceLogic->getAllByParameters(
entityId,
currentEntity,
static_cast<EntityType>(currentEntity),
searchText,
filterParams,
sortOrder
@ -117,7 +97,7 @@ QHttpServerResponse ApiServer::handleGetFilteredDevices(const QHttpServerRequest
QHttpServerResponse ApiServer::handleGetAllDepartments(const QHttpServerRequest &request)
{
QMap<int, Department> departments = departmentLogic->getAll();
QMap<int, Department> departments = _departmentLogic->getAll();
if (departments.isEmpty()) {
return QHttpServerResponse("Failed to retrieve departments", QHttpServerResponse::StatusCode::InternalServerError);
@ -133,7 +113,7 @@ QHttpServerResponse ApiServer::handleGetAllDepartments(const QHttpServerRequest
QHttpServerResponse ApiServer::handleGetAllDeviceModels(const QHttpServerRequest &request)
{
QMap<int, DeviceModel> deviceModels = deviceModelLogic->getAll();
QMap<int, DeviceModel> deviceModels = _deviceModelLogic->getAll();
if (deviceModels.isEmpty()) {
return QHttpServerResponse("Failed to retrieve device models", QHttpServerResponse::StatusCode::InternalServerError);
@ -149,7 +129,7 @@ QHttpServerResponse ApiServer::handleGetAllDeviceModels(const QHttpServerRequest
QHttpServerResponse ApiServer::handleGetAllDeviceTypes(const QHttpServerRequest &request)
{
QMap<int, DeviceType> deviceTypes = deviceTypeLogic->getAll();
QMap<int, DeviceType> deviceTypes = _deviceTypeLogic->getAll();
if (deviceTypes.isEmpty()) {
return QHttpServerResponse("Failed to retrieve device types", QHttpServerResponse::StatusCode::InternalServerError);
@ -165,7 +145,7 @@ QHttpServerResponse ApiServer::handleGetAllDeviceTypes(const QHttpServerRequest
QHttpServerResponse ApiServer::handleGetAllLocations(const QHttpServerRequest &request)
{
QMap<int, Location> locations = locationLogic->getAll();
QMap<int, Location> locations = _locationLogic->getAll();
if (locations.isEmpty()) {
return QHttpServerResponse("Failed to retrieve locations", QHttpServerResponse::StatusCode::InternalServerError);
@ -181,7 +161,7 @@ QHttpServerResponse ApiServer::handleGetAllLocations(const QHttpServerRequest &r
QHttpServerResponse ApiServer::handleGetAllManufacturers(const QHttpServerRequest &request)
{
QMap<int, Manufacturer> manufacturers = manufacturerLogic->getAll();
QMap<int, Manufacturer> manufacturers = _manufacturerLogic->getAll();
if (manufacturers.isEmpty()) {
return QHttpServerResponse("Failed to retrieve manufacturers", QHttpServerResponse::StatusCode::InternalServerError);
@ -210,7 +190,7 @@ QHttpServerResponse ApiServer::handleUpdateDevice(int id, const QHttpServerReque
device.fromJson(jsonObject);
device.setId(id);
if (!deviceLogic->updateDevice(device)) {
if (!_deviceLogic->updateDevice(device)) {
return QHttpServerResponse("Failed to update device", QHttpServerResponse::StatusCode::InternalServerError);
}
@ -226,3 +206,32 @@ QJsonArray ApiServer::createJsonArray(const QMap<int, T> &items)
}
return itemArray;
}
template<typename T>
T ApiServer::getQueryParamWithDefault(const QUrlQuery &query, const QString &paramName, const T &defaultValue)
{
QString value = query.queryItemValue(paramName);
if (value.isEmpty()) {
return defaultValue;
}
if constexpr (std::is_same<T, bool>::value) {
return value == "true";
}
if constexpr (std::is_same<T, int>::value) {
bool ok;
int result = value.toInt(&ok);
return ok ? result : defaultValue;
}
if constexpr (std::is_same<T, double>::value) {
bool ok;
double result = value.toDouble(&ok);
return ok ? result : defaultValue;
}
if constexpr (std::is_same<T, QString>::value) {
return value;
}
return defaultValue;
}

View File

@ -22,15 +22,6 @@ public:
void start(ServiceLoadDB *serviceDB);
private:
QHttpServer server;
DeviceLogic *deviceLogic;
DepartmentLogic *departmentLogic;
DeviceModelLogic *deviceModelLogic;
DeviceTypeLogic *deviceTypeLogic;
LocationLogic *locationLogic;
ManufacturerLogic *manufacturerLogic;
QHttpServerResponse handleGetFilteredDevices(const QHttpServerRequest &request);
QHttpServerResponse handleGetAllDepartments(const QHttpServerRequest &request);
QHttpServerResponse handleGetAllDeviceModels(const QHttpServerRequest &request);
@ -41,6 +32,21 @@ private:
template <typename T>
QJsonArray createJsonArray(const QMap<int, T> &items);
template <typename T>
T getQueryParamWithDefault(const QUrlQuery &query, const QString &paramName, const T &defaultValue);
private:
const QSet<QString> validSortOrders = {"Сначала новые", "Сначала старые", "Сначала дешевые", "Сначала дорогие", "Сначала с лайком"};
const QSet<int> validEntityTypeNumbers = {0, 1, 2, 3, 4, 5};
QHttpServer _server;
DeviceLogic *_deviceLogic;
DepartmentLogic *_departmentLogic;
DeviceModelLogic *_deviceModelLogic;
DeviceTypeLogic *_deviceTypeLogic;
LocationLogic *_locationLogic;
ManufacturerLogic *_manufacturerLogic;
};
#endif // APISERVER_H

View File

@ -1,14 +1,14 @@
SELECT
d.*,
l.name AS location_name,
CONCAT(e.last_name, ' ', e.first_name, ' ', e.patronymic) AS employee_full_name,
TRIM(CONCAT(e.last_name, ' ', e.first_name, ' ', e.patronymic)) AS employee_full_name,
e.fk_id_department AS department_id,
dep.name AS department_name
dep.name AS department_name
FROM
device d
JOIN
location l ON d.fk_id_location = l.id
JOIN
LEFT JOIN
employee e ON d.fk_id_employee = e.id
JOIN
LEFT JOIN
department dep ON e.fk_id_department = dep.id;

View File

@ -1,4 +1,5 @@
#include <QCoreApplication>
#include "service/serviceloaddb.h"
#include "apiserver.h"

View File

@ -11,7 +11,7 @@ public:
int id() const;
void setId(int newId);
virtual void fromJson(const QJsonObject &) {}
virtual void fromJson(const QJsonObject &) = 0;
virtual QJsonObject toJson() const = 0;
private:

View File

@ -164,7 +164,7 @@ void Device::fromJson(const QJsonObject &json)
setIsLiked(json["isLiked"].toBool());
DeviceModel model;
model.setId(json["idDeviceModel"].toInt());
model.fromJson(json["deviceModel"].toObject());
setDeviceModel(model);
}
@ -184,7 +184,7 @@ QJsonObject Device::toJson() const
obj["nameEmployee"] = nameEmployee();
obj["idDepartment"] = idDepartment();
obj["nameDepartment"] = nameDepartment();
obj["idDeviceModel"] = deviceModel().id();
obj["deviceModel"] = deviceModel().toJson();
obj["isLiked"] = isLiked();
return obj;
}

13
models/enums/entitytype.h Normal file
View File

@ -0,0 +1,13 @@
#ifndef ENTITYTYPE_H
#define ENTITYTYPE_H
enum class EntityType : int {
All = 0,
DeviceTypes = 1,
Locations = 2,
Departments = 3,
Manufacturers = 4,
DeviceModels = 5
};
#endif // ENTITYTYPE_H

View File

@ -33,22 +33,22 @@ void FilterParams::setPriceTo(double newPriceTo)
_priceTo = newPriceTo;
}
bool FilterParams::getDisregardState() const
bool FilterParams::disregardState() const
{
return disregardState;
return _disregardState;
}
void FilterParams::setDisregardState(bool newDisregardState)
{
disregardState = newDisregardState;
_disregardState = newDisregardState;
}
bool FilterParams::getApllyFilters() const
bool FilterParams::apllyFilters() const
{
return apllyFilters;
return _apllyFilters;
}
void FilterParams::setApllyFilters(bool newApllyFilters)
{
apllyFilters = newApllyFilters;
_apllyFilters = newApllyFilters;
}

View File

@ -15,18 +15,18 @@ public:
double priceTo() const;
void setPriceTo(double newPriceTo);
bool getDisregardState() const;
bool disregardState() const;
void setDisregardState(bool newDisregardState);
bool getApllyFilters() const;
bool apllyFilters() const;
void setApllyFilters(bool newApllyFilters);
private:
bool _isWorking = true;
double _priceFrom = -1;
double _priceTo = -1;
bool disregardState = false;
bool apllyFilters = false;
bool _disregardState = false;
bool _apllyFilters = false;
};
#endif // FILTERPARAMS_H

View File

@ -2,10 +2,10 @@
DepartmentLogic::DepartmentLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
_db = serviceDB;
}
QMap<int, Department> DepartmentLogic::getAll()
{
return db->loadDepartments();
return _db->loadDepartments();
}

View File

@ -10,7 +10,7 @@ public:
QMap<int, Department> getAll();
private:
ServiceLoadDB *db;
ServiceLoadDB *_db;
};
#endif // DEPARTMENTLOGIC_H

View File

@ -2,25 +2,25 @@
DeviceLogic::DeviceLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
_db = serviceDB;
}
QMap<int, Device> DeviceLogic::getAll()
{
db->loadDeviceModels();
return db->loadDevices();
_db->loadDeviceModels();
return _db->loadDevices();
}
QList<Device> DeviceLogic::getAllByParameters(
int entityId, int currentEntity,
int entityId, EntityType entityType,
QString searchText,
const FilterParams &filterParams,
const QString &sortOrder
)
{
db->loadDeviceModels();
auto devices = db->loadDevices();
auto filteredDevices = filterByEntity(devices, entityId, currentEntity);
_db->loadDeviceModels();
auto devices = _db->loadDevices();
auto filteredDevices = filterByEntity(devices, entityId, entityType);
filteredDevices = searchDevices(filteredDevices, searchText);
filteredDevices = applyFilters(filteredDevices, filterParams);
return sortDevices(filteredDevices, sortOrder);
@ -28,38 +28,50 @@ QList<Device> DeviceLogic::getAllByParameters(
bool DeviceLogic::updateDevice(const Device &device)
{
return db->updateDevice(device);
if (device.serialNumber().isEmpty()) {
qDebug() << "Неверный серийный номер устройства, переданного для обновления" << device.serialNumber();
return false;
}
if (device.price() <= 0) {
qDebug() << "Неверная цена устройства, переданного для обновления" << device.price();
return false;
}
if (device.purchaseDate() > device.warrantyExpireDate()) {
qDebug() << "Для корректного обновления устройства необходимо учитывать, что дата покупки не может быть позже даты истечения гарантии";
return false;
}
return _db->updateDevice(device);
}
QMap<int, Device> DeviceLogic::filterByEntity(const QMap<int, Device> &devices, int entityId, int currentEntity)
QMap<int, Device> DeviceLogic::filterByEntity(const QMap<int, Device> &devices, int entityId, EntityType entityType)
{
QMap<int, Device> result;
if (entityId == -1 || currentEntity == 0)
return devices; // "Все устройства"
if (entityId == -1 || entityType == EntityType::All)
return devices;
for (auto &device : devices) {
switch (currentEntity) {
case 1: // Типы устройств
if (device.deviceModel().idType() == entityId)
result.insert(device.id(), device);
break;
case 2: // Помещения
if (device.idLocation() == entityId)
result.insert(device.id(), device);
break;
case 3: // Отделы
if (device.idDepartment() == entityId)
result.insert(device.id(), device);
break;
case 4: // Производители
if (device.deviceModel().idManuf() == entityId)
result.insert(device.id(), device);
break;
case 5: // Модели устройств
if (device.deviceModel().id() == entityId)
result.insert(device.id(), device);
break;
default: break;
switch (entityType) {
case EntityType::DeviceTypes:
if (device.deviceModel().idType() == entityId)
result.insert(device.id(), device);
break;
case EntityType::Locations:
if (device.idLocation() == entityId)
result.insert(device.id(), device);
break;
case EntityType::Departments:
if (device.idDepartment() == entityId)
result.insert(device.id(), device);
break;
case EntityType::Manufacturers:
if (device.deviceModel().idManuf() == entityId)
result.insert(device.id(), device);
break;
case EntityType::DeviceModels:
if (device.deviceModel().id() == entityId)
result.insert(device.id(), device);
break;
default: break;
}
}
return result;
@ -83,10 +95,11 @@ QMap<int, Device> DeviceLogic::searchDevices(const QMap<int, Device> &devices, c
QMap<int, Device> DeviceLogic::applyFilters(const QMap<int, Device> &devices, const FilterParams &filterParams)
{
if (!filterParams.getApllyFilters())
if (!filterParams.apllyFilters())
return devices;
QMap<int, Device> result;
if (filterParams.getDisregardState())
if (filterParams.disregardState())
{
for (auto &device : devices) {
if (device.price() < filterParams.priceFrom() || device.price() > filterParams.priceTo())

View File

@ -3,6 +3,7 @@
#include "service/serviceloaddb.h"
#include "models/filterparams.h"
#include "models/enums/entitytype.h"
class DeviceLogic
{
@ -11,7 +12,7 @@ public:
QMap<int, Device> getAll();
QList<Device> getAllByParameters(
int entityId,
int currentEntity,
EntityType entityType,
QString searchText,
const FilterParams &filterParams,
const QString &sortOrder
@ -19,13 +20,13 @@ public:
bool updateDevice(const Device &device);
private:
QMap<int, Device> filterByEntity(const QMap<int, Device> &devices, int entityId, int currentEntity);
QMap<int, Device> filterByEntity(const QMap<int, Device> &devices, int entityId, EntityType entityType);
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;
ServiceLoadDB *_db;
};
#endif // DEVICELOGIC_H

View File

@ -2,10 +2,10 @@
DeviceModelLogic::DeviceModelLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
_db = serviceDB;
}
QMap<int, DeviceModel> DeviceModelLogic::getAll()
{
return db->loadDeviceModels();
return _db->loadDeviceModels();
}

View File

@ -10,7 +10,7 @@ public:
QMap<int, DeviceModel> getAll();
private:
ServiceLoadDB *db;
ServiceLoadDB *_db;
};
#endif // DEVICEMODELLOGIC_H

View File

@ -2,10 +2,10 @@
DeviceTypeLogic::DeviceTypeLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
_db = serviceDB;
}
QMap<int, DeviceType> DeviceTypeLogic::getAll()
{
return db->loadDeviceTypes();
return _db->loadDeviceTypes();
}

View File

@ -10,7 +10,7 @@ public:
QMap<int, DeviceType> getAll();
private:
ServiceLoadDB *db;
ServiceLoadDB *_db;
};
#endif // DEVICETYPELOGIC_H

View File

@ -2,10 +2,10 @@
LocationLogic::LocationLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
_db = serviceDB;
}
QMap<int, Location> LocationLogic::getAll()
{
return db->loadLocations();
return _db->loadLocations();
}

View File

@ -10,7 +10,7 @@ public:
QMap<int, Location> getAll();
private:
ServiceLoadDB *db;
ServiceLoadDB *_db;
};
#endif // LOCATIONLOGIC_H

View File

@ -2,10 +2,10 @@
ManufacturerLogic::ManufacturerLogic(ServiceLoadDB *serviceDB)
{
db = serviceDB;
_db = serviceDB;
}
QMap<int, Manufacturer> ManufacturerLogic::getAll()
{
return db->loadManufacturers();
return _db->loadManufacturers();
}

View File

@ -10,7 +10,7 @@ public:
QMap<int, Manufacturer> getAll();
private:
ServiceLoadDB *db;
ServiceLoadDB *_db;
};
#endif // MANUFACTURERLOGIC_H

View File

@ -5,35 +5,35 @@ ServiceLoadDB::ServiceLoadDB(QObject *parent) : QObject(parent)
void ServiceLoadDB::start()
{
db = QSqlDatabase::addDatabase("QPSQL");
db.setHostName("127.0.0.1");
db.setDatabaseName("hardware_accounting_db");
db.setUserName("postgres");
db.setPassword("pass");
if(!db.open()){
_db = QSqlDatabase::addDatabase("QPSQL");
_db.setHostName("127.0.0.1");
_db.setDatabaseName("hardware_accounting_db");
_db.setUserName("postgres");
_db.setPassword("pass");
if(!_db.open()){
qDebug() << "Не удалось открыть БД";
return;
}
query = QSqlQuery(db);
_query = QSqlQuery(_db);
}
QMap<int, Location> ServiceLoadDB::loadLocations()
{
QMap<int, Location> mapLocations;
db_input = "SELECT * FROM public.location";
if (!query.exec(db_input)) {
qDebug() << "Ошибка запроса к таблице location: " << query.lastError().text();
_dbInput = "SELECT * FROM public.location";
if (!_query.exec(_dbInput)) {
qDebug() << "Ошибка запроса к таблице location: " << _query.lastError().text();
return mapLocations;
}
QSqlRecord rec;
while (query.next()) {
rec = query.record();
while (_query.next()) {
rec = _query.record();
Location location;
location.setId(query.value(rec.indexOf("id")).toInt());
location.setName(query.value(rec.indexOf("name")).toString());
location.setId(_query.value(rec.indexOf("id")).toInt());
location.setName(_query.value(rec.indexOf("name")).toString());
mapLocations.insert(location.id(), location);
}
@ -45,19 +45,19 @@ QMap<int, Department> ServiceLoadDB::loadDepartments()
{
QMap<int, Department> mapDepartments;
db_input = "SELECT * FROM public.department";
if (!query.exec(db_input)) {
qDebug() << "Ошибка запроса к таблице department: " << query.lastError().text();
_dbInput = "SELECT * FROM public.department";
if (!_query.exec(_dbInput)) {
qDebug() << "Ошибка запроса к таблице department: " << _query.lastError().text();
return mapDepartments;
}
QSqlRecord rec;
while (query.next()) {
rec = query.record();
while (_query.next()) {
rec = _query.record();
Department department;
department.setId(query.value(rec.indexOf("id")).toInt());
department.setName(query.value(rec.indexOf("name")).toString());
department.setId(_query.value(rec.indexOf("id")).toInt());
department.setName(_query.value(rec.indexOf("name")).toString());
mapDepartments.insert(department.id(), department);
}
@ -69,19 +69,19 @@ QMap<int, Manufacturer> ServiceLoadDB::loadManufacturers()
{
QMap<int, Manufacturer> mapManufacturers;
db_input = "SELECT * FROM public.manufacturer";
if (!query.exec(db_input)) {
qDebug() << "Ошибка запроса к таблице manufacturer: " << query.lastError().text();
_dbInput = "SELECT * FROM public.manufacturer";
if (!_query.exec(_dbInput)) {
qDebug() << "Ошибка запроса к таблице manufacturer: " << _query.lastError().text();
return mapManufacturers;
}
QSqlRecord rec;
while (query.next()) {
rec = query.record();
while (_query.next()) {
rec = _query.record();
Manufacturer manufacturer;
manufacturer.setId(query.value(rec.indexOf("id")).toInt());
manufacturer.setName(query.value(rec.indexOf("name")).toString());
manufacturer.setId(_query.value(rec.indexOf("id")).toInt());
manufacturer.setName(_query.value(rec.indexOf("name")).toString());
mapManufacturers.insert(manufacturer.id(), manufacturer);
}
@ -93,19 +93,19 @@ QMap<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();
_dbInput = "SELECT * FROM public.device_type";
if (!_query.exec(_dbInput)) {
qDebug() << "Ошибка запроса к таблице device_type: " << _query.lastError().text();
return mapDeviceTypes;
}
QSqlRecord rec;
while (query.next()) {
rec = query.record();
while (_query.next()) {
rec = _query.record();
DeviceType deviceType;
deviceType.setId(query.value(rec.indexOf("id")).toInt());
deviceType.setName(query.value(rec.indexOf("name")).toString());
deviceType.setId(_query.value(rec.indexOf("id")).toInt());
deviceType.setName(_query.value(rec.indexOf("name")).toString());
mapDeviceTypes.insert(deviceType.id(), deviceType);
}
@ -121,38 +121,38 @@ QMap<int, DeviceModel> ServiceLoadDB::loadDeviceModels()
return QMap<int, DeviceModel>();
}
db_input = QString(file.readAll());
_dbInput = QString(file.readAll());
if (!query.exec(db_input)) {
qDebug() << "Ошибка запроса при получении информации о моделях устройств: " << query.lastError().text();
if (!_query.exec(_dbInput)) {
qDebug() << "Ошибка запроса при получении информации о моделях устройств: " << _query.lastError().text();
return QMap<int, DeviceModel>();
}
QSqlRecord rec;
while (query.next()) {
rec = query.record();
while (_query.next()) {
rec = _query.record();
DeviceModel deviceModel;
int id = query.value(rec.indexOf("id")).toInt();
int id = _query.value(rec.indexOf("id")).toInt();
deviceModel.setId(id);
deviceModel.setName(query.value(rec.indexOf("name")).toString());
deviceModel.setDescription(query.value(rec.indexOf("description")).toString());
deviceModel.setWorkEfficiency(query.value(rec.indexOf("work_efficiency")).toInt());
deviceModel.setReliability(query.value(rec.indexOf("reliability")).toInt());
deviceModel.setEnergyEfficiency(query.value(rec.indexOf("energy_efficiency")).toInt());
deviceModel.setUserFriendliness(query.value(rec.indexOf("user_friendliness")).toInt());
deviceModel.setDurability(query.value(rec.indexOf("durability")).toInt());
deviceModel.setAestheticQualities(query.value(rec.indexOf("aesthetic_qualities")).toInt());
deviceModel.setIdType(query.value(rec.indexOf("fk_id_type")).toInt());
deviceModel.setNameType(query.value(rec.indexOf("device_type_name")).toString());
deviceModel.setIdManuf(query.value(rec.indexOf("fk_id_manuf")).toInt());
deviceModel.setNameManuf(query.value(rec.indexOf("manufacturer_name")).toString());
deviceModel.setName(_query.value(rec.indexOf("name")).toString());
deviceModel.setDescription(getValueOrDefault<QString>(_query, rec, "description", QString("Описание отсутствует")));
deviceModel.setWorkEfficiency(_query.value(rec.indexOf("work_efficiency")).toInt());
deviceModel.setReliability(_query.value(rec.indexOf("reliability")).toInt());
deviceModel.setEnergyEfficiency(_query.value(rec.indexOf("energy_efficiency")).toInt());
deviceModel.setUserFriendliness(_query.value(rec.indexOf("user_friendliness")).toInt());
deviceModel.setDurability(_query.value(rec.indexOf("durability")).toInt());
deviceModel.setAestheticQualities(_query.value(rec.indexOf("aesthetic_qualities")).toInt());
deviceModel.setIdType(_query.value(rec.indexOf("fk_id_type")).toInt());
deviceModel.setNameType(_query.value(rec.indexOf("device_type_name")).toString());
deviceModel.setIdManuf(_query.value(rec.indexOf("fk_id_manuf")).toInt());
deviceModel.setNameManuf(_query.value(rec.indexOf("manufacturer_name")).toString());
deviceModel.setStructureElements(readStructureElements(id));
mapDeviceModels.insert(deviceModel.id(), deviceModel);
_mapDeviceModels.insert(deviceModel.id(), deviceModel);
}
return mapDeviceModels;
return _mapDeviceModels;
}
QMap<int, Device> ServiceLoadDB::loadDevices()
@ -160,50 +160,45 @@ QMap<int, Device> ServiceLoadDB::loadDevices()
QMap<int, Device> mapDevices;
QFile file("../../data/requestDevices.sql");
if (!file.open(QIODevice::ReadOnly))
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "Не получилось открыть файл \"requestDevices.sql\"";
return mapDevices;
}
db_input = QString(file.readAll());
_dbInput = QString(file.readAll());
if (!query.exec(db_input)) {
qDebug() << "Ошибка запроса при получении информации о устройствах: " << query.lastError().text();
if (!_query.exec(_dbInput)) {
qDebug() << "Ошибка запроса при получении информации о устройствах: " << _query.lastError().text();
return mapDevices;
}
QSqlRecord rec;
while (query.next()) {
rec = query.record();
while (_query.next()) {
rec = _query.record();
Device device;
int id = query.value(rec.indexOf("id")).toInt();
int idModel = query.value(rec.indexOf("fk_id_model")).toInt();
if (!mapDeviceModels.contains(idModel)) {
int id = _query.value(rec.indexOf("id")).toInt();
int idModel = _query.value(rec.indexOf("fk_id_model")).toInt();
if (!_mapDeviceModels.contains(idModel)) {
qDebug() << "Не загружена модель устройства. Идентификатор устройства: " << id;
return QMap<int, 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());
device.setSerialNumber(_query.value(rec.indexOf("serial_number")).toString());
device.setPurchaseDate(_query.value(rec.indexOf("purchase_date")).toDateTime());
device.setPrice(_query.value(rec.indexOf("price")).toDouble());
device.setWarrantyExpireDate(_query.value(rec.indexOf("warranty_expire_date")).toDateTime());
device.setIsWorking(_query.value(rec.indexOf("is_working")).toBool());
device.setFurtherInformation(getValueOrDefault<QString>(_query, rec, "further_information", QString("")));
device.setIdLocation(_query.value(rec.indexOf("fk_id_location")).toInt());
device.setNameLocation(_query.value(rec.indexOf("location_name")).toString());
device.setIdEmployee(getValueOrDefault<int>(_query, rec, "fk_id_employee", 0));
device.setNameEmployee(getValueOrDefault<QString>(_query, rec, "employee_full_name", QString("Не назначен")));
device.setIdDepartment(getValueOrDefault<int>(_query, rec, "department_id", 0));
device.setNameDepartment(getValueOrDefault<QString>(_query, rec, "department_name", QString("Не относится к отделу")));
device.setDeviceModel(_mapDeviceModels[idModel]);
device.setIsLiked(_query.value(rec.indexOf("is_liked")).toBool());
mapDevices.insert(device.id(), device);
}
@ -233,8 +228,8 @@ bool ServiceLoadDB::updateDevice(const Device &device)
.arg(device.isLiked() ? "TRUE" : "FALSE")
.arg(device.id());
if (!query.exec(db_input)) {
qDebug() << "Ошибка обновления устройства с id = " << device.id() << ": " << query.lastError().text();
if (!_query.exec(db_input)) {
qDebug() << "Ошибка обновления устройства с id = " << device.id() << ": " << _query.lastError().text();
return false;
}
@ -244,8 +239,8 @@ bool ServiceLoadDB::updateDevice(const Device &device)
QList<DeviceStructureElement> ServiceLoadDB::readStructureElements(int modelId)
{
QSqlQuery secondQuery;
db_input = "SELECT * FROM get_model_structure(:model_id)";
secondQuery.prepare(db_input);
_dbInput = "SELECT * FROM get_model_structure(:model_id)";
secondQuery.prepare(_dbInput);
secondQuery.bindValue(":model_id", modelId);
if (!secondQuery.exec()) {
qDebug() << "Ошибка при выполнении запроса для получения элементов структуры: " << secondQuery.lastError().text();
@ -270,3 +265,13 @@ QList<DeviceStructureElement> ServiceLoadDB::readStructureElements(int modelId)
return elements;
}
template<typename T>
T ServiceLoadDB::getValueOrDefault(const QSqlQuery &query, const QSqlRecord &record, const QString &fieldName, const T &defaultValue)
{
int index = record.indexOf(fieldName);
if (index == -1 || query.value(index).isNull()) {
return defaultValue;
}
return query.value(index).value<T>();
}

View File

@ -19,6 +19,7 @@
class ServiceLoadDB : public QObject
{
Q_OBJECT
public:
explicit ServiceLoadDB(QObject *parent = nullptr);
void start();
@ -33,12 +34,15 @@ public:
private:
QList<DeviceStructureElement> readStructureElements(int modelId);
private:
QSqlDatabase db;
QString db_input;
QSqlQuery query;
template <typename T>
T getValueOrDefault(const QSqlQuery &query, const QSqlRecord &record, const QString &fieldName, const T &defaultValue);
QMap<int, DeviceModel> mapDeviceModels;
private:
QSqlDatabase _db;
QString _dbInput;
QSqlQuery _query;
QMap<int, DeviceModel> _mapDeviceModels;
};
#endif // SERVICELOADDB_H