Files
qelectrotech-source-mirror/sources/ui/bomexportdialog.cpp
T
ispyisail 12ecf6b28f Add read-only enforcement, preview, import/export to custom SQL reports
Refs discussion #886: a saved-report manager built on custom SQL and
nomenclature.json. Most of what was asked for already existed --
Projet > Exporter au format CSV already builds/saves/reuses named
SELECT queries via ElementQueryWidget and nomenclature.json, and
Projet > Ajouter une nomenclature already inserts one into a folio.
This fills the three real gaps.

- projectDataBase::isReadOnlySelect() rejects anything that isn't a
  single SELECT/WITH statement. Checked in newQuery() itself, the one
  choke point every query path already goes through -- including a
  query loaded from a saved nomenclature/summary table's <query>
  element on project open, not just the dialog's own custom-SQL box.
  ElementQueryWidget shows the same check live as you type, and
  BOMExportDialog surfaces it before running or exporting anything.
- BOMExportDialog gains a Preview button + table (QSqlQueryModel),
  so a report can be checked on screen before committing to a CSV file.
- ElementQueryWidget gains Importer.../Exporter... buttons that
  read/write nomenclature.json's saved reports as a JSON file, so a
  report can be handed to a colleague or another install. Import asks
  before overwriting a locally-saved report of the same name.

Verified: Qt 6.10.2, builds clean, ctest 8/8. Drove the real dialog
through Xvfb: typed "DROP TABLE element" into the custom-SQL box and
got the inline warning immediately, then confirmed Preview also
refuses it with a "Requête refusée" dialog rather than running it.
Preview against the real default query returned live column headers
and a row. Export opens a save dialog without crashing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-17 10:09:14 +12:00

181 lines
5.1 KiB
C++

/*
Copyright 2006-2026 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech 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 2 of the License, or
(at your option) any later version.
QElectroTech 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 QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include "bomexportdialog.h"
#include "../dataBase/ui/elementquerywidget.h"
#include "../bomexport.h"
#include "../qetapp.h"
#include "../qetinformation.h"
#include "../qetproject.h"
#include "ui_bomexportdialog.h"
#include <QMessageBox>
#include <QSqlError>
#include <QSqlQueryModel>
#include <QSqlRecord>
/**
@brief BOMExportDialog::BOMExportDialog
@param project
@param parent
*/
BOMExportDialog::BOMExportDialog(QETProject *project, QWidget *parent) :
QDialog(parent),
ui(new Ui::BOMExportDialog),
m_project(project)
{
ui->setupUi(this);
m_query_widget = new ElementQueryWidget(this);
ui->m_main_layout->insertWidget(0, m_query_widget);
m_query_widget->setQuery(BomExport::defaultQuery());
on_m_format_as_bom_clicked(false);
m_preview_model = new QSqlQueryModel(this);
ui->m_preview_table->setModel(m_preview_model);
}
/**
@brief BOMExportDialog::~BOMExportDialog
*/
BOMExportDialog::~BOMExportDialog()
{
delete ui;
}
/**
@brief BOMExportDialog::exec
@return
*/
int BOMExportDialog::exec()
{
auto r = QDialog::exec();
if (r == QDialog::Accepted)
{
//save in csv file in same directory as project by default
QString dir = m_project->currentDir();
if (dir.isEmpty()) dir = QETApp::documentDir();
QString file_name = dir % "/" % tr("nomenclature_") % QString(m_project ->title() % ".csv");
QString file_path = QFileDialog::getSaveFileName(this, tr("Enregister sous... "), file_name, tr("Fichiers csv (*.csv)"));
if (!file_path.isEmpty())
{
QString error;
const auto csv = getBom(&error);
if (!error.isEmpty() || !BomExport::writeCsv(file_path, csv, &error)) {
QMessageBox::critical(
this, tr("Erreur"),
tr("Impossible d'enregistrer la nomenclature dans %1.\n%2")
.arg(file_path, error));
}
}
}
return r;
}
QByteArray BOMExportDialog::getBom(QString *error)
{
if (error) {
error->clear();
}
m_project->dataBase()->updateDB();
QString rejection;
auto query_ = m_project->dataBase()->newQuery(m_query_widget->queryStr(), &rejection);
if (!rejection.isEmpty()) {
if (error) {
*error = rejection;
}
return {};
}
if (!query_.exec()) {
qDebug() << "BOMExportDialog::getBom : query errir : " << query_.lastError();
if (error) {
*error = query_.lastError().text();
}
return {};
}
QStringList header_names;
if (ui->m_include_headers->isChecked())
{
const auto record_ = query_.record();
for (int i = 0; i < record_.count(); ++i)
{
const auto field_name = record_.fieldName(i);
if (field_name == QLatin1String("position")) {
header_names << tr("Position");
} else if (field_name == QLatin1String("diagram_position")) {
header_names << tr("Position du folio");
} else if (field_name == QLatin1String("designation_qty")) {
header_names << tr("Quantité numéro d'article", "Special field with name : designation quantity");
} else {
const auto translated = QETInformation::translatedInfoKey(field_name);
header_names << (translated.isEmpty() ? field_name : translated);
}
}
}
return BomExport::toCsv(
query_, header_names, ui->m_include_headers->isChecked());
}
/**
@brief BOMExportDialog::on_m_format_as_bom_clicked
@param checked
*/
void BOMExportDialog::on_m_format_as_bom_clicked(bool checked) {
m_query_widget->setGroupBy("designation", checked);
m_query_widget->setCount("COUNT(*) AS designation_qty", checked);
}
/**
@brief BOMExportDialog::on_m_preview_pb_clicked
Run the current query and show its result live, without going through
the CSV round-trip -- lets a report be checked and adjusted before
committing to a file (qelectrotech-source-mirror#886).
*/
void BOMExportDialog::on_m_preview_pb_clicked()
{
m_project->dataBase()->updateDB();
QString rejection;
auto query_ = m_project->dataBase()->newQuery(m_query_widget->queryStr(), &rejection);
if (!rejection.isEmpty()) {
QMessageBox::warning(this, tr("Requête refusée"), rejection);
return;
}
if (!query_.exec()) {
QMessageBox::warning(
this, tr("Erreur"),
tr("Erreur dans la requête :\n%1").arg(query_.lastError().text()));
return;
}
m_preview_model->setQuery(std::move(query_));
for (int i = 0; i < m_preview_model->columnCount(); ++i)
{
const auto field_name = m_preview_model->record().fieldName(i);
const auto translated = QETInformation::translatedInfoKey(field_name);
if (!translated.isEmpty()) {
m_preview_model->setHeaderData(i, Qt::Horizontal, translated);
}
}
ui->m_preview_table->resizeColumnsToContents();
}