src/EditProfileFerment.cpp

Thu, 18 Aug 2022 20:34:15 +0200

author
Michiel Broek <mbroek@mbse.eu>
date
Thu, 18 Aug 2022 20:34:15 +0200
changeset 401
583148eb6e01
parent 385
09af9f46518f
permissions
-rw-r--r--

Init est_carb field for new products.

/**
 * EditProfileFerment.cpp is part of bmsapp.
 *
 * bmsapp is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * bmsapp is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "EditProfileFerment.h"
#include "../ui/ui_EditProfileFerment.h"
#include "MainWindow.h"
#include "Utils.h"


EditProfileFerment::EditProfileFerment(int id, QWidget *parent) : QDialog(parent), ui(new Ui::EditProfileFerment)
{
    QSqlQuery query;

    qDebug() << "EditProfileFerment record:" << id;
    ui->setupUi(this);
    this->recno = id;

    ui->sensorEdit->addItem(tr("Beer"));
    ui->sensorEdit->addItem(tr("Fridge"));

    if (id >= 0) {
        query.prepare("SELECT * FROM profile_fermentation WHERE record = :recno");
        query.bindValue(":recno", id);
        query.exec();
        query.next();

        ui->nameEdit->setText(query.value(2).toString());
	ui->temploEdit->setValue(query.value(3).toDouble());
	ui->temphiEdit->setValue(query.value(4).toDouble());
	ui->sensorEdit->setCurrentIndex(query.value(5).toInt());

	QJsonParseError parseError;
        const auto& json = query.value(8).toString();

        if (!json.trimmed().isEmpty()) {
            const auto& formattedJson = QString("%1").arg(json);
            this->steps = QJsonDocument::fromJson(formattedJson.toUtf8(),  &parseError);

            if (parseError.error != QJsonParseError::NoError)
                qDebug() << "Parse error: " << parseError.errorString() << "at" << parseError.offset ;
	}

    } else {
        /* Set some defaults */
	const auto& formattedJson = QString("[]");
	this->steps = QJsonDocument::fromJson(formattedJson.toUtf8());
    }

    connect(ui->nameEdit, &QLineEdit::textChanged, this, &EditProfileFerment::is_changed);
    connect(ui->temploEdit, &QDoubleSpinBox::textChanged, this, &EditProfileFerment::templo_changed);
    connect(ui->temphiEdit, &QDoubleSpinBox::textChanged, this, &EditProfileFerment::temphi_changed);
    connect(ui->sensorEdit, &QComboBox::currentTextChanged, this, &EditProfileFerment::is_changed);
    connect(ui->stepsTable, SIGNAL(cellChanged(int, int)), this, SLOT(cell_Changed(int, int)));

    ui->saveButton->setEnabled(false);
    ui->deleteButton->setEnabled((id >= 0) ? true:false);

    emit refreshTable();

    WindowTitle();
}


void EditProfileFerment::refreshTable()
{
    QString w;
    QWidget* pWidget;
    QHBoxLayout* pLayout;
    double  d;

//    qDebug() << "refreshTable" << this->steps << this->steps.isArray() << this->steps.array().size() ;
    /*
     * During filling the table turn off the cellChanged signal because every cell that is filled
     * triggers the cellChanged signal. The QTableWidget has no better signal to use.
     */
    this->ignoreChanges = true;

    const QStringList labels({tr("Step name"), tr("Start °C"), tr("End °C"), tr("Sensor"), tr("Ramp time"), tr("Rest time"), tr("Button")});
    ui->stepsTable->setColumnCount(7);
    ui->stepsTable->setColumnWidth(0, 248);	/* Step name	*/
    ui->stepsTable->setColumnWidth(1,  75);	/* Start temp	*/
    ui->stepsTable->setColumnWidth(2,  75);	/* End temp	*/
    ui->stepsTable->setColumnWidth(3, 120);	/* Sensor	*/
    ui->stepsTable->setColumnWidth(4,  85);	/* Ramp time	*/
    ui->stepsTable->setColumnWidth(5,  85);	/* Rest time	*/
    ui->stepsTable->setColumnWidth(6,  80);	/* Button	*/
    ui->stepsTable->setHorizontalHeaderLabels(labels);
    ui->stepsTable->verticalHeader()->hide();
    ui->stepsTable->setRowCount(this->steps.array().size());

    totalsteps = 0;
    duration = 0;

    if (this->steps.isArray()) {
	totalsteps = this->steps.array().size();
	for (int i = 0; i < this->steps.array().size(); i++) {
	    QJsonObject obj = this->steps.array().at(i).toObject();

	    ui->stepsTable->setItem(i, 0, new QTableWidgetItem(obj["name"].toString()));

	    /* Numbers can be double quoted or not, the old application could do this wrong. */
	    if (obj["target_lo"].isString())
		d = QString(obj["target_lo"].toString()).toDouble();
	    else
		d = obj["target_lo"].toDouble();
	    w = QString("%1").arg(d, 2, 'f', 1, '0');
	    QTableWidgetItem *item = new QTableWidgetItem(w);
            item->setTextAlignment(Qt::AlignCenter|Qt::AlignVCenter);
	    ui->stepsTable->setItem(i, 1, item);

	    if (obj["target_hi"].isString())
                d = QString(obj["target_hi"].toString()).toDouble();
            else
                d = obj["target_hi"].toDouble();
            w = QString("%1").arg(d, 2, 'f', 1, '0');
            item = new QTableWidgetItem(w);
            item->setTextAlignment(Qt::AlignCenter|Qt::AlignVCenter);
            ui->stepsTable->setItem(i, 2, item);

	    /* Adding fridgemode 0, 1 as combobox. */
            QComboBox* myComboBox = new QComboBox();
            myComboBox->addItem(tr("Beer"));
            myComboBox->addItem(tr("Fridge"));
            ui->stepsTable->setCellWidget(i, 3, myComboBox);

            if (obj["fridgemode"].isString()) {
                d = QString(obj["fridgemode"].toString()).toDouble();
	    } else {
                d = obj["fridgemode"].toDouble();
	    }

            myComboBox->setCurrentIndex((int)d);
            connect<void(QComboBox::*)(int)>(myComboBox, &QComboBox::currentIndexChanged, this, &EditProfileFerment::combo_Changed);

	    if (obj["steptime"].isString())
                d = QString(obj["steptime"].toString()).toDouble();
            else
                d = obj["steptime"].toDouble();
            w = QString("%1").arg(d, 1, 'f', 0, '0');
            item = new QTableWidgetItem(w);
            item->setTextAlignment(Qt::AlignCenter|Qt::AlignVCenter);
            ui->stepsTable->setItem(i, 4, item);
	    duration += (int)d;

	    if (obj["resttime"].isString())
                d = QString(obj["resttime"].toString()).toDouble();
            else
                d = obj["resttime"].toDouble();
            w = QString("%1").arg(d, 1, 'f', 0, '0');
            item = new QTableWidgetItem(w);
            item->setTextAlignment(Qt::AlignCenter|Qt::AlignVCenter);
            ui->stepsTable->setItem(i, 5, item);
	    duration += (int)d;

	    /* Add the Delete row button */
            pWidget = new QWidget();
            QPushButton* btn_edit = new QPushButton();
            btn_edit->setObjectName(QString("%1").arg(i));  /* Send row with the button */
            btn_edit->setText(tr("Delete"));
            connect(btn_edit, SIGNAL(clicked()), this, SLOT(on_deleteRow_clicked()));
            pLayout = new QHBoxLayout(pWidget);
            pLayout->addWidget(btn_edit);
            pLayout->setContentsMargins(5, 0, 5, 0);
            pWidget->setLayout(pLayout);
            ui->stepsTable->setCellWidget(i, 6, pWidget);
	}
    }

    /* Show the calculated total fermentation time. */
    ui->totalEdit->setText(Utils::hours_to_string(duration));
    this->ignoreChanges = false;
}


EditProfileFerment::~EditProfileFerment()
{
    delete ui;
    emit entry_changed();
}


/*
 * Window header, mark any change with '**'
 */
void EditProfileFerment::WindowTitle()
{
    QString txt;

    if (this->recno < 0) {
	txt = QString(tr("BMSapp - Add new fermentation profile"));
    } else {
	txt = QString(tr("BMSapp - Edit fermentation profile %1").arg(this->recno));
    }

    if (this->textIsChanged) {
	txt.append((QString(" **")));
    }
    setWindowTitle(txt);
}


void EditProfileFerment::on_saveButton_clicked()
{
    QSqlQuery query;

    /* If there are errors in the form, show a message and do "return;" */
    if (ui->nameEdit->text().length() < 2) {
	QMessageBox::warning(this, tr("Edit Ferment"), tr("Name empty or too short."));
	return;
    }

    if (this->textIsChanged) {
    	if (this->recno == -1) {
    	    query.prepare("INSERT INTO profile_fermentation SET name=:name, inittemp_lo=:templo, "
		"inittemp_hi=:temphi, fridgemode=:fridgemode, totalsteps=:totalsteps, duration=:duration, "
		"steps=:steps, uuid = :uuid");
    	} else {
	    query.prepare("UPDATE profile_fermentation SET name=:name, inittemp_lo=:templo, "
		"inittemp_hi=:temphi, fridgemode=:fridgemode, totalsteps=:totalsteps, duration=:duration, "
                "steps=:steps WHERE record = :recno");
    	}
	query.bindValue(":name", ui->nameEdit->text());
	query.bindValue(":templo", QString("%1").arg(ui->temploEdit->value(), 2, 'f', 1, '0'));
	query.bindValue(":temphi", QString("%1").arg(ui->temphiEdit->value(), 2, 'f', 1, '0'));
	query.bindValue(":fridgemode", ui->sensorEdit->currentIndex());
	query.bindValue(":totalsteps", QString("%1").arg(totalsteps));
	query.bindValue(":duration", QString("%1").arg(duration));
	query.bindValue(":steps", this->steps.toJson(QJsonDocument::Compact));
	if (this->recno == -1) {
	    query.bindValue(":uuid", QUuid::createUuid().toString().mid(1, 36));
	} else {
	    query.bindValue(":recno", this->recno);
	}
	query.exec();
	if (query.lastError().isValid()) {
	    qWarning() << "EditProfileFerment" << query.lastError();
	    QMessageBox::warning(this, tr("Database error"),
                        tr("MySQL error: %1\n%2\n%3")
                        .arg(query.lastError().nativeErrorCode())
                        .arg(query.lastError().driverText())
                        .arg(query.lastError().databaseText()));
	} else {
	    qDebug() << "EditProfileFerment Saved";
	}
    }

    ui->saveButton->setEnabled(false);
    this->textIsChanged = false;
    WindowTitle();
}


void EditProfileFerment::on_cloneButton_clicked()
{
    QSqlQuery query;

    query.prepare("INSERT INTO profile_fermentation SET name=:name, inittemp_lo=:templo, "
                "inittemp_hi=:temphi, fridgemode=:fridgemode, totalsteps=:totalsteps, duration=:duration, "
                "steps=:steps, uuid = :uuid");

    query.bindValue(":name", ui->nameEdit->text() + " [copy]");
    query.bindValue(":templo", QString("%1").arg(ui->temploEdit->value(), 2, 'f', 1, '0'));
    query.bindValue(":temphi", QString("%1").arg(ui->temphiEdit->value(), 2, 'f', 1, '0'));
    query.bindValue(":fridgemode", ui->sensorEdit->currentIndex());
    query.bindValue(":totalsteps", QString("%1").arg(totalsteps));
    query.bindValue(":duration", QString("%1").arg(duration));
    query.bindValue(":steps", this->steps.toJson(QJsonDocument::Compact));
    query.bindValue(":uuid", QUuid::createUuid().toString().mid(1, 36));

    query.exec();
    if (query.lastError().isValid()) {
	qWarning() << "EditProfileFerment" << query.lastError();
	QMessageBox::warning(this, tr("Database error"),
                        tr("MySQL error: %1\n%2\n%3")
                        .arg(query.lastError().nativeErrorCode())
                        .arg(query.lastError().driverText())
                        .arg(query.lastError().databaseText()));
    } else {
	qDebug() << "EditProfileFerment Saved";
    }
}


void EditProfileFerment::on_deleteButton_clicked()
{
    QSqlQuery query;

    int rc = QMessageBox::warning(this, tr("Delete fermentation profile"), tr("Delete %1").arg(ui->nameEdit->text()),
                    QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
    if (rc == QMessageBox::No)
        return;

    query.prepare("DELETE FROM profile_fermentation WHERE record = :recno");
    query.bindValue(":recno", this->recno);
    query.exec();
    if (query.lastError().isValid()) {
	qWarning() << "EditProfileFerment" << query.lastError();
	QMessageBox::warning(this, tr("Database error"),
                        tr("MySQL error: %1\n%2\n%3")
                        .arg(query.lastError().nativeErrorCode())
                        .arg(query.lastError().driverText())
                        .arg(query.lastError().databaseText()));
    } else {
	qDebug() << "EditProfileFerment Deleted" << this->recno;
    }

    this->close();
    this->setResult(1);
}


void EditProfileFerment::is_changed()
{
    ui->saveButton->setEnabled(true);
    ui->deleteButton->setEnabled((this->recno >= 0) ? true:false);
    this->textIsChanged = true;
    WindowTitle();
}


/*
 * Rebuild the json string from the table contents.
 */
void EditProfileFerment::make_Json()
{
    QTableWidgetItem *item;
    QJsonArray array;

    for (int i = 0; i < ui->stepsTable->rowCount(); i++) {

	QJsonObject obj;
	item = ui->stepsTable->item(i, 0);
	obj.insert("name", item->text());
	item = ui->stepsTable->item(i, 1);
        obj.insert("target_lo", item->text().toDouble());
        item = ui->stepsTable->item(i, 2);
        obj.insert("target_hi", item->text().toDouble());
	QWidget *widget = ui->stepsTable->cellWidget(i, 3);
        obj.insert("fridgemode", static_cast<QComboBox*>(widget)->currentIndex() );
	item = ui->stepsTable->item(i, 4);
        obj.insert("steptime", item->text().toInt());
	item = ui->stepsTable->item(i, 5);
        obj.insert("resttime", item->text().toInt());
//	qDebug() << "make_Json" << i << obj;
	array.append(obj);	/* Append this object */
    }

//    qDebug() << array;
    /* Copy to the global array and refresh */
    this->steps.setArray(array);
    is_changed();
    emit refreshTable();
}


void EditProfileFerment::cell_Changed(int nRow, int nCol)
{
    QString w;

    if (this->ignoreChanges)
	return;

    qDebug() << "Cell at row " + QString::number(nRow) + " column " + QString::number(nCol) + " was changed.";

    /*
     * Check the temperature ranges. Make sure that the high temperature is at least
     * 0.1 degree higher then the low temperature.
     */
    if (nCol == 1) {		// Low temperature was changed
	if (ui->stepsTable->item(nRow, 1)->text().toDouble() > (ui->stepsTable->item(nRow, 2)->text().toDouble() - 0.1)) {
	    w = QString("%1").arg(ui->stepsTable->item(nRow, 1)->text().toDouble() + 0.1, 2, 'f', 1, '0');
	    ui->stepsTable->setItem(nRow, 2, new QTableWidgetItem(w));
	}
    } else if (nCol == 2) {	// High temperature was changed
	if (ui->stepsTable->item(nRow, 2)->text().toDouble() < (ui->stepsTable->item(nRow, 1)->text().toDouble() + 0.1)) {
	    w = QString("%1").arg(ui->stepsTable->item(nRow, 2)->text().toDouble() - 0.1, 2, 'f', 1, '0');
	    ui->stepsTable->setItem(nRow, 1, new QTableWidgetItem(w));
	}
    }
    make_Json();
}


void EditProfileFerment::combo_Changed()
{
    make_Json();
}


void EditProfileFerment::templo_changed()
{
    if (ui->temploEdit->value() > (ui->temphiEdit->value() - 0.1))
        ui->temphiEdit->setValue(ui->temploEdit->value() + 0.1);
    is_changed();
}


void EditProfileFerment::temphi_changed()
{
    if (ui->temphiEdit->value() < (ui->temploEdit->value() + 0.1))
        ui->temploEdit->setValue(ui->temphiEdit->value() - 0.1);
    is_changed();
}


/*
 * Add new row and initialize all fields.
 */
void EditProfileFerment::on_addButton_clicked()
{
    QWidget* pWidget;
    QHBoxLayout* pLayout;

    qDebug() << "Add row" << totalsteps;
    this->ignoreChanges = true;
    ui->stepsTable->insertRow(totalsteps);
    ui->stepsTable->setItem(totalsteps, 0, new QTableWidgetItem(QString("new row %1").arg(totalsteps)));
    ui->stepsTable->setItem(totalsteps, 1, new QTableWidgetItem(QString("19.8")));
    ui->stepsTable->setItem(totalsteps, 2, new QTableWidgetItem(QString("20.0")));
    QComboBox* myComboBox = new QComboBox();
    myComboBox->addItem(tr("Beer"));
    myComboBox->addItem(tr("Fridge"));
    myComboBox->setCurrentIndex(0);
    ui->stepsTable->setCellWidget(totalsteps, 3, myComboBox);
    ui->stepsTable->setItem(totalsteps, 4, new QTableWidgetItem(QString("0")));
    ui->stepsTable->setItem(totalsteps, 5, new QTableWidgetItem(QString("0")));

    pWidget = new QWidget();
    QPushButton* btn_edit = new QPushButton();
    btn_edit->setObjectName(QString("%1").arg(totalsteps));  /* Send row with the button */
    btn_edit->setText(tr("Delete"));
    connect(btn_edit, SIGNAL(clicked()), this, SLOT(on_deleteRow_clicked()));
    pLayout = new QHBoxLayout(pWidget);
    pLayout->addWidget(btn_edit);
    pLayout->setContentsMargins(5, 0, 5, 0);
    pWidget->setLayout(pLayout);
    ui->stepsTable->setCellWidget(totalsteps, 6, pWidget);

    this->ignoreChanges = false;
    make_Json();
}


void EditProfileFerment::on_deleteRow_clicked()
{
    QPushButton *pb = qobject_cast<QPushButton *>(QObject::sender());
    int row = pb->objectName().toInt();
    qDebug() << "Delete row" << row;
    ui->stepsTable->removeRow(row);
    make_Json();
}


void EditProfileFerment::on_quitButton_clicked()
{
    if (this->textIsChanged) {
	int rc = QMessageBox::warning(this, tr("Fermentation changed"), tr("This fermentation profile has been modified. Save changes?"),
                                QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save);
        switch (rc) {
            case QMessageBox::Save:
                        on_saveButton_clicked();
                        break;  /* Saved and then Quit */
            case QMessageBox::Discard:
                        break;  /* Quit without Save */
            case QMessageBox::Cancel:
                        return; /* Return to the editor page */
        }
    }

    this->close();
    this->setResult(1);
}

mercurial