File: atlasMap.cpp

package info (click to toggle)
postbooks 4.9.5-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 103,120 kB
  • sloc: cpp: 288,269; sh: 607; xml: 214; awk: 104; makefile: 49
file content (367 lines) | stat: -rw-r--r-- 10,687 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
 * This file is part of the xTuple ERP: PostBooks Edition, a free and
 * open source Enterprise Resource Planning software suite,
 * Copyright (c) 1999-2014 by OpenMFG LLC, d/b/a xTuple.
 * It is licensed to you under the Common Public Attribution License
 * version 1.0, the full text of which (including xTuple-specific Exhibits)
 * is available at www.xtuple.com/CPAL.  By using this software, you agree
 * to be bound by its terms.
 */

#include "atlasMap.h"

#include <QAbstractMessageHandler>
#include <QFile>
#include <QMessageBox>
#include <QSqlError>
#include <QVariant>
#include <QXmlQuery>

#include "storedProcErrorLookup.h"

#define DEBUG false

// TODO: replace with XMessageBoxMessageHandler
class AtlasMapMessageHandler : public QAbstractMessageHandler
{
  public:
    AtlasMapMessageHandler(QObject *p = 0) : QAbstractMessageHandler(p)
    {
    }

  protected:
    virtual void handleMessage(QtMsgType type, const QString &description, const QUrl &identifier, const QSourceLocation &sourceLocation)
    {
      QString msg = atlasMap::tr("<p>There was a problem reading the Atlas file, "
                       "line %1 column %2: %3<br>(%4)")
                        .arg(sourceLocation.line())
                        .arg(sourceLocation.column())
                        .arg(description)
                        .arg(identifier.toString());
      switch (type)
      {
        case QtDebugMsg:
          QMessageBox::information(0, atlasMap::tr("XML Error"), msg);
          break;
        case QtWarningMsg:
          QMessageBox::warning(0, atlasMap::tr("XML Error"), msg);
          break;
        case QtCriticalMsg:
        case QtFatalMsg:
        default:
          QMessageBox::critical(0, atlasMap::tr("XML Error"), msg);
          break;
      }
    }
};

bool atlasMap::userHasPriv()
{
  return _privileges->check("ConfigureImportExport");
}

int atlasMap::exec()
{
  if (userHasPriv())
    return XDialog::exec();
  else
  {
    systemError(this,
                tr("You do not have sufficient privilege to view this window"),
                __FILE__, __LINE__);
    return XDialog::Rejected;
  }
}

atlasMap::atlasMap(QWidget* parent, const char * name, Qt::WindowFlags fl)
    : XDialog(parent, name, fl)
{
  setupUi(this);

  connect(_atlas, SIGNAL(editingFinished()), this, SLOT(sHandleAtlas()));
  connect(_buttonBox, SIGNAL(accepted()), this, SLOT(sSave()));
  connect(_buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

  QString filter = tr("Atlas Files (*.xml)");
  _atlas->setFilter(filter);

  _filtertype->append(0, tr("File name"),          "filename");
  _filtertype->append(1, tr("First line of file"), "firstline");

  _mode         = cNew;
  _atlasmapId   = -1;
  _msghandler   = new AtlasMapMessageHandler(this);
#if defined Q_OS_MAC
  _defaultDir   = _metrics->value("CSVAtlasDefaultDirMac");
#elif defined Q_OS_WIN
  _defaultDir   = _metrics->value("CSVAtlasDefaultDirWindows");
#elif defined Q_OS_LINUX
  _defaultDir   = _metrics->value("CSVAtlasDefaultDirLinux");
#endif
}

atlasMap::~atlasMap()
{
  // no need to delete child widgets, Qt does it all for us
}

void atlasMap::languageChange()
{
  retranslateUi(this);
}

enum SetResponse atlasMap::set(const ParameterList &pParams)
{
  XDialog::set(pParams);
  QVariant param;
  bool     valid;

  param = pParams.value("defaultDir", &valid);
  if (valid)
    _defaultDir = param.toString();

  param = pParams.value("mode", &valid);
  if (valid)
  {
    if (param.toString() == "new")
    {
      _mode = cNew;
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;
    }
    else if (param.toString() == "view")
    {
      _mode = cView;

      _name->setEnabled(false);
      _filter->setEnabled(false);
      _filtertype->setEnabled(false);
      _atlas->setEnabled(false);
      _map->setEnabled(false);
      _firstLine->setEnabled(false);
      _buttonBox->setStandardButtons(QDialogButtonBox::Close);
    }
  }

  param = pParams.value("atlasmap_id", &valid);
  if (valid)
  {
    _atlasmapId = param.toInt();
    sPopulate();
  }

  return NoError;
}

void atlasMap::sSave()
{
  QString errorCaption = tr("Cannot Save Atlas Map");

  struct {
    bool        condition;
    QString     msg;
    QWidget*    widget;
  } error[] = {
    { _name->text().trimmed().isEmpty(),
      tr("<p>Please enter a name for this Atlas Map before saving it."),
      _name
    },
    { _filter->text().trimmed().isEmpty(),
      tr("<p>Please enter a filter before saving this Atlas Map."),
      _filter
    },
    { _filtertype->currentText().trimmed().isEmpty(),
      tr("<p>Please select a filter type before saving this Atlas Map."),
      _filtertype
    },
    { _atlas->text().trimmed().isEmpty(),
      tr("<p>Please enter an Atlas File Name before saving this Atlas Map."),
      _atlas
    },
    { _map->id() <= -1,
      tr("Please select a Map Name before saving this Atlas Map."),
      _map
    },
    { true, "", NULL }
  }; // error[]

  int errIndex;
  for (errIndex = 0; ! error[errIndex].condition; errIndex++)
    ;
  if (! error[errIndex].msg.isEmpty())
  {
    QMessageBox::critical(this, errorCaption,
                          error[errIndex].msg);
    error[errIndex].widget->setFocus();
    return;
  }

  XSqlQuery dupq;
  dupq.prepare( "SELECT atlasmap_name "
             "FROM atlasmap "
             "WHERE ((atlasmap_name=:name)"
             " AND   (atlasmap_id<>:atlasmap_id) );" );

  dupq.bindValue(":atlasmap_id",   _atlasmapId);
  dupq.bindValue(":name",          _name->text());
  dupq.exec();
  if (dupq.first())
  {
    QMessageBox::critical(this, errorCaption,
                          tr("<p>This Name is already in use by another "
                             "Atlas Map."));
    _name->setFocus();
    return;
  }
  else if (dupq.lastError().type() != QSqlError::NoError)
  {
    systemError(this, dupq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  XSqlQuery upsq;
  if (cNew == _mode)
    upsq.prepare("INSERT INTO atlasmap ("
                 "    atlasmap_name,  atlasmap_filter, atlasmap_filtertype,"
                 "    atlasmap_atlas, atlasmap_map,    atlasmap_headerline"
                 ") VALUES ("
                 "    :name,  :filter, :filtertype,"
                 "    :atlas, :map,    :headerline"
                 ") RETURNING atlasmap_id;");
  else if (cEdit == _mode)
  {
    upsq.prepare("UPDATE atlasmap SET"
                 "    atlasmap_name=:name,"
                 "    atlasmap_filter=:filter,"
                 "    atlasmap_filtertype=:filtertype,"
                 "    atlasmap_atlas=:atlas,"
                 "    atlasmap_map=:map,"
                 "    atlasmap_headerline=:headerline"
                 " WHERE (atlasmap_id=:id)"
                 " RETURNING atlasmap_id;");
    upsq.bindValue(":id", _atlasmapId);
  }

  upsq.bindValue(":name",       _name->text());
  upsq.bindValue(":filter",     _filter->text());
  upsq.bindValue(":filtertype", _filtertype->code());
  upsq.bindValue(":atlas",      _atlas->text());
  upsq.bindValue(":map",        _map->currentText());
  upsq.bindValue(":headerline", _firstLine->isChecked());
  upsq.exec();
  if (upsq.first())
    _atlasmapId = upsq.value("atlasmap_id").toInt();
  else if (upsq.lastError().type() != QSqlError::NoError)
  {
    systemError(this, upsq.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  accept();
}

void atlasMap::sPopulate()
{
  XSqlQuery atlasPopulate;
  if (_atlasmapId <= 0)
  {
    _name->clear();
    _filter->clear();
    _filtertype->setId(-1);
    _atlas->clear();
    _map->setId(-1);
    _firstLine->setChecked(false);
  }
  else
  {
    atlasPopulate.prepare("SELECT * FROM atlasmap WHERE (atlasmap_id=:id);");
    atlasPopulate.bindValue(":id", _atlasmapId);
    atlasPopulate.exec();
    if (atlasPopulate.first())
    {
      _name->setText(atlasPopulate.value("atlasmap_name").toString());
      _filter->setText(atlasPopulate.value("atlasmap_filter").toString());
      _filtertype->setCode(atlasPopulate.value("atlasmap_filtertype").toString());
      _atlas->setText(atlasPopulate.value("atlasmap_atlas").toString());
      sHandleAtlas();
      if (! atlasPopulate.value("atlasmap_map").toString().isEmpty())
        _map->setCode(atlasPopulate.value("atlasmap_map").toString());
      _firstLine->setChecked(atlasPopulate.value("atlasmap_headerline").toBool());
    }
    else if (atlasPopulate.lastError().type() != QSqlError::NoError)
    {
      systemError(this, atlasPopulate.lastError().databaseText(), __FILE__, __LINE__);
      return;
    }
  }
}

void atlasMap::sHandleAtlas()
{
  _map->clear();

  if (_atlas->text().isEmpty())
    return;

  if (DEBUG)
    qDebug("atlasMap::sHandleAtlas() entered with %s and %s",
           qPrintable(_atlas->text()), qPrintable(_defaultDir));

  if (! _defaultDir.isEmpty() && _atlas->text().startsWith(_defaultDir))
    _atlas->setText(_atlas->text().remove(0, _defaultDir.length() + 1));

  QFile atlasfile;
  if (QFile::exists(_atlas->text()))
    atlasfile.setFileName(_atlas->text());
  else if (QFile::exists(_defaultDir + QDir::separator() + _atlas->text()))
    atlasfile.setFileName(_defaultDir + QDir::separator() + _atlas->text());
  else
  {
    QMessageBox::warning(this, tr("Could not find Atlas"),
                         tr("<p>Could not find the Atlas file to open to look "
                            "for CSV import Maps."));
    return;
  }

  if (! atlasfile.open(QIODevice::ReadOnly))
  {
    QMessageBox::critical(this, tr("Could not open Atlas"),
                          tr("<p>Could not open the Atlas file %1 (error %2).")
                          .arg(atlasfile.fileName(), atlasfile.errorString()));
    return;
  }

  QXmlQuery mapq;
  mapq.setMessageHandler(_msghandler);

  if (! mapq.setFocus(&atlasfile))
  {
    QMessageBox::critical(this, tr("No Focus"),
                          tr("<p>Could not set focus on the Atlas %1")
                          .arg(atlasfile.fileName()));
    return;
  }

  // string() at the end tells the query to generate a sequence of values
  mapq.setQuery("/CSVAtlas/CSVMap/Name/text()/string()");
  if (! mapq.isValid())
  {
    QMessageBox::critical(this, tr("Invalid Query"),
                          tr("<p>The query is not valid for some reason"));
    return;
  }

  QStringList maplist;
  if (! mapq.evaluateTo(&maplist))
  {
    QMessageBox::warning(this, tr("No Maps"),
                         tr("<p>Could not find any Maps in the Atlas %1")
                         .arg(atlasfile.fileName()));
    return;
  }
  else
    for (int i = 0; i < maplist.size(); i++)
      _map->append(i, maplist.at(i));
}