diff --git a/kmymoney/plugins/kbanking/CMakeLists.txt b/kmymoney/plugins/kbanking/CMakeLists.txt index f73fac3ce..79c739618 100644 --- a/kmymoney/plugins/kbanking/CMakeLists.txt +++ b/kmymoney/plugins/kbanking/CMakeLists.txt @@ -1,78 +1,83 @@ # patch the version with the version defined in the build system configure_file(${CMAKE_CURRENT_SOURCE_DIR}/kmm_kbanking.desktop ${CMAKE_CURRENT_BINARY_DIR}/kmm_kbanking.desktop) include_directories(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/dialogs ${CMAKE_CURRENT_BINARY_DIR}/dialogs ${CMAKE_CURRENT_SOURCE_DIR}/widgets ${CMAKE_CURRENT_BINARY_DIR}/widgets ${GWENHYWFAR_INCLUDE_DIRS} ${AQBANKING_INCLUDE_DIRS} ${gwengui-cpp_INCLUDE_DIRS} ${gwengui-qt4_INCLUDE_DIRS} ) +file(STRINGS "${AQBANKING_INCLUDE_DIRS}/aqbanking/banking.h" HAVE_REGISTRATION_FEATURE REGEX "AB_Banking_RuntimeConfig_SetCharValue") +if (NOT ${HAVE_REGISTRATION_FEATURE} STREQUAL "") + add_definitions(-DENABLE_FINTS_REGISTRATION) +endif() + add_subdirectory( dialogs ) add_subdirectory( widgets ) add_subdirectory( qml ) add_subdirectory( tasksettings ) ########### next target ############### set(kmm_kbanking_PART_SRCS mymoneybanking.cpp banking.cpp aqbankingkmmoperators.cpp gwenhywfarqtoperators.cpp gwenkdegui.cpp ) set(kmm_kbanking_HEADERS aqbankingqtoperators.h gwenhywfarqtoperators.h ) kde4_add_kcfg_files(kmm_kbanking_settings_SRCS kbankingsettings.kcfgc) kde4_add_library(kmm_kbanking_settings STATIC ${kmm_kbanking_settings_SRCS}) add_dependencies(kmm_kbanking_widgets kmm_kbanking_settings) kde4_add_plugin(kmm_kbanking ${kmm_kbanking_PART_SRCS}) # newer version of Gwenhywfar provide the variables GWENHYWFAR_QT4GUI_LDFLAGS # and GWENHYWFAR_CORE_LDFLAGS, older ones use GWENHYWFAR_LIBRARIES instead # we add both here for some time. At a later point simply remove # GWENHYWFAR_LIBRARIES. target_link_libraries(kmm_kbanking kmm_kbanking_dialogs kmm_kbanking_widgets kmm_kbanking_settings kmm_kbanking_tasksettings kmm_mymoney kmm_widgets kmm_plugin payeeidentifier_iban_bic payeeidentifier_nationalAccount ${KDE4_KDEUI_LIBS} ${QT_QTDECLARATIVE_LIBRARY} ${GWENHYWFAR_LIBRARIES} ${gwengui-qt4_LIBRARIES} ${gwengui-cpp_LIBRARIES} ${AQBANKING_LIBRARIES} ${LIBALKIMIA_LIBRARIES} ) ########### install files ############### install(FILES kmm_kbanking.rc DESTINATION ${DATA_INSTALL_DIR}/kmm_kbanking) install(TARGETS kmm_kbanking DESTINATION ${PLUGIN_INSTALL_DIR}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/kmm_kbanking.desktop DESTINATION ${SERVICES_INSTALL_DIR}) install(FILES kbanking.kcfg DESTINATION ${KCFG_INSTALL_DIR}) diff --git a/kmymoney/plugins/kbanking/banking.cpp b/kmymoney/plugins/kbanking/banking.cpp index 5f0fe3757..1f2647740 100644 --- a/kmymoney/plugins/kbanking/banking.cpp +++ b/kmymoney/plugins/kbanking/banking.cpp @@ -1,466 +1,476 @@ -/*************************************************************************** - begin : Mon Mar 01 2004 - copyright : (C) 2004 by Martin Preuss - email : martin@libchipcard.de - - *************************************************************************** - * * - * 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. * - * * - ***************************************************************************/ - +/* + * Copyright 2004 Martin Preuss + * Copyright 2004-2019 Thomas Baumgart + * + * 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 . + */ #ifdef HAVE_CONFIG_H # include #endif #include "banking.hpp" #include #include #include #include #include AB_Banking::AB_Banking(const char *appname, const char *fname) { assert(appname); _banking = AB_Banking_new(appname, fname, 0); } +void AB_Banking::registerFinTs(const char* regKey, const char* version) const +{ +#ifdef ENABLE_FINTS_REGISTRATION + AB_Banking_RuntimeConfig_SetCharValue(_banking, "fintsRegistrationKey", regKey); + AB_Banking_RuntimeConfig_SetCharValue(_banking, "fintsApplicationVersionString", version); +#endif +} AB_Banking::~AB_Banking() { DBG_NOTICE(AQBANKING_LOGDOMAIN, "~AB_Banking: Freeing AB_Banking"); AB_Banking_free(_banking); } int AB_Banking::init() { return AB_Banking_Init(_banking); } int AB_Banking::fini() { return AB_Banking_Fini(_banking); } int AB_Banking::onlineInit() { return AB_Banking_OnlineInit(_banking); } int AB_Banking::onlineFini() { return AB_Banking_OnlineFini(_banking); } const char *AB_Banking::getAppName() { return AB_Banking_GetAppName(_banking); } std::list AB_Banking::getAccounts() { AB_ACCOUNT_LIST2 *ll; std::list rl; ll = AB_Banking_GetAccounts(_banking); if (ll) { AB_ACCOUNT *a; AB_ACCOUNT_LIST2_ITERATOR *it; it = AB_Account_List2_First(ll); assert(it); a = AB_Account_List2Iterator_Data(it); assert(a); while (a) { rl.push_back(a); a = AB_Account_List2Iterator_Next(it); } AB_Account_List2Iterator_free(it); AB_Account_List2_free(ll); } return rl; } AB_ACCOUNT *AB_Banking::getAccount(uint32_t uniqueId) { return AB_Banking_GetAccount(_banking, uniqueId); } std::list AB_Banking::getUsers() { AB_USER_LIST2 *ll; std::list rl; ll = AB_Banking_GetUsers(_banking); if (ll) { AB_USER *a; AB_USER_LIST2_ITERATOR *it; it = AB_User_List2_First(ll); assert(it); a = AB_User_List2Iterator_Data(it); assert(a); while (a) { rl.push_back(a); a = AB_User_List2Iterator_Next(it); } AB_User_List2Iterator_free(it); AB_User_List2_free(ll); } return rl; } int AB_Banking::getUserDataDir(GWEN_BUFFER *buf) const { return AB_Banking_GetUserDataDir(_banking, buf); } int AB_Banking::getAppUserDataDir(GWEN_BUFFER *buf) const { return AB_Banking_GetAppUserDataDir(_banking, buf); } AB_BANKING *AB_Banking::getCInterface() { return _banking; } std::list AB_Banking::getActiveProviders() { const GWEN_STRINGLIST *sl; std::list l; sl = AB_Banking_GetActiveProviders(_banking); if (sl) { GWEN_STRINGLISTENTRY *se; se = GWEN_StringList_FirstEntry(sl); assert(se); while (se) { const char *p; p = GWEN_StringListEntry_Data(se); assert(p); l.push_back(p); se = GWEN_StringListEntry_Next(se); } /* while */ } return l; } AB_PROVIDER *AB_Banking::getProvider(const char *name) { return AB_Banking_GetProvider(_banking, name); } bool AB_Banking::importContext(AB_IMEXPORTER_CONTEXT *ctx, uint32_t flags) { AB_IMEXPORTER_ACCOUNTINFO *ai; ai = AB_ImExporterContext_GetFirstAccountInfo(ctx); while (ai) { if (!importAccountInfo(ai, flags)) return false; ai = AB_ImExporterContext_GetNextAccountInfo(ctx); } return true; } bool AB_Banking::importAccountInfo(AB_IMEXPORTER_ACCOUNTINFO*, uint32_t) { return false; } int AB_Banking::executeJobs(AB_JOB_LIST2 *jl, AB_IMEXPORTER_CONTEXT *ctx) { return AB_Banking_ExecuteJobs(_banking, jl, ctx); } int AB_Banking::loadSharedConfig(const char *name, GWEN_DB_NODE **pDb) { return AB_Banking_LoadSharedConfig(_banking, name, pDb); } int AB_Banking::saveSharedConfig(const char *name, GWEN_DB_NODE *db) { return AB_Banking_SaveSharedConfig(_banking, name, db); } int AB_Banking::lockSharedConfig(const char *name) { return AB_Banking_LockSharedConfig(_banking, name); } int AB_Banking::unlockSharedConfig(const char *name) { return AB_Banking_UnlockSharedConfig(_banking, name); } int AB_Banking::loadSharedSubConfig(const char *name, const char *subGroup, GWEN_DB_NODE **pDb) { GWEN_DB_NODE *dbShared = NULL; int rv; rv = loadSharedConfig(name, &dbShared); if (rv < 0) { DBG_ERROR(0, "Unable to load config (%d)", rv); GWEN_DB_Group_free(dbShared); return rv; } else { GWEN_DB_NODE *dbSrc; dbSrc = GWEN_DB_GetGroup(dbShared, GWEN_PATH_FLAGS_NAMEMUSTEXIST, subGroup); if (dbSrc) { *pDb = GWEN_DB_Group_dup(dbSrc); } else { *pDb = GWEN_DB_Group_new("config"); } GWEN_DB_Group_free(dbShared); return 0; } } int AB_Banking::saveSharedSubConfig(const char *name, const char *subGroup, GWEN_DB_NODE *dbSrc) { GWEN_DB_NODE *dbShared = NULL; int rv; rv = lockSharedConfig(name); if (rv < 0) { DBG_ERROR(0, "Unable to lock config"); return rv; } else { rv = loadSharedConfig(name, &dbShared); if (rv < 0) { DBG_ERROR(0, "Unable to load config (%d)", rv); unlockSharedConfig(name); return rv; } else { GWEN_DB_NODE *dbDst; dbDst = GWEN_DB_GetGroup(dbShared, GWEN_DB_FLAGS_OVERWRITE_GROUPS, subGroup); assert(dbDst); if (dbSrc) GWEN_DB_AddGroupChildren(dbDst, dbSrc); rv = saveSharedConfig(name, dbShared); if (rv < 0) { DBG_ERROR(0, "Unable to store config (%d)", rv); unlockSharedConfig(name); GWEN_DB_Group_free(dbShared); return rv; } GWEN_DB_Group_free(dbShared); } rv = unlockSharedConfig(name); if (rv < 0) { DBG_ERROR(0, "Unable to unlock config (%d)", rv); return rv; } } return 0; } int AB_Banking::loadAppConfig(GWEN_DB_NODE **pDb) { return AB_Banking_LoadAppConfig(_banking, pDb); } int AB_Banking::saveAppConfig(GWEN_DB_NODE *db) { return AB_Banking_SaveAppConfig(_banking, db); } int AB_Banking::lockAppConfig() { return AB_Banking_LockAppConfig(_banking); } int AB_Banking::unlockAppConfig() { return AB_Banking_UnlockAppConfig(_banking); } int AB_Banking::loadAppSubConfig(const char *subGroup, GWEN_DB_NODE **pDb) { GWEN_DB_NODE *dbApp = NULL; int rv; rv = loadAppConfig(&dbApp); if (rv < 0) { DBG_ERROR(0, "Unable to load config (%d)", rv); GWEN_DB_Group_free(dbApp); return rv; } else { GWEN_DB_NODE *dbSrc; dbSrc = GWEN_DB_GetGroup(dbApp, GWEN_PATH_FLAGS_NAMEMUSTEXIST, subGroup); if (dbSrc) { *pDb = GWEN_DB_Group_dup(dbSrc); } else { *pDb = GWEN_DB_Group_new("config"); } GWEN_DB_Group_free(dbApp); return 0; } } int AB_Banking::saveAppSubConfig(const char *subGroup, GWEN_DB_NODE *dbSrc) { GWEN_DB_NODE *dbApp = NULL; int rv; rv = lockAppConfig(); if (rv < 0) { DBG_ERROR(0, "Unable to lock config"); return rv; } else { rv = loadAppConfig(&dbApp); if (rv < 0) { DBG_ERROR(0, "Unable to load config (%d)", rv); unlockAppConfig(); return rv; } else { GWEN_DB_NODE *dbDst; dbDst = GWEN_DB_GetGroup(dbApp, GWEN_DB_FLAGS_OVERWRITE_GROUPS, subGroup); assert(dbDst); if (dbSrc) GWEN_DB_AddGroupChildren(dbDst, dbSrc); rv = saveAppConfig(dbApp); if (rv < 0) { DBG_ERROR(0, "Unable to store config (%d)", rv); unlockAppConfig(); GWEN_DB_Group_free(dbApp); return rv; } GWEN_DB_Group_free(dbApp); } rv = unlockAppConfig(); if (rv < 0) { DBG_ERROR(0, "Unable to unlock config (%d)", rv); return rv; } } return 0; } int AB_Banking::beginExclUseAccount(AB_ACCOUNT *a) { return AB_Banking_BeginExclUseAccount(_banking, a); } int AB_Banking::endExclUseAccount(AB_ACCOUNT *a, int abandon) { return AB_Banking_EndExclUseAccount(_banking, a, abandon); } int AB_Banking::beginExclUseUser(AB_USER *u) { return AB_Banking_BeginExclUseUser(_banking, u); } int AB_Banking::endExclUseUser(AB_USER *u, int abandon) { return AB_Banking_EndExclUseUser(_banking, u, abandon); } void AB_Banking::setAccountAlias(AB_ACCOUNT *a, const char *alias) { AB_Banking_SetAccountAlias(_banking, a, alias); } diff --git a/kmymoney/plugins/kbanking/banking.hpp b/kmymoney/plugins/kbanking/banking.hpp index 58de6bfb6..b559f12f8 100644 --- a/kmymoney/plugins/kbanking/banking.hpp +++ b/kmymoney/plugins/kbanking/banking.hpp @@ -1,185 +1,197 @@ -/*************************************************************************** - begin : Mon Mar 01 2004 - copyright : (C) 2004 by Martin Preuss - email : martin@libchipcard.de - - *************************************************************************** - * This file is part of the project "AqBanking". * - * Please see toplevel file COPYING of that project for license details. * - ***************************************************************************/ +/* + * Copyright 2004 Martin Preuss + * Copyright 2004-2019 Thomas Baumgart + * + * 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 . + */ /** @file * @short A C++ wrapper of the main aqbanking interface */ #ifndef AQ_BANKING_CPP_H #define AQ_BANKING_CPP_H #include #include #include #include /** * @brief A C++ binding for the C module @ref AB_BANKING * * This class simply is a C++ binding for the C module @ref AB_BANKING. * It redirects C callbacks used by AB_BANKING to virtual functions in * this class. It als transforms some return values inconveniant for * C++ into STL objects (such as "list"). * * @ingroup G_AB_CPP_INTERFACE * * @author Martin Preuss */ class AB_Banking { private: AB_BANKING *_banking; public: AB_Banking(const char *appname, const char *fname); virtual ~AB_Banking(); AB_BANKING *getCInterface(); /** * See @ref AB_Banking_Init */ virtual int init(); /** * See @ref AB_Banking_Fini */ virtual int fini(); /** * See @ref AB_Banking_OnlineInit */ int onlineInit(); /** * See @ref AB_Banking_OnlineFini */ int onlineFini(); /** * Loads a backend with the given name. You can use * @ref AB_Banking_GetProviderDescrs to retrieve a list of available * backends. Such a backend can then be asked to return an account list. */ AB_PROVIDER *getProvider(const char *name); /** * Returns the application name as given to @ref AB_Banking_new. */ const char *getAppName(); /** * Returns a list of pointers to currently known accounts. * Please note that the pointers in this list are still owned by * AqBanking, so you MUST NOT free them. * However, destroying the list will not free the accounts, so it is * safe to do that. */ std::list getAccounts(); /** * This function does an account lookup based on the given unique id. * This id is assigned by AqBanking when an account is created. * The pointer returned is still owned by AqBanking, so you MUST NOT free * it. */ AB_ACCOUNT *getAccount(uint32_t uniqueId); /** * Returns a list of pointers to currently known users. * Please note that the pointers in this list are still owned by * AqBanking, so you MUST NOT free them. * However, destroying the list will not free the users, so it is * safe to do that. */ std::list getUsers(); int getUserDataDir(GWEN_BUFFER *buf) const ; int getAppUserDataDir(GWEN_BUFFER *buf) const ; int loadAppConfig(GWEN_DB_NODE **pDb); int saveAppConfig(GWEN_DB_NODE *db); int lockAppConfig(); int unlockAppConfig(); int loadAppSubConfig(const char *subGroup, - GWEN_DB_NODE **pDb); + GWEN_DB_NODE **pDb); int saveAppSubConfig(const char *subGroup, - GWEN_DB_NODE *dbSrc); + GWEN_DB_NODE *dbSrc); int loadSharedConfig(const char *name, GWEN_DB_NODE **pDb); int saveSharedConfig(const char *name, GWEN_DB_NODE *db); int lockSharedConfig(const char *name); int unlockSharedConfig(const char *name); int loadSharedSubConfig(const char *name, - const char *subGroup, - GWEN_DB_NODE **pDb); + const char *subGroup, + GWEN_DB_NODE **pDb); int saveSharedSubConfig(const char *name, - const char *subGroup, - GWEN_DB_NODE *dbSrc); + const char *subGroup, + GWEN_DB_NODE *dbSrc); int beginExclUseAccount(AB_ACCOUNT *a); int endExclUseAccount(AB_ACCOUNT *a, int abandon); int beginExclUseUser(AB_USER *u); int endExclUseUser(AB_USER *u, int abandon); std::list getActiveProviders(); void setAccountAlias(AB_ACCOUNT *a, const char *alias); + /** + * Provide interface to setup ZKA FinTS registration + */ + void registerFinTs(const char* regKey, const char* version) const; /** @name Enqueueing, Dequeueing and Executing Jobs * * Enqueued jobs are preserved across shutdowns. As soon as a job has been * sent to the appropriate backend it will be removed from the queue. * Only those jobs are saved/reloaded which have been enqueued but never * presented to the backend. This means after calling * @ref AB_Banking_ExecuteQueue only those jobs are still in the queue which * have not been processed (e.g. because they belonged to a second backend * but the user aborted while the jobs for a first backend were in process). */ /*@{*/ /** * This function sends all jobs in the list to their corresponding backends * and allows that backend to process it. */ virtual int executeJobs(AB_JOB_LIST2 *jl, - AB_IMEXPORTER_CONTEXT *ctx); + AB_IMEXPORTER_CONTEXT *ctx); /*@}*/ /** * Let the application import a given statement context. */ virtual bool importContext(AB_IMEXPORTER_CONTEXT *ctx, uint32_t flags); virtual bool importAccountInfo(AB_IMEXPORTER_ACCOUNTINFO *ai, uint32_t flags); }; #endif /* AQ_BANKING_CPP_H */ diff --git a/kmymoney/plugins/kbanking/mymoneybanking.cpp b/kmymoney/plugins/kbanking/mymoneybanking.cpp index a64eaf610..5ef9417ca 100644 --- a/kmymoney/plugins/kbanking/mymoneybanking.cpp +++ b/kmymoney/plugins/kbanking/mymoneybanking.cpp @@ -1,1465 +1,1478 @@ /*************************************************************************** * Copyright 2004 Martin Preuss aquamaniac@users.sourceforge.net * * Copyright 2009 Cristian Onet onet.cristian@gmail.com * * Copyright 2010 Thomas Baumgart ipwizard@users.sourceforge.net * * Copyright 2015 Christian David christian-david@web.de * * * * 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) version 3 or any later version * * accepted by the membership of KDE e.V. (or its successor approved * * by the membership of KDE e.V.), which shall act as a proxy * * defined in Section 14 of version 3 of the license. * * * * 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 * ***************************************************************************/ #ifdef HAVE_CONFIG_H # include #endif #include "mymoneybanking.h" // ---------------------------------------------------------------------------- // QT Includes #include #include #include #include #include #include #include #include //! @todo remove @c #include // ---------------------------------------------------------------------------- // KDE Includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // ---------------------------------------------------------------------------- // Library Includes #include #include #include #include #include #include #include #include #include #include #include #include // ---------------------------------------------------------------------------- // Project Includes +#include "config-kmymoney-version.h" #include "mymoney/onlinejob.h" #include "kbaccountsettings.h" #include "kbmapaccount.h" #include "mymoneyfile.h" #include "onlinejobadministration.h" #include "kmymoneyview.h" #include "kbpickstartdate.h" #include "gwenkdegui.h" #include "gwenhywfarqtoperators.h" #include "aqbankingkmmoperators.h" K_PLUGIN_FACTORY(KBankingFactory, registerPlugin();) K_EXPORT_PLUGIN(KBankingFactory("kmm_kbanking")) class KBankingPlugin::Private { public: Private() : passwordCacheTimer(0), jobList(), fileId() { QString gwenProxy = QString::fromLocal8Bit(qgetenv("GWEN_PROXY")); if (gwenProxy.isEmpty()) { QScopedPointer cfg(new KConfig("kioslaverc")); QRegExp exp("(\\w+://)?([^/]{2}.+:\\d+)"); QString proxy; KConfigGroup grp = cfg->group("Proxy Settings"); int type = grp.readEntry("ProxyType", 0); switch (type) { case 0: // no proxy break; case 1: // manual specified proxy = grp.readEntry("httpsProxy"); qDebug("KDE https proxy setting is '%s'", qPrintable(proxy)); if (exp.exactMatch(proxy)) { proxy = exp.cap(2); qDebug("Setting GWEN_PROXY to '%s'", qPrintable(proxy)); if (setenv("GWEN_PROXY", qPrintable(proxy), 1) == -1) { qDebug("Unable to setup GWEN_PROXY"); } } break; default: // other currently not supported qDebug("KDE proxy setting of type %d not supported", type); break; } } } /** * KMyMoney asks for accounts over and over again which causes a lot of "Job not supported with this account" error messages. * This function filters messages with that string. */ static int gwenLogHook(GWEN_GUI* gui, const char* domain, GWEN_LOGGER_LEVEL level, const char* message) { Q_UNUSED(gui); Q_UNUSED(domain); Q_UNUSED(level); const char* messageToFilter = "Job not supported with this account"; if (strstr(message, messageToFilter) != 0) return 1; return 0; } QTimer *passwordCacheTimer; QMap jobList; QString fileId; }; KBankingPlugin::KBankingPlugin(QObject *parent, const QVariantList&) : KMyMoneyPlugin::OnlinePluginExtended(parent, "KBanking"/*must be the same as X-KDE-PluginInfo-Name*/), d(new Private), m_configAction(0), m_importAction(0), // m_kbanking(), set below m_protocolConversionMap(), m_accountSettings(0), m_onlineJobQueue() { m_kbanking = new KMyMoneyBanking(this, "KMyMoney"); d->passwordCacheTimer = new QTimer(this); d->passwordCacheTimer->setSingleShot(true); d->passwordCacheTimer->setInterval(60000); connect(d->passwordCacheTimer, SIGNAL(timeout()), this, SLOT(slotClearPasswordCache())); if (m_kbanking) { if (AB_Banking_HasConf4(m_kbanking->getCInterface())) { qDebug("KBankingPlugin: No AqB4 config found."); if (AB_Banking_HasConf3(m_kbanking->getCInterface())) { qDebug("KBankingPlugin: No AqB3 config found."); if (!AB_Banking_HasConf2(m_kbanking->getCInterface())) { qDebug("KBankingPlugin: AqB2 config found - converting."); AB_Banking_ImportConf2(m_kbanking->getCInterface()); } } else { qDebug("KBankingPlugin: AqB3 config found - converting."); AB_Banking_ImportConf3(m_kbanking->getCInterface()); } } //! @todo when is gwenKdeGui deleted? gwenKdeGui *gui = new gwenKdeGui(); GWEN_Gui_SetGui(gui->getCInterface()); GWEN_Logger_SetLevel(0, GWEN_LoggerLevel_Warning); if (m_kbanking->init() == 0) { // Tell the host application to load my GUI component setComponentData(KBankingFactory::componentData()); setXMLFile("kmm_kbanking.rc"); qDebug("KMyMoney kbanking plugin loaded"); // get certificate handling and dialog settings management AB_Gui_Extend(gui->getCInterface(), m_kbanking->getCInterface()); // create actions createActions(); // load protocol conversion list loadProtocolConversion(); GWEN_Logger_SetLevel(AQBANKING_LOGDOMAIN, GWEN_LoggerLevel_Warning); GWEN_Gui_SetLogHookFn(GWEN_Gui_GetGui(), &KBankingPlugin::Private::gwenLogHook); } else { qWarning("Could not initialize KBanking online banking interface"); delete m_kbanking; m_kbanking = 0; } } } KBankingPlugin::~KBankingPlugin() { if (m_kbanking) { m_kbanking->fini(); delete m_kbanking; } delete d; } void KBankingPlugin::loadProtocolConversion() { if (m_kbanking) { m_protocolConversionMap.clear(); m_protocolConversionMap["aqhbci"] = "HBCI"; m_protocolConversionMap["aqofxconnect"] = "OFX"; m_protocolConversionMap["aqyellownet"] = "YellowNet"; m_protocolConversionMap["aqgeldkarte"] = "Geldkarte"; m_protocolConversionMap["aqdtaus"] = "DTAUS"; } } void KBankingPlugin::protocols(QStringList& protocolList) const { if (m_kbanking) { std::list list = m_kbanking->getActiveProviders(); std::list::iterator it; for (it = list.begin(); it != list.end(); ++it) { // skip the dummy if (*it == "aqnone") continue; QMap::const_iterator it_m; it_m = m_protocolConversionMap.find((*it).c_str()); if (it_m != m_protocolConversionMap.end()) protocolList << (*it_m); else protocolList << (*it).c_str(); } } } QWidget* KBankingPlugin::accountConfigTab(const MyMoneyAccount& acc, QString& name) { const MyMoneyKeyValueContainer& kvp = acc.onlineBankingSettings(); name = i18n("Online settings"); if (m_kbanking) { m_accountSettings = new KBAccountSettings(acc, 0); m_accountSettings->loadUi(kvp); return m_accountSettings; } QLabel* label = new QLabel(i18n("KBanking module not correctly initialized"), 0); label->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter); return label; } MyMoneyKeyValueContainer KBankingPlugin::onlineBankingSettings(const MyMoneyKeyValueContainer& current) { MyMoneyKeyValueContainer kvp(current); kvp["provider"] = objectName(); if (m_accountSettings) { m_accountSettings->loadKvp(kvp); } return kvp; } void KBankingPlugin::createActions() { KAction *settings_aqbanking = actionCollection()->addAction("settings_aqbanking"); settings_aqbanking->setText(i18n("Configure Aq&Banking...")); connect(settings_aqbanking, SIGNAL(triggered()), this, SLOT(slotSettings())); KAction *file_import_aqbanking = actionCollection()->addAction("file_import_aqbanking"); file_import_aqbanking->setText(i18n("AqBanking importer...")); connect(file_import_aqbanking, SIGNAL(triggered()), this, SLOT(slotImport())); connect(viewInterface(), SIGNAL(viewStateChanged(bool)), action("file_import_aqbanking"), SLOT(setEnabled(bool))); } void KBankingPlugin::slotSettings() { if (m_kbanking) { GWEN_DIALOG* dlg = AB_SetupDialog_new(m_kbanking->getCInterface()); if (dlg == NULL) { DBG_ERROR(0, "Could not create setup dialog."); return; } if (GWEN_Gui_ExecDialog(dlg, 0) == 0) { DBG_ERROR(0, "Aborted by user"); GWEN_Dialog_free(dlg); return; } GWEN_Dialog_free(dlg); } } bool KBankingPlugin::mapAccount(const MyMoneyAccount& acc, MyMoneyKeyValueContainer& settings) { bool rc = false; if (m_kbanking && !acc.id().isEmpty()) { m_kbanking->askMapAccount(acc); // at this point, the account should be mapped // so we search it and setup the account reference in the KMyMoney object AB_ACCOUNT* ab_acc; ab_acc = aqbAccount(acc); if (ab_acc) { MyMoneyAccount a(acc); setupAccountReference(a, ab_acc); settings = a.onlineBankingSettings(); rc = true; } } return rc; } AB_ACCOUNT* KBankingPlugin::aqbAccount(const MyMoneyAccount& acc) const { if (m_kbanking == 0) { return 0; } // certainly looking for an expense or income account does not make sense at this point // so we better get out right away if (acc.isIncomeExpense()) { return 0; } AB_ACCOUNT *ab_acc = AB_Banking_GetAccountByAlias(m_kbanking->getCInterface(), m_kbanking->mappingId(acc).toUtf8().data()); // if the account is not found, we temporarily scan for the 'old' mapping (the one w/o the file id) // in case we find it, we setup the new mapping in addition on the fly. if (!ab_acc && acc.isAssetLiability()) { ab_acc = AB_Banking_GetAccountByAlias(m_kbanking->getCInterface(), acc.id().toUtf8().data()); if (ab_acc) { qDebug("Found old mapping for '%s' but not new. Setup new mapping", qPrintable(acc.name())); m_kbanking->setAccountAlias(ab_acc, m_kbanking->mappingId(acc).toUtf8().constData()); // TODO at some point in time, we should remove the old mapping } } return ab_acc; } AB_ACCOUNT* KBankingPlugin::aqbAccount(const QString& accountId) const { MyMoneyAccount account = MyMoneyFile::instance()->account(accountId); return aqbAccount(account); } QString KBankingPlugin::stripLeadingZeroes(const QString& s) const { QString rc(s); QRegExp exp("^(0*)([^0].*)"); if (exp.exactMatch(s)) { rc = exp.cap(2); } return rc; } void KBankingPlugin::setupAccountReference(const MyMoneyAccount& acc, AB_ACCOUNT* ab_acc) { MyMoneyKeyValueContainer kvp; if (ab_acc) { QString accountNumber = stripLeadingZeroes(AB_Account_GetAccountNumber(ab_acc)); QString routingNumber = stripLeadingZeroes(AB_Account_GetBankCode(ab_acc)); QString val = QString("%1-%2").arg(routingNumber, accountNumber); if (val != acc.onlineBankingSettings().value("kbanking-acc-ref")) { MyMoneyKeyValueContainer kvp; // make sure to keep our own previous settings const QMap& vals = acc.onlineBankingSettings().pairs(); QMap::const_iterator it_p; for (it_p = vals.begin(); it_p != vals.end(); ++it_p) { if (QString(it_p.key()).startsWith("kbanking-")) { kvp.setValue(it_p.key(), *it_p); } } kvp.setValue("kbanking-acc-ref", val); kvp.setValue("provider", objectName()); setAccountOnlineParameters(acc, kvp); } } else { // clear the connection setAccountOnlineParameters(acc, kvp); } } bool KBankingPlugin::accountIsMapped(const MyMoneyAccount& acc) { return aqbAccount(acc) != 0; } bool KBankingPlugin::updateAccount(const MyMoneyAccount& acc) { return updateAccount(acc, false); } bool KBankingPlugin::updateAccount(const MyMoneyAccount& acc, bool moreAccounts) { if (!m_kbanking) return false; bool rc = false; if (!acc.id().isEmpty()) { AB_JOB *job = 0; int rv; /* get AqBanking account */ AB_ACCOUNT *ba = aqbAccount(acc); // Update the connection between the KMyMoney account and the AqBanking equivalent. // If the account is not found anymore ba == 0 and the connection is removed. setupAccountReference(acc, ba); if (!ba) { KMessageBox::error(0, i18n("" "The given application account %1 " "has not been mapped to an online " "account." "", acc.name()), i18n("Account Not Mapped")); } else { bool enqueJob = true; if (acc.onlineBankingSettings().value("kbanking-txn-download") != "no") { /* create getTransactions job */ job = AB_JobGetTransactions_new(ba); rv = AB_Job_CheckAvailability(job); if (rv) { DBG_ERROR(0, "Job \"GetTransactions\" is not available (%d)", rv); KMessageBox::error(0, i18n("" "The update job is not supported by the " "bank/account/backend.\n" ""), i18n("Job not Available")); AB_Job_free(job); job = 0; } if (job) { int days = AB_JobGetTransactions_GetMaxStoreDays(job); QDate qd; if (days > 0) { GWEN_TIME *ti1; GWEN_TIME *ti2; ti1 = GWEN_CurrentTime(); ti2 = GWEN_Time_fromSeconds(GWEN_Time_Seconds(ti1) - (60 * 60 * 24 * days)); GWEN_Time_free(ti1); ti1 = ti2; int year, month, day; if (GWEN_Time_GetBrokenDownDate(ti1, &day, &month, &year)) { DBG_ERROR(0, "Bad date"); qd = QDate(); } else qd = QDate(year, month + 1, day); GWEN_Time_free(ti1); } // get last statement request date from application account object // and start from a few days before if the date is valid QDate lastUpdate = QDate::fromString(acc.value("lastImportedTransactionDate"), Qt::ISODate); if (lastUpdate.isValid()) lastUpdate = lastUpdate.addDays(-3); int dateOption = acc.onlineBankingSettings().value("kbanking-statementDate").toInt(); switch (dateOption) { case 0: // Ask user break; case 1: // No date qd = QDate(); break; case 2: // Last download qd = lastUpdate; break; case 3: // First possible // qd is already setup break; } // the pick start date option dialog is needed in // case the dateOption is 0 or the date option is > 1 // and the qd is invalid if (dateOption == 0 || (dateOption > 1 && !qd.isValid())) { QPointer psd = new KBPickStartDate(m_kbanking, qd, lastUpdate, acc.name(), lastUpdate.isValid() ? 2 : 3, 0, true); if (psd->exec() == QDialog::Accepted) { qd = psd->date(); } else { enqueJob = false; } delete psd; } if (enqueJob) { if (qd.isValid()) { GWEN_TIME *ti1; ti1 = GWEN_Time_new(qd.year(), qd.month() - 1, qd.day(), 0, 0, 0, 0); AB_JobGetTransactions_SetFromTime(job, ti1); GWEN_Time_free(ti1); } rv = m_kbanking->enqueueJob(job); if (rv) { DBG_ERROR(0, "Error %d", rv); KMessageBox::error(0, i18n("" "Could not enqueue the job.\n" ""), i18n("Error")); } } AB_Job_free(job); } } if (enqueJob) { /* create getBalance job */ job = AB_JobGetBalance_new(ba); rv = AB_Job_CheckAvailability(job); if (!rv) rv = m_kbanking->enqueueJob(job); else rv = 0; AB_Job_free(job); if (rv) { DBG_ERROR(0, "Error %d", rv); KMessageBox::error(0, i18n("" "Could not enqueue the job.\n" ""), i18n("Error")); } else { rc = true; emit queueChanged(); } } } } // make sure we have at least one job in the queue before sending it if (!moreAccounts && m_kbanking->getEnqueuedJobs().size() > 0) executeQueue(); return rc; } void KBankingPlugin::executeQueue() { if (m_kbanking && m_kbanking->getEnqueuedJobs().size() > 0) { AB_IMEXPORTER_CONTEXT *ctx; ctx = AB_ImExporterContext_new(); int rv = m_kbanking->executeQueue(ctx); if (!rv) { m_kbanking->importContext(ctx, 0); } else { DBG_ERROR(0, "Error: %d", rv); } AB_ImExporterContext_free(ctx); } } /** @todo improve error handling, e.g. by adding a .isValid to nationalTransfer * @todo use new onlineJob system */ void KBankingPlugin::sendOnlineJob(QList& jobs) { Q_CHECK_PTR(m_kbanking); m_onlineJobQueue.clear(); QList unhandledJobs; if (!jobs.isEmpty()) { foreach (onlineJob job, jobs) { if (sepaOnlineTransfer::name() == job.task()->taskName()) { onlineJobTyped typedJob(job); enqueTransaction(typedJob); job = typedJob; } else { job.addJobMessage(onlineJobMessage(onlineJobMessage::error, "KBanking", "Cannot handle this request")); unhandledJobs.append(job); } m_onlineJobQueue.insert(m_kbanking->mappingId(job), job); } executeQueue(); } jobs = m_onlineJobQueue.values() + unhandledJobs; m_onlineJobQueue.clear(); } QStringList KBankingPlugin::availableJobs(QString accountId) { try { MyMoneyAccount acc = MyMoneyFile::instance()->account(accountId); QString id = MyMoneyFile::instance()->value("kmm-id"); if(id != d->fileId) { d->jobList.clear(); d->fileId = id; } } catch (const MyMoneyException&) { // Exception usually means account was not found return QStringList(); } if(d->jobList.contains(accountId)) { return d->jobList[accountId]; } QStringList list; AB_ACCOUNT* abAccount = aqbAccount(accountId); if (!abAccount) { return list; } // Check availableJobs // sepa transfer AB_JOB* abJob = AB_JobSepaTransfer_new(abAccount); if (AB_Job_CheckAvailability(abJob) == 0) list.append(sepaOnlineTransfer::name()); AB_Job_free(abJob); d->jobList[accountId] = list; return list; } /** @brief experimenting with QScopedPointer and aqBanking pointers */ class QScopedPointerAbJobDeleter { public: static void cleanup(AB_JOB* job) { AB_Job_free(job); } }; /** @brief experimenting with QScopedPointer and aqBanking pointers */ class QScopedPointerAbAccountDeleter { public: static void cleanup(AB_ACCOUNT* account) { AB_Account_free(account); } }; IonlineTaskSettings::ptr KBankingPlugin::settings(QString accountId, QString taskName) { AB_ACCOUNT* abAcc = aqbAccount(accountId); if (abAcc == 0) return IonlineTaskSettings::ptr(); if (sepaOnlineTransfer::name() == taskName) { // Get limits for sepaonlinetransfer QScopedPointer abJob(AB_JobSepaTransfer_new(abAcc)); if (AB_Job_CheckAvailability(abJob.data()) != 0) return IonlineTaskSettings::ptr(); const AB_TRANSACTION_LIMITS* limits = AB_Job_GetFieldLimits(abJob.data()); return AB_TransactionLimits_toSepaOnlineTaskSettings(limits).dynamicCast(); } return IonlineTaskSettings::ptr(); } bool KBankingPlugin::enqueTransaction(onlineJobTyped& job) { /* get AqBanking account */ const QString accId = job.constTask()->responsibleAccount(); AB_ACCOUNT *abAccount = aqbAccount(accId); if (!abAccount) { job.addJobMessage(onlineJobMessage(onlineJobMessage::warning, "KBanking", i18n("" "The given application account %1 " "has not been mapped to an online " "account." "", MyMoneyFile::instance()->account(accId).name()))); return false; } //setupAccountReference(acc, ba); // needed? AB_JOB *abJob = AB_JobSepaTransfer_new(abAccount); int rv = AB_Job_CheckAvailability(abJob); if (rv) { qDebug("AB_ERROR_OFFSET is %i", AB_ERROR_OFFSET); job.addJobMessage(onlineJobMessage(onlineJobMessage::error, "AqBanking", QString("Sepa credit transfers for account \"%1\" are not available, error code %2.").arg(MyMoneyFile::instance()->account(accId).name(), rv) ) ); return false; } AB_TRANSACTION *AbTransaction = AB_Transaction_new(); // Recipient payeeIdentifiers::ibanBic beneficiaryAcc = job.constTask()->beneficiaryTyped(); AB_Transaction_SetRemoteName(AbTransaction, GWEN_StringList_fromQString(beneficiaryAcc.ownerName())); AB_Transaction_SetRemoteIban(AbTransaction, beneficiaryAcc.electronicIban().toUtf8().constData()); AB_Transaction_SetRemoteBic(AbTransaction, beneficiaryAcc.fullStoredBic().toUtf8().constData()); // Origin Account AB_Transaction_SetLocalAccount(AbTransaction, abAccount); // Purpose QStringList qPurpose = job.constTask()->purpose().split('\n'); GWEN_STRINGLIST *purpose = GWEN_StringList_fromQStringList(qPurpose); AB_Transaction_SetPurpose(AbTransaction, purpose); GWEN_StringList_free(purpose); // Reference // AqBanking duplicates the string. This should be safe. AB_Transaction_SetEndToEndReference(AbTransaction, job.constTask()->endToEndReference().toUtf8().constData()); // Other Fields AB_Transaction_SetTextKey(AbTransaction, job.constTask()->textKey()); AB_Transaction_SetValue(AbTransaction, AB_Value_fromMyMoneyMoney(job.constTask()->value())); /** @todo LOW remove Debug info */ qDebug() << "SetTransaction: " << AB_Job_SetTransaction(abJob, AbTransaction); GWEN_DB_NODE *gwenNode = AB_Job_GetAppData(abJob); GWEN_DB_SetCharValue(gwenNode, GWEN_DB_FLAGS_DEFAULT, "kmmOnlineJobId", m_kbanking->mappingId(job).toLatin1().constData()); qDebug() << "Enqueue: " << m_kbanking->enqueueJob(abJob); //delete localAcc; return true; } void KBankingPlugin::startPasswordTimer() { if (d->passwordCacheTimer->isActive()) d->passwordCacheTimer->stop(); d->passwordCacheTimer->start(); } void KBankingPlugin::slotClearPasswordCache() { m_kbanking->clearPasswordCache(); } void KBankingPlugin::slotImport() { if (!m_kbanking->interactiveImport()) qWarning("Error on import dialog"); } bool KBankingPlugin::importStatement(const MyMoneyStatement& s) { return statementInterface()->import(s); } const MyMoneyAccount& KBankingPlugin::account(const QString& key, const QString& value) const { return statementInterface()->account(key, value); } void KBankingPlugin::setAccountOnlineParameters(const MyMoneyAccount& acc, const MyMoneyKeyValueContainer& kvps) const { return statementInterface()->setAccountOnlineParameters(acc, kvps); } KMyMoneyBanking::KMyMoneyBanking(KBankingPlugin* parent, const char* appname, const char* fname) : AB_Banking(appname, fname) , m_parent(parent) , _jobQueue(0) { m_sepaKeywords << QString("SEPA-BASISLASTSCHRIFT") << QString::fromUtf8("SEPA-ÜBERWEISUNG"); + + QStringList versions = QString(VERSION).split("."); + + QByteArray regkey; + const char *p = "\x08\x0f\x41\x0f\x58\x5b\x56\x4a\x09\x7b\x40\x0e\x5f\x2a\x56\x3f\x0e\x7f\x3f\x7d\x5b\x56\x56\x4b\x0a\x4d"; + const char* q = appname; + while (*p) { + regkey += (*q++ ^ *p++) & 0xff; + if (!*q) + q = appname; + } + registerFinTs(regkey.data(), versions[0].toLatin1()); } int KMyMoneyBanking::init() { int rv = AB_Banking::init(); if (rv < 0) return rv; rv = onlineInit(); if (rv) { fprintf(stderr, "Error on online init (%d).\n", rv); AB_Banking::fini(); return rv; } _jobQueue = AB_Job_List2_new(); return 0; } int KMyMoneyBanking::fini() { if (_jobQueue) { AB_Job_List2_FreeAll(_jobQueue); _jobQueue = 0; } const int rv = onlineFini(); if (rv) { AB_Banking::fini(); return rv; } return AB_Banking::fini(); } int KMyMoneyBanking::executeQueue(AB_IMEXPORTER_CONTEXT *ctx) { m_parent->startPasswordTimer(); int rv = AB_Banking::executeJobs(_jobQueue, ctx); if (rv != 0) { qDebug() << "Sending queue by aqbanking got error no " << rv; } /** check result of each job */ AB_JOB_LIST2_ITERATOR* jobIter = AB_Job_List2_First(_jobQueue); if (jobIter) { AB_JOB* abJob = AB_Job_List2Iterator_Data(jobIter); while (abJob) { GWEN_DB_NODE* gwenNode = AB_Job_GetAppData(abJob); if (gwenNode == 0) { qWarning("Executed AB_Job without KMyMoney id"); abJob = AB_Job_List2Iterator_Next(jobIter); break; } QString jobIdent = QString::fromUtf8(GWEN_DB_GetCharValue(gwenNode, "kmmOnlineJobId", 0, "")); onlineJob job = m_parent->m_onlineJobQueue.value(jobIdent); if (job.isNull()) { // It should not be possiblie that this will happen (only if AqBanking fails heavily). //! @todo correct exception text qWarning("Executed a job which was not in queue. Please inform the KMyMoney developers."); abJob = AB_Job_List2Iterator_Next(jobIter); continue; } AB_JOB_STATUS abStatus = AB_Job_GetStatus(abJob); if (abStatus == AB_Job_StatusSent || abStatus == AB_Job_StatusPending || abStatus == AB_Job_StatusFinished || abStatus == AB_Job_StatusError || abStatus == AB_Job_StatusUnknown) job.setJobSend(); if (abStatus == AB_Job_StatusFinished) job.setBankAnswer(onlineJob::acceptedByBank); else if (abStatus == AB_Job_StatusError || abStatus == AB_Job_StatusUnknown) job.setBankAnswer(onlineJob::sendingError); job.addJobMessage(onlineJobMessage(onlineJobMessage::debug, "KBanking", "Job was processed")); m_parent->m_onlineJobQueue.insert(jobIdent, job); abJob = AB_Job_List2Iterator_Next(jobIter); } AB_Job_List2Iterator_free(jobIter); } AB_JOB_LIST2 *oldQ = _jobQueue; _jobQueue = AB_Job_List2_new(); AB_Job_List2_FreeAll(oldQ); emit m_parent->queueChanged(); m_parent->startPasswordTimer(); return rv; } void KMyMoneyBanking::clearPasswordCache() { /* clear password DB */ GWEN_Gui_SetPasswordStatus(NULL, NULL, GWEN_Gui_PasswordStatus_Remove, 0); } std::list KMyMoneyBanking::getEnqueuedJobs() { AB_JOB_LIST2 *ll; std::list rl; ll = _jobQueue; if (ll && AB_Job_List2_GetSize(ll)) { AB_JOB *j; AB_JOB_LIST2_ITERATOR *it; it = AB_Job_List2_First(ll); assert(it); j = AB_Job_List2Iterator_Data(it); assert(j); while (j) { rl.push_back(j); j = AB_Job_List2Iterator_Next(it); } AB_Job_List2Iterator_free(it); } return rl; } int KMyMoneyBanking::enqueueJob(AB_JOB *j) { assert(_jobQueue); assert(j); AB_Job_Attach(j); AB_Job_List2_PushBack(_jobQueue, j); return 0; } int KMyMoneyBanking::dequeueJob(AB_JOB *j) { assert(_jobQueue); AB_Job_List2_Remove(_jobQueue, j); AB_Job_free(j); emit m_parent->queueChanged(); return 0; } void KMyMoneyBanking::transfer() { //m_parent->transfer(); } bool KMyMoneyBanking::askMapAccount(const MyMoneyAccount& acc) { MyMoneyFile* file = MyMoneyFile::instance(); QString bankId; QString accountId; // extract some information about the bank. if we have a sortcode // (BLZ) we display it, otherwise the name is enough. try { const MyMoneyInstitution &bank = file->institution(acc.institutionId()); bankId = bank.name(); if (!bank.sortcode().isEmpty()) bankId = bank.sortcode(); } catch (const MyMoneyException &e) { // no bank assigned, we just leave the field emtpy } // extract account information. if we have an account number // we show it, otherwise the name will be displayed accountId = acc.number(); if (accountId.isEmpty()) accountId = acc.name(); // do the mapping. the return value of this method is either // true, when the user mapped the account or false, if he // decided to quit the dialog. So not really a great thing // to present some more information. KBMapAccount *w; w = new KBMapAccount(this, bankId.toUtf8().constData(), accountId.toUtf8().constData()); if (w->exec() == QDialog::Accepted) { AB_ACCOUNT *a; a = w->getAccount(); assert(a); DBG_NOTICE(0, "Mapping application account \"%s\" to " "online account \"%s/%s\"", qPrintable(acc.name()), AB_Account_GetBankCode(a), AB_Account_GetAccountNumber(a)); // TODO remove the following line once we don't need backward compatibility setAccountAlias(a, acc.id().toUtf8().constData()); qDebug("Setup mapping to '%s'", acc.id().toUtf8().constData()); setAccountAlias(a, mappingId(acc).toUtf8().constData()); qDebug("Setup mapping to '%s'", mappingId(acc).toUtf8().constData()); delete w; return true; } delete w; return false; } QString KMyMoneyBanking::mappingId(const MyMoneyObject& object) const { QString id = MyMoneyFile::instance()->storageId() + QLatin1Char('-') + object.id(); // AqBanking does not handle the enclosing parens, so we remove it id.remove('{'); id.remove('}'); return id; } bool KMyMoneyBanking::interactiveImport() { AB_IMEXPORTER_CONTEXT *ctx; GWEN_DIALOG *dlg; int rv; ctx = AB_ImExporterContext_new(); dlg = AB_ImporterDialog_new(getCInterface(), ctx, NULL); if (dlg == NULL) { DBG_ERROR(0, "Could not create importer dialog."); AB_ImExporterContext_free(ctx); return false; } rv = GWEN_Gui_ExecDialog(dlg, 0); if (rv == 0) { DBG_ERROR(0, "Aborted by user"); GWEN_Dialog_free(dlg); AB_ImExporterContext_free(ctx); return false; } if (!importContext(ctx, 0)) { DBG_ERROR(0, "Error on importContext"); GWEN_Dialog_free(dlg); AB_ImExporterContext_free(ctx); return false; } GWEN_Dialog_free(dlg); AB_ImExporterContext_free(ctx); return true; } const AB_ACCOUNT_STATUS* KMyMoneyBanking::_getAccountStatus(AB_IMEXPORTER_ACCOUNTINFO *ai) { const AB_ACCOUNT_STATUS *ast; const AB_ACCOUNT_STATUS *best; best = 0; ast = AB_ImExporterAccountInfo_GetFirstAccountStatus(ai); while (ast) { if (!best) best = ast; else { const GWEN_TIME *tiBest; const GWEN_TIME *ti; tiBest = AB_AccountStatus_GetTime(best); ti = AB_AccountStatus_GetTime(ast); if (!tiBest) { best = ast; } else { if (ti) { double d; /* we have two times, compare them */ d = GWEN_Time_Diff(ti, tiBest); if (d > 0) /* newer */ best = ast; } } } ast = AB_ImExporterAccountInfo_GetNextAccountStatus(ai); } /* while */ return best; } void KMyMoneyBanking::_xaToStatement(MyMoneyStatement &ks, const MyMoneyAccount& acc, const AB_TRANSACTION *t) { const GWEN_STRINGLIST *sl; QString s; QString memo; const char *p; const AB_VALUE *val; const GWEN_TIME *ti; const GWEN_TIME *startTime = 0; MyMoneyStatement::Transaction kt; unsigned long h; kt.m_fees = MyMoneyMoney(); // bank's transaction id p = AB_Transaction_GetFiId(t); if (p) kt.m_strBankID = QString("ID ") + QString::fromUtf8(p); // payee s.truncate(0); sl = AB_Transaction_GetRemoteName(t); if (sl) { GWEN_STRINGLISTENTRY *se; se = GWEN_StringList_FirstEntry(sl); while (se) { p = GWEN_StringListEntry_Data(se); assert(p); s += QString::fromUtf8(p); se = GWEN_StringListEntry_Next(se); } // while } kt.m_strPayee = s; // memo // The variable 's' contains the old method of extracting // the memo which added a linefeed after each part received // from AqBanking. The new variable 'memo' does not have // this inserted linefeed. We keep the variable 's' to // construct the hash-value to retrieve the reference s.truncate(0); sl = AB_Transaction_GetPurpose(t); if (sl) { GWEN_STRINGLISTENTRY *se; bool insertLineSep = false; se = GWEN_StringList_FirstEntry(sl); while (se) { p = GWEN_StringListEntry_Data(se); assert(p); if (insertLineSep) s += '\n'; insertLineSep = true; s += QString::fromUtf8(p).trimmed(); memo += QString::fromUtf8(p).trimmed(); se = GWEN_StringListEntry_Next(se); } // while // Sparda / Netbank hack: the software these banks use stores // parts of the payee name in the beginning of the purpose field // in case the payee name exceeds the 27 character limit. This is // the case, when one of the strings listed in m_sepaKeywords is part // of the purpose fields but does not start at the beginning. In this // case, the part leading up to the keyword is to be treated as the // tail of the payee. Also, a blank is inserted after the keyword. QSet::const_iterator itk; for (itk = m_sepaKeywords.constBegin(); itk != m_sepaKeywords.constEnd(); ++itk) { int idx = s.indexOf(*itk); if (idx >= 0) { if (idx > 0) { // re-add a possibly removed blank to name if (kt.m_strPayee.length() < 27) kt.m_strPayee += ' '; kt.m_strPayee += s.left(idx); s = s.mid(idx); } s = QString("%1 %2").arg(*itk).arg(s.mid((*itk).length())); // now do the same for 'memo' except for updating the payee idx = memo.indexOf(*itk); if (idx >= 0) { if (idx > 0) { memo = memo.mid(idx); } } memo = QString("%1 %2").arg(*itk).arg(memo.mid((*itk).length())); break; } } // in case we have some SEPA fields filled with information // we add them to the memo field p = AB_Transaction_GetEndToEndReference(t); if (p) { s += QString(", EREF: %1").arg(p); if(memo.length()) memo.append('\n'); memo.append(QString("EREF: %1").arg(p)); } p = AB_Transaction_GetCustomerReference(t); if (p) { s += QString(", CREF: %1").arg(p); if(memo.length()) memo.append('\n'); memo.append(QString("CREF: %1").arg(p)); } p = AB_Transaction_GetMandateId(t); if (p) { s += QString(", MREF: %1").arg(p); if(memo.length()) memo.append('\n'); memo.append(QString("MREF: %1").arg(p)); } p = AB_Transaction_GetCreditorSchemeId(t); if (p) { s += QString(", CRED: %1").arg(p); if(memo.length()) memo.append('\n'); memo.append(QString("CRED: %1").arg(p)); } p = AB_Transaction_GetOriginatorIdentifier(t); if (p) { s += QString(", DEBT: %1").arg(p); if(memo.length()) memo.append('\n'); memo.append(QString("DEBT: %1").arg(p)); } } kt.m_strMemo = memo; // calculate the hash code and start with the payee info // and append the memo field h = MyMoneyTransaction::hash(kt.m_strPayee.trimmed()); h = MyMoneyTransaction::hash(s, h); // see, if we need to extract the payee from the memo field const MyMoneyKeyValueContainer& kvp = acc.onlineBankingSettings(); QString rePayee = kvp.value("kbanking-payee-regexp"); if (!rePayee.isEmpty() && kt.m_strPayee.isEmpty()) { QString reMemo = kvp.value("kbanking-memo-regexp"); QStringList exceptions = kvp.value("kbanking-payee-exceptions").split(';', QString::SkipEmptyParts); bool needExtract = true; QStringList::const_iterator it_s; for (it_s = exceptions.constBegin(); needExtract && it_s != exceptions.constEnd(); ++it_s) { QRegExp exp(*it_s, Qt::CaseInsensitive); if (exp.indexIn(kt.m_strMemo) != -1) { needExtract = false; } } if (needExtract) { QRegExp expPayee(rePayee, Qt::CaseInsensitive); QRegExp expMemo(reMemo, Qt::CaseInsensitive); if (expPayee.indexIn(kt.m_strMemo) != -1) { kt.m_strPayee = expPayee.cap(1); if (expMemo.indexIn(kt.m_strMemo) != -1) { kt.m_strMemo = expMemo.cap(1); } } } } kt.m_strPayee = kt.m_strPayee.trimmed(); // date ti = AB_Transaction_GetDate(t); if (!ti) ti = AB_Transaction_GetValutaDate(t); if (ti) { int year, month, day; if (!startTime) startTime = ti; else { if (GWEN_Time_Diff(ti, startTime) < 0) startTime = ti; } if (!GWEN_Time_GetBrokenDownDate(ti, &day, &month, &year)) { kt.m_datePosted = QDate(year, month + 1, day); } } else { DBG_WARN(0, "No date for transaction"); } // value val = AB_Transaction_GetValue(t); if (val) { if (ks.m_strCurrency.isEmpty()) { p = AB_Value_GetCurrency(val); if (p) ks.m_strCurrency = p; } else { p = AB_Value_GetCurrency(val); if (p) s = p; if (ks.m_strCurrency.toLower() != s.toLower()) { // TODO: handle currency difference DBG_ERROR(0, "Mixed currencies currently not allowed"); } } kt.m_amount = MyMoneyMoney(AB_Value_GetValueAsDouble(val)); // The initial implementation of this feature was based on // a denominator of 100. Since the denominator might be // different nowadays, we make sure to use 100 for the // duplicate detection QString tmpVal = kt.m_amount.formatMoney(100, false); tmpVal.remove(QRegExp("[,\\.]")); tmpVal += QLatin1String("/100"); h = MyMoneyTransaction::hash(tmpVal, h); } else { DBG_WARN(0, "No value for transaction"); } if (startTime) { int year, month, day; if (!GWEN_Time_GetBrokenDownDate(startTime, &day, &month, &year)) { QDate d(year, month + 1, day); if (!ks.m_dateBegin.isValid()) ks.m_dateBegin = d; else if (d < ks.m_dateBegin) ks.m_dateBegin = d; if (!ks.m_dateEnd.isValid()) ks.m_dateEnd = d; else if (d > ks.m_dateEnd) ks.m_dateEnd = d; } } else { DBG_WARN(0, "No date in current transaction"); } // add information about remote account to memo in case we have something const char *remoteAcc = AB_Transaction_GetRemoteAccountNumber(t); const char *remoteBankCode = AB_Transaction_GetRemoteBankCode(t); if (remoteAcc && remoteBankCode) { kt.m_strMemo += QString("\n%1/%2").arg(remoteBankCode, remoteAcc); } // make hash value unique in case we don't have one already if (kt.m_strBankID.isEmpty()) { QString hashBase; hashBase.sprintf("%s-%07lx", qPrintable(kt.m_datePosted.toString(Qt::ISODate)), h); int idx = 1; QString hash; for (;;) { hash = QString("%1-%2").arg(hashBase).arg(idx); QMap::const_iterator it; it = m_hashMap.constFind(hash); if (it == m_hashMap.constEnd()) { m_hashMap[hash] = true; break; } ++idx; } kt.m_strBankID = QString("%1-%2").arg(acc.id()).arg(hash); } // store transaction ks.m_listTransactions += kt; } bool KMyMoneyBanking::importAccountInfo(AB_IMEXPORTER_ACCOUNTINFO *ai, uint32_t /*flags*/) { const char *p; DBG_INFO(0, "Importing account..."); // account number MyMoneyStatement ks; p = AB_ImExporterAccountInfo_GetAccountNumber(ai); if (p) { ks.m_strAccountNumber = m_parent->stripLeadingZeroes(p); } p = AB_ImExporterAccountInfo_GetBankCode(ai); if (p) { ks.m_strRoutingNumber = m_parent->stripLeadingZeroes(p); } MyMoneyAccount kacc = m_parent->account("kbanking-acc-ref", QString("%1-%2").arg(ks.m_strRoutingNumber, ks.m_strAccountNumber)); ks.m_accountId = kacc.id(); // account name p = AB_ImExporterAccountInfo_GetAccountName(ai); if (p) ks.m_strAccountName = p; // account type switch (AB_ImExporterAccountInfo_GetType(ai)) { case AB_AccountType_Bank: ks.m_eType = MyMoneyStatement::etSavings; break; case AB_AccountType_CreditCard: ks.m_eType = MyMoneyStatement::etCreditCard; break; case AB_AccountType_Checking: ks.m_eType = MyMoneyStatement::etCheckings; break; case AB_AccountType_Savings: ks.m_eType = MyMoneyStatement::etSavings; break; case AB_AccountType_Investment: ks.m_eType = MyMoneyStatement::etInvestment; break; case AB_AccountType_Cash: ks.m_eType = MyMoneyStatement::etNone; break; default: ks.m_eType = MyMoneyStatement::etNone; } // account status const AB_ACCOUNT_STATUS* ast = _getAccountStatus(ai); if (ast) { const AB_BALANCE *bal; bal = AB_AccountStatus_GetBookedBalance(ast); if (!bal) bal = AB_AccountStatus_GetNotedBalance(ast); if (bal) { const AB_VALUE* val = AB_Balance_GetValue(bal); if (val) { DBG_INFO(0, "Importing balance"); ks.m_closingBalance = AB_Value_toMyMoneyMoney(val); p = AB_Value_GetCurrency(val); if (p) ks.m_strCurrency = p; } const GWEN_TIME* ti = AB_Balance_GetTime(bal); if (ti) { int year, month, day; if (!GWEN_Time_GetBrokenDownDate(ti, &day, &month, &year)) ks.m_dateEnd = QDate(year, month + 1, day); } else { DBG_WARN(0, "No time for balance"); } } else { DBG_WARN(0, "No account balance"); } } else { DBG_WARN(0, "No account status"); } // clear hash map m_hashMap.clear(); // get all transactions const AB_TRANSACTION* t = AB_ImExporterAccountInfo_GetFirstTransaction(ai); while (t) { _xaToStatement(ks, kacc, t); t = AB_ImExporterAccountInfo_GetNextTransaction(ai); } // import them if (!m_parent->importStatement(ks)) { if (KMessageBox::warningYesNo(0, i18n("Error importing statement. Do you want to continue?"), i18n("Critical Error")) == KMessageBox::No) { DBG_ERROR(0, "User aborted"); return false; } } return true; }