File indexing completed on 2024-05-19 05:06:53

0001 /*
0002  *    SPDX-FileCopyrightText: 2022 Thomas Baumgart <tbaumgart@kde.org>
0003  *    SPDX-License-Identifier: GPL-2.0-or-later
0004  */
0005 
0006 // ----------------------------------------------------------------------------
0007 // QT Includes
0008 
0009 #include <QAbstractButton>
0010 #include <QComboBox>
0011 #include <QTimer>
0012 
0013 // ----------------------------------------------------------------------------
0014 // KDE Headers
0015 
0016 #include <KLocalizedString>
0017 
0018 // ----------------------------------------------------------------------------
0019 // Project Includes
0020 
0021 #include "kmymoneyutils.h"
0022 #include "mymoneyenums.h"
0023 #include "mymoneyfile.h"
0024 #include "payeecreator.h"
0025 
0026 PayeeCreator::PayeeCreator(QObject* parent)
0027     : QObject(parent)
0028     , m_comboBox(nullptr)
0029 {
0030 }
0031 
0032 void PayeeCreator::addButton(QAbstractButton* button)
0033 {
0034     m_buttons.append(button);
0035 }
0036 
0037 void PayeeCreator::setComboBox(QComboBox* cb)
0038 {
0039     m_comboBox = cb;
0040 }
0041 
0042 void PayeeCreator::createPayee()
0043 {
0044     // keep our own copy just in case it
0045     // gets overwritten in the combobox while we
0046     // are active
0047     m_name = m_comboBox->currentText();
0048 
0049     QTimer::singleShot(150, this, [&]() {
0050         // wait another round if any of the buttons is pressed
0051         if (std::any_of(m_buttons.constBegin(), m_buttons.constEnd(), [&](QAbstractButton* b) -> bool {
0052                 return b->isDown();
0053             })) {
0054             createPayee();
0055             return;
0056         }
0057 
0058         qDebug() << "createPayee" << m_name;
0059         QString payeeId;
0060         bool ok;
0061 
0062         MyMoneyFileTransaction ft(i18nc("Undo action description", "Create payee"), false);
0063         std::tie(ok, payeeId) = KMyMoneyUtils::newPayee(m_name);
0064         if (!ok) {
0065             m_comboBox->clearEditText();
0066             m_comboBox->setCurrentIndex(-1);
0067             m_comboBox->setFocus();
0068         } else {
0069             ft.commit();
0070             const auto index = m_comboBox->findData(payeeId, eMyMoney::Model::IdRole);
0071             if (index != -1) {
0072                 m_comboBox->setCurrentIndex(index);
0073                 auto widget = m_comboBox->nextInFocusChain();
0074                 widget->setFocus();
0075             } else {
0076                 m_comboBox->clearEditText();
0077                 m_comboBox->setCurrentIndex(-1);
0078                 m_comboBox->setFocus();
0079             }
0080         }
0081 
0082         // suicide, we're done
0083         deleteLater();
0084     });
0085 }