Example #1
0
static GtkWidget *
create_taxtable_widget (GNCOption *option, GtkWidget *hbox)
{
    GtkWidget *widget;
    GtkBuilder *builder;

    builder = gtk_builder_new();
    gnc_builder_add_from_file (builder, "business-options-gnome.glade", "taxtable_store");
    gnc_builder_add_from_file (builder, "business-options-gnome.glade", "taxtable_menu");

    widget = GTK_WIDGET (gtk_builder_get_object (builder, "taxtable_menu"));
    gnc_taxtables_combo (GTK_COMBO_BOX(widget), gnc_get_current_book (), TRUE, NULL);
    gtk_box_pack_start (GTK_BOX (hbox), widget, FALSE, FALSE, 0);

    gnc_option_set_widget (option, widget);

    g_signal_connect (widget, "changed",
                      G_CALLBACK (gnc_option_changed_option_cb), option);

    g_object_unref(G_OBJECT(builder));
    return widget;
}
Example #2
0
void
dai_match_page_prepare_cb(GnomeDruidPage *druid_page, GtkWidget *widget,
                          gpointer user_data)
{
    ABInitialInfo *info = user_data;
    Account *root;
    AccCbData data;

    g_return_if_fail(info && info->api);

    /* No way back */
    gnome_druid_set_buttons_sensitive(GNOME_DRUID(info->druid),
                                      FALSE, TRUE, TRUE, TRUE);

    /* Do not run this twice */
    if (info->match_page_prepared)
        return;
    else
        info->match_page_prepared = TRUE;

    /* Load aqbanking accounts */
#ifdef AQBANKING_VERSION_4_PLUS
    AB_Banking_OnlineInit(info->api, 0);
#else
    AB_Banking_OnlineInit(info->api);
#endif

    /* Determine current mapping */
    root = gnc_book_get_root_account(gnc_get_current_book());
    info->gnc_hash = g_hash_table_new(&g_direct_hash, &g_direct_equal);
    data.api = info->api;
    data.hash = info->gnc_hash;
    gnc_account_foreach_descendant(
        root, (AccountCb) hash_from_kvp_acc_cb, &data);

    /* Update the graphical representation */
    update_account_list(info);
}
Example #3
0
static gboolean
validate_type(const char *url_type, const char *location,
              const char *entity_type, GNCURLResult *result,
              GncGUID *guid, QofInstance **entity)
{
    QofCollection *col;
    QofBook     * book = gnc_get_current_book();
    if (!string_to_guid (location + strlen(url_type), guid))
    {
        result->error_message = g_strdup_printf (_("Bad URL: %s"), location);
        return FALSE;
    }
    col = qof_book_get_collection (book, entity_type);
    *entity = qof_collection_lookup_entity (col, guid);
    if (NULL == *entity)
    {
        result->error_message = g_strdup_printf (_("Entity Not Found: %s"),
                                location);
        return FALSE;
    }

    return TRUE;
}
Example #4
0
/* Get the rate from the price db */
static gnc_numeric
gtu_sr_get_rate_from_db (gnc_commodity *from, gnc_commodity *to)
{
    GNCPrice *prc;
    gnc_numeric rate_split;
    gboolean have_rate = FALSE;
    QofBook *book = gnc_get_current_book ();

    /* Do we have a rate allready */
    prc = gnc_pricedb_lookup_latest (gnc_pricedb_get_db (book), from, to);
    if (prc)
    {
        rate_split = gnc_price_get_value (prc);
        gnc_price_unref (prc);
        have_rate = TRUE;
    }

    /* Lets try reversing the commodities */
    if (!have_rate)
    {
        prc = gnc_pricedb_lookup_latest (gnc_pricedb_get_db (book), to, from);
        if (prc)
        {
            rate_split = gnc_numeric_div (gnc_numeric_create (100, 100), gnc_price_get_value (prc),
                                 GNC_DENOM_AUTO, GNC_HOW_DENOM_REDUCE);

            gnc_price_unref (prc);
            have_rate = TRUE;
        }
    }

    /* No rate, set to 1/1 */
    if (!have_rate)
        rate_split = gnc_numeric_create (100, 100);

    return rate_split;
}
void
gnc_sx_create_from_trans( Transaction *trans )
{
    int errno;
    SXFromTransInfo *sxfti = g_new0( SXFromTransInfo, 1);

    sxfti->gxml = gnc_glade_xml_new(SX_GLADE_FILE,
                                    SXFTD_DIALOG_GLADE_NAME);

    sxfti->dialog = glade_xml_get_widget(sxfti->gxml,
                                         SXFTD_DIALOG_GLADE_NAME);

    sxfti->trans = trans;

    sxfti->sx = xaccSchedXactionMalloc(gnc_get_current_book ());

    if ( (errno = sxftd_init( sxfti )) < 0 )
    {
        if ( errno == SXFTD_ERRNO_OPEN_XACTION )
        {
            gnc_error_dialog( gnc_ui_get_toplevel(), "%s",
                              _( "Cannot create a Scheduled Transaction "
                                 "from a Transaction currently "
                                 "being edited. Please Enter the "
                                 "Transaction before Scheduling." ) );
            sxftd_close( sxfti, TRUE );
            return;
        }
        else
        {
            g_error("sxftd_init: %d", errno);
        }
    }

    gtk_widget_show_all(GTK_WIDGET(sxfti->dialog));
}
GncSxInstanceModel*
gnc_sx_get_instances(GDate *range_end, gboolean include_disabled)
{
    GList *all_sxes = gnc_book_get_schedxactions(gnc_get_current_book())->sx_list;
    GncSxInstanceModel *instances;

    g_assert(range_end != NULL);
    g_assert(g_date_valid(range_end));

    instances = gnc_sx_instance_model_new();
    instances->include_disabled = include_disabled;
    instances->range_end = *range_end;

    if (include_disabled)
    {
        instances->sx_instance_list = gnc_g_list_map(all_sxes, (GncGMapFunc)_gnc_sx_gen_instances, range_end);
    }
    else
    {
        GList *sx_iter = g_list_first(all_sxes);
        GList *enabled_sxes = NULL;

        for (; sx_iter != NULL; sx_iter = sx_iter->next)
        {
            SchedXaction *sx = (SchedXaction*)sx_iter->data;
            if (xaccSchedXactionGetEnabled(sx))
            {
                enabled_sxes = g_list_append(enabled_sxes, sx);
            }
        }
        instances->sx_instance_list = gnc_g_list_map(enabled_sxes, (GncGMapFunc)_gnc_sx_gen_instances, range_end);
        g_list_free(enabled_sxes);
    }

    return instances;
}
static void
gnc_plugin_page_sx_list_init (GncPluginPageSxList *plugin_page)
{
    GtkActionGroup *action_group;
    GncPluginPage *parent;

    /* Init parent declared variables */
    parent = GNC_PLUGIN_PAGE(plugin_page);
    g_object_set(G_OBJECT(plugin_page),
                 "page-name",      _("Scheduled Transactions"),
                 "page-uri",       "default:",
                 "ui-description", "gnc-plugin-page-sx-list-ui.xml",
                 NULL);

    gnc_plugin_page_add_book(parent, gnc_get_current_book());
    action_group =
        gnc_plugin_page_create_action_group(parent,
                                            "GncPluginPageSxListActions");
    gtk_action_group_add_actions(action_group,
                                 gnc_plugin_page_sx_list_actions,
                                 gnc_plugin_page_sx_list_n_actions,
                                 plugin_page);
    /* gnc_plugin_init_short_names (action_group, toolbar_labels); */
}
Example #8
0
void
ap_assistant_book_prepare (GtkAssistant *assistant, gpointer user_data)
{
    QofBook *currbook;
    char close_date_str[MAX_DATE_LENGTH];
    char prev_close_date_str[MAX_DATE_LENGTH];
    const char *period_text;
    char *str;
    const char *cstr;
    int ntrans, nacc;
    GtkTextBuffer *buffer;

    AcctPeriodInfo *info = user_data;

    ENTER ("info=%p", info);

    /* Tell user about how the previous book closing went. */
    cstr = get_close_status_str (info);
    gtk_label_set_text (GTK_LABEL(info->close_results), cstr);
    info->close_status = -1;

    /* Pull info from widget, push into freq spec */
    //gnc_frequency_save_state (info->period_menu, info->period, &info->closing_date);
    recurrenceListFree(&info->period);
    gnc_frequency_save_to_recurrence(info->period_menu, &info->period, &info->closing_date);

    qof_print_date_dmy_buff (close_date_str, MAX_DATE_LENGTH,
                             g_date_get_day(&info->closing_date),
                             g_date_get_month(&info->closing_date),
                             g_date_get_year(&info->closing_date));

    currbook = gnc_get_current_book();
    ntrans = get_num_xactions_before_date(currbook,
                                          gnc_time64_get_day_end_gdate (&info->closing_date));

    nacc = gnc_account_n_descendants (gnc_book_get_root_account (currbook));

    /* Display the book info */

    period_text =
	/* Translators: Run the assistent in your language to see GTK's translation of the button labels. */
        _("You have asked for a book to be created. This book "
          "will contain all transactions up to midnight %s "
          "(for a total of %d transactions spread over %d accounts).\n\n "
          "Amend the Title and Notes or Click on \"Next\" to proceed.\n "
          "Click on \"Back\" to adjust the dates or \"Cancel\".");
    str = g_strdup_printf (period_text, close_date_str, ntrans, nacc);
    gtk_label_set_text (GTK_LABEL(info->book_details), str);
    g_free (str);

    gtk_widget_show (GTK_WIDGET (info->book_details));

    /* Create default settings for the title, notes fields */
    qof_print_date_dmy_buff (prev_close_date_str, MAX_DATE_LENGTH,
                             g_date_get_day(&info->prev_closing_date),
                             g_date_get_month(&info->prev_closing_date),
                             g_date_get_year(&info->prev_closing_date));

    str = g_strdup_printf (_("Period %s - %s"), prev_close_date_str, close_date_str);
    gtk_entry_set_text (GTK_ENTRY(info->book_title), str);

    buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(info->book_notes));
    gtk_text_buffer_set_text(buffer, str, -1);

    g_free (str);
}
Example #9
0
void
ap_assistant_menu_prepare (GtkAssistant *assistant, gpointer user_data)
{
    int nperiods;
    GDate period_begin, period_end, date_now;
    char * str;

    AcctPeriodInfo *info = user_data;

    ENTER ("info=%p", info);

    /* Pull info from widget, push into freq spec */
    //gnc_frequency_save_state (info->period_menu, info->period, &info->closing_date);
    recurrenceListFree(&info->period);
    gnc_frequency_save_to_recurrence(info->period_menu, &info->period, &info->closing_date);

    /* Count the number of periods that would be generated. */
    g_date_clear (&period_begin, 1);
    g_date_clear (&period_end, 1);
    g_date_clear (&date_now, 1);
    nperiods = 0;
    period_end = info->closing_date;
    gnc_gdate_set_time64 (&date_now, gnc_time (NULL));

    while (0 > g_date_compare(&period_end, &date_now ))
    {
        nperiods ++;
        PINFO ("Period = %d and End date is %d/%d/%d", nperiods,
               g_date_get_month(&period_end),
               g_date_get_day(&period_end),
               g_date_get_year(&period_end));
        period_begin = period_end;
        recurrenceListNextInstance(info->period, &period_begin, &period_end);

        /* FIXME Check for valid period_end, not sure why it won't be!!! */
        if (g_date_valid (&period_end) != TRUE)
            break;
    }

    /* Find the date of the earliest transaction in the current book.
     * Note that this could have changed since last time, since
     * we may have closed books since last time. */
    info->earliest = get_earliest_in_book (gnc_get_current_book());
    info->earliest_str = qof_print_date(info->earliest);
    PINFO ("Date of earliest transaction is %" G_GINT64_FORMAT " %s",
	   info->earliest, gnc_ctime (&info->earliest));

    /* Display the results */
    str = g_strdup_printf (
              /* Translators: %s is a date string. %d is the number of books
               * that will be created. This is a ngettext(3) message (but
               * only for the %d part). */
              ngettext("The earliest transaction date found in this book is %s. "
                       "Based on the selection made above, this book will be split "
                       "into %d book.",
                       "The earliest transaction date found in this book is %s. "
                       "Based on the selection made above, this book will be split "
                       "into %d books.",
                       nperiods),
              info->earliest_str,
              nperiods);
    gtk_label_set_text (GTK_LABEL(info->period_remarks), str);
    g_free (str);
}
Example #10
0
//! \brief try to fix some common errors in the csv representation of invoices
//! * corrects the date format
//! * corrects ambigous values in multi line invoices
//! * ensures customer exists
//! * if quantity is unset, set to 1
//! * if price is unset, delete row
void
gnc_bi_import_fix_bis (GtkListStore * store, guint * fixed, guint * deleted,
                       GString * info, gchar *type)
{
    GtkTreeIter iter;
    gboolean valid, row_deleted, row_fixed;
    gchar *id, *date_opened, *date_posted, *owner_id, *date, *quantity, *price;
    GString *prev_id, *prev_date_opened, *prev_date_posted, *prev_owner_id, *prev_date;	// needed to fix multi line invoices
    guint dummy;

    // allow the call to this function with only GtkListeStore* specified
    if (!fixed)
        fixed = &dummy;
    if (!deleted)
        deleted = &dummy;

    *fixed = 0;
    *deleted = 0;

    // init strings
    prev_id = g_string_new ("");
    prev_date_opened = g_string_new ("");
    prev_date_posted = g_string_new ("");
    prev_owner_id = g_string_new ("");
    prev_date = g_string_new ("");

    valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (store), &iter);
    while (valid)
    {
        row_deleted = FALSE;
        row_fixed = FALSE;

        // Walk through the list, reading each row
        gtk_tree_model_get (GTK_TREE_MODEL (store), &iter,
                            ID, &id,
                            DATE_OPENED, &date_opened,
                            DATE_POSTED, &date_posted,
                            OWNER_ID, &owner_id,
                            DATE, &date,
                            QUANTITY, &quantity, PRICE, &price, -1);

        if (strlen (price) == 0)
        {
            // invalid row (no price given)
            // no fix possible -> delete row
            gtk_list_store_remove (store, &iter);
            row_deleted = TRUE;
            g_string_append_printf (info,
                                    _("ROW DELETED, PRICE_NOT_SET: id=%s\n"),
                                    id);
        }
        else if (strlen (quantity) == 0)
        {
            // invalid row (no quantity given)
            // no fix possible -> delete row
            gtk_list_store_remove (store, &iter);
            row_deleted = TRUE;
            g_string_append_printf (info, _("ROW DELETED, QTY_NOT_SET: id=%s\n"),
                                    id);
        }
        else
        {
            if (strlen (id) == 0)
            {
                // no invoice id specified
                if (prev_id->len == 0)
                {
                    // cannot fix -> delete row
                    gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW DELETED, ID_NOT_SET\n"));
                }
                else
                {
                    // this is a fixable multi line invoice
                    gtk_list_store_set (store, &iter, ID, prev_id->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember invoice id (to be able to fix multi line invoices)
                g_string_assign (prev_id, id);
                // new invoice => reset all other fixable entries
                g_string_assign (prev_date_opened, "");
                g_string_assign (prev_date_posted, "");
                g_string_assign (prev_owner_id, "");
                g_string_assign (prev_date, "");
            }
        }

        if (!row_deleted)
        {
            // the row is valid (price and id are valid)

            if (strlen (date_opened) == 0)
            {
                if (prev_date_opened->len == 0)
                {
                    // fix this by using the current date (why is this so complicated?)
                    gchar temp[20];
                    GDate *date;
                    time_t secs;
                    struct tm now;
                    time (&secs);
                    localtime_r (&secs, &now);
                    date =
                        g_date_new_dmy (now.tm_mday, now.tm_mon + 1,
                                        now.tm_year + 1900);
                    g_date_strftime (temp, 20, "%x", date);	// create a locale specific date string
                    g_string_assign (prev_date_opened, temp);
                    g_date_free (date);
                }
                // fix this by using the previous date_opened value (multi line invoice)
                gtk_list_store_set (store, &iter, DATE_OPENED,
                                    prev_date_opened->str, -1);
                row_fixed = TRUE;
            }
            else
            {
                // remember date_opened (to be able to fix multi line invoices)
                g_string_assign (prev_date_opened, date_opened);
            }

            // date_opened is valid

            if (strlen (date_posted) == 0)
            {
                if (prev_date_posted->len == 0)
                {
                    // this invoice will have to get posted manually
                }
                else
                {
                    // multi line invoice => fix it
                    gtk_list_store_set (store, &iter, DATE_POSTED,
                                        prev_date_posted->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember date_opened (to be able to fix multi line invoices)
                g_string_assign (prev_date_posted, date_posted);
            }

            // date_posted is valid

            if (strlen (quantity) == 0)
            {
                // quantity is unset => set to 1
                gtk_list_store_set (store, &iter, QUANTITY, "1", -1);
                row_fixed = TRUE;
            }

            // quantity is valid

            if (strlen (owner_id) == 0)
            {
                if (prev_owner_id->len == 0)
                {
                    // no customer given and not fixable => delete row
                    gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW DELETED, OWNER_NOT_SET: id=%s\n"),
                                            id);
                }
                else
                {
                    gtk_list_store_set (store, &iter, owner_id,
                                        prev_owner_id->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember owner_id
                g_string_assign (prev_owner_id, owner_id);
            }
            if (g_ascii_strcasecmp (type, "BILL") == 0)
            {
                // BILL: check, if vendor exists
                if (!gnc_search_vendor_on_id
                        (gnc_get_current_book (), prev_owner_id->str))
                {
                    // vendor not found => delete row
                    gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW DELETED, VENDOR_DOES_NOT_EXIST: id=%s\n"),
                                            id);
                }
            }
            else if (g_ascii_strcasecmp (type, "INVOICE") == 0)
            {
                // INVOICE: check, if customer exists
                if (!gnc_search_customer_on_id
                        (gnc_get_current_book (), prev_owner_id->str))
                {
                    // customer not found => delete row
                    gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW DELETED, CUSTOMER_DOES_NOT_EXIST: id=%s\n"),
                                            id);
                }
            }

            // owner_id is valid
        }

        g_free (id);
        g_free (date_opened);
        g_free (date_posted);
        g_free (owner_id);
        g_free (date);
        g_free (quantity);
        g_free (price);
        if (row_deleted)
        {
            (*deleted)++;
            // reset all remembered values
            g_string_assign (prev_id, "");
            g_string_assign (prev_date_opened, "");
            g_string_assign (prev_date_posted, "");
            g_string_assign (prev_owner_id, "");
            g_string_assign (prev_date, "");
        }
        else if (row_fixed)
            (*fixed)++;
        valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (store), &iter);
    }

    // deallocate strings
    g_string_free (prev_id, TRUE);
    g_string_free (prev_date_opened, TRUE);
    g_string_free (prev_date_posted, TRUE);
    g_string_free (prev_owner_id, TRUE);
    g_string_free (prev_date, TRUE);

    if (info && (info->len > 0))
    {
        g_string_prepend (info, "\n\n");
        g_string_prepend (info, _("These rows were deleted:"));
    }
}
Example #11
0
GtkWidget *
gnc_reconcile_view_new (Account *account, GNCReconcileViewType type,
                       time64 statement_date)
{
    GNCReconcileView *view;
    GtkListStore     *liststore;
    gboolean          include_children, auto_check;
    GList            *accounts = NULL;
    GList            *splits;
    Query            *query;

    g_return_val_if_fail (account, NULL);
    g_return_val_if_fail ((type == RECLIST_DEBIT) ||
                         (type == RECLIST_CREDIT), NULL);

    view = g_object_new (GNC_TYPE_RECONCILE_VIEW, NULL);

    /* Create the list store with 6 columns and add to treeview,
       column 0 will be a pointer to the entry */
    liststore = gtk_list_store_new (6, G_TYPE_POINTER, G_TYPE_STRING,
                G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING,  G_TYPE_BOOLEAN );
    gtk_tree_view_set_model (GTK_TREE_VIEW (view), GTK_TREE_MODEL (liststore));
    g_object_unref (liststore);

    view->account = account;
    view->view_type = type;
    view->statement_date = statement_date;

    query = qof_query_create_for (GNC_ID_SPLIT);
    qof_query_set_book (query, gnc_get_current_book ());

    include_children = xaccAccountGetReconcileChildrenStatus (account);
    if (include_children)
        accounts = gnc_account_get_descendants (account);

    /* match the account */
    accounts = g_list_prepend (accounts, account);

    xaccQueryAddAccountMatch (query, accounts, QOF_GUID_MATCH_ANY, QOF_QUERY_AND);

    g_list_free (accounts);

    /* limit the matches to CREDITs and DEBITs only, depending on the type */
    if (type == RECLIST_CREDIT)
        xaccQueryAddValueMatch(query, gnc_numeric_zero (),
                               QOF_NUMERIC_MATCH_CREDIT,
                               QOF_COMPARE_GTE, QOF_QUERY_AND);
    else
        xaccQueryAddValueMatch(query, gnc_numeric_zero (),
                               QOF_NUMERIC_MATCH_DEBIT,
                               QOF_COMPARE_GTE, QOF_QUERY_AND);

    /* limit the matches only to Cleared and Non-reconciled splits */
    xaccQueryAddClearedMatch (query, CLEARED_NO | CLEARED_CLEARED, QOF_QUERY_AND);

    /* Initialize the QueryList */
    gnc_reconcile_view_construct (view, query);

    /* find the list of splits to auto-reconcile */
    auto_check = gnc_prefs_get_bool (GNC_PREFS_GROUP_RECONCILE, GNC_PREF_CHECK_CLEARED);

    if (auto_check)
    {
        time64 statement_date_day_end = gnc_time64_get_day_end(statement_date);
        for (splits = qof_query_run (query); splits; splits = splits->next)
        {
            Split *split = splits->data;
            char recn = xaccSplitGetReconcile (split);
            time64 trans_date = xaccTransGetDate (xaccSplitGetParent (split));

            /* Just an extra verification that our query is correct ;) */
            g_assert (recn == NREC || recn == CREC);

            if (recn == CREC &&
        gnc_difftime (trans_date, statement_date_day_end) <= 0)
        g_hash_table_insert (view->reconciled, split, split);
        }
    }

    /* Free the query -- we don't need it anymore */
    qof_query_destroy (query);

    return GTK_WIDGET (view);
}
Example #12
0
static void
_gnc_sx_instance_event_handler(QofInstance *ent, QofEventId event_type, gpointer user_data, gpointer evt_data)
{
    GncSxInstanceModel *instances = GNC_SX_INSTANCE_MODEL(user_data);

    /* selection rules {
    //   (gnc_collection_get_schedxaction_list(book), GNC_EVENT_ITEM_ADDED)
    //   (gnc_collection_get_schedxaction_list(book), GNC_EVENT_ITEM_REMOVED)
    //   (GNC_IS_SX(ent), QOF_EVENT_MODIFIED)
    // } */
    if (!(GNC_IS_SX(ent) || GNC_IS_SXES(ent)))
        return;

    if (GNC_IS_SX(ent))
    {
        SchedXaction *sx;
        gboolean sx_is_in_model = FALSE;

        sx = GNC_SX(ent);
        // only send `updated` if it's actually in the model
        sx_is_in_model = (g_list_find_custom(instances->sx_instance_list, sx, (GCompareFunc)_gnc_sx_instance_find_by_sx) != NULL);
        if (event_type & QOF_EVENT_MODIFY)
        {
            if (sx_is_in_model)
            {
                if (instances->include_disabled || xaccSchedXactionGetEnabled(sx))
                {
                    g_signal_emit_by_name(instances, "updated", (gpointer)sx);
                }
                else
                {
                    /* the sx was enabled but is now disabled */
                    g_signal_emit_by_name(instances, "removing", (gpointer)sx);
                }
            }
            else
            {
                /* determine if this is a legitimate SX or just a "one-off" / being created */
                GList *all_sxes = gnc_book_get_schedxactions(gnc_get_current_book())->sx_list;
                if (g_list_find(all_sxes, sx) && (!instances->include_disabled && xaccSchedXactionGetEnabled(sx)))
                {
                    /* it's moved from disabled to enabled, add the instances */
                    instances->sx_instance_list
                    = g_list_append(instances->sx_instance_list,
                                    _gnc_sx_gen_instances((gpointer)sx, (gpointer) & instances->range_end));
                    g_signal_emit_by_name(instances, "added", (gpointer)sx);
                }
            }
        }
        /* else { unsupported event type; ignore } */
    }
    else if (GNC_IS_SXES(ent))
    {
        SchedXactions *sxes = GNC_SXES(ent);
        SchedXaction *sx = GNC_SX(evt_data);

        sxes = NULL;
        if (event_type & GNC_EVENT_ITEM_REMOVED)
        {
            GList *instances_link;
            instances_link = g_list_find_custom(instances->sx_instance_list, sx, (GCompareFunc)_gnc_sx_instance_find_by_sx);
            if (instances_link != NULL)
            {
                g_signal_emit_by_name(instances, "removing", (gpointer)sx);
            }
            else if (instances->include_disabled)
            {
                g_warning("could not remove instances that do not exist in the model");
            }
        }
        else if (event_type & GNC_EVENT_ITEM_ADDED)
        {
            if (instances->include_disabled || xaccSchedXactionGetEnabled(sx))
            {
                /* generate instances, add to instance list, emit update. */
                instances->sx_instance_list
                = g_list_append(instances->sx_instance_list,
                                _gnc_sx_gen_instances((gpointer)sx, (gpointer) & instances->range_end));
                g_signal_emit_by_name(instances, "added", (gpointer)sx);
            }
        }
        /* else { g_critical("unsupported event type [%d]\n", event_type); } */
    }
}
Example #13
0
/*******************************************************
 * Create the Assistant
 *******************************************************/
static GtkWidget *
csv_export_assistant_create (CsvExportInfo *info)
{
    GtkBuilder *builder;
    GtkWidget *window;
    GtkWidget *box, *h_box;
    GtkWidget *button;
    GtkWidget *table, *hbox;
    time64 start_time, end_time;

    builder = gtk_builder_new();
    gnc_builder_add_from_file  (builder , "assistant-csv-export.glade", "CSV Export Assistant");
    window = GTK_WIDGET(gtk_builder_get_object (builder, "CSV Export Assistant"));
    info->window = window;

    /* Set the assistant colors */
    gnc_assistant_set_colors (GTK_ASSISTANT (info->window));

    /* Load default settings */
    load_settings (info);

    /* Start Page */
    info->start_page = GTK_WIDGET(gtk_builder_get_object(builder, "start_page"));
    info->start_label = GTK_WIDGET(gtk_builder_get_object(builder, "start_label"));
    info->custom_entry = GTK_WIDGET(gtk_builder_get_object(builder, "custom_entry"));
    gtk_widget_set_sensitive (info->custom_entry, FALSE);

    /* Account Page */
    info->account_page = GTK_WIDGET(gtk_builder_get_object(builder, "account_page"));

    if (info->export_type == XML_EXPORT_TREE)
        gtk_widget_destroy (info->account_page);
    else
    {
        GtkTreeView *tree_view;
        GtkTreeSelection *selection;
        GtkWidget *box, *label;

        info->csva.acct_info = GTK_WIDGET(gtk_builder_get_object (builder, "acct_info_vbox"));
        info->csva.num_acct_label = GTK_WIDGET(gtk_builder_get_object (builder, "num_accounts_label"));

        tree_view = gnc_tree_view_account_new (FALSE);
        info->csva.account_treeview = GTK_WIDGET(tree_view);

        selection = gtk_tree_view_get_selection (tree_view);
        gtk_tree_selection_set_mode (selection, GTK_SELECTION_EXTENDED);
        g_signal_connect (G_OBJECT(selection), "changed",
                          G_CALLBACK(csv_export_account_changed_cb), info);

        gtk_widget_show (info->csva.account_treeview);
        box = GTK_WIDGET(gtk_builder_get_object (builder, "account_scroll"));
        gtk_container_add (GTK_CONTAINER(box), info->csva.account_treeview);

        label = GTK_WIDGET(gtk_builder_get_object (builder, "accounts_label"));
        gtk_label_set_mnemonic_widget (GTK_LABEL(label), GTK_WIDGET(tree_view));

        /* select subaccounts button */
        button = GTK_WIDGET(gtk_builder_get_object (builder, "select_subaccounts_button"));
        info->csva.select_button = button;

        g_signal_connect (G_OBJECT(button), "clicked",
                          G_CALLBACK(csv_export_select_subaccounts_clicked_cb), info);
        g_signal_connect (G_OBJECT(info->csva.account_treeview), "cursor_changed",
                          G_CALLBACK(csv_export_cursor_changed_cb), info);

        /* Set the date info */
        button = GTK_WIDGET(gtk_builder_get_object (builder, "show_range"));

        /* Earliest and Latest in Book */
        start_time = get_earliest_in_book (gnc_get_current_book());
        end_time = gnc_time (NULL);

        info->csvd.start_time = start_time;
        info->csvd.end_time = end_time;
        gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(button), FALSE);

        table = GTK_WIDGET(gtk_builder_get_object (builder, "select_range_table"));
        info->csvd.table = table;
        gtk_widget_set_sensitive (GTK_WIDGET(table), FALSE);

        info->csvd.start_date_choose = GTK_WIDGET(gtk_builder_get_object (builder, "start_date_choose"));
        info->csvd.start_date_today = GTK_WIDGET(gtk_builder_get_object (builder, "start_date_today"));
        info->csvd.end_date_choose = GTK_WIDGET(gtk_builder_get_object (builder, "end_date_choose"));
        info->csvd.end_date_today = GTK_WIDGET(gtk_builder_get_object (builder, "end_date_today"));

        /* Start date info */
        info->csvd.start_date = gnc_date_edit_new (gnc_time (NULL), FALSE, FALSE);
        hbox = GTK_WIDGET(gtk_builder_get_object (builder, "start_date_hbox"));
        gtk_box_pack_start (GTK_BOX(hbox), info->csvd.start_date, TRUE, TRUE, 0);
        gtk_widget_show (info->csvd.start_date);
        gnc_date_edit_set_time (GNC_DATE_EDIT(info->csvd.start_date), start_time);
        g_signal_connect (G_OBJECT(info->csvd.start_date), "date-changed",
                        G_CALLBACK(csv_export_date_changed_cb), info);

        /* End date info */
        info->csvd.end_date = gnc_date_edit_new (gnc_time (NULL), FALSE, FALSE);
        hbox = GTK_WIDGET(gtk_builder_get_object (builder, "end_date_hbox"));
        gtk_box_pack_start (GTK_BOX(hbox), info->csvd.end_date, TRUE, TRUE, 0);
        gtk_widget_show (info->csvd.end_date);
        gnc_date_edit_set_time (GNC_DATE_EDIT(info->csvd.end_date), end_time);
        g_signal_connect (G_OBJECT (info->csvd.end_date), "date-changed",
                        G_CALLBACK (csv_export_date_changed_cb), info);

        /* Load Accounts */
        show_acct_type_accounts (info);
        update_accounts_tree (info);
    }

    /* File chooser Page */
    info->file_page = GTK_WIDGET(gtk_builder_get_object(builder, "file_page"));
    info->file_chooser = gtk_file_chooser_widget_new (GTK_FILE_CHOOSER_ACTION_SAVE);
    button = gtk_button_new_from_stock (GTK_STOCK_OK);
    gtk_widget_set_size_request (button, 100, -1);
    gtk_widget_show (button);
    h_box = gtk_hbox_new (TRUE, 0);
    gtk_box_pack_start(GTK_BOX(h_box), button, FALSE, FALSE, 0);
    gtk_file_chooser_set_extra_widget (GTK_FILE_CHOOSER(info->file_chooser), h_box);
    g_signal_connect (G_OBJECT(button), "clicked",
                      G_CALLBACK(csv_export_file_chooser_confirm_cb), info);

    box = GTK_WIDGET(gtk_builder_get_object (builder, "file_page"));
    gtk_box_pack_start (GTK_BOX (box), info->file_chooser, TRUE, TRUE, 6);
    gtk_widget_show (info->file_chooser);

    /* Finish Page */
    info->finish_label = GTK_WIDGET(gtk_builder_get_object (builder, "end_page"));

    /* Summary Page */
    info->summary_label = GTK_WIDGET(gtk_builder_get_object (builder, "summary_page"));

    g_signal_connect (G_OBJECT(window), "destroy",
                      G_CALLBACK(csv_export_assistant_destroy_cb), info);

    gnc_restore_window_size (GNC_PREFS_GROUP, GTK_WINDOW(info->window));
    if (gnc_prefs_get_bool (GNC_PREFS_GROUP_GENERAL, GNC_PREF_SAVE_GEOMETRY))
    {
        GObject *object = gtk_builder_get_object (builder, "paned");
        gnc_prefs_bind (GNC_PREFS_GROUP, GNC_PREF_PANED_POS, object, "position");
    }

    gtk_builder_connect_signals (builder, info);
    g_object_unref (G_OBJECT(builder));
    return window;
}
Example #14
0
/** Create the preferences dialog.  This function first reads the
 *  dialog-preferences.glade file to obtain the content and then
 *  the dialog is created with a set of common preferences.  It then
 *  runs the list of add-ins, calling a helper function to add each full/partial
 *  page to this dialog, Finally it builds the "interesting widgets"
 *  table that is used for connecting the widgets up to callback functions.
 *
 *  @internal
 *
 *  @return A pointer to the newly created dialog.
 */
static GtkWidget *
gnc_preferences_dialog_create(void)
{
    GtkBuilder *builder;
    GtkWidget *dialog, *notebook, *label, *image;
    GtkWidget *box, *date, *period, *currency;
    GHashTable *prefs_table;
    GDate* gdate = NULL;
    gchar buf[128];
    GtkListStore *store;
    GtkTreePath *path;
    GtkTreeIter iter;
    gnc_commodity *locale_currency;
    const gchar *currency_name;
    QofBook *book;
    KvpFrame *book_frame;
    gint64 month, day;
    GDate fy_end;
    gboolean date_is_valid = FALSE;

    ENTER("");
    DEBUG("Opening dialog-preferences.glade:");
    builder = gtk_builder_new();

    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "auto_decimal_places_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "autosave_interval_minutes_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "save_on_close_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "date_backmonth_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "max_transactions_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "key_length_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "new_search_limit_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "retain_days_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "tab_width_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "date_formats");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "GnuCash Preferences");

    dialog = GTK_WIDGET(gtk_builder_get_object (builder, "GnuCash Preferences"));

#ifndef REGISTER2_ENABLED
    /* Hide preferences that are related to register2 */
    box = GTK_WIDGET (gtk_builder_get_object (builder, "label14"));
    gtk_widget_hide (box);
    box = GTK_WIDGET (gtk_builder_get_object (builder, "pref/general.register/key-length"));
    gtk_widget_hide (box);
    box = GTK_WIDGET (gtk_builder_get_object (builder, "pref/general.register/show-extra-dates"));
    gtk_widget_hide (box);
    box = GTK_WIDGET (gtk_builder_get_object (builder, "pref/general.register/show-calendar-buttons"));
    gtk_widget_hide (box);
    box = GTK_WIDGET (gtk_builder_get_object (builder, "pref/general.register/selection-to-blank-on-expand"));
    gtk_widget_hide (box);
    box = GTK_WIDGET (gtk_builder_get_object (builder, "pref/general.register/show-extra-dates-on-selection"));
    gtk_widget_hide (box);
#endif

    label = GTK_WIDGET(gtk_builder_get_object (builder, "sample_account"));
    g_object_set_data(G_OBJECT(dialog), "sample_account", label);

    image = GTK_WIDGET(gtk_builder_get_object (builder, "separator_error"));
    g_object_set_data(G_OBJECT(dialog), "separator_error", image);

    DEBUG("autoconnect");
    gtk_builder_connect_signals_full (builder, gnc_builder_connect_full_func, dialog);

    DEBUG("done");

    notebook = GTK_WIDGET(gtk_builder_get_object (builder, "notebook1"));
    prefs_table = g_hash_table_new(g_str_hash, g_str_equal);
    g_object_set_data(G_OBJECT(dialog), NOTEBOOK, notebook);
    g_object_set_data_full(G_OBJECT(dialog), PREFS_WIDGET_HASH,
                           prefs_table, (GDestroyNotify)g_hash_table_destroy);


    book = gnc_get_current_book();
    g_date_clear (&fy_end, 1);
    qof_instance_get (QOF_INSTANCE (book),
		      "fy-end", &fy_end,
		      NULL);
    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_ACCT_SUMMARY "/" GNC_PREF_START_PERIOD));
    period = gnc_period_select_new(TRUE);
    gtk_widget_show (period);
    gtk_box_pack_start (GTK_BOX (box), period, TRUE, TRUE, 0);
    if (date_is_valid)
        gnc_period_select_set_fy_end(GNC_PERIOD_SELECT (period), &fy_end);

    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_ACCT_SUMMARY "/" GNC_PREF_END_PERIOD));
    period = gnc_period_select_new(FALSE);
    gtk_widget_show (period);
    gtk_box_pack_start (GTK_BOX (box), period, TRUE, TRUE, 0);
    if (date_is_valid)
        gnc_period_select_set_fy_end(GNC_PERIOD_SELECT (period), &fy_end);

    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_ACCT_SUMMARY "/" GNC_PREF_START_DATE));
    date = gnc_date_edit_new(gnc_time (NULL), FALSE, FALSE);
    gtk_widget_show (date);
    gtk_box_pack_start (GTK_BOX (box), date, TRUE, TRUE, 0);

    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_ACCT_SUMMARY "/" GNC_PREF_END_DATE));
    date = gnc_date_edit_new(gnc_time (NULL), FALSE, FALSE);
    gtk_widget_show (date);
    gtk_box_pack_start (GTK_BOX (box), date, TRUE, TRUE, 0);

    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_GENERAL "/" GNC_PREF_CURRENCY_OTHER));
    currency = gnc_currency_edit_new();
    gnc_currency_edit_set_currency (GNC_CURRENCY_EDIT(currency), gnc_default_currency());
    gtk_widget_show (currency);
    gtk_box_pack_start(GTK_BOX (box), currency, TRUE, TRUE, 0);

    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_GENERAL_REPORT "/" GNC_PREF_CURRENCY_OTHER));
    currency = gnc_currency_edit_new();
    gnc_currency_edit_set_currency (GNC_CURRENCY_EDIT(currency), gnc_default_currency());
    gtk_widget_show (currency);
    gtk_box_pack_start(GTK_BOX (box), currency, TRUE, TRUE, 0);


    /* Add to the list of interesting widgets */
    gnc_prefs_build_widget_table(builder, dialog);

    g_slist_foreach(add_ins, gnc_preferences_build_page, dialog);

    /* Sort tabs alphabetically */
    gnc_prefs_sort_pages(GTK_NOTEBOOK(notebook));
    gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), 0);

    DEBUG("We have the following interesting widgets:");
    g_hash_table_foreach(prefs_table, (GHFunc)gnc_prefs_connect_one, dialog);
    DEBUG("Done with interesting widgets.");

    /* Other stuff */
    gdate = g_date_new_dmy(31, G_DATE_JULY, 2013);
    g_date_strftime(buf, sizeof(buf), "%x", gdate);
    store = GTK_LIST_STORE(gtk_builder_get_object (builder, "date_formats"));
    path = gtk_tree_path_new_from_indices (QOF_DATE_FORMAT_LOCALE, -1);
    if (gtk_tree_model_get_iter (GTK_TREE_MODEL (store), &iter, path))
            gtk_list_store_set (store, &iter, 1, buf, -1);
    g_date_free(gdate);

    locale_currency = gnc_locale_default_currency ();
    currency_name = gnc_commodity_get_printname(locale_currency);
    label = GTK_WIDGET(gtk_builder_get_object (builder, "locale_currency"));
    gtk_label_set_label(GTK_LABEL(label), currency_name);
    label = GTK_WIDGET(gtk_builder_get_object (builder, "locale_currency2"));
    gtk_label_set_label(GTK_LABEL(label), currency_name);

    g_object_unref(G_OBJECT(builder));

    LEAVE("dialog %p", dialog);
    return dialog;
}
Example #15
0
/*******************************************************
 * account_splits
 *
 * gather the splits / transactions for an account and
 * send them to a file
 *******************************************************/
static
void account_splits (CsvExportInfo *info, Account *acc, FILE *fh )
{
    Query   *q;
    GSList  *p1, *p2;
    GList   *splits;
    QofBook *book;

    gchar   *end_sep;
    gchar   *mid_sep;

    q = qof_query_create_for(GNC_ID_SPLIT);
    book = gnc_get_current_book();
    qof_query_set_book (q, book);

    /* Set up separators */
    if (info->use_quotes)
    {
        end_sep = "\"";
        mid_sep = g_strconcat ( "\"", info->separator_str, "\"", NULL);
    }
    else
    {
        end_sep = "";
        mid_sep = g_strconcat ( info->separator_str, NULL);
    }

    /* Sort by transaction date */
    p1 = g_slist_prepend (NULL, TRANS_DATE_POSTED);
    p1 = g_slist_prepend (p1, SPLIT_TRANS);
    p2 = g_slist_prepend (NULL, QUERY_DEFAULT_SORT);
    qof_query_set_sort_order (q, p1, p2, NULL);

    xaccQueryAddSingleAccountMatch (q, acc, QOF_QUERY_AND);
    xaccQueryAddDateMatchTT (q, TRUE, info->csvd.start_time, TRUE, info->csvd.end_time, QOF_QUERY_AND);

    /* Run the query */
    for (splits = qof_query_run(q); splits; splits = splits->next)
    {
        Split       *split;
        Transaction *trans;
        SplitList   *s_list;
        GList       *node;
        Split       *t_split;
        int          nSplits;
        int          cnt;
        gchar       *part1;
        gchar       *part2;
        gchar       *date;
        const gchar *currentSel;
        const gchar *split_amount;

        split = splits->data;
        trans = xaccSplitGetParent(split);
        nSplits = xaccTransCountSplits(trans);
        s_list = xaccTransGetSplitList(trans);

        /* Date */
        date = qof_print_date ( xaccTransGetDate(trans));
        part1 = g_strconcat ( end_sep, date, mid_sep, NULL);
        g_free(date);
        /* Name */
        currentSel = xaccAccountGetName(acc);
        part2 = g_strconcat ( part1, currentSel, mid_sep, NULL);
        g_free(part1);
        /* Number */
        currentSel = gnc_get_num_action(trans, NULL);
        part1 = g_strconcat ( part2, currentSel, mid_sep, NULL);
        g_free(part2);
        /* Description */
        currentSel = xaccTransGetDescription(trans);
        part2 = g_strconcat ( part1, currentSel, mid_sep, NULL);
        g_free(part1);
        /* Notes */
        currentSel = xaccTransGetNotes(trans);
        if (currentSel == NULL)
            part1 = g_strconcat ( part2, mid_sep, NULL);
        else
            part1 = g_strconcat ( part2, currentSel, mid_sep, NULL);
        g_free(part2);
        /* Memo */
        currentSel = xaccSplitGetMemo(split);
        part2 = g_strconcat ( part1, currentSel, mid_sep, NULL);
        g_free(part1);
        /* Category */
        currentSel = xaccSplitGetCorrAccountName(split);
        part1 = g_strconcat ( part2, currentSel, mid_sep, "T", mid_sep, NULL);
        g_free(part2);
        /* Action */
        currentSel =  gnc_get_num_action(NULL, split);
        part2 = g_strconcat ( part1, currentSel, mid_sep, NULL);
        g_free(part1);
        /* Reconcile */
        switch (xaccSplitGetReconcile (split))
        {
        case NREC:
            currentSel = "N";
            break;
        case CREC:
            currentSel = "C";
            break;
        case YREC:
            currentSel = "Y";
            break;
        case FREC:
            currentSel = "F";
            break;
        case VREC:
            currentSel = "V";
            break;
        default:
            currentSel = "N";
        }
        part1 = g_strconcat ( part2, currentSel, mid_sep, NULL);
        g_free(part2);
        /* To with Symbol */
        split_amount = xaccPrintAmount(xaccSplitGetAmount(split), gnc_split_amount_print_info(split, TRUE));
        part2 = g_strconcat ( part1, split_amount, mid_sep, NULL);
        g_free(part1);

        /* From with Symbol */
        part1 = g_strconcat ( part2, "", mid_sep, NULL);
        g_free(part2);

        /* To Number Only */
        split_amount = xaccPrintAmount(xaccSplitGetAmount(split), gnc_split_amount_print_info(split, FALSE));
        part2 = g_strconcat ( part1, split_amount, mid_sep, NULL);
        g_free(part1);

        /* From Number Only */
        part1 = g_strconcat ( part2, "", mid_sep, "", mid_sep, "", end_sep, "\n", NULL);
        g_free(part2);

        /* Write to file */
        if (!write_line_to_file(fh, part1))
        {
            info->failed = TRUE;
            break;
        }
        g_free(part1);

        /* Loop through the list of splits for the Transcation */
        node = s_list;
        cnt = 0;
        while ( (cnt < nSplits) && (info->failed == FALSE))
        {
            t_split = node->data;

            /* Start of line */
            part1 = g_strconcat ( end_sep, mid_sep, mid_sep, mid_sep, mid_sep, mid_sep, NULL);

            /* Memo */
            currentSel = xaccSplitGetMemo(t_split);
            part2 = g_strconcat ( part1, currentSel, mid_sep, NULL);
            g_free(part1);

            /* Account */
            currentSel = xaccAccountGetName( xaccSplitGetAccount(t_split));
            part1 = g_strconcat ( part2, currentSel, mid_sep, "S", mid_sep, NULL);
            g_free(part2);

            /* Action */
            currentSel = gnc_get_num_action(NULL, t_split);
            part2 = g_strconcat ( part1, currentSel, mid_sep, NULL);
            g_free(part1);

            /* Reconcile */
            switch (xaccSplitGetReconcile (split))
            {
            case NREC:
                currentSel = "N";
                break;
            case CREC:
                currentSel = "C";
                break;
            case YREC:
                currentSel = "Y";
                break;
            case FREC:
                currentSel = "F";
                break;
            case VREC:
                currentSel = "V";
                break;
            default:
                currentSel = "N";
            }
            part1 = g_strconcat ( part2, currentSel, mid_sep, NULL);
            g_free(part2);

            /* From / To with Symbol */
            split_amount = xaccPrintAmount(xaccSplitGetAmount(t_split), gnc_split_amount_print_info(t_split, TRUE));
            if (xaccSplitGetAccount(t_split) == acc)
                part2 = g_strconcat ( part1,  split_amount, mid_sep, mid_sep, NULL);
            else
                part2 = g_strconcat ( part1, mid_sep, split_amount, mid_sep, NULL);
            g_free(part1);

            /* From / To Numbers only */
            split_amount = xaccPrintAmount(xaccSplitGetAmount(t_split), gnc_split_amount_print_info(t_split, FALSE));
            if (xaccSplitGetAccount(t_split) == acc)
                part1 = g_strconcat ( part2,  split_amount, mid_sep, mid_sep, NULL);
            else
                part1 = g_strconcat ( part2, mid_sep, split_amount, mid_sep, NULL);
            g_free(part2);

            /* From / To - Share Price / Conversion factor */
            split_amount = xaccPrintAmount(xaccSplitGetSharePrice(t_split), gnc_split_amount_print_info(t_split, FALSE));
            if (xaccSplitGetAccount(t_split) == acc)
                part2 = g_strconcat ( part1,  split_amount, mid_sep, end_sep, "\n", NULL);
            else
                part2 = g_strconcat ( part1, mid_sep, split_amount, end_sep, "\n", NULL);
            g_free(part1);

            if (!write_line_to_file(fh, part2))
                info->failed = TRUE;

            g_free(part2);
            cnt++;
            node = node->next;
        }
    }
    g_free(mid_sep);
    qof_query_destroy (q);
    g_list_free( splits );
}
Example #16
0
static gint
_get_vars_helper(Transaction *txn, void *var_hash_data)
{
    GHashTable *var_hash = (GHashTable*)var_hash_data;
    GList *split_list;
    kvp_frame *kvpf;
    kvp_value *kvp_val;
    Split *s;
    char *str;
    gnc_commodity *first_cmdty = NULL;

    split_list = xaccTransGetSplitList(txn);
    if (split_list == NULL)
    {
        return 1;
    }

    for ( ; split_list; split_list = split_list->next)
    {
        gnc_commodity *split_cmdty = NULL;
        GncGUID *acct_guid;
        Account *acct;

        s = (Split*)split_list->data;
        kvpf = xaccSplitGetSlots(s);
        kvp_val = kvp_frame_get_slot_path(kvpf,
                                          GNC_SX_ID,
                                          GNC_SX_ACCOUNT,
                                          NULL);
        acct_guid = kvp_value_get_guid(kvp_val);
        acct = xaccAccountLookup(acct_guid, gnc_get_current_book());
        split_cmdty = xaccAccountGetCommodity(acct);
        if (first_cmdty == NULL)
        {
            first_cmdty = split_cmdty;
        }

        if (! gnc_commodity_equal(split_cmdty, first_cmdty))
        {
            GncSxVariable *var;
            GString *var_name;
            const gchar *split_mnemonic, *first_mnemonic;

            var_name = g_string_sized_new(16);
            split_mnemonic = gnc_commodity_get_mnemonic(split_cmdty);
            first_mnemonic = gnc_commodity_get_mnemonic(first_cmdty);
            g_string_printf(var_name, "%s -> %s",
                            split_mnemonic ? split_mnemonic : "(null)",
                            first_mnemonic ? first_mnemonic : "(null)");
            var = gnc_sx_variable_new(g_strdup(var_name->str));
            g_hash_table_insert(var_hash, g_strdup(var->name), var);
            g_string_free(var_name, TRUE);
        }

        // existing... ------------------------------------------
        kvp_val = kvp_frame_get_slot_path(kvpf,
                                          GNC_SX_ID,
                                          GNC_SX_CREDIT_FORMULA,
                                          NULL);
        if (kvp_val != NULL)
        {
            str = kvp_value_get_string(kvp_val);
            if (str && strlen(str) != 0)
            {
                gnc_sx_parse_vars_from_formula(str, var_hash, NULL);
            }
        }

        kvp_val = kvp_frame_get_slot_path(kvpf,
                                          GNC_SX_ID,
                                          GNC_SX_DEBIT_FORMULA,
                                          NULL);
        if (kvp_val != NULL)
        {
            str = kvp_value_get_string(kvp_val);
            if (str && strlen(str) != 0)
            {
                gnc_sx_parse_vars_from_formula(str, var_hash, NULL);
            }
        }
    }

    return 0;
}
Example #17
0
static gboolean
gnc_html_register_url_cb (const char *location, const char *label,
                          gboolean new_window, GNCURLResult *result)
{
    GncPluginPage *page = NULL;
    GNCSplitReg * gsr   = NULL;
    Split       * split = NULL;
    Account     * account = NULL;
    Transaction * trans;
    GList       * node;
    QofBook     * book = gnc_get_current_book();
    GncGUID       guid;
    QofInstance * entity = NULL;

    g_return_val_if_fail (location != NULL, FALSE);
    g_return_val_if_fail (result != NULL, FALSE);

    result->load_to_stream = FALSE;

    /* href="gnc-register:account=My Bank Account" */
    if (strncmp("account=", location, 8) == 0)
    {
        account = gnc_account_lookup_by_full_name (gnc_get_current_root_account (),
                  location + 8);
    }

    /* href="gnc-register:guid=12345678901234567890123456789012" */
    else if (strncmp ("acct-guid=", location, strlen ("acct-guid=")) == 0)
    {
        if (!validate_type("acct-guid=", location, GNC_ID_ACCOUNT, result, &guid, &entity))
            return FALSE;

        account = GNC_ACCOUNT(entity);
    }

    else if (strncmp ("trans-guid=", location, strlen ("trans-guid=")) == 0)
    {
        if (!validate_type("trans-guid=", location, GNC_ID_TRANS, result, &guid, &entity))
            return FALSE;

        trans = (Transaction *) entity;

        for (node = xaccTransGetSplitList (trans); node; node = node->next)
        {
            split = node->data;
            account = xaccSplitGetAccount(split);
            if (account) break;
        }

        if (!account)
        {
            result->error_message =
                g_strdup_printf (_("Transaction with no Accounts: %s"), location);
            return FALSE;
        }
    }

    else if (strncmp ("split-guid=", location, strlen ("split-guid=")) == 0)
    {
        if (!validate_type("split-guid=", location, GNC_ID_SPLIT, result, &guid, &entity))
            return FALSE;

        split = (Split *) entity;
        account = xaccSplitGetAccount(split);
    }
    else
    {
        result->error_message =
            g_strdup_printf (_("Unsupported entity type: %s"), location);
        return FALSE;
    }

    page = gnc_plugin_page_register_new (account, FALSE);
    gnc_main_window_open_page (NULL, page);
    if (split)
    {
        gsr = gnc_plugin_page_register_get_gsr(page);
        gnc_split_reg_jump_to_split( gsr, split );
    }

    return TRUE;
}
Example #18
0
void GncPriceImport::create_price (std::vector<parse_line_t>::iterator& parsed_line)
{
    StrVec line;
    std::string error_message;
    std::shared_ptr<GncImportPrice> price_props = nullptr;
    bool skip_line = false;
    std::tie(line, error_message, price_props, skip_line) = *parsed_line;

    if (skip_line)
        return;

    error_message.clear();

    // Add a TO_CURRENCY property with the selected 'currency to' if no 'currency to' column was set by the user
    auto line_to_currency = price_props->get_to_currency();
    if (!line_to_currency)
    {
        if (m_settings.m_to_currency)
            price_props->set_to_currency(m_settings.m_to_currency);
        else
        {
            // Oops - the user didn't select a 'currency to' column *and* we didn't get a selected value either!
            // Note if you get here this suggests a bug in the code!
            error_message = _("No 'Currency to' column selected and no selected Currency specified either.\n"
                                       "This should never happen. Please report this as a bug.");
            PINFO("User warning: %s", error_message.c_str());
            throw std::invalid_argument(error_message);
        }
    }

    // Add a FROM_COMMODITY property with the selected 'commodity from' if no 'commodity from' column was set by the user
    auto line_from_commodity = price_props->get_from_commodity();
    if (!line_from_commodity)
    {
        if (m_settings.m_from_commodity)
            price_props->set_from_commodity(m_settings.m_from_commodity);
        else
        {
            // Oops - the user didn't select a 'commodity from' column *and* we didn't get a selected value either!
            // Note if you get here this suggests a bug in the code!
            error_message = _("No 'Commodity from' column selected and no selected Commodity specified either.\n"
                                       "This should never happen. Please report this as a bug.");
            PINFO("User warning: %s", error_message.c_str());
            throw std::invalid_argument(error_message);
        }
    }

    /* If column parsing was successful, convert price properties into a price. */
    try
    {
        price_properties_verify_essentials (parsed_line);

        QofBook* book = gnc_get_current_book();
        GNCPriceDB *pdb = gnc_pricedb_get_db (book);

        /* If all went well, add this price to the list. */
        auto price_created = price_props->create_price (book, pdb, m_over_write);
        if (price_created == ADDED)
            m_prices_added++;
        else if (price_created == DUPLICATED)
            m_prices_duplicated++;
        else if (price_created == REPLACED)
            m_prices_replaced++;
    }
    catch (const std::invalid_argument& e)
    {
        error_message = e.what();
        PINFO("User warning: %s", error_message.c_str());
    }
}
Example #19
0
static void
gnc_plugin_business_cmd_test_init_data (GtkAction *action,
                                        GncMainWindowActionData *data)
{
    QofBook *book       = gnc_get_current_book();
    GncCustomer *customer   = gncCustomerCreate(book);
    GncAddress *address = gncCustomerGetAddr(customer);
    GncInvoice *invoice = gncInvoiceCreate(book);
    GncOwner *owner     = gncOwnerNew();
    GncJob *job         = gncJobCreate(book);
    Account *root       = gnc_book_get_root_account(book);
    Account *inc_acct   = xaccMallocAccount(book);
    Account *bank_acct  = xaccMallocAccount(book);
    Account *tax_acct   = xaccMallocAccount(book);
    Account *ar_acct    = xaccMallocAccount(book);
    Timespec now;

    // Create Customer
    gncCustomerSetID(customer, "000001");
    gncCustomerSetName(customer, "Test Customer");
    gncCustomerSetCurrency(customer, gnc_default_currency());
    gncAddressSetName(address, "Contact Person");
    gncAddressSetAddr1(address, "20 Customer Lane");
    gncAddressSetAddr2(address, "Customer M/S");
    gncAddressSetAddr3(address, "Addr3, XXX  12345");

    // Create the Owner
    gncOwnerInitCustomer(owner, customer);

    // Create the Invoice
    timespecFromTime64(&now, time(NULL));
    gncInvoiceSetID(invoice, "000012");
    gncInvoiceSetOwner(invoice, owner);
    gncInvoiceSetDateOpened(invoice, now);
    gncInvoiceSetCurrency(invoice, gnc_default_currency());

    // Create the Job
    gncJobSetID(job, "000025");
    gncJobSetName(job, "Test Job");
    gncJobSetReference(job, "Customer's ref#");
    gncJobSetOwner(job, owner);

    // MODIFY THE OWNER
    gncOwnerInitJob(owner, job);

    // Create the A/R account
    xaccAccountSetType(ar_acct, ACCT_TYPE_RECEIVABLE);
    xaccAccountSetName(ar_acct, "A/R");
    xaccAccountSetCommodity(ar_acct, gnc_default_currency());
    gnc_account_append_child(root, ar_acct);

    // Create the Income account
    xaccAccountSetType(inc_acct, ACCT_TYPE_INCOME);
    xaccAccountSetName(inc_acct, "Income");
    xaccAccountSetCommodity(inc_acct, gnc_default_currency());
    gnc_account_append_child(root, inc_acct);

    // Create the Bank account
    xaccAccountSetType(bank_acct, ACCT_TYPE_BANK);
    xaccAccountSetName(bank_acct, "Bank");
    xaccAccountSetCommodity(bank_acct, gnc_default_currency());
    gnc_account_append_child(root, bank_acct);

    // Create the Tax account
    xaccAccountSetType(tax_acct, ACCT_TYPE_LIABILITY);
    xaccAccountSetName(tax_acct, "Tax-Holding");
    xaccAccountSetCommodity(tax_acct, gnc_default_currency());
    gnc_account_append_child(root, tax_acct);

    // Launch the invoice editor
    gnc_ui_invoice_edit (GTK_WINDOW (data->window), invoice);
}
Example #20
0
static GtkWidget *
ap_assistant_create (AcctPeriodInfo *info)
{
    GtkBuilder *builder;
    GtkWidget *window;
    GtkWidget *box;

    builder = gtk_builder_new();
    gnc_builder_add_from_file  (builder , "assistant-acct-period.glade", "account_period_assistant");
    window = GTK_WIDGET(gtk_builder_get_object (builder, "account_period_assistant"));
    info->window = window;

    // Set the style context for this assistant so it can be easily manipulated with css
    gnc_widget_set_style_context (GTK_WIDGET(window), "GncAssistAccountPeriod");

    /* Enable all pages except menu page. */
    gtk_assistant_set_page_complete (GTK_ASSISTANT (window),
                                     GTK_WIDGET(gtk_builder_get_object(builder, "start_page")),
                                     TRUE);
    gtk_assistant_set_page_complete (GTK_ASSISTANT (window),
                                     GTK_WIDGET(gtk_builder_get_object(builder, "book_page")),
                                     TRUE);
    gtk_assistant_set_page_complete (GTK_ASSISTANT (window),
                                     GTK_WIDGET(gtk_builder_get_object(builder, "finish_page")),
                                     TRUE);
    gtk_assistant_set_page_complete (GTK_ASSISTANT (window),
                                     GTK_WIDGET(gtk_builder_get_object(builder, "summary_page")),
                                     TRUE);

    info->close_status = -1;

    /* Find the date of the earliest transaction in the book.
     * Add a year minus a day as the first guess for book closing,
     * and use that to set up the freq spec widget. */
    info->earliest = get_earliest_in_book (gnc_get_current_book());
    info->earliest_str = qof_print_date(info->earliest);
    PINFO ("date of earliest transaction is %" G_GINT64_FORMAT " %s",
           info->earliest, gnc_ctime (&info->earliest));

    g_date_clear (&info->closing_date, 1);
    gnc_gdate_set_time64 (&info->closing_date, info->earliest);
    g_date_clear (&info->prev_closing_date, 1);
    info->prev_closing_date = info->closing_date;
    g_date_add_years (&info->closing_date, 1);

    {
        Recurrence *r = g_new0(Recurrence, 1);
        recurrenceSet(r, 1, PERIOD_MONTH, &info->closing_date, WEEKEND_ADJ_NONE);
        info->period = NULL;
        info->period = g_list_append(info->period, r);
    }

    info->period_menu = GNC_FREQUENCY(
                            gnc_frequency_new_from_recurrence(info->period, &info->closing_date));

    /* Change the text so that its more mainingful for this assistant */
    gnc_frequency_set_frequency_label_text(info->period_menu, _("Period:"));
    gnc_frequency_set_date_label_text(info->period_menu, _("Closing Date:"));

    /* Reparent to the correct location */

    box = GTK_WIDGET(gtk_builder_get_object(builder, "period_hbox"));
    gtk_box_pack_start (GTK_BOX (box), GTK_WIDGET (info->period_menu), TRUE, TRUE, 0);
    g_signal_connect (info->period_menu, "changed",
                      G_CALLBACK (ap_assistant_menu_changed_cb), info);

    /* Get handles to all of the other widgets we'll need */
    info->period_remarks = GTK_WIDGET(gtk_builder_get_object(builder, "remarks_label"));

    info->close_results = GTK_WIDGET(gtk_builder_get_object(builder, "results_label"));

    info->book_details = GTK_WIDGET(gtk_builder_get_object(builder, "book_label"));

    info->book_title = GTK_WIDGET(gtk_builder_get_object(builder, "book_title_entry"));

    info->book_notes = GTK_TEXT_VIEW(gtk_builder_get_object(builder, "book_notes_view"));

    info->apply_label = GTK_WIDGET(gtk_builder_get_object(builder, "finish_page"));

    info->summary = GTK_WIDGET(gtk_builder_get_object(builder, "summary_label"));

    g_signal_connect (G_OBJECT(window), "destroy",
                      G_CALLBACK (ap_assistant_destroy_cb), info);

    gtk_builder_connect_signals(builder, info);
    g_object_unref(G_OBJECT(builder));
    return window;
}
Example #21
0
//! \brief try to fix some common errors in the csv representation of invoices
//! * corrects the date format
//! * corrects ambigous values in multi line invoices
//! * ensures customer exists
//! * if quantity is unset, set to 1
//! * if price is unset, delete row
void
gnc_bi_import_fix_bis (GtkListStore * store, guint * fixed, guint * deleted,
                       GString * info, gchar *type)
{
    GtkTreeIter iter;
    gboolean valid, row_deleted, row_fixed;
    gchar *id, *date_opened, *date_posted, *due_date, *owner_id, *date, *quantity, *price;
    GString *prev_id, *prev_date_opened, *prev_date_posted, *prev_owner_id, *prev_date;	// needed to fix multi line invoices
    guint dummy;
    gint row = 1;
    const gchar* date_format_string = qof_date_format_get_string (qof_date_format_get()); // Get the user set date format string
    
    
    //date_format_string = qof_date_format_get_string (qof_date_format_get());	

    DEBUG("date_format_string: %s",date_format_string);
    // allow the call to this function with only GtkListeStore* specified
    if (!fixed)
        fixed = &dummy;
    if (!deleted)
        deleted = &dummy;

    *fixed = 0;
    *deleted = 0;

    // init strings
    prev_id = g_string_new ("");
    prev_date_opened = g_string_new ("");
    prev_date_posted = g_string_new ("");
    prev_owner_id = g_string_new ("");
    prev_date = g_string_new ("");

    valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (store), &iter);
    while (valid)
    {
        row_deleted = FALSE;
        row_fixed = FALSE;

        // Walk through the list, reading each row
        gtk_tree_model_get (GTK_TREE_MODEL (store), &iter,
                            ID, &id,
                            DATE_OPENED, &date_opened,
                            DATE_POSTED, &date_posted,
                            DUE_DATE, &due_date,
                            OWNER_ID, &owner_id,
                            DATE, &date,
                            QUANTITY, &quantity, PRICE, &price, -1);

        if (strlen (price) == 0)
        {
            // invalid row (no price given)
            // no fix possible -> delete row
            valid = gtk_list_store_remove (store, &iter);
            row_deleted = TRUE;
            g_string_append_printf (info,
                                    _("ROW %d DELETED, PRICE_NOT_SET: id=%s\n"),
                                    row, id);
        }
        // TODO: QTY get set to 1 later if field is empty.  Delete this section?
        else if (strlen (quantity) == 0)
        {
            // invalid row (no quantity given)
            // no fix possible -> delete row
            valid = gtk_list_store_remove (store, &iter);
            row_deleted = TRUE;
            g_string_append_printf (info, _("ROW %d DELETED, QTY_NOT_SET: id=%s\n"),
                                    row, id);
        }
        else
        {   // TODO: If id is empty get the next one in the series.  Bug 731105 
            if (strlen (id) == 0)
            {
                // no invoice id specified
                if (prev_id->len == 0)
                {
                    // cannot fix -> delete row
                    valid = gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW %d DELETED, ID_NOT_SET\n"), row);
                }
                else
                {
                    // this is a fixable multi line invoice
                    gtk_list_store_set (store, &iter, ID, prev_id->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember invoice id (to be able to fix multi line invoices)
                g_string_assign (prev_id, id);
                // new invoice => reset all other fixable entries
                g_string_assign (prev_date_opened, "");
                g_string_assign (prev_date_posted, "");
                g_string_assign (prev_owner_id, "");
                g_string_assign (prev_date, "");
            }
        }

        if (!row_deleted)
        {
            // the row is valid (price and id are valid)

            if(!isDateValid(date_opened))
            {
                if (prev_date_opened->len == 0)
                {
                    // fix this by using the current date
                    gchar temp[20];
                    GDate date;
                    g_date_clear (&date, 1);
                    gnc_gdate_set_today (&date);
                    g_date_strftime (temp, 20, date_format_string, &date);	// Create a user specified date string.
                    g_string_assign (prev_date_opened, temp);
                }
                // fix this by using the previous date_opened value (multi line invoice)
                gtk_list_store_set (store, &iter, DATE_OPENED,
                                    prev_date_opened->str, -1);
                row_fixed = TRUE;
            }
            else
            {
                // remember date_opened (to be able to fix multi line invoices)
                g_string_assign (prev_date_opened, date_opened);
            }

            // date_opened is valid

             if(!isDateValid(date_posted))
             {
                if (prev_date_posted->len == 0)
                {
                    // this invoice will have to get posted manually
                }
                else
                {
                    // multi line invoice => fix it
                    gtk_list_store_set (store, &iter, DATE_POSTED,
                                        prev_date_posted->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember date_opened (to be able to fix multi line invoices)
                g_string_assign (prev_date_posted, date_posted);
            }

            // date_posted is valid
            /*
            // Check if due date is valid.  Set it to date_posted if not valid or missing.
            if(!isDateValid(due_date))
            {
                gtk_list_store_set (store, &iter, DUE_DATE,
                                        date_posted, -1);
                row_fixed = TRUE;
                
            }
            
            // due_date is valid
            */
            if (strlen (quantity) == 0)
            {
                // quantity is unset => set to 1
                gtk_list_store_set (store, &iter, QUANTITY, "1", -1);
                row_fixed = TRUE;
            }
            

            // quantity is valid

            if (strlen (owner_id) == 0)
            {
                if (prev_owner_id->len == 0)
                {
                    // no customer given and not fixable => delete row
                    valid = gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW %d DELETED, OWNER_NOT_SET: id=%s\n"),
                                            row, id);
                }
                else
                {
                    gtk_list_store_set (store, &iter, owner_id,
                                        prev_owner_id->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember owner_id
                g_string_assign (prev_owner_id, owner_id);
            }
            if (g_ascii_strcasecmp (type, "BILL") == 0)
            {
                // BILL: check, if vendor exists
                if (!gnc_search_vendor_on_id
                        (gnc_get_current_book (), prev_owner_id->str))
                {
                    // vendor not found => delete row
                    valid = gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW %d DELETED, VENDOR_DOES_NOT_EXIST: id=%s\n"),
                                            row, id);
                }
            }
            else if (g_ascii_strcasecmp (type, "INVOICE") == 0)
            {
                // INVOICE: check, if customer exists
                if (!gnc_search_customer_on_id
                        (gnc_get_current_book (), prev_owner_id->str))
                {
                    // customer not found => delete row
                    valid = gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW %d DELETED, CUSTOMER_DOES_NOT_EXIST: id=%s\n"),
                                            row, id);
                }
            }

            // owner_id is valid
        }

        g_free (id);
        g_free (date_opened);
        g_free (date_posted);
        g_free (owner_id);
        g_free (date);
        g_free (quantity);
        g_free (price);
        if (row_deleted)
        {
            (*deleted)++;
            // reset all remembered values
            g_string_assign (prev_id, "");
            g_string_assign (prev_date_opened, "");
            g_string_assign (prev_date_posted, "");
            g_string_assign (prev_owner_id, "");
            g_string_assign (prev_date, "");
        }
        else if (row_fixed)
            (*fixed)++;

        if (!row_deleted)
            valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (store), &iter);

        row++;
    }

    // deallocate strings
    g_string_free (prev_id, TRUE);
    g_string_free (prev_date_opened, TRUE);
    g_string_free (prev_date_posted, TRUE);
    g_string_free (prev_owner_id, TRUE);
    g_string_free (prev_date, TRUE);

    if (info && (info->len > 0))
    {
        g_string_prepend (info, "\n\n");
        g_string_prepend (info, _("These rows were deleted:"));
    }
}
Example #22
0
static guint
sxftd_add_template_trans(SXFromTransInfo *sxfti)
{

    Transaction *tr = sxfti->trans;
    GList *tt_list = NULL;
    GList *splits, *template_splits = NULL;
    TTInfo *tti = gnc_ttinfo_malloc();
    TTSplitInfo *ttsi;
    Split *sp;
    gnc_numeric runningBalance;
    gnc_numeric split_value;
    const char *tmpStr;

    runningBalance = gnc_numeric_zero();

    gnc_ttinfo_set_description(tti, xaccTransGetDescription(tr));
    gnc_ttinfo_set_num(tti, gnc_get_num_action(tr, NULL));
    gnc_ttinfo_set_currency(tti, xaccTransGetCurrency(tr));

    for (splits = xaccTransGetSplitList(tr); splits; splits = splits->next)
    {
        sp = splits->data;
        ttsi = gnc_ttsplitinfo_malloc();
        gnc_ttsplitinfo_set_action(ttsi, gnc_get_num_action(NULL, sp));
        split_value = xaccSplitGetValue(sp);
        gnc_ttsplitinfo_set_memo(ttsi, xaccSplitGetMemo(sp));

        runningBalance = gnc_numeric_add( runningBalance, split_value,
                                          100, (GNC_DENOM_AUTO | GNC_HOW_DENOM_LCD) );

        if (gnc_numeric_positive_p(split_value))
        {
            tmpStr = xaccPrintAmount( split_value,
                                      gnc_default_print_info(FALSE) );
            gnc_ttsplitinfo_set_debit_formula( ttsi, tmpStr );
        }
        else
        {
            /* Negate the numeric so it prints w/o the sign at the front. */
            tmpStr = xaccPrintAmount( gnc_numeric_neg( split_value ),
                                      gnc_default_print_info(FALSE) );
            gnc_ttsplitinfo_set_credit_formula( ttsi, tmpStr );
        }

        /* Copy over per-split account info */
        gnc_ttsplitinfo_set_account( ttsi, xaccSplitGetAccount( sp ) );

        template_splits = g_list_append(template_splits, ttsi);
    }

    if ( ! gnc_numeric_zero_p( runningBalance )
            && !gnc_verify_dialog( (GtkWidget *)sxfti->dialog,
                                   FALSE, "%s",
                                   _("The Scheduled Transaction Editor "
                                     "cannot automatically balance "
                                     "this transaction. "
                                     "Should it still be "
                                     "entered?") ) )
    {
        return SXFTD_ERRNO_UNBALANCED_XACTION;
    }

    gnc_ttinfo_set_template_splits(tti, template_splits);

    tt_list = g_list_append(tt_list, tti);

    gnc_suspend_gui_refresh ();
    xaccSchedXactionSetTemplateTrans(sxfti->sx, tt_list,
                                     gnc_get_current_book ());
    gnc_resume_gui_refresh ();

    return 0;
}
void
gnc_stock_split_assistant_finish (GtkAssistant *assistant,
                                  gpointer user_data)
{
    StockSplitInfo *info = user_data;
    GList *account_commits;
    GList *node;

    gnc_numeric amount;
    Transaction *trans;
    Account *account;
    Split *split;
    time64 date;

    account = info->acct;
    g_return_if_fail (account != NULL);

    amount = gnc_amount_edit_get_amount
             (GNC_AMOUNT_EDIT (info->distribution_edit));
    g_return_if_fail (!gnc_numeric_zero_p (amount));

    gnc_suspend_gui_refresh ();

    trans = xaccMallocTransaction (gnc_get_current_book ());

    xaccTransBeginEdit (trans);

    xaccTransSetCurrency (trans, gnc_default_currency ());

    date = gnc_date_edit_get_date (GNC_DATE_EDIT (info->date_edit));
    xaccTransSetDatePostedSecsNormalized (trans, date);

    {
        const char *description;

        description = gtk_entry_get_text (GTK_ENTRY (info->description_entry));
        xaccTransSetDescription (trans, description);
    }

    split = xaccMallocSplit (gnc_get_current_book ());

    xaccAccountBeginEdit (account);
    account_commits = g_list_prepend (NULL, account);

    xaccTransAppendSplit (trans, split);

    xaccAccountInsertSplit (account, split);

    xaccSplitSetAmount (split, amount);
    xaccSplitMakeStockSplit (split);
    /* Set split-action with gnc_set_num_action which is the same as
     * xaccSplitSetAction with these arguments */
    /* Translators: This string has a disambiguation prefix */
    gnc_set_num_action (NULL, split, NULL, Q_("Action Column|Split"));

    amount = gnc_amount_edit_get_amount (GNC_AMOUNT_EDIT (info->price_edit));
    if (gnc_numeric_positive_p (amount))
    {
        QofBook *book;
        GNCPrice *price;
        GNCPriceDB *pdb;
        GNCCurrencyEdit *ce;
        Timespec ts;

        ce = GNC_CURRENCY_EDIT (info->price_currency_edit);

        ts.tv_sec = date;
        ts.tv_nsec = 0;

        price = gnc_price_create (gnc_get_current_book ());

        gnc_price_begin_edit (price);
        gnc_price_set_commodity (price, xaccAccountGetCommodity (account));
        gnc_price_set_currency (price, gnc_currency_edit_get_currency (ce));
        gnc_price_set_time (price, ts);
        gnc_price_set_source (price, PRICE_SOURCE_STOCK_SPLIT);
        gnc_price_set_typestr (price, PRICE_TYPE_UNK);
        gnc_price_set_value (price, amount);
        gnc_price_commit_edit (price);

        book = gnc_get_current_book ();
        pdb = gnc_pricedb_get_db (book);

        if (!gnc_pricedb_add_price (pdb, price))
            gnc_error_dialog (info->window, "%s", _("Error adding price."));

    }

    amount = gnc_amount_edit_get_amount (GNC_AMOUNT_EDIT (info->cash_edit));
    if (gnc_numeric_positive_p (amount))
    {
        const char *memo;

        memo = gtk_entry_get_text (GTK_ENTRY (info->memo_entry));

        /* asset split */
        account = gnc_tree_view_account_get_selected_account (GNC_TREE_VIEW_ACCOUNT(info->asset_tree));

        split = xaccMallocSplit (gnc_get_current_book ());

        xaccAccountBeginEdit (account);
        account_commits = g_list_prepend (account_commits, account);

        xaccAccountInsertSplit (account, split);

        xaccTransAppendSplit (trans, split);

        xaccSplitSetAmount (split, amount);
        xaccSplitSetValue (split, amount);

        xaccSplitSetMemo (split, memo);


        /* income split */
        account = gnc_tree_view_account_get_selected_account (GNC_TREE_VIEW_ACCOUNT(info->income_tree));

        split = xaccMallocSplit (gnc_get_current_book ());

        xaccAccountBeginEdit (account);
        account_commits = g_list_prepend (account_commits, account);

        xaccAccountInsertSplit (account, split);

        xaccTransAppendSplit (trans, split);

        xaccSplitSetAmount (split, gnc_numeric_neg (amount));
        xaccSplitSetValue (split, gnc_numeric_neg (amount));

        xaccSplitSetMemo (split, memo);
    }

    xaccTransCommitEdit (trans);

    for (node = account_commits; node; node = node->next)
        xaccAccountCommitEdit (node->data);
    g_list_free (account_commits);

    gnc_resume_gui_refresh ();

    gnc_close_gui_component_by_data (ASSISTANT_STOCK_SPLIT_CM_CLASS, info);
}
static void
after_assistant(void)
{
    qof_book_mark_session_dirty(gnc_get_current_book());
    gnc_ui_file_access_for_save_as();
}
void
gnc_split_register_load (SplitRegister *reg, GList * slist,
                         Account *default_account)
{
    SRInfo *info;
    Transaction *pending_trans;
    CursorBuffer *cursor_buffer;
    GHashTable *trans_table = NULL;
    CellBlock *cursor_header;
    CellBlock *lead_cursor;
    CellBlock *split_cursor;
    Transaction *blank_trans;
    Transaction *find_trans;
    Transaction *trans;
    CursorClass find_class;
    Split *find_trans_split;
    Split *blank_split;
    Split *find_split;
    Split *split;
    Table *table;
    GList *node;

    gboolean start_primary_color = TRUE;
    gboolean found_pending = FALSE;
    gboolean need_divider_upper = FALSE;
    gboolean found_divider_upper = FALSE;
    gboolean found_divider = FALSE;
    gboolean has_last_num = FALSE;
    gboolean multi_line;
    gboolean dynamic;
    gboolean we_own_slist = FALSE;
    gboolean use_autoreadonly = qof_book_uses_autoreadonly(gnc_get_current_book());

    VirtualCellLocation vcell_loc;
    VirtualLocation save_loc;

    int new_trans_split_row = -1;
    int new_trans_row = -1;
    int new_split_row = -1;
    time64 present, autoreadonly_time = 0;

    g_return_if_fail(reg);
    table = reg->table;
    g_return_if_fail(table);
    info = gnc_split_register_get_info (reg);
    g_return_if_fail(info);

    ENTER("reg=%p, slist=%p, default_account=%p", reg, slist, default_account);

    blank_split = xaccSplitLookup (&info->blank_split_guid,
                                   gnc_get_current_book ());

    pending_trans = xaccTransLookup (&info->pending_trans_guid,
                                     gnc_get_current_book ());

    /* make sure we have a blank split */
    if (blank_split == NULL)
    {
	/* Wouldn't it be a bug to open the new transaction if there was
	 * already a pending transaction?
	*/
	g_assert(pending_trans == NULL);
	blank_split = create_blank_split (default_account, info);
    }
    blank_trans = xaccSplitGetParent (blank_split);

    DEBUG("blank_split=%p, blank_trans=%p, pending_trans=%p",
          blank_split, blank_trans, pending_trans);

    info->default_account = *xaccAccountGetGUID (default_account);

    // gnc_table_leave_update (table, table->current_cursor_loc);

    multi_line = (reg->style == REG_STYLE_JOURNAL);
    dynamic    = (reg->style == REG_STYLE_AUTO_LEDGER);

    lead_cursor = gnc_split_register_get_passive_cursor (reg);
    split_cursor = gnc_table_layout_get_cursor (table->layout, CURSOR_SPLIT);

    /* figure out where we are going to. */
    if (info->traverse_to_new)
    {
        find_trans = blank_trans;
        find_split = NULL;
        find_trans_split = blank_split;
        find_class = CURSOR_CLASS_SPLIT;
    }
    else
    {
        find_trans = info->cursor_hint_trans;
        find_split = info->cursor_hint_split;
        find_trans_split = info->cursor_hint_trans_split;
        find_class = info->cursor_hint_cursor_class;
    }

    save_loc = table->current_cursor_loc;

    /* If the current cursor has changed we save the values for later
     * possible restoration. */
    if (gnc_table_current_cursor_changed (table, TRUE) &&
            (find_split == gnc_split_register_get_current_split (reg)))
    {
        cursor_buffer = gnc_cursor_buffer_new ();
        gnc_table_save_current_cursor (table, cursor_buffer);
    }
    else
        cursor_buffer = NULL;

    /* disable move callback -- we don't want the cascade of
     * callbacks while we are fiddling with loading the register */
    gnc_table_control_allow_move (table->control, FALSE);

    /* invalidate the cursor */
    {
        VirtualLocation virt_loc;

        gnc_virtual_location_init(&virt_loc);
        gnc_table_move_cursor_gui (table, virt_loc);
    }

    /* make sure that the header is loaded */
    vcell_loc.virt_row = 0;
    vcell_loc.virt_col = 0;
    cursor_header = gnc_table_layout_get_cursor (table->layout, CURSOR_HEADER);
    gnc_table_set_vcell (table, cursor_header, NULL, TRUE, TRUE, vcell_loc);
    vcell_loc.virt_row++;

    /* get the current time and reset the dividing row */
    present = gnc_time64_get_today_end ();
    if (use_autoreadonly)
    {
        GDate *d = qof_book_get_autoreadonly_gdate(gnc_get_current_book());
        // "d" is NULL if use_autoreadonly is FALSE
        autoreadonly_time = d ? timespecToTime64(gdate_to_timespec(*d)) : 0;
        g_date_free(d);
    }

    if (info->first_pass)
    {
        if (default_account)
        {
            const char *last_num = xaccAccountGetLastNum (default_account);

            if (last_num)
            {
                NumCell *cell;

                cell = (NumCell *) gnc_table_layout_get_cell(table->layout, NUM_CELL);
                gnc_num_cell_set_last_num (cell, last_num);
                has_last_num = TRUE;
            }
        }

        /* load up account names into the transfer combobox menus */
        gnc_split_register_load_xfer_cells (reg, default_account);
        gnc_split_register_load_recn_cells (reg);
        gnc_split_register_load_type_cells (reg);
    }

    if (info->separator_changed)
	change_account_separator (info, table, reg);

    table->model->dividing_row_upper = -1;
    table->model->dividing_row = -1;

    // Ensure that the transaction and splits being edited are in the split
    // list we're about to load.
    if (pending_trans != NULL)
    {
        for (node = xaccTransGetSplitList(pending_trans); node; node = node->next)
        {
            Split *pending_split = (Split*)node->data;
            if (!xaccTransStillHasSplit(pending_trans, pending_split)) continue;
            if (g_list_find(slist, pending_split) != NULL)
                continue;

            if (g_list_find_custom(slist, pending_trans,
                                   _find_split_with_parent_txn) != NULL)
                continue;

            if (!we_own_slist)
            {
                // lazy-copy
                slist = g_list_copy(slist);
                we_own_slist = TRUE;
            }
            slist = g_list_append(slist, pending_split);
        }
    }

    if (multi_line)
        trans_table = g_hash_table_new (g_direct_hash, g_direct_equal);

    /* populate the table */
    for (node = slist; node; node = node->next)
    {
        split = node->data;
        trans = xaccSplitGetParent (split);

        if (!xaccTransStillHasSplit(trans, split))
            continue;

        if (pending_trans == trans)
            found_pending = TRUE;
	/* If the transaction has only one split, and it's not our
	 * pending_trans, then it's another register's blank split and
	 * we don't want to see it.
	 */
	else if (xaccTransCountSplits (trans) == 1 &&
		 xaccSplitGetAccount (split) == NULL)
	    continue;


        /* Do not load splits from the blank transaction. */
        if (trans == blank_trans)
            continue;

        if (multi_line)
        {
            /* Skip this split if its transaction has already been loaded. */
            if (g_hash_table_lookup (trans_table, trans))
                continue;

            g_hash_table_insert (trans_table, trans, trans);
        }

        if (info->show_present_divider &&
                use_autoreadonly &&
                !found_divider_upper)
        {
            if (xaccTransGetDate (trans) >= autoreadonly_time)
            {
                table->model->dividing_row_upper = vcell_loc.virt_row;
                found_divider_upper = TRUE;
            }
            else
            {
                need_divider_upper = TRUE;
            }
        }

        if (info->show_present_divider &&
                !found_divider &&
                (xaccTransGetDate (trans) > present))
        {
            table->model->dividing_row = vcell_loc.virt_row;
            found_divider = TRUE;
        }

        /* If this is the first load of the register,
         * fill up the quickfill cells. */
        if (info->first_pass)
            add_quickfill_completions(reg->table->layout, trans, split, has_last_num);

        if (trans == find_trans)
            new_trans_row = vcell_loc.virt_row;

        if (split == find_trans_split)
            new_trans_split_row = vcell_loc.virt_row;

        gnc_split_register_add_transaction (reg, trans, split,
                                            lead_cursor, split_cursor,
                                            multi_line, start_primary_color,
                                            TRUE,
                                            find_trans, find_split, find_class,
                                            &new_split_row, &vcell_loc);

        if (!multi_line)
            start_primary_color = !start_primary_color;
    }

    if (multi_line)
        g_hash_table_destroy (trans_table);

    /* add the blank split at the end. */
    if (pending_trans == blank_trans)
        found_pending = TRUE;

    /* No upper divider yet? Store it now */
    if (info->show_present_divider &&
            use_autoreadonly &&
            !found_divider_upper && need_divider_upper)
    {
        table->model->dividing_row_upper = vcell_loc.virt_row;
        found_divider_upper = TRUE;
    }

    if (blank_trans == find_trans)
        new_trans_row = vcell_loc.virt_row;

    if (blank_split == find_trans_split)
        new_trans_split_row = vcell_loc.virt_row;

    /* If we didn't find the pending transaction, it was removed
     * from the account. */
    if (!found_pending)
    {
        info->pending_trans_guid = *guid_null ();
        if (xaccTransIsOpen (pending_trans))
            xaccTransCommitEdit (pending_trans);
        else if (pending_trans)
            g_assert_not_reached();

        pending_trans = NULL;
    }

    /* go to blank on first pass */
    if (info->first_pass)
    {
        new_split_row = -1;
        new_trans_split_row = -1;
        new_trans_row = -1;

        save_loc.vcell_loc = vcell_loc;
        save_loc.phys_row_offset = 0;
        save_loc.phys_col_offset = 0;
    }

    gnc_split_register_add_transaction (reg, blank_trans, blank_split,
                                        lead_cursor, split_cursor,
                                        multi_line, start_primary_color,
                                        info->blank_split_edited, find_trans,
                                        find_split, find_class, &new_split_row,
                                        &vcell_loc);

    /* resize the table to the sizes we just counted above */
    /* num_virt_cols is always one. */
    gnc_table_set_size (table, vcell_loc.virt_row, 1);

    /* restore the cursor to its rightful position */
    {
        VirtualLocation trans_split_loc;

        if (new_split_row > 0)
            save_loc.vcell_loc.virt_row = new_split_row;
        else if (new_trans_split_row > 0)
            save_loc.vcell_loc.virt_row = new_trans_split_row;
        else if (new_trans_row > 0)
            save_loc.vcell_loc.virt_row = new_trans_row;

        trans_split_loc = save_loc;

	gnc_split_register_get_trans_split (reg, save_loc.vcell_loc,
					    &trans_split_loc.vcell_loc);

        if (dynamic || multi_line || info->trans_expanded)
        {
            gnc_table_set_virt_cell_cursor(
                table, trans_split_loc.vcell_loc,
                gnc_split_register_get_active_cursor (reg));
            gnc_split_register_set_trans_visible (reg, trans_split_loc.vcell_loc,
                                                  TRUE, multi_line);

            info->trans_expanded = (reg->style == REG_STYLE_LEDGER);
        }
        else
        {
            save_loc = trans_split_loc;
            info->trans_expanded = FALSE;
        }

        if (gnc_table_find_close_valid_cell (table, &save_loc, FALSE))
        {
            gnc_table_move_cursor_gui (table, save_loc);
            new_split_row = save_loc.vcell_loc.virt_row;

            if (find_split == gnc_split_register_get_current_split (reg))
                gnc_table_restore_current_cursor (table, cursor_buffer);
        }
    }
    gnc_cursor_buffer_destroy (cursor_buffer);
    cursor_buffer = NULL;

    update_info (info, reg);

    gnc_split_register_set_cell_fractions(
        reg, gnc_split_register_get_current_split (reg));

    gnc_table_refresh_gui (table, TRUE);

    gnc_split_register_show_trans (reg, table->current_cursor_loc.vcell_loc);

    /* enable callback for cursor user-driven moves */
    gnc_table_control_allow_move (table->control, TRUE);

    if (we_own_slist)
        g_list_free(slist);

    LEAVE(" ");
}
/*******************************************************
 * account_splits
 *
 * gather the splits / transactions for an account and
 * send them to a file
 *******************************************************/
static
void account_splits (CsvExportInfo *info, Account *acc, FILE *fh )
{
    Query   *q;
    GSList  *p1, *p2;
    GList   *splits;
    QofBook *book;

    q = qof_query_create_for (GNC_ID_SPLIT);
    book = gnc_get_current_book();
    qof_query_set_book (q, book);

    /* Sort by transaction date */
    p1 = g_slist_prepend (NULL, TRANS_DATE_POSTED);
    p1 = g_slist_prepend (p1, SPLIT_TRANS);
    p2 = g_slist_prepend (NULL, QUERY_DEFAULT_SORT);
    qof_query_set_sort_order (q, p1, p2, NULL);

    xaccQueryAddSingleAccountMatch (q, acc, QOF_QUERY_AND);
    xaccQueryAddDateMatchTT (q, TRUE, info->csvd.start_time, TRUE, info->csvd.end_time, QOF_QUERY_AND);

    /* Run the query */
    for (splits = qof_query_run (q); splits; splits = splits->next)
    {
        Split       *split;
        Transaction *trans;
        SplitList   *s_list;
        GList       *node;
        Split       *t_split;
        int          nSplits;
        int          cnt;
        gchar       *line;

        split = splits->data;
        trans = xaccSplitGetParent (split);
        nSplits = xaccTransCountSplits (trans);
        s_list = xaccTransGetSplitList (trans);

        // Look for trans already exported in trans_list
        if (g_list_find (info->trans_list, trans) != NULL)
            continue;

        // Simple Layout
        if (info->simple_layout)
        {
            line = make_simple_trans_line (acc, trans, split, info);

            /* Write to file */
            if (!write_line_to_file (fh, line))
            {
                info->failed = TRUE;
                break;
            }
            g_free (line);
            continue;
        }

        // Complex Transaction Line.
        line = make_complex_trans_line (acc, trans, split, info);

        /* Write to file */
        if (!write_line_to_file (fh, line))
        {
            info->failed = TRUE;
            break;
        }
        g_free (line);

        /* Loop through the list of splits for the Transaction */
        node = s_list;
        cnt = 0;
        while ((cnt < nSplits) && (info->failed == FALSE))
        {
            t_split = node->data;

            // Complex Split Line.
            line = make_complex_split_line (trans, t_split, info);

            if (!write_line_to_file (fh, line))
                info->failed = TRUE;

            g_free (line);

            cnt++;
            node = node->next;
        }
        info->trans_list = g_list_prepend (info->trans_list, trans); // add trans to trans_list
    }
    qof_query_destroy (q);
    g_list_free (splits);
}
GNCSearchWindow *
gnc_ui_find_transactions_dialog_create2 (GNCLedgerDisplay2 * orig_ledg)
{
    QofIdType type = GNC_ID_SPLIT;
    struct _ftd_data *ftd;
    static GList *params = NULL;
    QofQuery *start_q, *show_q = NULL;
    gboolean num_action =
                qof_book_use_split_action_for_num_field(gnc_get_current_book());

    /* Build parameter list in reverse order */
    if (params == NULL)
    {
        params = gnc_search_param_prepend (params, N_("All Accounts"),
                                           ACCOUNT_MATCH_ALL_TYPE,
                                           type, SPLIT_TRANS, TRANS_SPLITLIST,
                                           SPLIT_ACCOUNT_GUID, NULL);
        params = gnc_search_param_prepend (params, N_("Account"), GNC_ID_ACCOUNT,
                                           type, SPLIT_ACCOUNT, QOF_PARAM_GUID,
                                           NULL);
        params = gnc_search_param_prepend (params, N_("Balanced"), NULL,
                                           type, SPLIT_TRANS, TRANS_IS_BALANCED,
                                           NULL);
        params = gnc_search_param_prepend (params, N_("Reconcile"), RECONCILED_MATCH_TYPE,
                                           type, SPLIT_RECONCILE, NULL);
        params = gnc_search_param_prepend (params, N_("Share Price"), NULL,
                                           type, SPLIT_SHARE_PRICE, NULL);
        params = gnc_search_param_prepend (params, N_("Shares"), NULL,
                                           type, SPLIT_AMOUNT, NULL);
        params = gnc_search_param_prepend (params, N_("Value"), NULL,
                                           type, SPLIT_VALUE, NULL);
        params = gnc_search_param_prepend (params, N_("Date Posted"), NULL,
                                           type, SPLIT_TRANS, TRANS_DATE_POSTED,
                                           NULL);
        params = gnc_search_param_prepend (params, N_("Notes"), NULL,
                                           type, SPLIT_TRANS, TRANS_NOTES, NULL);
        params = gnc_search_param_prepend (params, (num_action
                                                    ? N_("Number/Action")
                                                    : N_("Action")), NULL,
                                           type, SPLIT_ACTION, NULL);
        params = gnc_search_param_prepend (params, (num_action
                                                    ? N_("Transaction Number")
                                                    : N_("Number")), NULL,
                                           type, SPLIT_TRANS, TRANS_NUM, NULL);
        params = gnc_search_param_prepend (params, N_("Memo"), NULL,
                                           type, SPLIT_MEMO, NULL);
        params = gnc_search_param_prepend (params, N_("Description"), NULL,
                                           type, SPLIT_TRANS, TRANS_DESCRIPTION,
                                           NULL);
    }
    else
    {
        GList *l;
        for (l = params; l; l = l->next)
        {
            GNCSearchParam *param = l->data;

            if (num_action)
            {
                if (strcmp (param->title, N_("Action")) == 0)
                    gnc_search_param_set_title (param, N_("Number/Action"));
                if (strcmp (param->title, N_("Number")) == 0)
                    gnc_search_param_set_title (param, N_("Transaction Number"));
            }
            else
            {
                if (strcmp (param->title, N_("Number/Action")) == 0)
                    gnc_search_param_set_title (param, N_("Action"));
                if (strcmp (param->title, N_("Transaction Number")) == 0)
                    gnc_search_param_set_title (param, N_("Number"));
            }
        }
    }

    ftd = g_new0 (struct _ftd_data, 1);

    if (orig_ledg)
    {
        ftd->ledger_q = gnc_ledger_display2_get_query (orig_ledg);
        start_q = show_q = qof_query_copy (ftd->ledger_q);
    }
    else
    {
        start_q = qof_query_create ();
        qof_query_set_book (start_q, gnc_get_current_book ());

        /* In lieu of not "mis-using" some portion of the infrastructure by writing
         * a bunch of new code, we just filter out the accounts of the template
         * transactions.  While these are in a seperate Account trees just for this
         * reason, the query engine makes no distinction between Account trees.
         * See Gnome Bug 86302.
         * 	-- jsled
         *
         * copied from gnc-ledger-display2.c:gnc_ledger_display2_gl()  -- warlord
         *
         * <jsled> Alternatively, you could look for a GNC_SX_ACCOUNT [SchedAction.h]
         * key in the KVP frame of the split.
         */
        {
            Account *tRoot;
            GList *al;

            tRoot = gnc_book_get_template_root( gnc_get_current_book() );
            al = gnc_account_get_descendants( tRoot );
            xaccQueryAddAccountMatch( start_q, al, QOF_GUID_MATCH_NONE, QOF_QUERY_AND );
            g_list_free (al);
            al = NULL;
            tRoot = NULL;
        }

        ftd->q = start_q;		/* save this to destroy it later */
    }

    ftd->sw = gnc_search_dialog_create (type, _("Find Transaction"),
                                        params, NULL, start_q, show_q,
                                        NULL, do_find_cb, NULL,
                                        ftd, free_ftd_cb, GNC_PREFS_GROUP_SEARCH, NULL);

    if (!ftd->sw)
    {
        free_ftd_cb (ftd);
        return NULL;
    }

    return ftd->sw;
}
/*******************************************************
 * csv_transactions_export
 *
 * write a list of transactions to a text file
 *******************************************************/
void csv_transactions_export (CsvExportInfo *info)
{
    FILE    *fh;
    Account *acc;
    GList   *ptr;
    gboolean num_action = qof_book_use_split_action_for_num_field (gnc_get_current_book());

    ENTER("");
    DEBUG("File name is : %s", info->file_name);

    info->failed = FALSE;

    /* Set up separators */
    if (info->use_quotes)
    {
        info->end_sep = "\"";
        info->mid_sep = g_strconcat ("\"", info->separator_str, "\"", NULL);
    }
    else
    {
        info->end_sep = "";
        info->mid_sep = g_strconcat (info->separator_str, NULL);
    }

    /* Open File for writing */
    fh = g_fopen (info->file_name, "w" );
    if (fh != NULL)
    {
        gchar *header;
        int i;

        /* Header string */
        if (info->simple_layout)
        {
            header = g_strconcat (info->end_sep, _("Date"), info->mid_sep, _("Account Name"),
                                  info->mid_sep, (num_action ? _("Transaction Number") : _("Number")),
                                  info->mid_sep, _("Description"), info->mid_sep, _("Full Category Path"),
                                  info->mid_sep, _("Reconcile"), info->mid_sep, _("Amount With Sym"),
                                  info->mid_sep, _("Amount Num."), info->mid_sep, _("Rate/Price"),
                                  info->end_sep, EOLSTR, NULL);
        }
        else
        {
            header = g_strconcat (info->end_sep, _("Date"), info->mid_sep, _("Transaction Type"), info->mid_sep, _("Second Date"),
                                  info->mid_sep, _("Account Name"), info->mid_sep, (num_action ? _("Transaction Number") : _("Number")),
                                  info->mid_sep, _("Description"), info->mid_sep, _("Notes"), info->mid_sep, _("Memo"),
                                  info->mid_sep, _("Full Category Path"), info->mid_sep, _("Category"), info->mid_sep, _("Row Type"),
                                  info->mid_sep, (num_action ? _("Number/Action") : _("Action")),
                                  info->mid_sep, _("Reconcile"), info->mid_sep, _("Amount With Sym"),
                                  info->mid_sep, _("Commodity Mnemonic"), info->mid_sep, _("Commodity Namespace"),
                                  info->mid_sep, _("Amount Num."), info->mid_sep, _("Rate/Price"),
                                  info->end_sep, EOLSTR, NULL);
        }
        DEBUG("Header String: %s", header);

        /* Write header line */
        if (!write_line_to_file (fh, header))
        {
            info->failed = TRUE;
            g_free (header);
            return;
        }
        g_free (header);

        /* Go through list of accounts */
        for (ptr = info->csva.account_list, i = 0; ptr; ptr = g_list_next(ptr), i++)
        {
            acc = ptr->data;
            DEBUG("Account being processed is : %s", xaccAccountGetName (acc));
            account_splits (info, acc, fh);
        }
        g_list_free (info->trans_list); // free trans_list
    }
    else
        info->failed = TRUE;
    if (fh)
        fclose (fh);
    LEAVE("");
}
void
on_final_account_prepare (hierarchy_data  *data)
{
    GSList *actlist;
    GtkTreeView *tree_view;
    GtkTreeSelection *selection;
    GtkCellRenderer *renderer;
    GtkTreeViewColumn *column;
    gnc_commodity *com;

    /* Anything to do? */
    if (!data->category_set_changed)
        return;
    data->category_set_changed = FALSE;

    gnc_suspend_gui_refresh ();

    /* Delete any existing account tree */
    if (data->final_account_tree)
    {
        gtk_widget_destroy(GTK_WIDGET(data->final_account_tree));
        data->final_account_tree = NULL;
    }
    delete_our_account_tree (data);


    /* Build a new account list */
    actlist = get_selected_account_list (data->categories_tree);
    com = gnc_currency_edit_get_currency (GNC_CURRENCY_EDIT(data->currency_selector));
    data->our_account_tree = hierarchy_merge_accounts (actlist, com);


    /* Now build a new account tree */
    data->final_account_tree
        = GNC_TREE_VIEW_ACCOUNT(gnc_tree_view_account_new_with_root (data->our_account_tree, FALSE));
    tree_view = GTK_TREE_VIEW(data->final_account_tree);
    gnc_tree_view_account_set_name_edited(data->final_account_tree,
                                          gnc_tree_view_account_name_edited_cb);
    gnc_tree_view_account_set_code_edited(data->final_account_tree,
                                          gnc_tree_view_account_code_edited_cb);
    gnc_tree_view_account_set_description_edited(data->final_account_tree,
            gnc_tree_view_account_description_edited_cb);
    gnc_tree_view_account_set_notes_edited(data->final_account_tree,
                                           gnc_tree_view_account_notes_edited_cb);

    gtk_tree_view_set_headers_visible (tree_view, TRUE);
    column = gnc_tree_view_find_column_by_name (
                 GNC_TREE_VIEW(data->final_account_tree), "type");
    g_object_set_data(G_OBJECT(column), DEFAULT_VISIBLE, GINT_TO_POINTER(1));
    gnc_tree_view_configure_columns (GNC_TREE_VIEW(data->final_account_tree));
    gnc_tree_view_set_show_column_menu (GNC_TREE_VIEW(data->final_account_tree),
                                        FALSE);

    selection = gtk_tree_view_get_selection (tree_view);
    gtk_tree_selection_set_mode (selection, GTK_SELECTION_BROWSE);

    // This is a re-definition of the placeholder that the account-tree model
    // provides, reflecting the to-be-created state of the account tree
    // post-merge.
    {
        renderer = gtk_cell_renderer_toggle_new();
        g_object_set(G_OBJECT (renderer),
                     "activatable", FALSE,
                     "sensitive", FALSE,
                     NULL);
        column = gtk_tree_view_column_new_with_attributes(_("Placeholder"),
                 renderer, NULL);
        gtk_tree_view_column_set_cell_data_func (column, renderer,
                placeholder_cell_data_func,
                (gpointer)data, NULL);
        gnc_tree_view_append_column (GNC_TREE_VIEW(tree_view), column);
    }


    {
        renderer = gtk_cell_renderer_text_new ();
        g_object_set (G_OBJECT (renderer),
                      "xalign", 1.0,
                      (char *)NULL);
        g_signal_connect (G_OBJECT (renderer), "edited",
                          G_CALLBACK (balance_cell_edited),
                          data);
        column = gtk_tree_view_column_new_with_attributes (_("Opening Balance"),
                 renderer,
                 NULL);
        gtk_tree_view_column_set_cell_data_func (column, renderer,
                balance_cell_data_func,
                (gpointer)data, NULL);
        gnc_tree_view_append_column (GNC_TREE_VIEW(tree_view), column);
    }

    // only in the case where there *are* existing accounts...
    if (gnc_account_n_descendants(gnc_book_get_root_account(gnc_get_current_book())) > 0)
    {
        GList *renderers;
        column = gnc_tree_view_add_text_column(GNC_TREE_VIEW(tree_view),
                                               _("Use Existing"),
                                               NULL,
                                               NULL,
                                               "yes",
                                               GNC_TREE_VIEW_COLUMN_DATA_NONE,
                                               GNC_TREE_VIEW_COLUMN_VISIBLE_ALWAYS,
                                               NULL);
        renderers = gtk_cell_layout_get_cells(GTK_CELL_LAYOUT(column));
        g_object_set(G_OBJECT(renderer), "xalign", 1.0, (char*)NULL);
        gtk_tree_view_column_set_cell_data_func(column, GTK_CELL_RENDERER(renderers->data),
                                                use_existing_account_data_func, (gpointer)data, NULL);
        g_list_free(renderers);
    }

    gtk_container_add(GTK_CONTAINER(data->final_account_tree_container),
                      GTK_WIDGET(data->final_account_tree));

    /* Expand the entire tree */
    gtk_tree_view_expand_all (tree_view);
    gtk_widget_show(GTK_WIDGET(data->final_account_tree));
    gnc_resume_gui_refresh ();
}
Example #30
0
/*******************************************************
 * csv_tree_export
 *
 * write a list of accounts settings to a text file
 *******************************************************/
void csv_tree_export (CsvExportInfo *info)
{
    FILE    *fh;
    Account *root;
    Account *acc;
    GList   *accts, *ptr;

    ENTER("");
    DEBUG("File name is : %s", info->file_name);

    /* Get list of Accounts */
    root = gnc_book_get_root_account (gnc_get_current_book());
    accts = gnc_account_get_descendants_sorted (root);
    info->failed = FALSE;

    /* Open File for writing */
    fh = g_fopen (info->file_name, "w");
    if (fh != NULL)
    {
        gchar *header;
        gchar *part1;
        gchar *part2;
        const gchar *currentSel;
        gchar *end_sep;
        gchar *mid_sep;
        int i;


        /* Set up separators */
        if (info->use_quotes)
        {
            end_sep = "\"";
            mid_sep = g_strconcat ("\"", info->separator_str, "\"", NULL);
        }
        else
        {
            end_sep = "";
            mid_sep = g_strconcat (info->separator_str, NULL);
        }

        /* Header string, 'eol = end of line marker' */
        header = g_strconcat (end_sep, _("type"), mid_sep, _("full_name"), mid_sep, _("name"), mid_sep,
                                _("code"), mid_sep, _("description"), mid_sep, _("color"), mid_sep,
                                _("notes"), mid_sep, _("commoditym"), mid_sep, _("commodityn"), mid_sep,
                                _("hidden"), mid_sep, _("tax"), mid_sep, _("place_holder"), end_sep, EOLSTR, NULL);
        DEBUG("Header String: %s", header);

        /* Write header line */
        if (!write_line_to_file (fh, header))
        {
            info->failed = TRUE;
            g_free (mid_sep);
            g_free (header);
            return;
        }
        g_free (header);

        /* Go through list of accounts */
        for (ptr = accts, i = 0; ptr; ptr = g_list_next (ptr), i++)
        {
            gchar *fullname = NULL;
            gchar *str_temp = NULL;
            acc = ptr->data;
            DEBUG("Account being processed is : %s", xaccAccountGetName (acc));
            /* Type */
            currentSel = xaccAccountTypeEnumAsString (xaccAccountGetType (acc));
            part1 = g_strconcat (end_sep, currentSel, mid_sep, NULL);
            /* Full Name */
            fullname = gnc_account_get_full_name (acc);
            str_temp = csv_test_field_string (info, fullname);
            part2 = g_strconcat (part1, str_temp, mid_sep, NULL);
            g_free (str_temp);
            g_free (fullname);
            g_free (part1);
            /* Name */
            currentSel = xaccAccountGetName (acc);
            str_temp = csv_test_field_string (info, currentSel);
            part1 = g_strconcat (part2, str_temp, mid_sep, NULL);
            g_free (str_temp);
            g_free (part2);
            /* Code */
            currentSel = xaccAccountGetCode (acc) ? xaccAccountGetCode (acc) : "";
            str_temp = csv_test_field_string (info, currentSel);
            part2 = g_strconcat (part1, str_temp, mid_sep, NULL);
            g_free (str_temp);
            g_free (part1);
            /* Description */
            currentSel = xaccAccountGetDescription (acc) ? xaccAccountGetDescription (acc) : "";
            str_temp = csv_test_field_string (info, currentSel);
            part1 = g_strconcat (part2, str_temp, mid_sep, NULL);
            g_free (str_temp);
            g_free (part2);
            /* Color */
            currentSel = xaccAccountGetColor (acc) ? xaccAccountGetColor (acc) : "" ;
            str_temp = csv_test_field_string (info, currentSel);
            part2 = g_strconcat (part1, str_temp, mid_sep, NULL);
            g_free (str_temp);
            g_free (part1);
            /* Notes */
            currentSel = xaccAccountGetNotes (acc) ? xaccAccountGetNotes (acc) : "" ;
            str_temp = csv_test_field_string (info, currentSel);
            part1 = g_strconcat (part2, str_temp, mid_sep, NULL);
            g_free (str_temp);
            g_free (part2);
            /* Commodity Mnemonic */
            currentSel = gnc_commodity_get_mnemonic (xaccAccountGetCommodity (acc));
            str_temp = csv_test_field_string (info, currentSel);
            part2 = g_strconcat (part1, str_temp, mid_sep, NULL);
            g_free (str_temp);
            g_free (part1);
            /* Commodity Namespace */
            currentSel = gnc_commodity_get_namespace (xaccAccountGetCommodity (acc));
            str_temp = csv_test_field_string (info, currentSel);
            part1 = g_strconcat (part2, str_temp, mid_sep, NULL);
            g_free (str_temp);
            g_free (part2);
            /* Hidden */
            currentSel = xaccAccountGetHidden (acc) ? "T" : "F" ;
            part2 = g_strconcat (part1, currentSel, mid_sep, NULL);
            g_free (part1);
            /* Tax */
            currentSel = xaccAccountGetTaxRelated (acc) ? "T" : "F" ;
            part1 = g_strconcat (part2, currentSel, mid_sep, NULL);
            g_free (part2);
            /* Place Holder / end of line marker */
            currentSel = xaccAccountGetPlaceholder (acc) ? "T" : "F" ;
            part2 = g_strconcat (part1, currentSel, end_sep, EOLSTR, NULL);
            g_free (part1);

            DEBUG("Account String: %s", part2);

            /* Write to file */
            if (!write_line_to_file (fh, part2))
            {
                info->failed = TRUE;
                break;
            }
            g_free (part2);
        }
        g_free (mid_sep);
    }
    else
        info->failed = TRUE;
    if (fh)
        fclose (fh);

    g_list_free (accts);
    LEAVE("");
}