399 lines
16 KiB
C++
399 lines
16 KiB
C++
#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;
|
||
|
||
_dbInput = "SELECT * FROM public.location";
|
||
if (!_query.exec(_dbInput)) {
|
||
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;
|
||
|
||
_dbInput = "SELECT * FROM public.department";
|
||
if (!_query.exec(_dbInput)) {
|
||
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;
|
||
|
||
_dbInput = "SELECT * FROM public.manufacturer";
|
||
if (!_query.exec(_dbInput)) {
|
||
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;
|
||
|
||
_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();
|
||
|
||
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()
|
||
{
|
||
QMap<int, DeviceModel> mapDeviceModels;
|
||
|
||
_dbInput = "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 ";
|
||
|
||
if (!_query.exec(_dbInput)) {
|
||
qDebug() << "Ошибка запроса при получении информации о моделях устройств: " << _query.lastError().text();
|
||
return mapDeviceModels;
|
||
}
|
||
|
||
QSqlRecord rec;
|
||
while (_query.next()) {
|
||
rec = _query.record();
|
||
|
||
DeviceModel deviceModel = getModelObject(_query.value(rec.indexOf("id")).toInt(), _query.value(rec.indexOf("name")).toString(),
|
||
getValueOrDefault<QString>(_query, rec, "description", QString("Описание отсутствует")), _query.value(rec.indexOf("work_efficiency")).toInt(),
|
||
_query.value(rec.indexOf("reliability")).toInt(), _query.value(rec.indexOf("energy_efficiency")).toInt(), _query.value(rec.indexOf("user_friendliness")).toInt(),
|
||
_query.value(rec.indexOf("durability")).toInt(), _query.value(rec.indexOf("aesthetic_qualities")).toInt(), _query.value(rec.indexOf("fk_id_type")).toInt(),
|
||
_query.value(rec.indexOf("device_type_name")).toString(), _query.value(rec.indexOf("fk_id_manuf")).toInt(), _query.value(rec.indexOf("manufacturer_name")).toString());
|
||
|
||
mapDeviceModels.insert(deviceModel.id(), deviceModel);
|
||
}
|
||
|
||
return mapDeviceModels;
|
||
}
|
||
|
||
QList<Device> ServiceLoadDB::loadDevices(int entityId, EntityType entityType,
|
||
QString searchText,
|
||
const FilterParams &filterParams,
|
||
const QString &sortOrder)
|
||
{
|
||
QList<Device> devices;
|
||
|
||
QString baseQuery = "SELECT "
|
||
"d.*, "
|
||
"l.name AS location_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, "
|
||
"dm.name AS model_name, "
|
||
"dm.description AS model_description, "
|
||
"dm.work_efficiency, dm.reliability, dm.energy_efficiency, "
|
||
"dm.user_friendliness, dm.durability, dm.aesthetic_qualities, "
|
||
"dm.fk_id_type AS device_type_id, "
|
||
"dt.name AS device_type_name, "
|
||
"dm.fk_id_manuf AS manufacturer_id, "
|
||
"m.name AS manufacturer_name "
|
||
"FROM device d "
|
||
"JOIN device_model dm ON d.fk_id_model = dm.id "
|
||
"JOIN manufacturer m ON dm.fk_id_manuf = m.id "
|
||
"JOIN device_type dt ON dm.fk_id_type = dt.id "
|
||
"JOIN location l ON d.fk_id_location = l.id "
|
||
"LEFT JOIN employee e ON d.fk_id_employee = e.id "
|
||
"LEFT JOIN department dep ON e.fk_id_department = dep.id ";
|
||
|
||
QStringList conditions;
|
||
QList<QVariant> params;
|
||
|
||
if (entityId != -1 && entityType != EntityType::All) {
|
||
switch (entityType) {
|
||
case EntityType::DeviceTypes:
|
||
conditions.append("d.fk_id_model IN (SELECT id FROM device_model WHERE fk_id_type = ?)");
|
||
params.append(entityId);
|
||
break;
|
||
case EntityType::Locations:
|
||
conditions.append("d.fk_id_location = ?");
|
||
params.append(entityId);
|
||
break;
|
||
case EntityType::Departments:
|
||
conditions.append("d.fk_id_employee IN (SELECT id FROM employee WHERE fk_id_department = ?)");
|
||
params.append(entityId);
|
||
break;
|
||
case EntityType::Manufacturers:
|
||
conditions.append("d.fk_id_model IN (SELECT id FROM device_model WHERE fk_id_manuf = ?)");
|
||
params.append(entityId);
|
||
break;
|
||
case EntityType::DeviceModels:
|
||
conditions.append("d.fk_id_model = ?");
|
||
params.append(entityId);
|
||
break;
|
||
default: break;
|
||
}
|
||
}
|
||
|
||
if (!searchText.isEmpty()) {
|
||
conditions.append("(d.serial_number ILIKE ? OR "
|
||
"d.fk_id_model IN (SELECT id FROM device_model WHERE name ILIKE ?) OR "
|
||
"d.fk_id_model IN ("
|
||
"SELECT dm.id "
|
||
"FROM device_model dm "
|
||
"JOIN device_type dt ON dm.fk_id_type = dt.id "
|
||
"WHERE dt.name ILIKE ?))");
|
||
params.append("%" + searchText + "%");
|
||
params.append("%" + searchText + "%");
|
||
params.append("%" + searchText + "%");
|
||
}
|
||
|
||
if (filterParams.apllyFilters()) {
|
||
if (filterParams.disregardState()) {
|
||
conditions.append("d.price BETWEEN ? AND ?");
|
||
params.append(filterParams.priceFrom());
|
||
params.append(filterParams.priceTo());
|
||
} else {
|
||
conditions.append("d.is_working = ? AND d.price BETWEEN ? AND ?");
|
||
params.append(filterParams.isWorking());
|
||
params.append(filterParams.priceFrom());
|
||
params.append(filterParams.priceTo());
|
||
}
|
||
}
|
||
|
||
if (!conditions.isEmpty()) {
|
||
baseQuery.append("WHERE " + conditions.join(" AND "));
|
||
}
|
||
|
||
if (!sortOrder.isEmpty()) {
|
||
if (sortOrder == "Сначала новые") {
|
||
baseQuery.append(" ORDER BY d.purchase_date DESC");
|
||
}
|
||
if (sortOrder == "Сначала старые") {
|
||
baseQuery.append(" ORDER BY d.purchase_date ASC");
|
||
}
|
||
if (sortOrder == "Сначала дешевые") {
|
||
baseQuery.append(" ORDER BY d.price ASC");
|
||
}
|
||
if (sortOrder == "Сначала дорогие") {
|
||
baseQuery.append(" ORDER BY d.price DESC");
|
||
}
|
||
if (sortOrder == "Сначала с лайком") {
|
||
baseQuery.append(" ORDER BY d.is_liked DESC");
|
||
}
|
||
}
|
||
|
||
_dbInput = baseQuery;
|
||
|
||
if (!_query.prepare(_dbInput)) {
|
||
qDebug() << "Ошибка подготовки запроса: " << _query.lastError().text();
|
||
return devices;
|
||
}
|
||
|
||
for (int i = 0; i < params.size(); i++) {
|
||
_query.bindValue(i, params[i]);
|
||
}
|
||
|
||
if (!_query.exec()) {
|
||
qDebug() << "Ошибка запроса при получении информации о устройствах: " << _query.lastError().text();
|
||
return devices;
|
||
}
|
||
|
||
QSqlRecord rec;
|
||
while (_query.next()) {
|
||
rec = _query.record();
|
||
|
||
Device device;
|
||
|
||
device.setId(_query.value(rec.indexOf("id")).toInt());
|
||
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.setIsLiked(_query.value(rec.indexOf("is_liked")).toBool());
|
||
device.setDeviceModel(getModelObject(_query.value(rec.indexOf("fk_id_model")).toInt(), _query.value(rec.indexOf("model_name")).toString(),
|
||
getValueOrDefault<QString>(_query, rec, "model_description", QString("Описание отсутствует")), _query.value(rec.indexOf("work_efficiency")).toInt(),
|
||
_query.value(rec.indexOf("reliability")).toInt(), _query.value(rec.indexOf("energy_efficiency")).toInt(), _query.value(rec.indexOf("user_friendliness")).toInt(),
|
||
_query.value(rec.indexOf("durability")).toInt(), _query.value(rec.indexOf("aesthetic_qualities")).toInt(), _query.value(rec.indexOf("device_type_id")).toInt(),
|
||
_query.value(rec.indexOf("device_type_name")).toString(), _query.value(rec.indexOf("manufacturer_id")).toInt(), _query.value(rec.indexOf("manufacturer_name")).toString()));
|
||
|
||
devices.append(device);
|
||
}
|
||
|
||
return devices;
|
||
}
|
||
|
||
bool ServiceLoadDB::updateDevice(const Device &device)
|
||
{
|
||
_dbInput = "UPDATE device "
|
||
"SET serial_number = ?, "
|
||
"purchase_date = ?, "
|
||
"price = ?, "
|
||
"warranty_expire_date = ?, "
|
||
"is_working = ?, "
|
||
"further_information = ?, "
|
||
"fk_id_location = ?, "
|
||
"fk_id_employee = ?, "
|
||
"fk_id_model = ?, "
|
||
"is_liked = ? "
|
||
"WHERE id = ?";
|
||
|
||
_query.prepare(_dbInput);
|
||
_query.bindValue(0, device.serialNumber());
|
||
_query.bindValue(1, device.purchaseDate().toString("yyyy-MM-dd HH:mm:ss"));
|
||
_query.bindValue(2, device.price());
|
||
_query.bindValue(3, device.warrantyExpireDate().toString("yyyy-MM-dd HH:mm:ss"));
|
||
_query.bindValue(4, device.isWorking() ? "TRUE" : "FALSE");
|
||
_query.bindValue(5, device.furtherInformation());
|
||
_query.bindValue(6, device.idLocation());
|
||
_query.bindValue(7, device.idEmployee());
|
||
_query.bindValue(8, device.deviceModel().id());
|
||
_query.bindValue(9, device.isLiked() ? "TRUE" : "FALSE");
|
||
_query.bindValue(10, device.id());
|
||
|
||
if (!_query.exec()) {
|
||
qDebug() << "Ошибка обновления устройства с id = " << device.id() << ": " << _query.lastError().text();
|
||
return false;
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
QList<DeviceStructureElement> ServiceLoadDB::readStructureElements(int modelId)
|
||
{
|
||
QSqlQuery secondQuery;
|
||
_dbInput = "SELECT * FROM get_model_structure(:model_id)";
|
||
secondQuery.prepare(_dbInput);
|
||
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;
|
||
}
|
||
|
||
DeviceModel ServiceLoadDB::getModelObject(int id, QString name, QString description, int workEfficiency, int reliability, int energyEfficiency, int userFriendlines, int durability,
|
||
int aestheticQualities, int idType, QString nameType, int idManuf, QString nameManuf)
|
||
{
|
||
DeviceModel deviceModel;
|
||
deviceModel.setId(id);
|
||
deviceModel.setName(name);
|
||
deviceModel.setDescription(description);
|
||
deviceModel.setWorkEfficiency(workEfficiency);
|
||
deviceModel.setReliability(reliability);
|
||
deviceModel.setEnergyEfficiency(energyEfficiency);
|
||
deviceModel.setUserFriendliness(userFriendlines);
|
||
deviceModel.setDurability(durability);
|
||
deviceModel.setAestheticQualities(aestheticQualities);
|
||
deviceModel.setIdType(idType);
|
||
deviceModel.setNameType(nameType);
|
||
deviceModel.setIdManuf(idManuf);
|
||
deviceModel.setNameManuf(nameManuf);
|
||
deviceModel.setStructureElements(readStructureElements(id));
|
||
return deviceModel;
|
||
}
|
||
|
||
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>();
|
||
}
|