LCOV - code coverage report
Current view: top level - libgnucash/engine - Scrub.cpp (source / functions) Coverage Total Hit
Test: gnucash.info Lines: 48.8 % 701 342
Test Date: 2026-11-24 04:31:04 Functions: 53.7 % 54 29
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /********************************************************************\
       2              :  * Scrub.c -- convert single-entry accounts into clean double-entry *
       3              :  *                                                                  *
       4              :  * This program is free software; you can redistribute it and/or    *
       5              :  * modify it under the terms of the GNU General Public License as   *
       6              :  * published by the Free Software Foundation; either version 2 of   *
       7              :  * the License, or (at your option) any later version.              *
       8              :  *                                                                  *
       9              :  * This program is distributed in the hope that it will be useful,  *
      10              :  * but WITHOUT ANY WARRANTY; without even the implied warranty of   *
      11              :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    *
      12              :  * GNU General Public License for more details.                     *
      13              :  *                                                                  *
      14              :  * You should have received a copy of the GNU General Public License*
      15              :  * along with this program; if not, contact:                        *
      16              :  *                                                                  *
      17              :  * Free Software Foundation           Voice:  +1-617-542-5942       *
      18              :  * 51 Franklin Street, Fifth Floor    Fax:    +1-617-542-2652       *
      19              :  * Boston, MA  02110-1301,  USA       gnu@gnu.org                   *
      20              :  *                                                                  *
      21              : \********************************************************************/
      22              : 
      23              : /*
      24              :  * FILE:
      25              :  * Scrub.c
      26              :  *
      27              :  * FUNCTION:
      28              :  * Provides a set of functions and utilities for scrubbing clean
      29              :  * single-entry accounts so that they can be promoted into
      30              :  * self-consistent, clean double-entry accounts.
      31              :  *
      32              :  * HISTORY:
      33              :  * Created by Linas Vepstas December 1998
      34              :  * Copyright (c) 1998-2000, 2003 Linas Vepstas <linas@linas.org>
      35              :  * Copyright (c) 2002 Christian Stimming
      36              :  * Copyright (c) 2006 David Hampton
      37              :  */
      38              : 
      39              : #include <config.h>
      40              : 
      41              : #include <glib.h>
      42              : #include <glib/gi18n.h>
      43              : #include <stdio.h>
      44              : #include <string.h>
      45              : #include <stdint.h>
      46              : #include <stdbool.h>
      47              : #include <string>
      48              : #include <unordered_set>
      49              : 
      50              : #include "Account.h"
      51              : #include "AccountP.hpp"
      52              : #include "Account.hpp"
      53              : #include "Scrub.h"
      54              : #include "Transaction.h"
      55              : #include "TransactionP.hpp"
      56              : #include "gnc-commodity.h"
      57              : #include "qofinstance-p.h"
      58              : #include "gnc-session.h"
      59              : 
      60              : #undef G_LOG_DOMAIN
      61              : #define G_LOG_DOMAIN "gnc.engine.scrub"
      62              : 
      63              : static QofLogModule log_module = G_LOG_DOMAIN;
      64              : static gboolean abort_now = FALSE;
      65              : static gint scrub_depth = 0;
      66              : 
      67              : 
      68              : static Account* xaccScrubUtilityGetOrMakeAccount (Account *root,
      69              :                                                   gnc_commodity* currency,
      70              :                                                   const char* accname,
      71              :                                                   GNCAccountType acctype,
      72              :                                                   gboolean placeholder,
      73              :                                                   gboolean checkname);
      74              : 
      75              : void
      76            0 : gnc_set_abort_scrub (gboolean abort)
      77              : {
      78            0 :     abort_now = abort;
      79            0 : }
      80              : 
      81              : gboolean
      82            0 : gnc_get_abort_scrub (void)
      83              : {
      84            0 :     return abort_now;
      85              : }
      86              : 
      87              : gboolean
      88            0 : gnc_get_ongoing_scrub (void)
      89              : {
      90            0 :     return scrub_depth > 0;
      91              : }
      92              : 
      93              : /* ================================================================ */
      94              : 
      95              : using TransSet = std::unordered_set<Transaction*>;
      96              : 
      97              : static TransSet
      98            0 : get_all_transactions (Account *account, bool descendants)
      99              : {
     100            0 :     TransSet set;
     101            0 :     auto add_transactions = [&set](auto a)
     102            0 :     { gnc_account_foreach_split (a, [&set](auto s){ set.insert (xaccSplitGetParent (s)); }); };
     103            0 :     add_transactions (account);
     104            0 :     if (descendants)
     105            0 :         gnc_account_foreach_descendant (account, add_transactions);
     106            0 :     return set;
     107            0 : }
     108              : 
     109              : /* ================================================================ */
     110              : 
     111              : static void
     112         1626 : TransScrubOrphansFast (Transaction *trans, Account *root)
     113              : {
     114         1626 :     g_return_if_fail (trans && trans->common_currency && root);
     115              : 
     116         4910 :     for (GList *node = trans->splits; node; node = node->next)
     117              :     {
     118         3300 :         Split *split = GNC_SPLIT(node->data);
     119         3300 :         if (abort_now) break;
     120              : 
     121         3300 :         if (split->acc) continue;
     122              : 
     123           61 :         DEBUG ("Found an orphan\n");
     124              : 
     125              :         gchar *accname = g_strconcat
     126           61 :             (_("Orphan"), "-", gnc_commodity_get_mnemonic (trans->common_currency),
     127              :              nullptr);
     128              : 
     129              :         Account *orph = xaccScrubUtilityGetOrMakeAccount
     130           61 :             (root, trans->common_currency, accname, ACCT_TYPE_BANK, false, true);
     131              : 
     132           61 :         g_free (accname);
     133           61 :         if (!orph) continue;
     134              : 
     135           61 :         xaccSplitSetAccount(split, orph);
     136              :     }
     137              : }
     138              : 
     139              : static void
     140            0 : AccountScrubOrphans (Account *acc, bool descendants, QofPercentageFunc percentagefunc)
     141              : {
     142            0 :     if (!acc) return;
     143            0 :     scrub_depth++;
     144              : 
     145            0 :     auto transactions = get_all_transactions (acc, descendants);
     146            0 :     auto total_trans = transactions.size();
     147            0 :     const char *message = _("Looking for orphans in transaction: %u of %zu");
     148            0 :     guint current_trans = 0;
     149              : 
     150            0 :     for (auto trans : transactions)
     151              :     {
     152            0 :         if (current_trans % 10 == 0)
     153              :         {
     154            0 :             char *progress_msg = g_strdup_printf (message, current_trans, total_trans);
     155            0 :             (percentagefunc)(progress_msg, (100 * current_trans) / total_trans);
     156            0 :             g_free (progress_msg);
     157            0 :             if (abort_now) break;
     158              :         }
     159              : 
     160            0 :         TransScrubOrphansFast (trans, gnc_account_get_root (acc));
     161            0 :         current_trans++;
     162              :     }
     163            0 :     (percentagefunc)(nullptr, -1.0);
     164            0 :     scrub_depth--;
     165            0 : }
     166              : 
     167              : void
     168            0 : xaccAccountScrubOrphans (Account *acc, QofPercentageFunc percentagefunc)
     169              : {
     170            0 :     AccountScrubOrphans (acc, false, percentagefunc);
     171            0 : }
     172              : 
     173              : void
     174            0 : xaccAccountTreeScrubOrphans (Account *acc, QofPercentageFunc percentagefunc)
     175              : {
     176            0 :     AccountScrubOrphans (acc, true, percentagefunc);
     177            0 : }
     178              : 
     179              : void
     180         1626 : xaccTransScrubOrphans (Transaction *trans)
     181              : {
     182              :     SplitList *node;
     183         1626 :     QofBook *book = nullptr;
     184         1626 :     Account *root = nullptr;
     185              : 
     186         1626 :     if (!trans) return;
     187              : 
     188         1698 :     for (node = trans->splits; node; node = node->next)
     189              :     {
     190         1632 :         Split *split = GNC_SPLIT(node->data);
     191         1632 :         if (abort_now) break;
     192              : 
     193         1632 :         if (split->acc)
     194              :         {
     195         1560 :             TransScrubOrphansFast (trans, gnc_account_get_root(split->acc));
     196         1560 :             return;
     197              :         }
     198              :     }
     199              : 
     200              :     /* If we got to here, then *none* of the splits belonged to an
     201              :      * account.  Not a happy situation.  We should dig an account
     202              :      * out of the book the transaction belongs to.
     203              :      * XXX we should probably *always* to this, instead of the above loop!
     204              :      */
     205           66 :     PINFO ("Free Floating Transaction!");
     206           66 :     book = xaccTransGetBook (trans);
     207           66 :     root = gnc_book_get_root_account (book);
     208           66 :     TransScrubOrphansFast (trans, root);
     209              : }
     210              : 
     211              : /* ================================================================ */
     212              : 
     213              : void
     214           22 : xaccAccountTreeScrubSplits (Account *account)
     215              : {
     216           22 :     if (!account) return;
     217              : 
     218           22 :     xaccAccountScrubSplits (account);
     219           22 :     gnc_account_foreach_descendant(account,
     220              :                                    (AccountCb)xaccAccountScrubSplits, nullptr);
     221              : }
     222              : 
     223              : void
     224          456 : xaccAccountScrubSplits (Account *account)
     225              : {
     226          456 :     scrub_depth++;
     227         2522 :     for (auto s : xaccAccountGetSplits (account))
     228              :     {
     229         1610 :         if (abort_now) break;
     230         1610 :         xaccSplitScrub (s);
     231              :     }
     232          456 :     scrub_depth--;
     233          456 : }
     234              : 
     235              : static std::string
     236          145 : make_imbalance_account_name (const gnc_commodity* currency)
     237              : {
     238          580 :     return std::string (_("Imbalance")) + "-" + gnc_commodity_get_mnemonic (currency);
     239              : }
     240              : 
     241              : /* if dry_run is true, this function will analyze the split and
     242              :    return true if the split will be modified during the actual scrub. */
     243              : static bool
     244         8498 : split_scrub_or_dry_run (Split *split, bool dry_run)
     245              : {
     246              :     Account *account;
     247              :     Transaction *trans;
     248              :     gnc_numeric value, amount;
     249              :     gnc_commodity *currency, *acc_commodity;
     250              :     int scu;
     251              : 
     252         8498 :     if (!split) return false;
     253         8498 :     ENTER ("(split=%p)", split);
     254              : 
     255         8498 :     trans = xaccSplitGetParent (split);
     256         8498 :     if (!trans)
     257              :     {
     258            8 :         LEAVE("no trans");
     259            8 :         return false;
     260              :     }
     261              : 
     262         8490 :     account = xaccSplitGetAccount (split);
     263              : 
     264              :     /* If there's no account, this split is an orphan.
     265              :      * We need to fix that first, before proceeding.
     266              :      */
     267         8490 :     if (!account)
     268              :     {
     269          146 :         if (dry_run)
     270              :         {
     271           73 :             LEAVE ("(split=%p) no account. must scrub orphans.", split);
     272           73 :             return true;
     273              :         }
     274              :         else
     275           73 :             xaccTransScrubOrphans (trans);
     276           73 :         account = xaccSplitGetAccount (split);
     277              :     }
     278              : 
     279              :     /* Grrr... the register gnc_split_register_load() line 203 of
     280              :      *  src/register/ledger-core/split-register-load.c will create
     281              :      * free-floating bogus transactions. Ignore these for now ...
     282              :      */
     283         8417 :     if (!account)
     284              :     {
     285           16 :         PINFO ("Free Floating Transaction!");
     286           16 :         LEAVE ("no account");
     287           16 :         return false;
     288              :     }
     289              : 
     290              :     /* Split amounts and values should be valid numbers */
     291         8401 :     value = xaccSplitGetValue (split);
     292         8401 :     if (gnc_numeric_check (value))
     293              :     {
     294            0 :         value = gnc_numeric_zero();
     295            0 :         if (dry_run)
     296              :         {
     297            0 :             LEAVE ("(split=%p) invalid value, reset to zero", split);
     298            0 :             return true;
     299              :         }
     300              :         else
     301            0 :             xaccSplitSetValue (split, value);
     302              :     }
     303              : 
     304         8401 :     amount = xaccSplitGetAmount (split);
     305         8401 :     if (gnc_numeric_check (amount))
     306              :     {
     307            0 :         amount = gnc_numeric_zero();
     308            0 :         if (dry_run)
     309              :         {
     310            0 :             LEAVE ("(split=%p) invalid amount, reset to zero", split);
     311            0 :             return true;
     312              :         }
     313              :         else
     314            0 :             xaccSplitSetAmount (split, amount);
     315              :     }
     316              : 
     317         8401 :     currency = xaccTransGetCurrency (trans);
     318              : 
     319              :     /* If the account doesn't have a commodity,
     320              :      * we should attempt to fix that first.
     321              :      */
     322         8401 :     acc_commodity = xaccAccountGetCommodity(account);
     323         8401 :     if (!acc_commodity)
     324              :     {
     325         1362 :         if (dry_run)
     326              :         {
     327          454 :             LEAVE ("(split=%p) account without commodity", split);
     328          454 :             return true;
     329              :         }
     330              :         else
     331          908 :             xaccAccountScrubCommodity (account);
     332              :     }
     333         7947 :     if (!acc_commodity || !gnc_commodity_equiv(acc_commodity, currency))
     334              :     {
     335         2796 :         LEAVE ("(split=%p) inequiv currency", split);
     336         2796 :         return false;
     337              :     }
     338              : 
     339          463 :     auto null_or_empty = [](const char* str) -> bool { return !str || !*str; };
     340        20602 :     if (xaccTransStillHasSplit (trans, split) &&
     341         5149 :         gnc_numeric_zero_p (value) &&
     342          492 :         gnc_numeric_zero_p (amount) &&
     343          463 :         null_or_empty (xaccSplitGetMemo (split)) &&
     344          217 :         null_or_empty (xaccSplitGetAction (split)) &&
     345        10398 :         xaccAccountGetType (account) == ACCT_TYPE_BANK &&
     346         5249 :         make_imbalance_account_name (currency) == xaccAccountGetName (account))
     347              :     {
     348            4 :         if (!dry_run)
     349            2 :             xaccSplitDestroy (split);
     350            4 :         LEAVE ("(split=%p) zero imbalance", split);
     351            4 :         return true;
     352              :     }
     353              : 
     354         5147 :     scu = MIN (xaccAccountGetCommoditySCU (account),
     355              :                gnc_commodity_get_fraction (currency));
     356              : 
     357         5147 :     if (gnc_numeric_same (amount, value, scu, GNC_HOW_RND_ROUND_HALF_UP))
     358              :     {
     359         5080 :         LEAVE("(split=%p) different values", split);
     360         5080 :         return false;
     361              :     }
     362              : 
     363           67 :     if (dry_run)
     364              :     {
     365           30 :         LEAVE("(split=%p) trans->currency == split->account->currency but amount != value, reset to value", split);
     366           30 :         return true;
     367              :     }
     368              : 
     369              :     /*
     370              :      * This will be hit every time you answer yes to the dialog "The
     371              :      * current transaction has changed. Would you like to record it.
     372              :      */
     373           37 :     PINFO ("Adjusted split with mismatched values, desc=\"%s\" memo=\"%s\""
     374              :            " old amount %s %s, new amount %s",
     375              :            trans->description, split->memo,
     376              :            gnc_num_dbg_to_string (xaccSplitGetAmount(split)),
     377              :            gnc_commodity_get_mnemonic (currency),
     378              :            gnc_num_dbg_to_string (xaccSplitGetValue(split)));
     379              : 
     380           37 :     xaccTransBeginEdit (trans);
     381           37 :     xaccSplitSetAmount (split, value);
     382           37 :     xaccTransCommitEdit (trans);
     383           37 :     LEAVE ("(split=%p)", split);
     384           37 :     return true;
     385              : }
     386              : 
     387              : /* ================================================================ */
     388              : 
     389              : 
     390              : static void
     391            0 : AccountScrubImbalance (Account *acc, bool descendants,
     392              :                        QofPercentageFunc percentagefunc)
     393              : {
     394            0 :     const char *message = _("Looking for imbalances in transaction date %s: %u of %zu");
     395              : 
     396            0 :     if (!acc) return;
     397              : 
     398            0 :     QofBook *book = qof_session_get_book (gnc_get_current_session ());
     399            0 :     Account *root = gnc_book_get_root_account (book);
     400            0 :     auto transactions = get_all_transactions (acc, descendants);
     401            0 :     auto count = transactions.size();
     402            0 :     auto curr_trans = 0;
     403              : 
     404            0 :     scrub_depth++;
     405            0 :     for (auto trans : transactions)
     406              :     {
     407            0 :         if (abort_now) break;
     408              : 
     409            0 :         PINFO("Start processing transaction %d of %zu", curr_trans + 1, count);
     410              : 
     411            0 :         if (curr_trans % 10 == 0)
     412              :         {
     413            0 :             char *date = qof_print_date (xaccTransGetDate (trans));
     414            0 :             char *progress_msg = g_strdup_printf (message, date, curr_trans, count);
     415            0 :             (percentagefunc)(progress_msg, (100 * curr_trans) / count);
     416            0 :             g_free (progress_msg);
     417            0 :             g_free (date);
     418              :         }
     419              : 
     420            0 :         TransScrubOrphansFast (trans, root);
     421            0 :         xaccTransScrubCurrency(trans);
     422            0 :         xaccTransScrubImbalance (trans, root, nullptr);
     423              : 
     424            0 :         PINFO("Finished processing transaction %d of %zu", curr_trans + 1, count);
     425            0 :         curr_trans++;
     426              :     }
     427            0 :     (percentagefunc)(nullptr, -1.0);
     428            0 :     scrub_depth--;
     429            0 : }
     430              : 
     431              : void
     432         3067 : xaccTransScrubSplits (Transaction *trans)
     433              : {
     434         3067 :     if (!trans) return;
     435              : 
     436         3067 :     gnc_commodity *currency = xaccTransGetCurrency (trans);
     437         3067 :     if (!currency)
     438          166 :         PERR ("Transaction doesn't have a currency!");
     439              : 
     440         3067 :     bool must_scrub = false;
     441              : 
     442        14551 :     for (GList *n = xaccTransGetSplitList (trans); !must_scrub && n; n = g_list_next (n))
     443         5742 :         if (split_scrub_or_dry_run (GNC_SPLIT(n->data), true))
     444          559 :             must_scrub = true;
     445              : 
     446         3067 :     if (!must_scrub)
     447         2508 :         return;
     448              : 
     449          559 :     xaccTransBeginEdit(trans);
     450              :     /* The split scrub expects the transaction to have a currency! */
     451              : 
     452         2751 :     for (GList *n = xaccTransGetSplitList (trans); n; n = g_list_next (n))
     453         1096 :         xaccSplitScrub (GNC_SPLIT(n->data));
     454              : 
     455          559 :     xaccTransCommitEdit(trans);
     456              : }
     457              : 
     458              : /* ================================================================ */
     459              : 
     460              : void
     461         2756 : xaccSplitScrub (Split *split)
     462              : {
     463         2756 :     split_scrub_or_dry_run (split, false);
     464         2756 : }
     465              : 
     466              : /* ================================================================ */
     467              : 
     468              : 
     469              : void
     470            0 : xaccAccountTreeScrubImbalance (Account *acc, QofPercentageFunc percentagefunc)
     471              : {
     472            0 :     AccountScrubImbalance (acc, true, percentagefunc);
     473            0 : }
     474              : 
     475              : void
     476            0 : xaccAccountScrubImbalance (Account *acc, QofPercentageFunc percentagefunc)
     477              : {
     478            0 :     AccountScrubImbalance (acc, false, percentagefunc);
     479            0 : }
     480              : 
     481              : static Split *
     482           47 : get_balance_split (Transaction *trans, Account *root, Account *account,
     483              :                    gnc_commodity *commodity)
     484              : {
     485              :     Split *balance_split;
     486              : 
     487           47 :     if (!account ||
     488            0 :         !gnc_commodity_equiv (commodity, xaccAccountGetCommodity(account)))
     489              :     {
     490           47 :         if (!root)
     491              :         {
     492           47 :             root = gnc_book_get_root_account (xaccTransGetBook (trans));
     493           47 :             if (nullptr == root)
     494              :             {
     495              :                 /* This can't occur, things should be in books */
     496            0 :                 PERR ("Bad data corruption, no root account in book");
     497            0 :                 return nullptr;
     498              :             }
     499              :         }
     500           47 :         auto accname = make_imbalance_account_name (commodity);
     501           47 :         account = xaccScrubUtilityGetOrMakeAccount (root, commodity,
     502              :                                                     accname.c_str(), ACCT_TYPE_BANK,
     503              :                                                     FALSE, TRUE);
     504           47 :         if (!account)
     505              :         {
     506            0 :             PERR ("Can't get balancing account");
     507            0 :             return nullptr;
     508              :         }
     509           47 :     }
     510              : 
     511           47 :     balance_split = xaccTransFindSplitByAccount(trans, account);
     512              : 
     513              :     /* Put split into account before setting split value */
     514           47 :     if (!balance_split)
     515              :     {
     516           38 :         balance_split = xaccMallocSplit (qof_instance_get_book(trans));
     517              : 
     518           38 :         xaccTransBeginEdit (trans);
     519           38 :         xaccSplitSetParent(balance_split, trans);
     520           38 :         xaccSplitSetAccount(balance_split, account);
     521           38 :         xaccTransCommitEdit (trans);
     522              :     }
     523              : 
     524           47 :     return balance_split;
     525              : }
     526              : 
     527              : static gnc_commodity*
     528           83 : find_root_currency(void)
     529              : {
     530           83 :     QofSession *sess = gnc_get_current_session ();
     531           83 :     Account *root = gnc_book_get_root_account (qof_session_get_book (sess));
     532           83 :     gnc_commodity *root_currency = xaccAccountGetCommodity (root);
     533              : 
     534              :     /* Some older books may not have a currency set on the root
     535              :      * account. In that case find the first top-level INCOME account
     536              :      * and use its currency. */
     537           83 :     if (!root_currency)
     538              :     {
     539           83 :          GList *children = gnc_account_get_children (root);
     540           87 :          for (GList *node = children; node && !root_currency;
     541            2 :               node = g_list_next (node))
     542              :          {
     543            2 :               Account *child = GNC_ACCOUNT (node->data);
     544            2 :               if (xaccAccountGetType (child) == ACCT_TYPE_INCOME)
     545            0 :                    root_currency = xaccAccountGetCommodity (child);
     546              :          }
     547           83 :          g_list_free (children);
     548              :     }
     549           83 :     return root_currency;
     550              : }
     551              : 
     552              : /* Get the trading split for a given commodity, creating it (and the
     553              :    necessary parent accounts) if it doesn't exist. */
     554              : static Split *
     555            0 : get_trading_split (Transaction *trans, Account *base,
     556              :                    gnc_commodity *commodity)
     557              : {
     558              :     Split *balance_split;
     559              :     Account *trading_account;
     560              :     Account *ns_account;
     561              :     Account *account;
     562            0 :     Account* root = gnc_book_get_root_account (xaccTransGetBook (trans));
     563              : 
     564            0 :     trading_account = xaccScrubUtilityGetOrMakeAccount (root,
     565              :                                                         nullptr,
     566            0 :                                                         _("Trading"),
     567              :                                                         ACCT_TYPE_TRADING,
     568              :                                                         TRUE, FALSE);
     569            0 :     if (!trading_account)
     570              :     {
     571            0 :         PERR ("Can't get trading account");
     572            0 :         return nullptr;
     573              :     }
     574              : 
     575            0 :     ns_account = xaccScrubUtilityGetOrMakeAccount (trading_account,
     576              :                                                    nullptr,
     577              :                                                    gnc_commodity_get_namespace(commodity),
     578              :                                                    ACCT_TYPE_TRADING,
     579              :                                                    TRUE, TRUE);
     580            0 :     if (!ns_account)
     581              :     {
     582            0 :         PERR ("Can't get namespace account");
     583            0 :         return nullptr;
     584              :     }
     585              : 
     586            0 :     account = xaccScrubUtilityGetOrMakeAccount (ns_account, commodity,
     587              :                                                 gnc_commodity_get_mnemonic(commodity),
     588              :                                                 ACCT_TYPE_TRADING,
     589              :                                                 FALSE, FALSE);
     590            0 :     if (!account)
     591              :     {
     592            0 :         PERR ("Can't get commodity account");
     593            0 :         return nullptr;
     594              :     }
     595              : 
     596              : 
     597            0 :     balance_split = xaccTransFindSplitByAccount(trans, account);
     598              : 
     599              :     /* Put split into account before setting split value */
     600            0 :     if (!balance_split)
     601              :     {
     602            0 :         balance_split = xaccMallocSplit (qof_instance_get_book(trans));
     603            0 :         xaccDisableDataScrubbing();
     604              : 
     605            0 :         xaccTransBeginEdit (trans);
     606            0 :         xaccSplitSetParent(balance_split, trans);
     607            0 :         xaccSplitSetAccount(balance_split, account);
     608            0 :         xaccTransCommitEdit (trans);
     609            0 :         xaccEnableDataScrubbing();
     610              :     }
     611              : 
     612            0 :     return balance_split;
     613              : }
     614              : 
     615              : static void
     616           47 : add_balance_split (Transaction *trans, gnc_numeric imbalance,
     617              :                    Account *root, Account *account)
     618              : {
     619              :     const gnc_commodity *commodity;
     620              :     gnc_numeric old_value, new_value;
     621              :     Split *balance_split;
     622           47 :     gnc_commodity *currency = xaccTransGetCurrency (trans);
     623              : 
     624           47 :     balance_split = get_balance_split(trans, root, account, currency);
     625           47 :     if (!balance_split)
     626              :     {
     627              :         /* Error already logged */
     628            0 :         LEAVE("");
     629            0 :         return;
     630              :     }
     631              : 
     632           47 :     old_value = xaccSplitGetValue (balance_split);
     633              : 
     634              :     /* Note: We have to round for the commodity's fraction, NOT any
     635              :      * already existing denominator (bug #104343), because either one
     636              :      * of the denominators might already be reduced.  */
     637           47 :     new_value = gnc_numeric_sub (old_value, imbalance,
     638           47 :                                  gnc_commodity_get_fraction(currency),
     639              :                                  GNC_HOW_RND_ROUND_HALF_UP);
     640              : 
     641           47 :     if (gnc_numeric_zero_p (new_value))
     642              :     {
     643              :         const char *p;
     644            5 :         p = xaccSplitGetMemo (balance_split);
     645            5 :         if (!p || !*p)
     646              :         {
     647            5 :             p = xaccSplitGetAction (balance_split);
     648            5 :             if (!p || !*p)
     649              :             {
     650            5 :                 xaccSplitDestroy (balance_split);
     651            5 :                 return;
     652              :             }
     653              :         }
     654              :     }
     655              : 
     656           42 :     xaccTransBeginEdit (trans);
     657           42 :     xaccSplitSetValue (balance_split, new_value);
     658              :         
     659           42 :     account = xaccSplitGetAccount(balance_split);
     660           42 :     commodity = xaccAccountGetCommodity (account);
     661           42 :     if (gnc_commodity_equiv (currency, commodity))
     662              :     {
     663           42 :         xaccSplitSetAmount (balance_split, new_value);
     664              :     }
     665              : 
     666           42 :     xaccSplitScrub (balance_split);
     667           42 :     xaccTransCommitEdit (trans);
     668              : }
     669              : 
     670              : /* Balance a transaction without trading accounts. */
     671              : static void
     672           47 : gnc_transaction_balance_no_trading (Transaction *trans, Account *root,
     673              :                                     Account *account)
     674              : {
     675           47 :     gnc_numeric imbalance  = xaccTransGetImbalanceValue (trans);
     676              : 
     677              :     /* Make the value sum to zero */
     678           47 :     if (! gnc_numeric_zero_p (imbalance))
     679              :     {
     680           47 :         PINFO ("Value unbalanced transaction");
     681              : 
     682           47 :         add_balance_split (trans, imbalance, root, account);
     683              :     }
     684              : 
     685           47 : }
     686              : 
     687              : static gnc_numeric
     688            0 : gnc_transaction_get_commodity_imbalance (Transaction *trans,
     689              :                                          gnc_commodity *commodity)
     690              : {
     691              :     /* Find the value imbalance in this commodity */
     692            0 :     gnc_numeric val_imbalance = gnc_numeric_zero();
     693            0 :     GList *splits = nullptr;
     694            0 :     for (splits = trans->splits; splits; splits = splits->next)
     695              :     {
     696            0 :         Split *split = GNC_SPLIT(splits->data);
     697              :         gnc_commodity *split_commodity =
     698            0 :             xaccAccountGetCommodity(xaccSplitGetAccount(split));
     699            0 :         if (xaccTransStillHasSplit (trans, split) &&
     700            0 :             gnc_commodity_equal (commodity, split_commodity))
     701            0 :             val_imbalance = gnc_numeric_add (val_imbalance,
     702              :                                              xaccSplitGetValue (split),
     703              :                                              GNC_DENOM_AUTO,
     704              :                                              GNC_HOW_DENOM_EXACT);
     705              :     }
     706            0 :     return val_imbalance;
     707              : }
     708              : 
     709              : /* GFunc wrapper for xaccSplitDestroy */
     710              : static void
     711            0 : destroy_split (void* ptr)
     712              : {
     713            0 :     Split *split = GNC_SPLIT (ptr);
     714            0 :     if (split)
     715            0 :         xaccSplitDestroy (split);
     716            0 : }
     717              : 
     718              : /* Balancing transactions with trading accounts works best when
     719              :  * starting with no trading splits.
     720              :  */
     721              : static void
     722            0 : xaccTransClearTradingSplits (Transaction *trans)
     723              : {
     724            0 :     GList *trading_splits = nullptr;
     725              : 
     726            0 :     for (GList* node = trans->splits; node; node = node->next)
     727              :     {
     728            0 :          Split* split = GNC_SPLIT(node->data);
     729            0 :          Account* acc = nullptr;
     730            0 :          if (!split)
     731            0 :               continue;
     732            0 :          acc = xaccSplitGetAccount(split);
     733            0 :          if (acc && xaccAccountGetType(acc) == ACCT_TYPE_TRADING)
     734            0 :             trading_splits = g_list_prepend (trading_splits, node->data);
     735              :     }
     736              : 
     737            0 :     if (!trading_splits)
     738            0 :         return;
     739              : 
     740            0 :     xaccTransBeginEdit (trans);
     741              :     /* destroy_splits doesn't actually free the splits but this gets
     742              :      * the list itself freed.
     743              :      */
     744            0 :     g_list_free_full (trading_splits, destroy_split);
     745            0 :     xaccTransCommitEdit (trans);
     746              : }
     747              : 
     748              : static void
     749            0 : gnc_transaction_balance_trading (Transaction *trans, Account *root)
     750              : {
     751              :     MonetaryList *imbal_list;
     752              :     MonetaryList *imbalance_commod;
     753            0 :     Split *balance_split = nullptr;
     754              : 
     755              :     /* If the transaction is balanced, nothing more to do */
     756            0 :     imbal_list = xaccTransGetImbalance (trans);
     757            0 :     if (!imbal_list)
     758              :     {
     759            0 :         LEAVE("transaction is balanced");
     760            0 :         return;
     761              :     }
     762              : 
     763            0 :     PINFO ("Currency unbalanced transaction");
     764              : 
     765            0 :     for (imbalance_commod = imbal_list; imbalance_commod;
     766            0 :          imbalance_commod = imbalance_commod->next)
     767              :     {
     768            0 :         auto imbal_mon = static_cast<gnc_monetary*>(imbalance_commod->data);
     769              :         gnc_commodity *commodity;
     770              :         gnc_numeric old_amount, new_amount;
     771            0 :         const gnc_commodity *txn_curr = xaccTransGetCurrency (trans);
     772              : 
     773            0 :         commodity = gnc_monetary_commodity (*imbal_mon);
     774              : 
     775            0 :         balance_split = get_trading_split(trans, root, commodity);
     776            0 :         if (!balance_split)
     777              :         {
     778              :             /* Error already logged */
     779            0 :             gnc_monetary_list_free(imbal_list);
     780            0 :             LEAVE("");
     781            0 :             return;
     782              :         }
     783              : 
     784            0 :         xaccTransBeginEdit (trans);
     785              : 
     786            0 :         old_amount = xaccSplitGetAmount (balance_split);
     787            0 :         new_amount = gnc_numeric_sub (old_amount, gnc_monetary_value(*imbal_mon),
     788            0 :                                       gnc_commodity_get_fraction(commodity),
     789              :                                       GNC_HOW_RND_ROUND_HALF_UP);
     790              : 
     791            0 :         xaccSplitSetAmount (balance_split, new_amount);
     792              : 
     793            0 :         if (gnc_commodity_equal (txn_curr, commodity))
     794              :         {
     795              :             /* Imbalance commodity is the transaction currency, value in the
     796              :                split must be the same as the amount */
     797            0 :             xaccSplitSetValue (balance_split, new_amount);
     798              :         }
     799              :         else
     800              :         {
     801            0 :             gnc_numeric val_imbalance = gnc_transaction_get_commodity_imbalance (trans,            commodity);
     802              : 
     803            0 :             gnc_numeric old_value = xaccSplitGetValue (balance_split);
     804            0 :             gnc_numeric new_value = gnc_numeric_sub (old_value, val_imbalance,
     805            0 :                                          gnc_commodity_get_fraction(txn_curr),
     806              :                                          GNC_HOW_RND_ROUND_HALF_UP);
     807              : 
     808            0 :             xaccSplitSetValue (balance_split, new_value);
     809              :         }
     810              : 
     811            0 :         xaccSplitScrub (balance_split);
     812            0 :         xaccTransCommitEdit (trans);
     813              :     }
     814              : 
     815            0 :     gnc_monetary_list_free(imbal_list);
     816              : }
     817              : 
     818              : /** Balance the transaction by adding more trading splits. This shouldn't
     819              :  * ordinarily be necessary.
     820              :  * @param trans the transaction to balance
     821              :  * @param root the root account
     822              :  */
     823              : static void
     824            0 : gnc_transaction_balance_trading_more_splits (Transaction *trans, Account *root)
     825              : {
     826              :     /* Copy the split list so we don't see the splits we're adding */
     827            0 :     GList *splits_dup = g_list_copy(trans->splits), *splits = nullptr;
     828            0 :     const gnc_commodity  *txn_curr = xaccTransGetCurrency (trans);
     829            0 :     for (splits = splits_dup; splits; splits = splits->next)
     830              :     {
     831            0 :         Split *split = GNC_SPLIT(splits->data);
     832            0 :         if (! xaccTransStillHasSplit(trans, split)) continue;
     833            0 :         if (!gnc_numeric_zero_p(xaccSplitGetValue(split)) &&
     834            0 :             gnc_numeric_zero_p(xaccSplitGetAmount(split)))
     835              :         {
     836              :             gnc_commodity *commodity;
     837              :             gnc_numeric old_value, new_value;
     838              :             Split *balance_split;
     839              : 
     840            0 :             commodity = xaccAccountGetCommodity(xaccSplitGetAccount(split));
     841            0 :             if (!commodity)
     842              :             {
     843            0 :                 PERR("Split has no commodity");
     844            0 :                 continue;
     845              :             }
     846            0 :             balance_split = get_trading_split(trans, root, commodity);
     847            0 :             if (!balance_split)
     848              :             {
     849              :                 /* Error already logged */
     850            0 :                 LEAVE("");
     851            0 :                 return;
     852              :             }
     853            0 :             xaccTransBeginEdit (trans);
     854              : 
     855            0 :             old_value = xaccSplitGetValue (balance_split);
     856            0 :             new_value = gnc_numeric_sub (old_value, xaccSplitGetValue(split),
     857            0 :                                          gnc_commodity_get_fraction(txn_curr),
     858              :                                          GNC_HOW_RND_ROUND_HALF_UP);
     859            0 :             xaccSplitSetValue (balance_split, new_value);
     860              : 
     861              :             /* Don't change the balance split's amount since the amount
     862              :                is zero in the split we're working on */
     863              : 
     864            0 :             xaccSplitScrub (balance_split);
     865            0 :             xaccTransCommitEdit (trans);
     866              :         }
     867              :     }
     868              : 
     869            0 :     g_list_free(splits_dup);
     870              : }
     871              : 
     872              : /** Correct transaction imbalances.
     873              :  * @param trans The Transaction
     874              :  * @param root The (hidden) root account, for the book default currency.
     875              :  * @param account The account whose currency in which to balance.
     876              :  */
     877              : 
     878              : void
     879         3067 : xaccTransScrubImbalance (Transaction *trans, Account *root,
     880              :                          Account *account)
     881              : {
     882              :     gnc_numeric imbalance;
     883              : 
     884         6134 :     if (!trans) return;
     885              : 
     886         3067 :     ENTER ("()");
     887              : 
     888              :     /* Must look for orphan splits even if there is no imbalance. */
     889         3067 :     xaccTransScrubSplits (trans);
     890              : 
     891              :     /* Return immediately if things are balanced. */
     892         3067 :     if (xaccTransIsBalanced (trans))
     893              :     {
     894         3020 :         LEAVE ("transaction is balanced");
     895         3020 :         return;
     896              :     }
     897              : 
     898           47 :     if (! xaccTransUseTradingAccounts (trans))
     899              :     {
     900           47 :         gnc_transaction_balance_no_trading (trans, root, account);
     901           47 :         LEAVE ("transaction balanced, no managed trading accounts");
     902           47 :         return;
     903              :     }
     904              : 
     905            0 :     xaccTransClearTradingSplits (trans);
     906            0 :     imbalance = xaccTransGetImbalanceValue (trans);
     907            0 :     if (! gnc_numeric_zero_p (imbalance))
     908              :     {
     909            0 :         PINFO ("Value unbalanced transaction");
     910              : 
     911            0 :         add_balance_split (trans, imbalance, root, account);
     912              :     }
     913              : 
     914            0 :     gnc_transaction_balance_trading (trans, root);
     915            0 :     if (gnc_numeric_zero_p(xaccTransGetImbalanceValue(trans)))
     916              :     {
     917            0 :         LEAVE ("()");
     918            0 :         return;
     919              :     }
     920              :     /* If the transaction is still not balanced, it's probably because there
     921              :        are splits with zero amount and non-zero value.  These are usually
     922              :        realized gain/loss splits.  Add a reversing split for each of them to
     923              :        balance the value. */
     924              : 
     925            0 :     gnc_transaction_balance_trading_more_splits (trans, root);
     926            0 :     if (!gnc_numeric_zero_p(xaccTransGetImbalanceValue(trans)))
     927            0 :         PERR("Balancing currencies unbalanced value");
     928              : 
     929              : }
     930              : 
     931              : /* ================================================================ */
     932              : /* The xaccTransFindCommonCurrency () method returns
     933              :  *    a gnc_commodity indicating a currency denomination that all
     934              :  *    of the splits in this transaction have in common, using the
     935              :  *    old/obsolete currency/security fields of the split accounts.
     936              :  */
     937              : 
     938              : static gnc_commodity *
     939            0 : FindCommonExclSCurrency (SplitList *splits,
     940              :                          gnc_commodity * ra, gnc_commodity * rb,
     941              :                          Split *excl_split)
     942              : {
     943              :     GList *node;
     944              : 
     945            0 :     if (!splits) return nullptr;
     946              : 
     947            0 :     for (node = splits; node; node = node->next)
     948              :     {
     949            0 :         Split *s = GNC_SPLIT(node->data);
     950              :         gnc_commodity * sa, * sb;
     951              : 
     952            0 :         if (s == excl_split) continue;
     953              : 
     954            0 :         g_return_val_if_fail (s->acc, nullptr);
     955              : 
     956            0 :         sa = DxaccAccountGetCurrency (s->acc);
     957            0 :         sb = xaccAccountGetCommodity (s->acc);
     958              : 
     959            0 :         if (ra && rb)
     960              :         {
     961            0 :             int aa = !gnc_commodity_equiv(ra, sa);
     962            0 :             int ab = !gnc_commodity_equiv(ra, sb);
     963            0 :             int ba = !gnc_commodity_equiv(rb, sa);
     964            0 :             int bb = !gnc_commodity_equiv(rb, sb);
     965              : 
     966            0 :             if ( (!aa) && bb) rb = nullptr;
     967            0 :             else if ( (!ab) && ba) rb = nullptr;
     968            0 :             else if ( (!ba) && ab) ra = nullptr;
     969            0 :             else if ( (!bb) && aa) ra = nullptr;
     970            0 :             else if ( aa && bb && ab && ba )
     971              :             {
     972            0 :                 ra = nullptr;
     973            0 :                 rb = nullptr;
     974              :             }
     975              : 
     976            0 :             if (!ra)
     977              :             {
     978            0 :                 ra = rb;
     979            0 :                 rb = nullptr;
     980              :             }
     981            0 :         }
     982            0 :         else if (ra && !rb)
     983              :         {
     984            0 :             int aa = !gnc_commodity_equiv(ra, sa);
     985            0 :             int ab = !gnc_commodity_equiv(ra, sb);
     986            0 :             if ( aa && ab ) ra = nullptr;
     987            0 :         }
     988            0 :         else if (!ra && rb)
     989              :         {
     990            0 :             int aa = !gnc_commodity_equiv(rb, sa);
     991            0 :             int ab = !gnc_commodity_equiv(rb, sb);
     992            0 :             ra = ( aa && ab ) ? nullptr : rb;
     993              :         }
     994              : 
     995            0 :         if ((!ra) && (!rb)) return nullptr;
     996              :     }
     997              : 
     998            0 :     return (ra);
     999              : }
    1000              : 
    1001              : /* This is the wrapper for those calls (i.e. the older ones) which
    1002              :  * don't exclude one split from the splitlist when looking for a
    1003              :  * common currency.
    1004              :  */
    1005              : static gnc_commodity *
    1006            0 : FindCommonCurrency (GList *splits, gnc_commodity * ra, gnc_commodity * rb)
    1007              : {
    1008            0 :     return FindCommonExclSCurrency(splits, ra, rb, nullptr);
    1009              : }
    1010              : 
    1011              : static gnc_commodity *
    1012            0 : xaccTransFindOldCommonCurrency (Transaction *trans, QofBook *book)
    1013              : {
    1014              :     gnc_commodity *ra, *rb, *retval;
    1015              :     Split *split;
    1016              : 
    1017            0 :     if (!trans) return nullptr;
    1018              : 
    1019            0 :     if (trans->splits == nullptr) return nullptr;
    1020              : 
    1021            0 :     g_return_val_if_fail (book, nullptr);
    1022              : 
    1023            0 :     split = GNC_SPLIT(trans->splits->data);
    1024              : 
    1025            0 :     if (!split || nullptr == split->acc) return nullptr;
    1026              : 
    1027            0 :     ra = DxaccAccountGetCurrency (split->acc);
    1028            0 :     rb = xaccAccountGetCommodity (split->acc);
    1029              : 
    1030            0 :     retval = FindCommonCurrency (trans->splits, ra, rb);
    1031              : 
    1032            0 :     if (retval && !gnc_commodity_is_currency(retval))
    1033            0 :         retval = nullptr;
    1034              : 
    1035            0 :     return retval;
    1036              : }
    1037              : 
    1038              : /* Test the currency of the splits and find the most common and return
    1039              :  * it, or nullptr if there is no currency more common than the
    1040              :  * others -- or none at all.
    1041              :  */
    1042              : typedef struct
    1043              : {
    1044              :     gnc_commodity *commodity;
    1045              :     unsigned int count;
    1046              : } CommodityCount;
    1047              : 
    1048              : static gint
    1049          202 : commodity_equal (gconstpointer a, gconstpointer b)
    1050              : {
    1051          202 :     CommodityCount *cc = (CommodityCount*)a;
    1052          202 :     gnc_commodity *com = (gnc_commodity*)b;
    1053          404 :     if ( cc == nullptr || cc->commodity == nullptr ||
    1054          202 :          !GNC_IS_COMMODITY( cc->commodity ) ) return -1;
    1055          202 :     if ( com == nullptr || !GNC_IS_COMMODITY( com ) ) return 1;
    1056          202 :     if ( gnc_commodity_equal(cc->commodity, com) )
    1057          202 :         return 0;
    1058            0 :     return 1;
    1059              : }
    1060              : 
    1061              : static gint
    1062            0 : commodity_compare( gconstpointer a, gconstpointer b)
    1063              : {
    1064            0 :     CommodityCount *ca = (CommodityCount*)a, *cb = (CommodityCount*)b;
    1065            0 :     if (ca == nullptr || ca->commodity == nullptr ||
    1066            0 :         !GNC_IS_COMMODITY( ca->commodity ) )
    1067              :     {
    1068            0 :         if (cb == nullptr || cb->commodity == nullptr ||
    1069            0 :             !GNC_IS_COMMODITY( cb->commodity ) )
    1070            0 :             return 0;
    1071            0 :         return -1;
    1072              :     }
    1073            0 :     if (cb == nullptr || cb->commodity == nullptr ||
    1074            0 :         !GNC_IS_COMMODITY( cb->commodity ) )
    1075            0 :         return 1;
    1076            0 :     if (ca->count == cb->count)
    1077            0 :         return 0;
    1078            0 :     return ca->count > cb->count ? 1 : -1;
    1079              : }
    1080              : 
    1081              : /* Find the commodities in the account of each of the splits of a
    1082              :  * transaction, and rank them by how many splits in which they
    1083              :  * occur. Commodities which are currencies count more than those which
    1084              :  * aren't, because for simple buy and sell transactions it makes
    1085              :  * slightly more sense for the transaction commodity to be the
    1086              :  * currency -- to the extent that it makes sense for a transaction to
    1087              :  * have a currency at all. jralls, 2010-11-02 */
    1088              : 
    1089              : static gnc_commodity *
    1090          198 : xaccTransFindCommonCurrency (Transaction *trans, QofBook *book)
    1091              : {
    1092              :     gnc_commodity *com_scratch;
    1093          198 :     GList *node = nullptr;
    1094          198 :     GSList *comlist = nullptr, *found = nullptr;
    1095              : 
    1096          198 :     if (!trans) return nullptr;
    1097              : 
    1098          198 :     if (trans->splits == nullptr) return nullptr;
    1099              : 
    1100          198 :     g_return_val_if_fail (book, nullptr);
    1101              : 
    1102              :     /* Find the most commonly used currency among the splits.  If a given split
    1103              :        is in a non-currency commodity, then look for an ancestor account in a
    1104              :        currency, but prefer currencies used directly in splits.  Ignore trading
    1105              :        account splits in this whole process, they don't add any value to this algorithm. */
    1106          601 :     for (node = trans->splits; node; node = node->next)
    1107              :     {
    1108          403 :         Split *s = GNC_SPLIT(node->data);
    1109              :         unsigned int curr_weight;
    1110              : 
    1111          403 :         if (s == nullptr || s->acc == nullptr) continue;
    1112          403 :         if (xaccAccountGetType(s->acc) == ACCT_TYPE_TRADING) continue;
    1113          403 :         com_scratch = xaccAccountGetCommodity(s->acc);
    1114          403 :         if (com_scratch && gnc_commodity_is_currency(com_scratch))
    1115              :         {
    1116           71 :             curr_weight = 3;
    1117              :         }
    1118              :         else
    1119              :         {
    1120          332 :             com_scratch = gnc_account_get_currency_or_parent(s->acc);
    1121          332 :             if (com_scratch == nullptr) continue;
    1122          329 :             curr_weight = 1;
    1123              :         }
    1124          400 :         if ( comlist )
    1125              :         {
    1126          202 :             found = g_slist_find_custom(comlist, com_scratch, commodity_equal);
    1127              :         }
    1128          400 :         if (comlist == nullptr || found == nullptr)
    1129              :         {
    1130          198 :             CommodityCount *count = g_slice_new0(CommodityCount);
    1131          198 :             count->commodity = com_scratch;
    1132          198 :             count->count = curr_weight;
    1133          198 :             comlist = g_slist_append(comlist, count);
    1134          198 :         }
    1135              :         else
    1136              :         {
    1137          202 :             CommodityCount *count = (CommodityCount*)(found->data);
    1138          202 :             count->count += curr_weight;
    1139              :         }
    1140              :     }
    1141          198 :     found = g_slist_sort( comlist, commodity_compare);
    1142              : 
    1143          198 :     if ( found && found->data && (((CommodityCount*)(found->data))->commodity != nullptr))
    1144              :     {
    1145          198 :         return ((CommodityCount*)(found->data))->commodity;
    1146              :     }
    1147              :     /* We didn't find a currency in the current account structure, so try
    1148              :      * an old one. */
    1149            0 :     return xaccTransFindOldCommonCurrency( trans, book );
    1150              : }
    1151              : 
    1152              : /* ================================================================ */
    1153              : 
    1154              : void
    1155         1553 : xaccTransScrubCurrency (Transaction *trans)
    1156              : {
    1157              :     SplitList *node;
    1158              :     gnc_commodity *currency;
    1159              : 
    1160         1553 :     if (!trans) return;
    1161              : 
    1162              :     /* If there are any orphaned splits in a transaction, then the
    1163              :      * this routine will fail.  Therefore, we want to make sure that
    1164              :      * there are no orphans (splits without parent account).
    1165              :      */
    1166         1553 :     xaccTransScrubOrphans (trans);
    1167              : 
    1168         1553 :     currency = xaccTransGetCurrency (trans);
    1169         1553 :     if (currency && gnc_commodity_is_currency(currency)) return;
    1170              : 
    1171          198 :     currency = xaccTransFindCommonCurrency (trans, qof_instance_get_book(trans));
    1172          198 :     if (currency)
    1173              :     {
    1174          198 :         xaccTransBeginEdit (trans);
    1175          198 :         xaccTransSetCurrency (trans, currency);
    1176          198 :         xaccTransCommitEdit (trans);
    1177              :     }
    1178              :     else
    1179              :     {
    1180            0 :         if (nullptr == trans->splits)
    1181              :         {
    1182            0 :             PWARN ("Transaction \"%s\" has no splits in it!", trans->description);
    1183              :         }
    1184              :         else
    1185              :         {
    1186              :             SplitList *node;
    1187              :             char guid_str[GUID_ENCODING_LENGTH + 1];
    1188            0 :             guid_to_string_buff(xaccTransGetGUID(trans), guid_str);
    1189            0 :             PWARN ("no common transaction currency found for trans=\"%s\" (%s);",
    1190              :                    trans->description, guid_str);
    1191              : 
    1192            0 :             for (node = trans->splits; node; node = node->next)
    1193              :             {
    1194            0 :                 Split *split = GNC_SPLIT(node->data);
    1195            0 :                 if (nullptr == split->acc)
    1196              :                 {
    1197            0 :                     PWARN (" split=\"%s\" is not in any account!", split->memo);
    1198              :                 }
    1199              :                 else
    1200              :                 {
    1201            0 :                     gnc_commodity *currency = xaccAccountGetCommodity(split->acc);
    1202            0 :                     PWARN ("setting to split=\"%s\" account=\"%s\" commodity=\"%s\"",
    1203              :                            split->memo, xaccAccountGetName(split->acc),
    1204              :                            gnc_commodity_get_mnemonic(currency));
    1205              : 
    1206            0 :                     xaccTransBeginEdit (trans);
    1207            0 :                     xaccTransSetCurrency (trans, currency);
    1208            0 :                     xaccTransCommitEdit (trans);
    1209            0 :                     return;
    1210              :                 }
    1211              :             }
    1212              :         }
    1213            0 :         return;
    1214              :     }
    1215              : 
    1216          601 :     for (node = trans->splits; node; node = node->next)
    1217              :     {
    1218          403 :         Split *sp = GNC_SPLIT(node->data);
    1219              : 
    1220          403 :         if (!gnc_numeric_equal(xaccSplitGetAmount (sp),
    1221              :                                xaccSplitGetValue (sp)))
    1222              :         {
    1223              :             gnc_commodity *acc_currency;
    1224              : 
    1225          299 :             acc_currency = sp->acc ? xaccAccountGetCommodity(sp->acc) : nullptr;
    1226          299 :             if (acc_currency == currency)
    1227              :             {
    1228              :                 /* This Split needs fixing: The transaction-currency equals
    1229              :                  * the account-currency/commodity, but the amount/values are
    1230              :                  * inequal i.e. they still correspond to the security
    1231              :                  * (amount) and the currency (value). In the new model, the
    1232              :                  * value is the amount in the account-commodity -- so it
    1233              :                  * needs to be set to equal the amount (since the
    1234              :                  * account-currency doesn't exist anymore).
    1235              :                  *
    1236              :                  * Note: Nevertheless we lose some information here. Namely,
    1237              :                  * the information that the 'amount' in 'account-old-security'
    1238              :                  * was worth 'value' in 'account-old-currency'. Maybe it would
    1239              :                  * be better to store that information in the price database?
    1240              :                  * But then, for old currency transactions there is still the
    1241              :                  * 'other' transaction, which is going to keep that
    1242              :                  * information. So I don't bother with that here. -- cstim,
    1243              :                  * 2002/11/20. */
    1244              : 
    1245            0 :                 PWARN ("Adjusted split with mismatched values, desc=\"%s\" memo=\"%s\""
    1246              :                        " old amount %s %s, new amount %s",
    1247              :                        trans->description, sp->memo,
    1248              :                        gnc_num_dbg_to_string (xaccSplitGetAmount(sp)),
    1249              :                        gnc_commodity_get_mnemonic (currency),
    1250              :                        gnc_num_dbg_to_string (xaccSplitGetValue(sp)));
    1251            0 :                 xaccTransBeginEdit (trans);
    1252            0 :                 xaccSplitSetAmount (sp, xaccSplitGetValue(sp));
    1253            0 :                 xaccTransCommitEdit (trans);
    1254              :             }
    1255              :             /*else
    1256              :               {
    1257              :               PINFO ("Ok: Split '%s' Amount %s %s, value %s %s",
    1258              :               xaccSplitGetMemo (sp),
    1259              :               gnc_num_dbg_to_string (amount),
    1260              :               gnc_commodity_get_mnemonic (currency),
    1261              :               gnc_num_dbg_to_string (value),
    1262              :               gnc_commodity_get_mnemonic (acc_currency));
    1263              :               }*/
    1264              :         }
    1265              :     }
    1266              : 
    1267              : }
    1268              : 
    1269              : /* ================================================================ */
    1270              : 
    1271              : void
    1272         2543 : xaccAccountScrubCommodity (Account *account)
    1273              : {
    1274              :     gnc_commodity *commodity;
    1275              : 
    1276         2543 :     if (!account) return;
    1277         2543 :     if (xaccAccountGetType(account) == ACCT_TYPE_ROOT) return;
    1278              : 
    1279         2466 :     commodity = xaccAccountGetCommodity (account);
    1280         2466 :     if (commodity) return;
    1281              : 
    1282              :     /* Use the 'obsolete' routines to try to figure out what the
    1283              :      * account commodity should have been. */
    1284          908 :     commodity = xaccAccountGetCommodity (account);
    1285          908 :     if (commodity)
    1286              :     {
    1287            0 :         xaccAccountSetCommodity (account, commodity);
    1288            0 :         return;
    1289              :     }
    1290              : 
    1291          908 :     commodity = DxaccAccountGetCurrency (account);
    1292          908 :     if (commodity)
    1293              :     {
    1294            0 :         xaccAccountSetCommodity (account, commodity);
    1295            0 :         return;
    1296              :     }
    1297              : 
    1298          908 :     PERR ("Account \"%s\" does not have a commodity!",
    1299              :           xaccAccountGetName(account));
    1300              : }
    1301              : 
    1302              : /* ================================================================ */
    1303              : 
    1304              : /* EFFECTIVE FRIEND FUNCTION declared in qofinstance-p.h */
    1305              : extern void qof_instance_set_dirty (QofInstance*);
    1306              : 
    1307              : static void
    1308          456 : xaccAccountDeleteOldData (Account *account)
    1309              : {
    1310          456 :     if (!account) return;
    1311          456 :     xaccAccountBeginEdit (account);
    1312          456 :     qof_instance_set_kvp (QOF_INSTANCE (account), nullptr, 1, "old-currency");
    1313          456 :     qof_instance_set_kvp (QOF_INSTANCE (account), nullptr, 1, "old-security");
    1314          456 :     qof_instance_set_kvp (QOF_INSTANCE (account), nullptr, 1, "old-currency-scu");
    1315          456 :     qof_instance_set_kvp (QOF_INSTANCE (account), nullptr, 1, "old-security-scu");
    1316          456 :     qof_instance_set_dirty (QOF_INSTANCE (account));
    1317          456 :     xaccAccountCommitEdit (account);
    1318              : }
    1319              : 
    1320              : static int
    1321          774 : scrub_trans_currency_helper (Transaction *t, gpointer data)
    1322              : {
    1323          774 :     xaccTransScrubCurrency (t);
    1324          774 :     return 0;
    1325              : }
    1326              : 
    1327              : static void
    1328          456 : scrub_account_commodity_helper (Account *account, gpointer data)
    1329              : {
    1330          456 :     scrub_depth++;
    1331          456 :     xaccAccountScrubCommodity (account);
    1332          456 :     xaccAccountDeleteOldData (account);
    1333          456 :     scrub_depth--;
    1334          456 : }
    1335              : 
    1336              : void
    1337           22 : xaccAccountTreeScrubCommodities (Account *acc)
    1338              : {
    1339           22 :     if (!acc) return;
    1340           22 :     scrub_depth++;
    1341           22 :     xaccAccountTreeForEachTransaction (acc, scrub_trans_currency_helper, nullptr);
    1342              : 
    1343           22 :     scrub_account_commodity_helper (acc, nullptr);
    1344           22 :     gnc_account_foreach_descendant (acc, scrub_account_commodity_helper, nullptr);
    1345           22 :     scrub_depth--;
    1346              : }
    1347              : 
    1348              : /* ================================================================ */
    1349              : 
    1350              : static gboolean
    1351         5080 : check_quote_source (gnc_commodity *com, gpointer data)
    1352              : {
    1353         5080 :     gboolean *commodity_has_quote_src = (gboolean *)data;
    1354         5080 :     if (com && !gnc_commodity_is_iso(com))
    1355           86 :         *commodity_has_quote_src |= gnc_commodity_get_quote_flag(com);
    1356         5080 :     return TRUE;
    1357              : }
    1358              : 
    1359              : static void
    1360          456 : move_quote_source (Account *account, gpointer data)
    1361              : {
    1362              :     gnc_commodity *com;
    1363              :     gnc_quote_source *quote_source;
    1364          456 :     gboolean new_style = GPOINTER_TO_INT(data);
    1365              :     const char *source, *tz;
    1366              : 
    1367          456 :     com = xaccAccountGetCommodity(account);
    1368          456 :     if (!com)
    1369           19 :         return;
    1370              : 
    1371          437 :     if (!new_style)
    1372              :     {
    1373          424 :         source = dxaccAccountGetPriceSrc(account);
    1374          424 :         if (!source || !*source)
    1375          424 :             return;
    1376            0 :         tz = dxaccAccountGetQuoteTZ(account);
    1377              : 
    1378            0 :         PINFO("to %8s from %s", gnc_commodity_get_mnemonic(com),
    1379              :               xaccAccountGetName(account));
    1380            0 :         gnc_commodity_set_quote_flag(com, TRUE);
    1381            0 :         quote_source = gnc_quote_source_lookup_by_internal(source);
    1382            0 :         if (!quote_source)
    1383            0 :             quote_source = gnc_quote_source_add_new(source, FALSE);
    1384            0 :         gnc_commodity_set_quote_source(com, quote_source);
    1385            0 :         gnc_commodity_set_quote_tz(com, tz);
    1386              :     }
    1387              : 
    1388           13 :     dxaccAccountSetPriceSrc(account, nullptr);
    1389           13 :     dxaccAccountSetQuoteTZ(account, nullptr);
    1390           13 :     return;
    1391              : }
    1392              : 
    1393              : 
    1394              : void
    1395           22 : xaccAccountTreeScrubQuoteSources (Account *root, gnc_commodity_table *table)
    1396              : {
    1397           22 :     gboolean new_style = FALSE;
    1398           22 :     ENTER(" ");
    1399              : 
    1400           22 :     if (!root || !table)
    1401              :     {
    1402            0 :         LEAVE("Oops");
    1403            0 :         return;
    1404              :     }
    1405           22 :     scrub_depth++;
    1406           22 :     gnc_commodity_table_foreach_commodity (table, check_quote_source, &new_style);
    1407              : 
    1408           22 :     move_quote_source(root, GINT_TO_POINTER(new_style));
    1409           22 :     gnc_account_foreach_descendant (root, move_quote_source,
    1410           22 :                                     GINT_TO_POINTER(new_style));
    1411           22 :     LEAVE("Migration done");
    1412           22 :     scrub_depth--;
    1413              : }
    1414              : 
    1415              : /* ================================================================ */
    1416              : 
    1417              : void
    1418          455 : xaccAccountScrubKvp (Account *account)
    1419              : {
    1420          455 :     GValue v = G_VALUE_INIT;
    1421              :     gchar *str2;
    1422              : 
    1423          455 :     if (!account) return;
    1424          455 :     scrub_depth++;
    1425              : 
    1426          455 :     qof_instance_get_kvp (QOF_INSTANCE (account), &v, 1, "notes");
    1427          455 :     if (G_VALUE_HOLDS_STRING (&v))
    1428              :     {
    1429            1 :         str2 = g_strstrip(g_value_dup_string(&v));
    1430            1 :         if (strlen(str2) == 0)
    1431            0 :             qof_instance_slot_delete (QOF_INSTANCE (account), "notes");
    1432            1 :         g_free(str2);
    1433              :     }
    1434              : 
    1435          455 :     qof_instance_get_kvp (QOF_INSTANCE (account), &v, 1, "placeholder");
    1436          455 :     if ((G_VALUE_HOLDS_STRING (&v) &&
    1437          910 :         strcmp(g_value_get_string (&v), "false") == 0) ||
    1438          455 :         (G_VALUE_HOLDS_BOOLEAN (&v) && ! g_value_get_boolean (&v)))
    1439            0 :         qof_instance_slot_delete (QOF_INSTANCE (account), "placeholder");
    1440              : 
    1441          455 :     g_value_unset (&v);
    1442          455 :     qof_instance_slot_delete_if_empty (QOF_INSTANCE (account), "hbci");
    1443          455 :     scrub_depth--;
    1444              : }
    1445              : 
    1446              : /* ================================================================ */
    1447              : 
    1448              : void
    1449            0 : xaccAccountScrubColorNotSet (QofBook *book)
    1450              : {
    1451            0 :     GValue value_s = G_VALUE_INIT;
    1452              :     gboolean already_scrubbed;
    1453              : 
    1454              :     // get the run-once value
    1455            0 :     qof_instance_get_kvp (QOF_INSTANCE (book), &value_s, 1, "remove-color-not-set-slots");
    1456              : 
    1457            0 :     already_scrubbed = (G_VALUE_HOLDS_STRING (&value_s) &&
    1458            0 :                         !g_strcmp0 (g_value_get_string (&value_s), "true"));
    1459            0 :     g_value_unset (&value_s);
    1460              : 
    1461            0 :     if (already_scrubbed)
    1462            0 :         return;
    1463              :     else
    1464              :     {
    1465            0 :         GValue value_b = G_VALUE_INIT;
    1466            0 :         Account *root = gnc_book_get_root_account (book);
    1467            0 :         GList *accts = gnc_account_get_descendants_sorted (root);
    1468              :         GList *ptr;
    1469              : 
    1470            0 :         for (ptr = accts; ptr; ptr = g_list_next (ptr))
    1471              :         {
    1472            0 :             auto acct = GNC_ACCOUNT(ptr->data);
    1473            0 :             auto color = xaccAccountGetColor (acct);
    1474              : 
    1475            0 :             if (g_strcmp0 (color, "Not Set") == 0)
    1476            0 :                 xaccAccountSetColor (acct, "");
    1477              :         }
    1478            0 :         g_list_free (accts);
    1479              : 
    1480            0 :         g_value_init (&value_b, G_TYPE_BOOLEAN);
    1481            0 :         g_value_set_boolean (&value_b, TRUE);
    1482              : 
    1483              :         // set the run-once value
    1484            0 :         qof_instance_set_kvp (QOF_INSTANCE (book),  &value_b, 1, "remove-color-not-set-slots");
    1485            0 :         g_value_unset (&value_b);
    1486              :     }
    1487              : }
    1488              : 
    1489              : /* ================================================================ */
    1490              : 
    1491              : static Account*
    1492           83 : construct_account (Account *root, gnc_commodity *currency, const char *accname,
    1493              :                    GNCAccountType acctype, gboolean placeholder)
    1494              : {
    1495           83 :     gnc_commodity* root_currency = find_root_currency ();
    1496           83 :     Account *acc = xaccMallocAccount(gnc_account_get_book (root));
    1497           83 :     xaccAccountBeginEdit (acc);
    1498           83 :     if (accname && *accname)
    1499           83 :          xaccAccountSetName (acc, accname);
    1500           83 :     if (currency || root_currency)
    1501           83 :          xaccAccountSetCommodity (acc, currency ? currency : root_currency);
    1502           83 :     xaccAccountSetType (acc, acctype);
    1503           83 :     xaccAccountSetPlaceholder (acc, placeholder);
    1504              : 
    1505              :     /* Hang the account off the root. */
    1506           83 :     gnc_account_append_child (root, acc);
    1507           83 :     xaccAccountCommitEdit (acc);
    1508           83 :     return acc;
    1509              : }
    1510              : 
    1511              : static Account*
    1512            0 : find_root_currency_account_in_list (GList *acc_list)
    1513              : {
    1514            0 :     gnc_commodity* root_currency = find_root_currency();
    1515            0 :     for (GList *node = acc_list; node; node = g_list_next (node))
    1516              :     {
    1517            0 :         Account *acc = GNC_ACCOUNT (node->data);
    1518            0 :         gnc_commodity *acc_commodity = nullptr;
    1519            0 :         if (G_UNLIKELY (!acc)) continue;
    1520            0 :         acc_commodity = xaccAccountGetCommodity(acc);
    1521            0 :         if (gnc_commodity_equiv (acc_commodity, root_currency))
    1522            0 :             return acc;
    1523              :     }
    1524              : 
    1525            0 :     return nullptr;
    1526              : }
    1527              : 
    1528              : static Account*
    1529            0 : find_account_matching_name_in_list (GList *acc_list, const char* accname)
    1530              : {
    1531            0 :     for (GList* node = acc_list; node; node = g_list_next(node))
    1532              :     {
    1533            0 :         Account *acc = GNC_ACCOUNT (node->data);
    1534            0 :         if (G_UNLIKELY (!acc)) continue;
    1535            0 :         if (g_strcmp0 (accname, xaccAccountGetName (acc)) == 0)
    1536            0 :             return acc;
    1537              :     }
    1538            0 :     return nullptr;
    1539              : }
    1540              : 
    1541              : Account *
    1542          108 : xaccScrubUtilityGetOrMakeAccount (Account *root, gnc_commodity * currency,
    1543              :                                   const char *accname, GNCAccountType acctype,
    1544              :                                   gboolean placeholder, gboolean checkname)
    1545              : {
    1546              :     GList* acc_list;
    1547          108 :     Account *acc = nullptr;
    1548              : 
    1549          108 :     g_return_val_if_fail (root, nullptr);
    1550              : 
    1551              :     acc_list =
    1552          108 :         gnc_account_lookup_by_type_and_commodity (root,
    1553              :                                                   checkname ? accname : nullptr,
    1554              :                                                   acctype, currency);
    1555              : 
    1556          108 :     if (!acc_list)
    1557           83 :         return construct_account (root, currency, accname,
    1558           83 :                                   acctype, placeholder);
    1559              : 
    1560           25 :     if (g_list_next(acc_list))
    1561              :     {
    1562            0 :         if (!currency)
    1563            0 :             acc = find_root_currency_account_in_list (acc_list);
    1564              : 
    1565            0 :         if (!acc)
    1566            0 :             acc = find_account_matching_name_in_list (acc_list, accname);
    1567              :     }
    1568              : 
    1569           25 :     if (!acc)
    1570           25 :         acc = GNC_ACCOUNT (acc_list->data);
    1571              : 
    1572           25 :     g_list_free (acc_list);
    1573           25 :     return acc;
    1574              : }
    1575              : 
    1576              : void
    1577          791 : xaccTransScrubPostedDate (Transaction *trans)
    1578              : {
    1579          791 :     time64 orig = xaccTransGetDate(trans);
    1580          791 :     if(orig == INT64_MAX)
    1581              :     {
    1582            0 :         GDate date = xaccTransGetDatePostedGDate(trans);
    1583            0 :         time64 time = gdate_to_time64(date);
    1584            0 :         if(time != INT64_MAX)
    1585              :         {
    1586              :             // xaccTransSetDatePostedSecs handles committing the change.
    1587            0 :             xaccTransSetDatePostedSecs(trans, time);
    1588              :         }
    1589              :     }
    1590          791 : }
    1591              : 
    1592              : /* ==================== END OF FILE ==================== */
        

Generated by: LCOV version 2.0-1