File: ordercluster.cpp

package info (click to toggle)
postbooks 4.10.0-2
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 112,660 kB
  • ctags: 22,890
  • sloc: cpp: 310,358; sh: 607; xml: 214; python: 140; awk: 104; makefile: 50
file content (987 lines) | stat: -rw-r--r-- 25,100 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
/*
 * 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 <QMessageBox>
#include <QSqlError>

#include "ordercluster.h"
#include "errorReporter.h"
#include "xsqlquery.h"

#define DEBUG false

OrderCluster::OrderCluster(QWidget *pParent, const char *pName) :
  VirtualCluster(pParent, pName)
{
  addNumberWidget(new OrderLineEdit(this, pName));
  
  _name->setVisible(true);
  _grid->removeWidget(_number);
  _grid->removeWidget(_description);
  _grid->removeWidget(_name);

  _grid->addWidget(_number,		0, 1, 1, 2);
  _grid->addWidget(_name,		1, 1);
  _grid->addWidget(_description,	1, 2);

  _fromLit	= new QLabel(this);	_fromLit->setObjectName("_fromLit");
  _from		= new QLabel(this);	_from->setObjectName("_from");
  _toLit	= new QLabel(this);	_toLit->setObjectName("_toLit");
  _to		= new QLabel(this);	_to->setObjectName("_to");

  _grid->addWidget(_fromLit,	2, 1);
  _grid->addWidget(_from,	2, 2);
  _grid->addWidget(_toLit,	2, 3);
  _grid->addWidget(_to,		2, 4);

  connect(_number, SIGNAL(newId(const int, const QString &)), this, SIGNAL(newId(const int, const QString &)));
  connect(_number, SIGNAL(numberChanged(const QString &, const QString &)), this, SIGNAL(numberChanged(const QString &, const QString &)));

  setAllowedStatuses(OrderLineEdit::AnyStatus);
  setAllowedTypes(OrderLineEdit::AnyType);
  setNameVisible(true);
  setDescriptionVisible(true);
  setLabel(tr("Order #:"));
}

OrderLineEdit::OrderStatuses OrderCluster::allowedStatuses() const
{
  return ((OrderLineEdit*)_number)->allowedStatuses();
}

OrderLineEdit::OrderTypes OrderCluster::allowedTypes() const
{
  return ((OrderLineEdit*)_number)->allowedTypes();
}

QString OrderCluster::from() const
{
  return ((OrderLineEdit*)_number)->from();
}

bool OrderCluster::isClosed() const
{
  return ((OrderLineEdit*)_number)->isClosed();
}

bool OrderCluster::isOpen() const
{
  return ((OrderLineEdit*)_number)->isOpen();
}

bool OrderCluster::isPO() const
{
  return ((OrderLineEdit*)_number)->isPO();
}

bool OrderCluster::isRA() const
{
  return ((OrderLineEdit*)_number)->isRA();
}

bool OrderCluster::isSO() const
{
  return ((OrderLineEdit*)_number)->isSO();
}

bool OrderCluster::isTO() const
{
  return ((OrderLineEdit*)_number)->isTO();
}

bool OrderCluster::isUnposted() const
{
  return ((OrderLineEdit*)_number)->isUnposted();
}

bool OrderCluster::fromSitePrivsEnforced() const
{
  return ((OrderLineEdit*)_number)->fromSitePrivsEnforced();
}

bool OrderCluster::toSitePrivsEnforced() const
{
  return ((OrderLineEdit*)_number)->toSitePrivsEnforced();
}

void OrderCluster::setExtraClause(const QString &pType, const QString &pClause)
{
  ((OrderLineEdit*)_number)->setExtraClause(pType, pClause);
}

void OrderCluster::setExtraClause(const OrderLineEdit::OrderTypes pTypes,
				  const QString &pClause)
{
  ((OrderLineEdit*)_number)->setExtraClause(pTypes, pClause);
}

void OrderCluster::setAllowedStatuses(const OrderLineEdit::OrderStatuses p)
{
  ((OrderLineEdit*)_number)->setAllowedStatuses(p);
}

void OrderCluster::setAllowedStatuses(const int p)
{
  ((OrderLineEdit*)_number)->setAllowedStatuses((OrderLineEdit::OrderStatuses)p);
}

void OrderCluster::setFromSitePrivsEnforced(const bool p)
{
  ((OrderLineEdit*)_number)->setFromSitePrivsEnforced(p);
}

void OrderCluster::setToSitePrivsEnforced(const bool p)
{
  ((OrderLineEdit*)_number)->setFromSitePrivsEnforced(p);
}

OrderLineEdit::OrderStatus  OrderCluster::status() const
{
  return ((OrderLineEdit*)_number)->status();
}

QString OrderCluster::to() const
{
  return ((OrderLineEdit*)_number)->to();
}

QString OrderCluster::type() const
{
  return ((OrderLineEdit*)_number)->type();
}

void OrderCluster::setAllowedType(const QString &p)
{
  ((OrderLineEdit*)_number)->setAllowedType(p);
}

void OrderCluster::setAllowedTypes(const OrderLineEdit::OrderTypes p)
{
  ((OrderLineEdit*)_number)->setAllowedTypes(p);
}

void OrderCluster::setAllowedTypes(const int p)
{
  setAllowedTypes((OrderLineEdit::OrderTypes)p);
}

void OrderCluster::setCustId(int p)
{
  ((OrderLineEdit*)_number)->setCustId(p);
}

bool OrderCluster::descriptionVisible() const
{
  return _descripVisible;
}

bool OrderCluster::lockSelected()
{
 return ((OrderLineEdit*)_number)->lockSelected();
}

void OrderCluster::setLockSelected(bool lock)
{
  ((OrderLineEdit*)_number)->setLockSelected(lock);
}

void OrderCluster::setDescriptionVisible(const bool p)
{
  _fromLit->setVisible(p);
  _from->setVisible(p);
  _toLit->setVisible(p);
  _to->setVisible(p);

  _descripVisible=p;
}

bool OrderCluster::nameVisible() const
{
  return _nameVisible;
}

void OrderCluster::setNameVisible(const bool p)
{
  _name->setVisible(p);
  _description->setVisible(p);

  _nameVisible=p;
}

void OrderCluster::setId(const int pId, const QString &pType)
{
  ((OrderLineEdit*)_number)->setId(pId, pType);
}

void OrderCluster::sRefresh()
{
  VirtualCluster::sRefresh();

  _grid->removeWidget(_fromLit);
  _grid->removeWidget(_toLit);
  _grid->removeWidget(_from);
  _grid->removeWidget(_to);

  if (type() == "PO")
  {
    _grid->addWidget(_fromLit,	2, 1);
    _grid->addWidget(_from,	2, 2, 1, -1);
    _grid->addWidget(_toLit,	2, 0);
    _grid->addWidget(_to,	2, 0);

    _fromLit->setText("Vendor:");
    _toLit->setText("");
  }
  else if (type() == "RA")
  {
    _grid->addWidget(_fromLit,	2, 1);
    _grid->addWidget(_from,	2, 2, 1, -1);
    _grid->addWidget(_toLit,	2, 0);
    _grid->addWidget(_to,	2, 0);

    _fromLit->setText("Customer:");
    _toLit->setText("");
  }
  else if (type() == "SO")
  {
    _grid->addWidget(_fromLit,	2, 0);
    _grid->addWidget(_from,	2, 0);
    _grid->addWidget(_toLit,	2, 1);
    _grid->addWidget(_to,	2, 2, 1, -1);

    _fromLit->setText("");
    _toLit->setText("Customer:");
  }
  else if (type() == "TO")
  {
    _grid->addWidget(_fromLit,	2, 1);
    _grid->addWidget(_from,	2, 2);
    _grid->addWidget(_toLit,	2, 3);
    _grid->addWidget(_to,	2, 4);

    _fromLit->setText(tr("From:"));
    _toLit->setText(tr("To:"));
  }
  else
  {
    _grid->addWidget(_fromLit,	2, 1);
    _grid->addWidget(_from,	2, 2);
    _grid->addWidget(_toLit,	2, 3);
    _grid->addWidget(_to,	2, 4);

    _fromLit->setText("");
    _toLit->setText("");
  }

  _from->setText(((OrderLineEdit*)_number)->from());
  _to->setText(((OrderLineEdit*)_number)->to());
}

// LineEdit ///////////////////////////////////////////////////////////////////

OrderLineEdit::OrderLineEdit(QWidget *pParent, const char *pName) :
  VirtualClusterLineEdit(pParent, "orderhead", "orderhead_id",
			 "orderhead_number", "orderhead_type",
			 "orderhead_status", pName)
{

  _toPrivs=false;
  _fromPrivs=false;
  _custid = -1;
  _lockOnSelect = false;
  
  setTitles(tr("Order"), tr("Orders"));

  connect(this, SIGNAL(newId(int)), this, SLOT(sNewId(int)));

  _query = "SELECT orderhead_id AS id, orderhead_number AS number,"
	   "       orderhead_type AS name, orderhead_status AS description,"
	   "       orderhead_from, orderhead_to "
	   "FROM orderhead WHERE (true) ";
}

OrderLineEdit::~OrderLineEdit()
{
  unlock();
}

void OrderLineEdit::sNewId(const int p)
{
  emit newId(p, _name);
  emit numberChanged(text(), _name);
}

void OrderLineEdit::sParse()
{
  if (DEBUG)
    qDebug("VCLE %s::sParse() entered with _parsed %d and text() %s",
           qPrintable(objectName()), _parsed, qPrintable(text()));

    if (! _parsed)
    {
      _parsed = true;
      QString stripped = text().trimmed().toUpper();
      if (stripped.length() == 0)
      {
        setId(-1);
      }
      else
      { 
        XSqlQuery numQ;
        numQ.prepare(_query + _numClause +
                    (_extraClause.isEmpty() || !_strict ? "" : " AND " + _extraClause) +
                    (_hasActive ? _activeClause : "" ) +
                    QString("ORDER BY %1 LIMIT 1;").arg(_numColName));
        numQ.bindValue(":number", "^" + stripped);
        numQ.exec();
        if(numQ.first())
        {
          // Check for other active orders with the same number
          XSqlQuery countQ;
          countQ.prepare("SELECT COUNT(*) AS count FROM orderhead WHERE (true) " + _numClause +
                          (_extraClause.isEmpty() || !_strict ? "" : " AND " + _extraClause) +
                          (_hasActive ? _activeClause : "" ) + QString(";"));
          countQ.bindValue(":number", numQ.value("number").toString());
          countQ.exec();
          countQ.first();
          int result = countQ.value("count").toInt();
          if (result <= 0)
            setId(-1);
          else if (result == 1)
          {
            _valid = true;
            _name = (numQ.value("name").toString());
            _description = numQ.value("description").toString();
            _from = numQ.value("orderhead_from").toString();
            _to	= numQ.value("orderhead_to").toString();
            setId(numQ.value("id").toInt(), numQ.value("name").toString());
          }
          else
          {
            setText(numQ.value("number").toString());
            sEllipses();
          }
        }
        else
        {
          setId(-1);
          if (numQ.lastError().type() != QSqlError::NoError)
              QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
                                            .arg(__FILE__)
                                            .arg(__LINE__),
                      numQ.lastError().databaseText());
        }
      }
      emit valid(_valid);
      emit parsed();
      emit numberChanged(text(), _name);
    }
}

void OrderLineEdit::sList()
{
  disconnect(this, SIGNAL(editingFinished()), this, SLOT(sParse()));

  OrderList* newdlg = new OrderList(this);
  if (newdlg)
  {
    int id = newdlg->exec();
    if(id != -1)
      setId(id, newdlg->type());
  }
  else
    QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
                          .arg(__FILE__)
                          .arg(__LINE__),
                          tr("%1::sList() not yet defined").arg(objectName()));

  connect(this, SIGNAL(editingFinished()), this, SLOT(sParse()));
}

void OrderLineEdit::sSearch()
{
  disconnect(this, SIGNAL(editingFinished()), this, SLOT(sParse()));

  OrderSearch* newdlg = new OrderSearch(this);
  if (newdlg)
  {
    QString stripped = text().trimmed();
    if(stripped.length())
    {
      XSqlQuery numQ;
      numQ.prepare(_query + _numClause +
                   (_extraClause.isEmpty() || !_strict ? "" : " AND " + _extraClause) +
                   ((_hasActive && ! _showInactive) ? _activeClause : "" ) +
                   QString("ORDER BY %1;").arg(_numColName));
      numQ.bindValue(":number", "^" + stripped);
      numQ.exec();
      if (numQ.first())
        newdlg->setQuery(numQ);
    }
    newdlg->setSearchText(text());
    int id = newdlg->exec();
    if(id != -1)
      setId(id, newdlg->type());
  }
  else
    QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
                          .arg(__FILE__)
                          .arg(__LINE__),
                          tr("%1::sSearch() not yet defined").arg(objectName()));

  connect(this, SIGNAL(editingFinished()), this, SLOT(sParse()));
}

OrderLineEdit::OrderStatuses OrderLineEdit::allowedStatuses() const
{
  return _allowedStatuses;
}

OrderLineEdit::OrderTypes OrderLineEdit::allowedTypes() const
{
  return _allowedTypes;
}

void OrderLineEdit::clear()
{
  _from = "";
  _to = "";
  VirtualClusterLineEdit::clear();
}

QString OrderLineEdit::from() const
{
  return _from;
}

bool OrderLineEdit::isClosed() const
{
  return _description == "C";
}

bool OrderLineEdit::isOpen() const
{
  return _description == "O";
}

bool OrderLineEdit::isPO() const
{
  return _name == "PO";
}

bool OrderLineEdit::isRA() const
{
  return _name == "RA";
}

bool OrderLineEdit::isSO() const
{
  return _name == "SO";
}

bool OrderLineEdit::isTO() const
{
  return _name == "TO";
}

bool OrderLineEdit::isUnposted() const
{
  return _description == "U";
}

void OrderLineEdit::setExtraClause(const QString &pType, const QString &pClause)
{
  if (pType == "" || pType.compare("All", Qt::CaseInsensitive) == 0 ||
	   pType.compare("Any", Qt::CaseInsensitive) == 0)
  {
    _poClause = _raClause = _soClause = _toClause = "";
    _allClause = pClause;
  }
  else if (pType == "PO")
    _poClause = " (((orderhead_type='PO') AND (" + pClause + ")) OR (orderhead_type != 'PO')) ";
  else if (pType == "RA")
    _raClause = " (((orderhead_type='RA') AND (" + pClause + ")) OR (orderhead_type != 'RA')) ";
  else if (pType == "SO")
    _soClause = " (((orderhead_type='SO') AND (" + pClause + ")) OR (orderhead_type != 'SO')) ";
  else if (pType == "TO")
    _toClause = " (((orderhead_type='TO') AND (" + pClause + ")) OR (orderhead_type != 'TO')) ";
  else
  {
    QMessageBox::critical(this, tr("Invalid Order Type"),
			  tr("%1 is not a valid Order Type.").arg(pType));
    _allClause = _poClause = _raClause = _soClause = _toClause = "";
  }

  VirtualClusterLineEdit::setExtraClause(buildExtraClause());
}

void OrderLineEdit::setExtraClause(const OrderTypes pTypes, const QString &pClause)
{
  if (pTypes == AnyType ||
      ((pTypes & Purchase) &&
       ((pTypes & Return) || ! _x_metrics->boolean("EnableReturnAuth")) &&
       (pTypes & Sales) &&
       ((pTypes & Transfer) || ! _x_metrics->boolean("MultiWhs"))))
    _allClause = pClause;
  else
  {
    // not else if because multiple flags can be set
    if (pTypes | Purchase)	setExtraClause("PO", pClause);
    if (pTypes | Return)		setExtraClause("RA", pClause);
    if (pTypes | Sales)		setExtraClause("SO", pClause);
    if (pTypes | Transfer)	setExtraClause("TO", pClause);
  }

  VirtualClusterLineEdit::setExtraClause(buildExtraClause());
}

void OrderLineEdit::setToSitePrivsEnforced(const bool p)
{
  if (_toPrivs == p)
    return;
  
  _toPrivs=p;
  if (p)
    _toPrivsClause = " AND ((orderhead_type='TO' "
                     " AND orderhead_to_id IN (SELECT warehous_id FROM site()))"
                     " OR (orderhead_type != 'TO'))";
  else
    _toPrivsClause.clear();
}

void OrderLineEdit::setFromSitePrivsEnforced(const bool p)
{
  if (_fromPrivs == p)
    return;
  
  _fromPrivs=p;
  if (p)
    _fromPrivsClause = " AND ((orderhead_type='TO' "
                     " AND orderhead_from_id IN (SELECT warehous_id FROM site()))"
                     " OR (orderhead_type != 'TO'))";
  else
    _fromPrivsClause.clear();
}

VirtualList * OrderLineEdit::listFactory()
{
  return new OrderList(this);
}

VirtualSearch * OrderLineEdit::searchFactory()
{
  return new OrderSearch(this);
}

OrderLineEdit::OrderStatus  OrderLineEdit::status()
{
  if (_description.isEmpty())	return OrderLineEdit::AnyStatus;
  else if (_description == "O")	return OrderLineEdit::Open;
  else if (_description == "C")	return OrderLineEdit::Closed;
  else
  {
    QMessageBox::critical(this, tr("Invalid Order Status"),
			  tr("Order %1 has an invalid status %2.")
			    .arg(text()).arg(_description));
    return AnyStatus;
  }
}

QString OrderLineEdit::to() const
{
  return _to;
}

QString OrderLineEdit::type()
{
  return _name;
}

void OrderLineEdit::setAllowedStatuses(const OrderStatuses p)
{
  if (p && (p != Unposted + Open + Closed))
  {
    QStringList statusList;

    if (p & Unposted)	statusList << "'U'";
    if (p & Open)	statusList << "'O'";
    if (p & Closed)	statusList << "'C'";

    _statusClause = "(orderhead_status IN (" +
		    statusList.join(", ") +
		    "))";
  }
  else
    _statusClause = "";

  VirtualClusterLineEdit::setExtraClause(buildExtraClause());

  _allowedStatuses = p;
}

void OrderLineEdit::setAllowedType(const QString &p)
{
  if (p == "PO")	setAllowedTypes(Purchase);
  else if (p == "RA")	setAllowedTypes(Return);
  else if (p == "SO")	setAllowedTypes(Sales);
  else if (p == "TO")	setAllowedTypes(Transfer);
  else			setAllowedTypes(AnyType);
}

void OrderLineEdit::setAllowedTypes(const OrderTypes p)
{
  if (_x_metrics &&
      (p & Purchase) &&
      ((p & Return) || ! _x_metrics->boolean("EnableReturnAuth")) &&
      (p & Sales) &&
      ((p & Transfer) || ! _x_metrics->boolean("MultiWhs")))
  {
    _typeClause = "";
    _allowedTypes = AnyType;
  }

  else if (p)
  {
    QStringList typeList;

    if (p & Purchase)
      typeList << "'PO'";

    if (p & Sales)
      typeList << "'SO'";

    if (p & Transfer && _x_metrics->boolean("MultiWhs"))
      typeList << "'TO'";

    if (p & Return)
      typeList << "'RA'";

    if (typeList.count() == 1)
    {
      if (p & Purchase)
      {
        setUiName("purchaseOrder");
        setNewPriv("MaintainPurchaseOrders");
      }
      else if (p & Sales)
      {
        setUiName("salesOrder");
        setNewPriv("MaintainSalesOrders");
      }
      else if (p & Transfer && _x_metrics->boolean("MultiWhs"))
      {
        setUiName("transferOrder");
        setNewPriv("MaintainTransferOrders");
      }
      else
      {
        setUiName("returnAuthorization");
        setNewPriv("MaintainReturns");
      }
    }
    else
      setNewPriv("");

    _typeClause = "(orderhead_type IN (" + typeList.join(", ") + "))" ;
    _allowedTypes = p;
  }
  else
  {
    _typeClause = "";
    _allowedTypes = AnyType;
  }

  VirtualClusterLineEdit::setExtraClause(buildExtraClause());
}

void OrderLineEdit::setCustId(int pId)
{
  if (pId != -1)
    setAllowedTypes(Sales);

  _custid = pId;
  setExtraClause(buildExtraClause());
}

void OrderLineEdit::setId(const int pId, const QString &pType)
{
  // Release any previous lock
  unlock();

  if (pId == -1)
    clear();
  else
  {
    OrderTypes oldTypes = _allowedTypes;
    if(!pType.isNull())
      setAllowedType(pType);
    silentSetId(pId);
    // Attempt to obtain an application lock on the order
    if (_lockOnSelect && _id != -1)
    {
      QString _table;
      if (isPO())
        _table = "pohead";
      else if (isSO())
        _table = "cohead";
      else if (isRA())
        _table = "rahead";
      else if (isTO())
        _table = "tohead";

      if (!_lock.acquire(_table, _id, AppLock::Interactive))
      {
        clear();
        if(!pType.isNull())
          setAllowedTypes(oldTypes);
        return;
      }
    }
    if(!pType.isNull())
      setAllowedTypes(oldTypes);
    emit newId(pId, pType);
    emit valid(_valid);
  }
}

QString OrderLineEdit::buildExtraClause()
{
  QStringList clauses;
  if (! _statusClause.isEmpty()) clauses << _statusClause;
  if (! _typeClause.isEmpty())   clauses << _typeClause;
  if (! _allClause.isEmpty())	 clauses << _allClause;
  if (! _poClause.isEmpty())	 clauses << _poClause;
  if (! _raClause.isEmpty())	 clauses << _raClause;
  if (! _soClause.isEmpty())	 clauses << _soClause;
  if (! _toClause.isEmpty())	 clauses << _toClause;

  QString tmpClause = clauses.join(" AND ");
  if (DEBUG) qDebug("buildExtraClause returning %s",
                    qPrintable(tmpClause));

  if (_custid != -1 && !tmpClause.isEmpty())
    tmpClause += " AND ";

  if (_custid != -1)
    tmpClause += QString(" orderhead_to_id=%1 ").arg(_custid);

  return tmpClause;
}

void OrderLineEdit::silentSetId(const int pId)
{
  if (pId == -1)
    XLineEdit::clear();
  else
  {
    QString oldExtraClause = _extraClause;

    XSqlQuery countQ;
    countQ.prepare("SELECT COUNT(*) AS count FROM orderhead WHERE (true) " + _idClause +
		    (_extraClause.isEmpty() || !_strict ? "" : " AND " + _extraClause) +
		    QString(";"));
    countQ.bindValue(":id", pId);
    countQ.exec();
    if (countQ.first())
    {
      int result = countQ.value("count").toInt();
      if (result <= 0)
      {
	_id = -1;
	XLineEdit::clear();
      }
      else if (result == 1)
	_id = pId;
      else
      {
	_extraClause += "AND (orderhead_id=" + QString::number(pId) + ")";
        sEllipses();
	_extraClause += "AND (orderhead_type='" + type() + "')";
      }
    }
    else if (countQ.lastError().type() != QSqlError::NoError)
    {
      QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
				    .arg(__FILE__)
                                    .arg(__LINE__),
			    countQ.lastError().databaseText());
    }

    if (_id > 0)
    {
      XSqlQuery idQ;
      idQ.prepare(_query + _idClause +
		  (_extraClause.isEmpty() || !_strict ? "" : " AND " + _extraClause) +
		  QString(";"));
      idQ.bindValue(":id", pId);
      idQ.exec();
      if (idQ.first())
      {
	_id = pId;
	_valid = true;
	setText(idQ.value("number").toString());
	_name		= idQ.value("name").toString();
	_description	= idQ.value("description").toString();
	_from		= idQ.value("orderhead_from").toString();
	_to		= idQ.value("orderhead_to").toString();
      }
      else if (idQ.lastError().type() != QSqlError::NoError)
	QMessageBox::critical(this, tr("A System Error Occurred at %1::%2.")
				      .arg(__FILE__)
				      .arg(__LINE__),
			      idQ.lastError().databaseText());
    }
  }

  if (isPO())
  {
    setUiName("purchaseOrder");
    setEditPriv("MaintainPurchaseOrders");
    setViewPriv("ViewPurchaseOrders");
    _idColName="pohead_id";
  }
  else if (isRA())
  {
    setUiName("returnAuthorization");
    setEditPriv("MaintainReturns");
    setViewPriv("ViewReturns");
    _idColName="rahead_id";
  }
  else if (isSO())
  {
    setUiName("salesOrder");
    setEditPriv("MaintainSalesOrders");
    setViewPriv("ViewSalesOrders");
    _idColName="sohead_id";
  }
  else if (isTO())
  {
    setUiName("transferOrder");
    setEditPriv("MaintainTransferOrders");
    setViewPriv("ViewTransferOrders");
    _idColName="tohead_id";
  }
  else
  {
    setUiName(QString());
    setEditPriv(QString());
    setViewPriv(QString());
    _idColName="orderhead_id";
  }

  _parsed = true;
  emit parsed();
}

void OrderLineEdit::unlock()
{
  if (_lockOnSelect && _id != -1)
  {
    if(!_lock.release())
      ErrorReporter::error(QtCriticalMsg, this, tr("Locking Error"),
                             _lock.lastError(), __FILE__, __LINE__);
  }
}

// List ///////////////////////////////////////////////////////////////////////

OrderList::OrderList(QWidget *pParent, Qt::WindowFlags pFlags) :
  VirtualList(pParent, pFlags)
{
  setAttribute(Qt::WA_DeleteOnClose, false);

  resize( QSize(490, 390).expandedTo(minimumSizeHint()) );

  QTreeWidgetItem *headerItem = _listTab->headerItem();
  headerItem->setText(1, tr("Order Type"));
  headerItem->setText(2, tr("Status"));

  _listTab->addColumn(tr("From"), -1, Qt::AlignLeft, true, "orderhead_from");
  _listTab->addColumn(tr("To"),   -1, Qt::AlignLeft, true, "orderhead_to");
  
  OrderLineEdit *lineedit = qobject_cast<OrderLineEdit*>(_parent);
  if (lineedit)
  {
    if (! lineedit->fromPrivsClause().isEmpty())
     lineedit->setExtraClause(lineedit->extraClause() +
                              lineedit->fromPrivsClause());
    if (! lineedit->toPrivsClause().isEmpty())
     lineedit->setExtraClause(lineedit->extraClause() +
                              lineedit->toPrivsClause());
  }
}

void OrderList::sClose()
{
  done(-1);
}

QString OrderList::type() const
{
  if(selectedAtDone.count() > 0)
  {
    return selectedAtDone.at(0)->text(1);
  }

  return "";
}

void OrderList::done(int p)
{
  selectedAtDone = _listTab->selectedItems();
  VirtualList::done(p);
}

// Search /////////////////////////////////////////////////////////////////////

OrderSearch::OrderSearch(QWidget *pParent, Qt::WindowFlags pFlags) :
  VirtualSearch(pParent, pFlags)
{
  setAttribute(Qt::WA_DeleteOnClose, false);
  QTreeWidgetItem *headerItem = _listTab->headerItem();
  headerItem->setText(1, tr("Order Type"));
  headerItem->setText(2, tr("Status"));
  
  resize( QSize(490, 390).expandedTo(minimumSizeHint()) );
  
  _searchName->setText(tr("Search through Order Type"));
  _searchDescrip->setText(tr("Search through Status"));

  _listTab->addColumn(tr("From"), -1, Qt::AlignLeft, true, "orderhead_from");
  _listTab->addColumn(tr("To"),   -1, Qt::AlignLeft, true, "orderhead_to");
  
  if (! ((OrderLineEdit*)_parent)->fromPrivsClause().isEmpty())
     ((OrderLineEdit*)_parent)->setExtraClause(((OrderLineEdit*)_parent)->extraClause() + ((OrderLineEdit*)_parent)->fromPrivsClause());
  if (! ((OrderLineEdit*)_parent)->toPrivsClause().isEmpty())
     ((OrderLineEdit*)_parent)->setExtraClause(((OrderLineEdit*)_parent)->extraClause() + ((OrderLineEdit*)_parent)->toPrivsClause());
       
  sFillList();
}

void OrderSearch::sClose()
{
  done(-1);
}

QString OrderSearch::type() const
{
  QList<XTreeWidgetItem*> items = (selectedAtDone.size() > 0) ? selectedAtDone :
						      _listTab->selectedItems();
  if(items.count() > 0)
    return items.at(0)->text(1);

  return "";
}

void OrderSearch::done(int p)
{
  selectedAtDone = _listTab->selectedItems();
  VirtualSearch::done(p);
}