~ubuntu-branches/ubuntu/lucid/skrooge/lucid

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
/***************************************************************************
 *   Copyright (C) 2008 by S. MANKOWSKI / G. DE BURE skrooge@mankowski.fr  *
 *                                                                         *
 *   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 2 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/>  *
 ***************************************************************************/
/** @file
 * This file is Skrooge plugin for unit management.
 *
 * @author Stephane MANKOWSKI / Guillaume DE BURE
 */
#include "skgunitpluginwidget.h"
#include "skgmainpanel.h"
#include "skgobjectmodel.h"
#include "skgbankincludes.h"
#include "skgservices.h"
#include "skgtraces.h"
#include "skgunit_settings.h"

#include <kstandarddirs.h>
#include <kio/netaccess.h>
#include <klocale.h>
#include <krun.h>
#include <KUrl>

#include <QtGui/QSortFilterProxyModel>
#include <QDomDocument>
#include <QFile>
#include <QKeyEvent>

SKGUnitPluginWidget::SKGUnitPluginWidget ( SKGDocumentBank* iDocument )
        :SKGTabPage ( iDocument )
{
    SKGTRACEIN ( 10, "SKGUnitPluginWidget::SKGUnitPluginWidget" );

    ui.setupUi ( this );
    //Add Standard KDE Icons to buttons to Accounts
    ui.kUnitAdd->setIcon ( KIcon ( "list-add" ) );
    ui.kUnitUpdate->setIcon ( KIcon ( "dialog-ok-apply" ) );
    ui.kUnitValueDownload->setIcon ( KIcon ( "network-workgroup" ) );

    ui.kStandardBtn->setIcon ( KIcon ( "dialog-ok-apply" ) );
    ui.kManualBtn->setIcon ( KIcon ( "user-properties" ) );
    ui.kValuesBtn->setIcon ( KIcon ( "skrooge_unit" ) );

    //Fill combo box for type
    ui.kTypeCreatorUnit->addItem ( i18nc ( "Noun", "Primary currency" ) );
    ui.kTypeCreatorUnit->addItem ( i18nc ( "Noun", "Secondary currency" ) );
    ui.kTypeCreatorUnit->addItem ( i18nc ( "Noun, a country's currency","Currency" ) );
    ui.kTypeCreatorUnit->addItem ( i18nc ( "Noun, a financial share, as in a stock market","Share" ) );
    ui.kTypeCreatorUnit->addItem ( i18nc ( "Noun, a financial index like the Dow Jones, NASDAQ, CAC40...","Index" ) );
    ui.kTypeCreatorUnit->addItem ( i18nc ( "Noun, a physical object like a house or a car","Object" ) );

    //Fill combo box for currency
    ui.kCurrencyList->addItems ( SKGUnitObject::getListofKnownCurrencies() );

    //Bind unit creation view
    {
        objectModel = new SKGObjectModel ( ( SKGDocumentBank* ) getDocument(), "v_unit_display", "", this, "", false );

        QSortFilterProxyModel* modelProxy = new QSortFilterProxyModel ( this );
        modelProxy->setSourceModel ( objectModel );
        modelProxy->setSortRole ( Qt::UserRole );
        modelProxy->setDynamicSortFilter ( true );
        ui.kFilterEdit->setProxy ( modelProxy );

        ui.kUnitTableViewEdition->setModel ( modelProxy );

        //Add registered global action in contextual menu
        if ( SKGMainPanel::getMainPanel() )
        {
            ui.kUnitTableViewEdition->insertAction ( 0, SKGMainPanel::getMainPanel()->getGlobalAction ( "edit_delete" ) );
            QAction* sep=new QAction ( this );
            sep->setSeparator ( true );
            ui.kUnitTableViewEdition->insertAction ( 0, sep );
            ui.kUnitTableViewEdition->insertAction ( 0, SKGMainPanel::getMainPanel()->getGlobalAction ( "edit_split_stock" ) );
            ui.kUnitTableViewEdition->insertAction ( 0, sep );
            ui.kUnitTableViewEdition->insertAction ( 0, SKGMainPanel::getMainPanel()->getGlobalAction ( "open_report" ) );
        }
        connect ( ui.kUnitTableViewEdition, SIGNAL ( selectionChangedDelayed() ), this, SLOT ( onSelectionChanged() ) );
        connect ( objectModel, SIGNAL ( beforeReset() ), ui.kUnitTableViewEdition, SLOT ( saveSelection() ) );
        connect ( objectModel, SIGNAL ( afterReset() ), ui.kUnitTableViewEdition, SLOT ( resetSelection() ) );
    }

    //Bind unit creation view
    {
        SKGObjectModel* objectModel2 = new SKGObjectModel ( ( SKGDocumentBank* ) getDocument(), "v_unitvalue_display", "1=0", this, "", false );

        ui.kUnitValueTableViewEdition->setModel ( objectModel2 );

        //Add registered global action in contextual menu
        if ( SKGMainPanel::getMainPanel() ) ui.kUnitValueTableViewEdition->insertAction ( 0, SKGMainPanel::getMainPanel()->getGlobalAction ( "edit_delete" ) );

        connect ( ui.kUnitValueTableViewEdition, SIGNAL ( selectionChangedDelayed() ), this, SLOT ( onSelectionValueChanged() ) );
    }

    //Refresh
    connect ( ( const QObject* ) getDocument(), SIGNAL ( tableModified ( QString, int ) ), this, SLOT ( dataModified ( QString, int ) ), Qt::QueuedConnection );
    setCurrentMode ( 0 );

    //Fill combo box for reference currency
    dataModified ( "", 0 );

    //Set Event filters to catch CTRL+ENTER or SHIFT+ENTER
    this->installEventFilter ( this );

}

SKGUnitPluginWidget::~SKGUnitPluginWidget()
{
    SKGTRACEIN ( 10, "SKGUnitPluginWidget::~SKGUnitPluginWidget" );
    objectModel=NULL;
}

bool SKGUnitPluginWidget::eventFilter ( QObject *object, QEvent *event )
{
    if ( event && event->type() == QEvent::KeyPress )
    {
        QKeyEvent *keyEvent = ( QKeyEvent * ) event;
        if ( ( keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter ) && object==this )
        {
            if ( QApplication::keyboardModifiers() &Qt::ControlModifier && ui.kUnitAdd->isEnabled() )
            {
                ui.kUnitAdd->click();
            }
            else if ( QApplication::keyboardModifiers() &Qt::ShiftModifier && ui.kUnitUpdate->isEnabled() )
            {
                ui.kUnitUpdate->click();
            }
        }
    }

    return false;
}

void SKGUnitPluginWidget::onSelectionChanged()
{
    SKGTRACEIN ( 10, "SKGUnitPluginWidget::onSelectionChanged" );
    //Mapping
    QItemSelectionModel *selModel=ui.kUnitTableViewEdition->selectionModel();
    if ( selModel )
    {
        QModelIndexList indexes=selModel->selectedRows();
        int nbSelect=indexes.count();
        if ( nbSelect )
        {
            QModelIndex idx=indexes[indexes.count()-1];

            QSortFilterProxyModel* proxyModel= ( QSortFilterProxyModel* ) ui.kUnitTableViewEdition->model();
            QModelIndex idxs=proxyModel->mapToSource ( idx );

            SKGUnitObject unit ( objectModel->getObject ( idxs ) );

            ui.kNameCreatorUnit->setText ( unit.getName() );
            ui.kSymbolCreatorUnit->setText ( unit.getSymbol() );
            ui.kCountryCreatorUnit->setText ( unit.getCountry() );
            ui.kTypeCreatorUnit->setCurrentIndex ( ( int ) unit.getType() );
            ui.kInternetCreatorUnit->setText ( unit.getInternetCode() );
            ui.kUnitCreatorUnit->setText ( unit.getAttribute ( "t_UNIT" ) );
            ui.kNbDecimal->setValue ( unit.getNumberDecimal() );
        }

        ui.kUnitValueFrame->setEnabled ( nbSelect==1 );
        ui.kNameCreatorUnit->setEnabled ( nbSelect<=1 );
        ui.kSymbolCreatorUnit->setEnabled ( nbSelect<=1 );
        ui.kInternetCreatorUnit->setEnabled ( nbSelect<=1 );
        ui.kUnitValueDownload->setEnabled ( nbSelect>0 );

        //Fill values
        QString wc="rd_unit_id=(select id from unit where t_name='"+SKGServices::stringToSqlString ( ui.kNameCreatorUnit->text() ) +"')";
        SKGObjectModel* objectModel = ( SKGObjectModel* ) ui.kUnitValueTableViewEdition->model();
        if ( objectModel )
        {
            objectModel->setFilter ( "" ); //Correction 2299600: to be sure that refresh will be done
            objectModel->setFilter ( wc+" order by d_date desc" );
            objectModel->refresh();
        }

        ui.kUnitOfUnitLbl->setText ( ui.kUnitCreatorUnit->text() );

        //Draw plot
        SKGStringListList table;
        getDocument()->getConsolidatedView ( "v_unitvalue_display", "d_date", "t_UNIT", "f_quantity", "TOTAL", wc, table , "" );

        SKGServices::SKGUnitInfo primaryUnit= ( ( SKGDocumentBank* ) getDocument() )->getPrimaryUnit();
        SKGServices::SKGUnitInfo secondaryUnit= ( ( SKGDocumentBank* ) getDocument() )->getSecondaryUnit();
        ui.kGraph->setData ( table, primaryUnit, secondaryUnit, SKGTableWithGraph::LIMITS );

        //Correction bug 2299394 vvv
        if ( ui.kUnitValueTableViewEdition->isAutoResized() ) ui.kUnitValueTableViewEdition->resizeColumnsToContents();
        //Correction bug 2299394 ^^^

        onUnitCreatorModified();
        emit selectionChanged();
    }
}

void SKGUnitPluginWidget::onSelectionValueChanged()
{
    SKGTRACEIN ( 10, "SKGUnitPluginWidget::onSelectionValueChanged" );
    //Mapping
    QItemSelectionModel *selModel=ui.kUnitValueTableViewEdition->selectionModel();
    if ( selModel )
    {
        QModelIndexList indexes=selModel->selectedRows();
        int nbSelect=indexes.count();
        if ( nbSelect )
        {
            QModelIndex idx=indexes[indexes.count()-1];

            SKGObjectModel* model= ( SKGObjectModel* ) ui.kUnitValueTableViewEdition->model();
            if ( model )
            {
                SKGUnitValueObject unit ( model->getObject ( idx ) );

                ui.kDateEdit->setDate ( unit.getDate() );
                ui.kAmountEdit->setText ( unit.getAttribute ( "f_quantity" ) );
            }
        }
        else
        {
            ui.kDateEdit->setDate ( QDate::currentDate() );
            ui.kAmountEdit->setText ( "" );
        }
        emit selectionChanged();
    }
}

int SKGUnitPluginWidget::getCurrentMode()
{
    return mode;
}

void SKGUnitPluginWidget::onBtnModeClicked()
{
    QWidget* sender=static_cast<QWidget*> ( this->sender() );

    int currentMode=getCurrentMode();
    int newMode=0;

    if ( sender==ui.kStandardBtn ) newMode=0;
    else if ( sender==ui.kManualBtn ) newMode=1;
    else if ( sender==ui.kValuesBtn ) newMode=2;

    if ( currentMode==newMode ) newMode=-1;
    setCurrentMode ( newMode );
}

void SKGUnitPluginWidget::setCurrentMode ( int iMode )
{
    mode=iMode;

    ui.kStandardFrm->hide();
    ui.kManualFrm->hide();
    ui.kValuesFrm->hide();

    ui.kStandardBtn->setChecked ( false );
    ui.kManualBtn->setChecked ( false );
    ui.kValuesBtn->setChecked ( false );
    ui.kBtnFrm->setVisible ( mode>=0 );

    if ( mode==0 )
    {
        ui.kStandardFrm->show();
        ui.kStandardBtn->setChecked ( true );
    }
    else if ( mode==1 )
    {
        ui.kManualFrm->show();
        ui.kManualBtn->setChecked ( true );
    }
    else if ( mode==2 )
    {
        ui.kValuesFrm->show();
        ui.kValuesBtn->setChecked ( true );
    }

    onUnitCreatorModified();
}

void SKGUnitPluginWidget::onUnitCreatorModified()
{
    SKGTRACEIN ( 10, "SKGUnitPluginWidget::onUnitCreatorModified" );

    bool activated=ui.kNameCreatorUnit->text().length() >0 &&
                   ui.kSymbolCreatorUnit->text().length() >0;

    int nbSelect=getNbSelectedObjects();

    ui.kUnitAdd->setEnabled ( activated || getCurrentMode() ==0 );
    ui.kUnitUpdate->setEnabled ( activated && nbSelect>0 && getCurrentMode() ==1 );

    ui.kValuesBtn->setEnabled ( activated && nbSelect==1 );
    if ( ! ( activated && nbSelect>0 ) && getCurrentMode() ==2 ) setCurrentMode ( 0 );
}

void SKGUnitPluginWidget::onAddUnit()
{
    SKGError err;
    SKGTRACEINRC ( 10, "SKGUnitPluginWidget::onAddUnit",err );
    QApplication::setOverrideCursor ( QCursor ( Qt::WaitCursor ) );
    int mode=getCurrentMode();

    if ( mode==0 )
    {
        QString untiname=ui.kCurrencyList->text();
        SKGBEGINTRANSACTION ( *getDocument(), i18nc ( "Noun, name of the user action", "Unit creation [%1]", untiname ), err );
        SKGUnitObject oUnit;
        err=SKGUnitObject::createCurrencyUnit ( ( SKGDocumentBank* ) getDocument(), ui.kCurrencyList->text(), oUnit );
    }
    else if ( mode==1 )
    {
        QString untiname=ui.kNameCreatorUnit->text();
        SKGUnitObject unitObj ( getDocument() );
        {
            SKGBEGINTRANSACTION ( *getDocument(), i18nc ( "Noun, name of the user action", "Unit creation [%1]", untiname ), err );

            //Create unit object
            if ( err.isSucceeded() ) err=unitObj.setName ( untiname );
            if ( err.isSucceeded() ) err=unitObj.setSymbol ( ui.kSymbolCreatorUnit->text() );
            if ( err.isSucceeded() ) err=unitObj.setCountry ( ui.kCountryCreatorUnit->text() );
            if ( err.isSucceeded() ) err=unitObj.setInternetCode ( ui.kInternetCreatorUnit->text() );
            if ( err.isSucceeded() ) err=unitObj.setType ( ( SKGUnitObject::UnitType ) ( ui.kTypeCreatorUnit->currentIndex() ) );
            if ( err.isSucceeded() ) err=unitObj.setNumberDecimal ( ui.kNbDecimal->value() );
            if ( err.isSucceeded() )
            {
                SKGUnitObject parent ( getDocument() );
                if ( err.isSucceeded() ) err=parent.setSymbol ( ui.kUnitCreatorUnit->text() );
                if ( err.isSucceeded() ) parent.load(); //Do not catch this error
                if ( err.isSucceeded() && parent.exist() ) err=unitObj.setUnit ( parent );
            }

            if ( err.isSucceeded() ) err=unitObj.save();
        }

        //status bar
        if ( err.isSucceeded() )
        {
            err=SKGError ( 0, i18nc ( "Successful message after an user action", "Unit [%1] created", untiname ) );
            ui.kUnitTableViewEdition->selectObject ( unitObj.getUniqueID() );
        }
        else err.addError ( ERR_FAIL, i18nc ( "Error message", "Unit creation failed" ) );
    }
    else if ( mode==2 )
    {
        QString untiname=ui.kNameCreatorUnit->text();
        SKGUnitValueObject unitValueObject;
        {
            SKGBEGINTRANSACTION ( *getDocument(), i18nc ( "Noun, name of the user action", "Unit value creation for [%1]", untiname ), err );
            err= ( ( SKGDocumentBank* ) getDocument() )->addOrModifyUnitValue ( untiname, ui.kDateEdit->date(), ui.kAmountEdit->value(), &unitValueObject );
        }
        //status bar
        if ( err.isSucceeded() )
        {
            err=SKGError ( 0, i18nc ( "Successful message after an user action", "Unit value created for [%1]", untiname ) );
            //TODO doesn't work because of unit table is modified an refreshed ui.kUnitValueTableViewEdition->selectObject(unitValueObject.getUniqueID());
        }
        else err.addError ( ERR_FAIL, i18nc ( "Error message", "Unit value creation failed" ) );
    }
    QApplication::restoreOverrideCursor();

    //Display error
    SKGMainPanel::getMainPanel()->displayErrorMessage ( err );
}



void SKGUnitPluginWidget::onModifyUnit()
{
    SKGError err;
    SKGTRACEINRC ( 10, "SKGUnitPluginWidget::onModifyUnit",err );
    QApplication::setOverrideCursor ( QCursor ( Qt::WaitCursor ) );
    //Get Selection
    SKGObjectBase::SKGListSKGObjectBase selection=getSelectedObjects();

    int nb=selection.count();
    if ( nb )
    {
        SKGBEGINPROGRESSTRANSACTION ( *getDocument(), ( nb==1 ? i18nc ( "Noun, name of the user action", "Unit [%1] update", ui.kNameCreatorUnit->text() ) : i18nc ( "Noun, name of the user action", "Updating %1 units.", nb ) )  , err, nb );

        for ( int i=0; err.isSucceeded() && i<nb; i++ )
        {
            //Modification of unit object
            SKGUnitObject unitObj=selection[i];
            if ( err.isSucceeded() && nb==1 ) err=unitObj.setName ( ui.kNameCreatorUnit->text() );
            if ( err.isSucceeded() && nb==1 ) err=unitObj.setSymbol ( ui.kSymbolCreatorUnit->text() );
            if ( err.isSucceeded() ) err=unitObj.setCountry ( ui.kCountryCreatorUnit->text() );
            if ( err.isSucceeded() && nb==1 ) err=unitObj.setInternetCode ( ui.kInternetCreatorUnit->text() );
            if ( err.isSucceeded() ) err=unitObj.setType ( ( SKGUnitObject::UnitType ) ( ui.kTypeCreatorUnit->currentIndex() ) );
            if ( err.isSucceeded() ) err=unitObj.setNumberDecimal ( ui.kNbDecimal->value() );
            QString parentName=ui.kUnitCreatorUnit->text();
            if ( err.isSucceeded() )
            {
                if ( !parentName.isEmpty() )
                {
                    SKGUnitObject parent ( getDocument() );
                    if ( err.isSucceeded() ) err=parent.setSymbol ( parentName );
                    if ( err.isSucceeded() ) err=parent.load();
                    if ( err.isSucceeded() && parent.exist() ) err=unitObj.setUnit ( parent );
                }
                else err=unitObj.removeUnit();
            }

            if ( err.isSucceeded() ) err=unitObj.save();
            if ( err.isSucceeded() ) err=getDocument()->stepForward ( i+1 );
        }

        //status bar
        if ( err.isSucceeded() ) err=SKGError ( 0, ( nb==1 ? i18nc ( "Message for successful user action", "Unit [%1] updated", ui.kNameCreatorUnit->text() ) : i18nc ( "Message for successful user action","%1 units updated.", nb ) ) );
        else err.addError ( ERR_FAIL, i18nc ( "Error message", "Unit update failed" ) );
    }
    QApplication::restoreOverrideCursor();

    //Display error
    SKGMainPanel::getMainPanel()->displayErrorMessage ( err );
}

void SKGUnitPluginWidget::onDoubleClickUnit()
{
    _SKGTRACEIN ( 10, "SKGUnitPluginWidget::onDoubleClick" );

    //Get selection
    SKGObjectBase::SKGListSKGObjectBase selection=getSelectedObjects();
    if ( selection.count() ==1 )
    {
        SKGUnitObject unit ( selection.at ( 0 ) );
        int unitid=unit.getID();

        //Build where clause and title
        QString wc="rc_unit_id="+SKGServices::intToString ( unitid );
        QString title=i18nc ( "Noun, a list of items", "Operations with unit equal to '%1'",  unit.getName() );

        //Open
        if ( QApplication::keyboardModifiers() &Qt::ControlModifier && QApplication::keyboardModifiers() &Qt::ShiftModifier )
        {
            //Call debug plugin
            QDomDocument doc ( "SKGML" );
            QDomElement root = doc.createElement ( "parameters" );
            doc.appendChild ( root );
            root.setAttribute ( "sqlOrder", "SELECT * from v_operation_display WHERE "+wc );

            SKGMainPanel::getMainPanel()->setNewTabContent ( SKGMainPanel::getMainPanel()->getPluginByName ( "Skrooge debug plugin" ), -1, doc.toString() );
        }
        else
        {
            //Call operation plugin
            QDomDocument doc ( "SKGML" );
            doc.setContent ( getDocument()->getParameter ( "SKGOPERATION_DEFAULT_PARAMETERS" ) );
            QDomElement root = doc.documentElement();
            if ( root.isNull() )
            {
                root=doc.createElement ( "parameters" );
                doc.appendChild ( root );
            }

            root.setAttribute ( "operationTable", "v_operation_display" );
            root.setAttribute ( "operationWhereClause", wc );
            root.setAttribute ( "title", title );
            root.setAttribute ( "title_icon", "skrooge_unit" );
            root.setAttribute ( "currentPage", "-1" );

            SKGMainPanel::getMainPanel()->setNewTabContent ( SKGMainPanel::getMainPanel()->getPluginByName ( "Skrooge operation plugin" ), -1, doc.toString() );
        }
    }
}

SKGError SKGUnitPluginWidget::downloadUnitValue ( const SKGUnitObject& iUnit, UnitDownloadMode iMode )
{
    SKGError err;
    SKGTRACEINRC ( 10, "SKGUnitPluginWidget::downloadUnitValue",err );

    QString unitname=iUnit.getName();
    QString code=iUnit.getInternetCode();
    SKGDocumentBank* doc= ( SKGDocumentBank* ) iUnit.getDocument();
    if ( !code.isEmpty() && doc )
    {
        bool invert=code.contains ( " /" );
        code.remove ( " /" );
        QString unitRef=doc->getPrimaryUnit().Name;
        //BUG: 209905 vvvv
        SKGUnitObject unitRefObj;
        if ( iUnit.getUnit ( unitRefObj ).isSucceeded() )
            unitRef=unitRefObj.getSymbol();
        if ( unitRef==iUnit.getSymbol() ) unitRef="";
        //BUG: 209905 ^^^^
        SKGBEGINTRANSACTION ( *doc, i18nc ( "Noun, name of the user action", "Download values for [%1 (%2)]", unitname, code ), err );

        //Get last date
        SKGStringListList result;
        QString dateParameters;
        SKGServices::executeSelectSqliteOrder ( doc, "SELECT MAX(d_date) FROM unitvalue where rd_unit_id=(SELECT id from unit where t_name='"+SKGServices::stringToSqlString ( unitname ) +"')",
                                                result );
        if ( result.count() ==2 )
        {
            QDate firstDate=SKGServices::stringToTime ( result.at ( 1 ).at ( 0 ) ).date();
            dateParameters="a="+SKGServices::intToString ( firstDate.month()-1 ) +"&b="+SKGServices::intToString ( firstDate.day() ) +"&c="+SKGServices::intToString ( firstDate.year() );
        }

        //Example of code: DSY.PA
        //http://ichart.yahoo.com/table.csv?s=DSY.PA&d=7&e=31&f=2008&g=d&a=0&b=1&c=2003&ignore=.csv
        //&g=w = weekly
        //&g=d = daily
        //&g=m = monthly
        QString parameters;
        UnitDownloadMode mode=iMode;
        if ( mode==AUTO )
        {
            if ( skgunit_settings::last() ) mode=LAST;
            else if ( skgunit_settings::last_monthly() ) mode=LAST_MONTHLY;
            else if ( skgunit_settings::last_weekly() )  mode=LAST_WEEKLY;
            else if ( skgunit_settings::last_daily() )   mode=LAST_DAILY;
            else if ( skgunit_settings::all_monthly() )  mode=ALL_MONTHLY;
            else if ( skgunit_settings::all_weekly() )   mode=ALL_WEEKLY;
            else if ( skgunit_settings::all_daily() )    mode=ALL_DAILY;
        }

        bool last= ( mode==LAST );
        if ( last ) parameters=dateParameters+"&g=d";
        else if ( mode==LAST_MONTHLY ) parameters=dateParameters+"&g=m";
        else if ( mode==LAST_WEEKLY )  parameters=dateParameters+"&g=w";
        else if ( mode==LAST_DAILY )   parameters=dateParameters+"&g=d";
        else if ( mode==ALL_MONTHLY )  parameters="g=m";
        else if ( mode==ALL_WEEKLY )   parameters="g=w";
        else if ( mode==ALL_DAILY )    parameters="g=d";

        //Download history
        if ( !last )
        {
            QString path="http://ichart.yahoo.com/table.csv?s="+code+"&ignore=.csv&"+parameters;
            KUrl url ( path );
            QString tmpFile;
            if ( KIO::NetAccess::download ( url, tmpFile, SKGMainPanel::getMainPanel() ) )
            {

                //Open file
                QFile file ( tmpFile );
                if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) )
                {
                    doc->sendMessage ( i18nc ( "An information message", "Open file [%1] failed",tmpFile ) );
                }
                else
                {
                    QTextStream stream ( &file );

                    //The file is something like this
                    //Date,Open,High,Low,Close,Volume,Adj Close
                    //2008-08-29,41.64,41.86,41.04,41.32,308800,41.32
                    //2008-08-28,40.43,41.93,40.25,41.67,362000,41.67
                    //2008-08-27,41.00,41.00,40.11,40.49,174200,40.49
                    //2008-08-26,40.44,41.00,40.20,40.95,228200,40.95
                    //2008-08-25,40.52,41.02,40.52,40.80,100100,40.80
                    stream.readLine(); //to forget column names

                    int nbLoaded=0;
                    while ( !stream.atEnd() && err.isSucceeded() && nbLoaded<skgunit_settings::nb_loaded_values()-1 )  //-1 because the value of the day will be loaded after
                    {
                        //Read line
                        QString line=stream.readLine().trimmed();
                        QStringList fields=SKGServices::splitCSVLine ( line, ',' );
                        if ( fields.count() ==7 )
                        {
                            QDate ds=QDate::fromString ( fields[0], "yyyy-MM-dd" );
                            double val=SKGServices::stringToDouble ( fields[6] );
                            double coef=1;
                            if ( !unitRef.isEmpty() )
                            {
                                SKGUnitObject unitTmp ( doc );
                                if ( err.isSucceeded() ) err=unitTmp.setSymbol ( unitRef );
                                if ( err.isSucceeded() && unitTmp.exist() )
                                {
                                    err=unitTmp.load();
                                    SKGUnitValueObject unitValTmp;
                                    if ( err.isSucceeded() ) err=unitTmp.getUnitValue ( ds, unitValTmp );
                                    //Correction: 2556409 vvv
                                    if ( err.isFailed() )
                                    {
                                        err=SKGError ( 0, "" );
                                        coef=1;
                                    }
                                    else coef=unitValTmp.getQuantity();
                                    //Correction: 2556409 ^^^
                                }
                            }

                            if ( err.isSucceeded() ) err=doc->addOrModifyUnitValue ( unitname, ds, coef* ( invert && val!=0 ? 1/val : val ) );
                        }
                        else
                        {
                            err.setReturnCode ( ERR_ABORT );
                            err.setMessage ( i18nc ( "An error message", "Invalid line [%1] found in downloaded file.\nCheck this page: %2",line, path ) );
                        }
                        nbLoaded++;
                    }

                    //close file
                    file.close();
                }

                //Remove tmp file
                KIO::NetAccess::removeTempFile ( tmpFile );
            }
            else
            {
                doc->sendMessage ( KIO::NetAccess::lastErrorString() );
            }
        }
        if ( err.isSucceeded() )
        {
            //http://download.finance.yahoo.com/d/quotes.csv?s=EURUSD=X&f=sl1d1t1c1ohgv&e=.csv
            QString path="http://download.finance.yahoo.com/d/quotes.csv?s="+code+"&f=sl1d1t1c1ohgv&e=.csv";
            KUrl url ( path );
            QString tmpFile;
            if ( KIO::NetAccess::download ( url, tmpFile, SKGMainPanel::getMainPanel() ) )
            {

                //Open file
                QFile file ( tmpFile );
                if ( !file.open ( QIODevice::ReadOnly | QIODevice::Text ) )
                {
                    doc->sendMessage ( i18nc ( "An information message", "Open file [%1] failed",tmpFile ) );
                }
                else
                {
                    QTextStream stream ( &file );

                    //The file is something like this
                    //"EURUSD=X",1.33,"10/20/2008","11:12am",N/A,N/A,N/A,N/A,N/A
                    //"DSY.PA",32.46,"11/3/2008","9:56am",+0.13,32.00,32.50,31.21,360802

                    //Read line
                    QString line=stream.readLine().trimmed();
                    line.remove ( '"' );
                    QStringList fields=SKGServices::splitCSVLine ( line, ',' );
                    QDate ds;
                    if ( fields.count() >=5 && ( ds=QDate::fromString ( fields[2], "M/d/yyyy" ) ).isValid() )
                    {
                        double val=SKGServices::stringToDouble ( fields[1] );
                        double coef=1;
                        if ( !unitRef.isEmpty() )
                        {
                            SKGUnitObject unitTmp ( doc );
                            if ( err.isSucceeded() ) err=unitTmp.setSymbol ( unitRef );
                            if ( err.isSucceeded() && unitTmp.exist() )
                            {
                                err=unitTmp.load();
                                SKGUnitValueObject unitValTmp;
                                if ( err.isSucceeded() ) err=unitTmp.getUnitValue ( ds, unitValTmp );
                                //Correction: 2556409 vvv
                                if ( err.isFailed() )
                                {
                                    err=SKGError ( 0, "" );
                                    coef=1;
                                }
                                else coef=unitValTmp.getQuantity();
                                //Correction: 2556409 ^^^
                            }
                        }

                        if ( err.isSucceeded() ) err=doc->addOrModifyUnitValue ( unitname, ds , coef* ( invert && val!=0 ? 1/val : val ) );
                    }
                    else
                    {
                        err.setReturnCode ( ERR_ABORT );
                        err.setMessage ( i18nc ( "An error message", "Invalid line [%1] found in downloaded file.\nCheck this page: %2",line, path ) );
                    }

                    //close file
                    file.close();
                }

                //Remove tmp file
                KIO::NetAccess::removeTempFile ( tmpFile );
            }
            else
            {
                doc->sendMessage ( KIO::NetAccess::lastErrorString() );
            }
        }
    }

    if ( err.isFailed() )
    {
        err.addError ( ERR_FAIL, i18nc ( "Error message", "Impossible to download unit %1 with Internet code %2.", unitname, code ) );
    }

    return err;
}

void SKGUnitPluginWidget::onDownloadUnitValue()
{
    SKGError err;
    SKGTRACEINRC ( 10, "SKGUnitPluginWidget::onDownloadUnitValue",err );
    QApplication::setOverrideCursor ( QCursor ( Qt::WaitCursor ) );
    {
        SKGObjectBase::SKGListSKGObjectBase selection=getSelectedObjects();
        int nb=selection.count();
        for ( int i=0; err.isSucceeded() && i<nb; ++i )
        {
            err=downloadUnitValue ( selection.at ( i ) );
        }
    }
    QApplication::restoreOverrideCursor();

    //Display error
    SKGMainPanel::getMainPanel()->displayErrorMessage ( err );
}

SKGObjectBase::SKGListSKGObjectBase SKGUnitPluginWidget::getSelectedObjects()
{
    SKGObjectBase::SKGListSKGObjectBase output;
    if ( ui.kUnitValueTableViewEdition->hasFocus() )
    {
        output=ui.kUnitValueTableViewEdition->getSelectedObjects();
    }
    if ( output.count() ==0 ) output=ui.kUnitTableViewEdition->getSelectedObjects();
    return output;
}

int SKGUnitPluginWidget::getNbSelectedObjects()
{
    int output=0;
    if ( ui.kUnitValueTableViewEdition->hasFocus() )
    {
        output=ui.kUnitValueTableViewEdition->getNbSelectedObjects();
    }
    if ( output==0 ) output=ui.kUnitTableViewEdition->getNbSelectedObjects();
    return output;
}


QString SKGUnitPluginWidget::getState()
{
    SKGTRACEIN ( 10, "SKGUnitPluginWidget::getState" );
    QDomDocument doc ( "SKGML" );
    QDomElement root = doc.createElement ( "parameters" );
    doc.appendChild ( root );

    root.setAttribute ( "splitter1State", QString ( ui.kMainSplitter->saveState().toHex() ) );
    root.setAttribute ( "splitter2State", QString ( ui.kValuesSplitter->saveState().toHex() ) );
    root.setAttribute ( "filter", ui.kFilterEdit->lineEdit()->text() );

    //Memorize table settings
    root.setAttribute ( "unitview", ui.kUnitTableViewEdition->getState() );
    root.setAttribute ( "unitvalueview", ui.kUnitValueTableViewEdition->getState() );
    root.setAttribute ( "currentPage", SKGServices::intToString ( getCurrentMode() ) );
    root.setAttribute ( "graphSettings", ui.kGraph->getState() );

    return doc.toString();
}

void SKGUnitPluginWidget::setState ( const QString& iState )
{
    SKGTRACEIN ( 10, "SKGUnitPluginWidget::setState" );
    QDomDocument doc ( "SKGML" );
    doc.setContent ( iState );
    QDomElement root = doc.documentElement();

    QString splitter1State=root.attribute ( "splitter1State" );
    if ( !splitter1State.isEmpty() ) ui.kMainSplitter->restoreState ( QByteArray::fromHex ( splitter1State.toAscii() ) );
    QString splitter2State=root.attribute ( "splitter2State" );
    if ( !splitter2State.isEmpty() ) ui.kValuesSplitter->restoreState ( QByteArray::fromHex ( splitter2State.toAscii() ) );
    QString currentPage=root.attribute ( "currentPage" );
    if ( !currentPage.isEmpty() ) setCurrentMode ( SKGServices::stringToInt ( currentPage ) );
    QString filter=root.attribute ( "filter" );
    if ( !filter.isEmpty() ) ui.kFilterEdit->setText ( filter );

    ui.kUnitTableViewEdition->setState ( root.attribute ( "unitview" ) );
    ui.kUnitValueTableViewEdition->setState ( root.attribute ( "unitvalueview" ) );
    ui.kGraph->setState ( root.attribute ( "graphSettings" ) );
    ui.kGraph->setGraphType ( SKGTableWithGraph::LINE );
}

QString SKGUnitPluginWidget::getDefaultStateAttribute()
{
    return "SKGUNIT_DEFAULT_PARAMETERS";
}

void SKGUnitPluginWidget::dataModified ( const QString& iTableName, int iIdTransaction )
{
    SKGTRACEIN ( 10, "SKGUnitPluginWidget::dataModified" );
    Q_UNUSED ( iIdTransaction );

    if ( iTableName=="unit" || iTableName.isEmpty() )
    {
        //Refresh widgets
        setEnabled ( getDocument()->getDatabase() !=NULL );

        //Correction bug 2299394 vvv
        if ( ui.kUnitTableViewEdition->isAutoResized() ) ui.kUnitTableViewEdition->resizeColumnsToContents();
        if ( ui.kUnitValueTableViewEdition->isAutoResized() ) ui.kUnitValueTableViewEdition->resizeColumnsToContents();
        //Correction bug 2299394 ^^^

        QStringList list;
        SKGServices::getDistinctValues ( getDocument(), "unit", "ifnull(t_symbol,t_name)", "t_type IN ('1','2','C')", list );

        //Fill combo
        ui.kUnitCreatorUnit->clear();
        list.insert ( 0, "" );
        ui.kUnitCreatorUnit->addItems ( list );

        onSelectionChanged();
    }
}

void SKGUnitPluginWidget::cleanEditor()
{
    if ( getNbSelectedObjects() ==0 )
    {
        ui.kNameCreatorUnit->setText ( "" );
        ui.kSymbolCreatorUnit->setText ( "" );
        ui.kCountryCreatorUnit->setText ( "" );
        ui.kInternetCreatorUnit->setText ( "" );
        ui.kUnitCreatorUnit->setText ( "" );
    }
}

#include "skgunitpluginwidget.moc"