adddialog.cpp 2.54 KB
#include "adddialog.h"
#include "ui_adddialog.h"
#include "mainwindow.h"
#include <iostream>
#include <QMessageBox>

AddDialog::AddDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddDialog)
{
    this->parent = parent;
    ui->setupUi(this);
    ui->nameLineEdit->setMaxLength(64);
    ui->phoneLineEdit->setMaxLength(9);
    ui->commentTextEdit->setMaxLength(140);
    connect(ui->buttonBox,SIGNAL(rejected()),parent,SLOT(dismissAddDialog()));
    connect(this,SIGNAL(requestClose()),parent,SLOT(dismissAddDialog()));
    connect(ui->buttonBox,SIGNAL(accepted()),this,SLOT(add()));
    showAssignatures();
}

void AddDialog::showAssignatures()
{
    tableViewModel.setQuery("SELECT nom AS \"Assignatura\" FROM assignatures ORDER by nom;");
    ui->assignaturesTableView->setModel(&tableViewModel);
    ui->assignaturesTableView->resizeColumnsToContents();
}

void AddDialog::add()
{
    QSqlQuery reserva;
    QSqlQuery assignatura;
    QModelIndexList indexes = ui->assignaturesTableView->selectionModel()->selectedRows();
    if(indexes.count())
    {
        if(!MainWindow::checkPhone(ui->phoneLineEdit->text()))
        {
            QMessageBox::critical(this,"Error",trUtf8("Número de telèfon invàlid"));
            return;
        }
        for(int i = 0; i < indexes.count(); i++)
        {
            int number = MainWindow::getNum(tableViewModel.data(indexes.at(i)).toString());
            reserva.prepare("INSERT into reserves VALUES(:name,:num,:phone,NOW(),:comm);");
            reserva.bindValue(":name",ui->nameLineEdit->text());
            reserva.bindValue(":num",number);
            reserva.bindValue(":phone",ui->phoneLineEdit->text().toInt());
            reserva.bindValue(":comm",ui->commentTextEdit->toPlainText());
            reserva.exec();
            assignatura.prepare("UPDATE assignatures SET agafats = '1' WHERE num = :n;");
            assignatura.bindValue(":n",number);
            assignatura.exec();
        }
        ((MainWindow*)parent)->triggerUpdate();
        if(reserva.isActive() && assignatura.isActive())
        {
            ((MainWindow*)parent)->setStatusMessage(trUtf8("Canvis desats: s'han afegit els préstecs"));
            emit requestClose();
            return;
        }
        ((MainWindow*)parent)->setStatusMessage(trUtf8("Error: no s'ha pogut escriure a la base de dades"));
        emit requestClose();
    }
    else
    {
        QMessageBox::critical(this,"Error",trUtf8("No s'ha seleccionat cap assignatura"));
        return;
    }
    emit requestClose();
}

AddDialog::~AddDialog()
{
    delete ui;
}