view src/util.cpp @ 254:0e0ad52994ca

Fix 10L.
author Matti Hamalainen <ccr@tnsp.org>
date Thu, 10 May 2018 01:16:30 +0300
parents eadffc38ab43
children 55581d90c55d
line wrap: on
line source

//
// Syntilista - debt list/management database program
// Programmed and designed by Matti Hämäläinen <ccr@tnsp.org>
// (C) Copyright 2017-2018 Tecnic Software productions (TNSP)
//
// Distributed under 3-clause BSD style license, refer to
// included file "COPYING" for exact terms.
//
#include "main.h"
#include "util.h"
#include <QMessageBox>


//
// Convert QString to a double value, replacing comma
//
double slMoneyStrToValue(const QString &str)
{
    QString str2 = str;
    return str2.replace(",", ".").toDouble();
}


//
// Convert double value to formatted QString
//
QString slMoneyValueToStr(double val)
{
    return QStringLiteral("%1").arg(val, 1, 'f', 2);
}


QString slMoneyValueToStrSign(double val)
{
    return QStringLiteral("%1%2").
        arg(val > 0 ? "+" : "").
        arg(val, 1, 'f', 2);
}


//
// Trim and cleanup given QString (removing double whitespace etc.)
//
QString slCleanupStr(const QString &str)
{
    return str.simplified().trimmed();
}


//
// Manipulate given QDateTime value to get desired
// correct timestamp.
//
const QDateTime slDateTimeToLocal(const QDateTime &val)
{
    QDateTime tmp = val;
    tmp.setOffsetFromUtc(0);
    return tmp.toLocalTime();
}


//
// Return a string representation of given QDateTime
// converted to local time.
//
const QString slDateTimeToStr(const QDateTime &val)
{
//    return slDateTimeToLocal(val).toString(QStringLiteral("yyyy-MM-dd hh:mm"));
    return slDateTimeToLocal(val).toString(QStringLiteral("dd.MM.yyyy hh:mm"));
}


//
// Error logging
//
void slLog(const QString &mtype, const QString &msg)
{
    QString filename = settings.dataPath + QDir::separator() + APP_LOG_FILE;
    QFile fh(filename);
    if (fh.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        QTextStream out(&fh);
        out <<
            slDateTimeToLocal(QDateTime::currentDateTimeUtc()).
            toString(QStringLiteral("yyyy-MM-dd hh:mm:ss"))
            << " [" << mtype << "]: " << msg << "\n";
        fh.close();
    }
}


//
// Display an error dialog with given title and message
//
int slErrorMsg(const QString &title, const QString &msg)
{
    QMessageBox dlg;

    slLog("ERROR", msg);

    dlg.setText(title);
    dlg.setInformativeText(msg);
    dlg.setTextFormat(Qt::RichText);
    dlg.setIcon(QMessageBox::Critical);
    dlg.setStandardButtons(QMessageBox::Ok);
    dlg.setDefaultButton(QMessageBox::Ok);

    return dlg.exec();
}


//
// Check if an SQL error has occured (for given QSqlError) and
// report it to stdout if so. Return "false" if error has occured,
// true otherwise.
//
bool slCheckAndReportSQLError(const QString where, const QSqlError &err, bool report)
{
    if (err.isValid())
    {
        // If an error has occured, log it
        slLog("ERROR",
            QStringLiteral("SQL %1: %2").
            arg(where).arg(err.text()));
        return false;
    }
    else
    {
        // If no error, but event reporting requested, log it
        if (report)
        {
            slLog("NOTE",
                QStringLiteral("SQL OK %1").arg(where));
        }
        return true;
    }
}


bool slConditionallyCreateSQLTables(QSqlDatabase &db, const SLSQLSchemaDef *schema, const int nschema)
{
    for (int ntable = 0; ntable < nschema; ntable++)
    {
        const SLSQLSchemaDef &table = schema[ntable];
        if (!db.tables().contains(table.name))
        {
            // Attempt to create the table
            QSqlQuery tcreate(db);
            QString sql =
                QStringLiteral("CREATE TABLE %1 (%2)").
                arg(table.name).
                arg(table.schema);

            tcreate.exec(sql);

            if (!slCheckAndReportSQLError(
                sql, tcreate.lastError(), true))
                return false;

            tcreate.finish();

            // If any inserts are specified, do them
            for (int n = 0; n < SQL_MAX_SCHEMA_INSERTS; n++)
            {
                const QString str = table.inserts[n];
                if (!str.isEmpty())
                {
                    QSqlQuery insert(db);
                    sql =
                        QStringLiteral("INSERT INTO %1 VALUES (%2)").
                        arg(table.name).
                        arg(str);

                    insert.exec(sql);

                    if (!slCheckAndReportSQLError(
                        sql, insert.lastError(), true))
                        return false;

                    insert.finish();
                }
            }
        }
    }

    return true;
}