Files
vehicle-voyage/src/jsonio.cpp
2020-06-17 14:08:09 -04:00

75 lines
3.0 KiB
C++

/*
* Copyright (C) 2020 <Kevin Whitakerr> <eyecreate@eyecreate.org>
*
* This program 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.
*
* This program 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 "jsonio.h"
#include <qfile.h>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QSqlRecord>
#include <QSqlQuery>
#include <QUrl>
JsonIO::JsonIO(SqlVehicle* vehicles, SqlServiceRecord* records, QObject* parent)
{
this->vehicles = vehicles;
this->records = records;
}
bool JsonIO::importCarfaxJsonToDB(QString fileLocation)
{
QFile file(QUrl(fileLocation).toLocalFile());
file.open(QIODevice::ReadOnly);
QString jsonContent;
jsonContent = file.readAll();
file.close();
QJsonDocument doc = QJsonDocument::fromJson(jsonContent.toUtf8());
QJsonObject root = doc.object();
if(root.contains("vehicle")) {
QJsonObject vehicle = root["vehicle"].toObject();
QString make = vehicle["make"].toString();
QString model = vehicle["model"].toString();
QString year = vehicle["year"].toString();
QString name = vehicle["nickname"].toString(make+" "+model);
QString vin = vehicle["vin"].toString();
this->vehicles->addNewVehicle(name, make, model, year.toInt(), nullptr, vin); //TODO: image source?
int vehicleId = vehicles->query().lastInsertId().toInt();
if(vehicle.contains("serviceRecords")) {
QJsonArray records = vehicle["serviceRecords"].toArray();
foreach(const QJsonValue & record,records) {
QJsonObject recordObj = record.toObject();
QString date = recordObj["date"].toString();
int miles = recordObj["odometer"].toString().replace(",","").toInt();
QString serviceProvider = recordObj["source"].toArray()[0].toObject()["text"].toString();
QString notes = recordObj["comments"].toString("");
QJsonArray details = recordObj["details"].toArray();
foreach(const QJsonValue & detail, details) {
QString service = detail.toObject()["text"].toString();
int serviceType = -1;
//Detect some common types
if(service == "Tires rotated") serviceType = 3;
if(service == "Oil and filter changed") serviceType = 0;
this->records->addNewRecord(vehicleId, serviceProvider, serviceType, service, date, miles, notes);
}
}
return true;
}
}
return false;
}