GnuCash 7574033+
Loading...
Searching...
No Matches
assistant-stock-transaction.cpp
1/********************************************************************\
2 * assistant-stock-transaction.cpp -- stock assistant for GnuCash *
3 * Copyright (C) 2022 Christopher Lam *
4 * *
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License as *
7 * published by the Free Software Foundation; either version 2 of *
8 * the License, or (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License*
16 * along with this program; if not, contact: *
17 * *
18 * Free Software Foundation Voice: +1-617-542-5942 *
19 * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 *
20 * Boston, MA 02110-1301, USA gnu@gnu.org *
21\********************************************************************/
22
23#include <config.h>
24
25#include <cstddef>
26#include <exception>
27#include <gtk/gtk.h>
28#include <glib/gi18n.h>
29#include <cinttypes>
30#include <memory>
31#include <vector>
32#include <string>
33#include <numeric>
34#include <algorithm>
35#include <optional>
36#include <stdexcept>
37#include <sstream>
38
39#include "Account.h"
40#include "Account.hpp"
41#include "Transaction.h"
42#include "engine-helpers.h"
43#include "dialog-utils.h"
44#include "assistant-stock-transaction.h"
45#include "gnc-account-sel.h"
46#include "gnc-amount-edit.h"
47#include "gnc-date.h"
48#include <gnc-date-edit.h>
49#include "gnc-engine.h"
50#include "gnc-numeric.h"
51#include "gnc-numeric.hpp"
52#include "gnc-prefs.h"
53#include "gnc-component-manager.h"
54#include "gnc-date-edit.h"
56#include "gnc-ui-util.h"
57#include "gnc-main-window.h"
59#include "gnc-split-reg.h"
60
61static QofLogModule log_module = GNC_MOD_ASSISTANT;
62
80
81extern "C"
82{
83// These functions are the GtkAssistant primary button callbacks. They're
84// connected to their signals in assistant-stock-transaction.glade so they
85// mustn't be name-mangled.
86void stock_assistant_prepare_cb (GtkAssistant *assistant, GtkWidget *page,
87 gpointer user_data);
88void stock_assistant_finish_cb (GtkAssistant *assistant, gpointer user_data);
89void stock_assistant_cancel_cb (GtkAssistant *gtkassistant, gpointer user_data);
90}
91
92static const char* GNC_PREFS_GROUP = "dialogs.stock-assistant";
93static const char* ASSISTANT_STOCK_TRANSACTION_CM_CLASS = "assistant-stock-transaction";
94
95static const char* DIVIDEND_KVP_TAG = "stock-dividends";
96static const char* CAPGAINS_KVP_TAG = "stock-capgains";
97static const char* PROCEEDS_KVP_TAG = "stock-cash-proceeds";
98static const char* FEES_KVP_TAG = "stock-broker-fees";
99
102enum class FieldMask : unsigned
103{
104 DISABLED = 0,
105 ENABLED_DEBIT = 1,
106 ENABLED_CREDIT = 1 << 1,
107 AMOUNT_DEBIT = 1 << 2, // stock only
108 AMOUNT_CREDIT = 1 << 3, // stock only
109 INPUT_NEW_BALANCE = 1 << 4, // stock_amt only: instead of amount, get new balance
110 ALLOW_ZERO = 1 << 5,
111 ALLOW_NEGATIVE = 1 << 6,
112 CAPITALIZE_DEFAULT = 1 << 7, // fees only: capitalize by default into stock acct
113 CAPGAINS_IN_STOCK = 1 << 8, // capg only: add a balancing split in stock acct
114 MARKER_SPLIT = 1 << 9, // stock only, place a no-amount, no-value split in the
115 // stock account to associate the income.
116};
117
118static FieldMask
119operator |(FieldMask lhs, FieldMask rhs)
120{
121 return static_cast<FieldMask> (static_cast<unsigned>(lhs) |
122 static_cast<unsigned>(rhs));
123};
124
125static bool
126operator &(FieldMask lhs, FieldMask rhs)
127{
128 return (static_cast<unsigned>(lhs) & static_cast<unsigned>(rhs));
129};
130
138{
139 FieldMask stock_amount;
140 FieldMask cash_value;
141 FieldMask fees_value;
142 FieldMask dividend_value;
143 FieldMask capgains_value;
144 const char* friendly_name;
145 const char* explanation;
146};
147
148using StringVec = std::vector<std::string>;
149using TxnTypeVec = std::vector<TxnTypeInfo>;
150using AccountVec = std::vector<Account*>;
151
152static const TxnTypeVec starting_types
153{
154
155 {
156 FieldMask::ENABLED_DEBIT | FieldMask::AMOUNT_DEBIT, // stock_amt
157 FieldMask::ENABLED_CREDIT, // cash_amt
158 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
159 FieldMask::DISABLED, // dividend_amt
160 FieldMask::DISABLED, // capg_amt
161 // Translators: this is a stock transaction describing an
162 // Initial stock long purchase
163 N_("Open buy"),
164 N_("Initial stock long purchase.")
165 },
166 {
167 FieldMask::ENABLED_CREDIT | FieldMask::AMOUNT_CREDIT, // stock_amt
168 FieldMask::ENABLED_DEBIT, // cash_amt
169 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
170 FieldMask::DISABLED, // dividend_amt
171 FieldMask::DISABLED, // capg_amt
172 // Translators: this is a stock transaction describing an
173 // initial stock short sale
174 N_("Open short"),
175 N_("Initial stock short sale.")
176 }
177};
178
179static const TxnTypeVec long_types
180{
181 {
182 FieldMask::ENABLED_DEBIT | FieldMask::AMOUNT_DEBIT, // stock_amt
183 FieldMask::ENABLED_CREDIT, // cash_amt
184 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
185 FieldMask::DISABLED, // dividend_amt
186 FieldMask::DISABLED, // capg_amt
187 // Translators: this is a stock transaction describing
188 // new purchase of stock.
189 N_("Buy"),
190 N_("Buying stock long.")
191 },
192 {
193 FieldMask::ENABLED_CREDIT | FieldMask::AMOUNT_CREDIT, // stock_amt
194 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO, // cash_amt
195 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO, // fees_amt
196 FieldMask::DISABLED, // dividend_amt
197 FieldMask::ENABLED_CREDIT | FieldMask::ALLOW_ZERO | FieldMask::ALLOW_NEGATIVE | FieldMask::CAPGAINS_IN_STOCK, // capgains_amt
198 // Translators: this is a stock transaction describing new
199 // sale of stock, and recording capital gain/loss
200 N_("Sell"),
201 N_("Selling stock long, and record capital gain/loss."
202 "\n\nIf you are unable to calculate capital gains you can enter a "
203 "placeholder amount and correct it in the transaction later.")
204 },
205 {
206 FieldMask::MARKER_SPLIT, // stock_amt
207 FieldMask::ENABLED_DEBIT, // cash_amt
208 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO, // fees_amt
209 FieldMask::ENABLED_CREDIT, // dividend_amt
210 FieldMask::DISABLED, // capg_amt
211 // Translators: this is a stock transaction describing
212 // dividends issued to holder
213 N_("Dividend"),
214 N_("Company issues cash dividends to holder.\n\nAny dividend being "
215 "reinvested must be subsequently recorded as a regular stock purchase.")
216 },
217 {
218 FieldMask::ENABLED_CREDIT, // stock_amt
219 FieldMask::ENABLED_DEBIT, // cash_amt
220 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
221 FieldMask::DISABLED, // dividend_amt
222 FieldMask::DISABLED, // capg_amt
223 // Translators: this is a stock transaction describing return
224 // of capital
225 N_("Return of capital"),
226 N_("Company returns capital, reducing the cost basis without affecting # units.")
227 },
228 {
229 FieldMask::ENABLED_CREDIT, // stock_amt
230 FieldMask::DISABLED, // cash_amt
231 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
232 FieldMask::ENABLED_DEBIT, // dividend_amt
233 FieldMask::DISABLED, // capg_amt
234 // Translators: this is a stock transaction describing return
235 // of capital, reclassifying a dividend into return of capital
236 N_("Return of capital (reclassification)"),
237 N_("Company returns capital, reducing the cost basis without affecting # units. "
238 "A distribution previously recorded as a dividend is reclassified to return "
239 "of capital, often due to end-of-year tax information.")
240 },
241 {
242 FieldMask::ENABLED_DEBIT, // stock_amt
243 FieldMask::DISABLED, // cash_amt
244 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO, // fees_amt
245 FieldMask::ENABLED_CREDIT, // dividend_amt
246 FieldMask::DISABLED, // capg_amt
247 // Translators: this is a stock transaction describing a
248 // notional distribution recorded as dividend
249 N_("Notional distribution (dividend)"),
250 N_("Company issues a notional distribution, which is recorded as dividend "
251 "income and increases the cost basis without affecting # units.")
252 },
253 {
254 FieldMask::ENABLED_DEBIT, // stock_amt
255 FieldMask::DISABLED, // cash_amt
256 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO, // fees_amt
257 FieldMask::DISABLED, // dividend_amt
258 FieldMask::ENABLED_CREDIT, // capg_amt
259 // Translators: this is a stock transaction describing a
260 // notional distribution recorded as capital gain
261 N_("Notional distribution (capital gain)"),
262 N_("Company issues a notional distribution, which is recorded as capital gain "
263 "and increases the cost basis without affecting # units.")
264 },
265 {
266 FieldMask::AMOUNT_DEBIT | FieldMask::INPUT_NEW_BALANCE, // stock_amt
267 FieldMask::ENABLED_CREDIT | FieldMask::ALLOW_ZERO, // cash_amt
268 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
269 FieldMask::DISABLED, // dividend_amt
270 FieldMask::DISABLED, // capg_amt
271 // Translators: this is a stock transaction describing a stock
272 // split
273 N_("Stock split"),
274 N_("Company issues additional units, thereby reducing the stock price by a divisor, "
275 "while keeping the total monetary value of the overall investment constant.\n\nIf "
276 "the split results in a cash in lieu for remainder units, please "
277 "record the sale using the Stock Transaction Assistant first, then record the split.")
278 },
279 {
280 FieldMask::AMOUNT_CREDIT | FieldMask::INPUT_NEW_BALANCE, // stock_amt
281 FieldMask::ENABLED_CREDIT | FieldMask::ALLOW_ZERO, // cash_amt
282 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
283 FieldMask::DISABLED, // dividend_amt
284 FieldMask::DISABLED, // capg_amt
285 // Translators: this is a stock transaction describing a reverse split
286 N_("Reverse split"),
287 N_("Company redeems units, thereby increasing the stock price by a multiple, while "
288 "keeping the total monetary value of the overall investment constant.\n\nIf the "
289 "reverse split results in a cash in lieu for remainder units, please record the "
290 "sale using the Stock Transaction Assistant first, then record the reverse split.")
291 }
292};
293
294static const TxnTypeVec short_types
295{
296 {
297 FieldMask::ENABLED_CREDIT | FieldMask::AMOUNT_CREDIT, // stock_amt
298 FieldMask::ENABLED_DEBIT, // cash_amt
299 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
300 FieldMask::DISABLED, // dividend_amt
301 FieldMask::DISABLED, // capg_amt
302 // Translators: this is a stock transaction describing
303 // shorting of stock.
304 N_("Short sell"),
305 N_("Selling stock short.")
306 },
307 {
308 FieldMask::ENABLED_DEBIT | FieldMask::AMOUNT_DEBIT, // stock_amt
309 FieldMask::ENABLED_CREDIT | FieldMask::ALLOW_ZERO, // cash_amt
310 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO, // fees_amt
311 FieldMask::DISABLED, // dividend_amt
312 FieldMask::ENABLED_CREDIT | FieldMask::ALLOW_ZERO | FieldMask::ALLOW_NEGATIVE | FieldMask::CAPGAINS_IN_STOCK, // capg_amt
313 // Translators: this is a stock transaction describing cover
314 // buying stock, and recording capital gain/loss
315 N_("Buy to cover short"),
316 N_("Buy back stock to cover short position, and record capital gain/loss.\n\nIf "
317 "you are unable to calculate capital gains you can enter a placeholder "
318 "amount and correct it in the transaction later.")
319 },
320 {
321 FieldMask::MARKER_SPLIT, // stock_amt
322 FieldMask::ENABLED_CREDIT, // cash_amt
323 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO, // fees_amt
324 FieldMask::ENABLED_DEBIT, // dividend_amt
325 FieldMask::DISABLED, // capg_amt
326 // Translators: this is a stock transaction describing
327 // dividends retrieved from holder when shorting stock
328 N_("Compensatory dividend"),
329 N_("Company issues dividends, and the short stock holder must make a compensatory "
330 "payment for the dividend.")
331 },
332 {
333 FieldMask::ENABLED_DEBIT, // stock_amt
334 FieldMask::ENABLED_CREDIT, // cash_amt
335 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
336 FieldMask::DISABLED, // dividend_amt
337 FieldMask::DISABLED, // capg_amt
338 // Translators: this is a stock transaction describing return
339 // of capital retrieved from holder when shorting stock
340 N_("Compensatory return of capital"),
341 N_("Company returns capital, and the short stock holder must make a compensatory "
342 "payment for the returned capital. This reduces the cost basis (less negative, "
343 "towards 0.00 value) without affecting # units.")
344 },
345 {
346 FieldMask::ENABLED_DEBIT, // stock_amt
347 FieldMask::DISABLED, // cash_amt
348 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
349 FieldMask::ENABLED_CREDIT, // dividend_amt
350 FieldMask::DISABLED, // capg_amt
351 // Translators: this is a stock transaction describing
352 // reclassifying a compensatory dividend into compensatory
353 // return of capital when shorting stock
354 N_("Compensatory return of capital (reclassification)"),
355 N_("Company returns capital, and the short stock holder must make a compensatory "
356 "payment for the returned capital. This reduces the cost basis (less negative, "
357 "towards 0.00 value) without affecting # units. A distribution previously recorded "
358 "as a compensatory dividend is reclassified to compensatory return of capital, "
359 "often due to end-of-year tax information.")
360 },
361 {
362 FieldMask::ENABLED_CREDIT, // stock_amt
363 FieldMask::DISABLED, // cash_amt
364 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO, // fees_amt
365 FieldMask::ENABLED_DEBIT, // dividend_amt
366 FieldMask::DISABLED, // capg_amt
367 // Translators: this is a stock transaction describing a
368 // notional distribution recorded as dividend when shorting
369 // stock
370 N_("Compensatory notional distribution (dividend)"),
371 N_("Company issues a notional distribution, and the short stock holder must make a "
372 "compensatory payment for the notional distribution. This is recorded as a "
373 "loss/negative dividend income amount, and increases the cost basis (more "
374 "negative, away from 0.00 value) without affecting # units.")
375 },
376 {
377 FieldMask::ENABLED_CREDIT, // stock_amt
378 FieldMask::DISABLED, // cash_amt
379 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO, // fees_amt
380 FieldMask::DISABLED, // dividend_amt
381 FieldMask::ENABLED_DEBIT, // capg_amt
382 // Translators: this is a stock transaction describing a
383 // notional distribution recorded as capital gain when
384 // shorting stock
385 N_("Compensatory notional distribution (capital gain)"),
386 N_("Company issues a notional distribution, and the short stock holder must make "
387 "a compensatory payment for the notional distribution. This is recorded as a "
388 "capital loss amount, and increases the cost basis (more negative, away from "
389 "0.00 value) without affecting # units.")
390 },
391 {
392 FieldMask::AMOUNT_CREDIT | FieldMask::INPUT_NEW_BALANCE, // stock_amt
393 FieldMask::ENABLED_CREDIT | FieldMask::ALLOW_ZERO, // cash_amt
394 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
395 FieldMask::DISABLED, // dividend_amt
396 FieldMask::DISABLED, // capg_amt
397 // Translators: this is a stock transaction describing a stock
398 // split when shorting stock
399 N_("Stock split"),
400 N_("Company issues additional units, thereby reducing the stock price by a divisor, "
401 "while keeping the total monetary value of the overall investment constant.\n\nIf "
402 "the split results in a cash in lieu for remainder units, please "
403 "record the cover buy using the Stock Transaction Assistant first, then record the split.")
404 },
405 {
406 FieldMask::AMOUNT_DEBIT | FieldMask::INPUT_NEW_BALANCE, // stock_amt
407 FieldMask::ENABLED_CREDIT | FieldMask::ALLOW_ZERO, // cash_amt
408 FieldMask::ENABLED_DEBIT | FieldMask::ALLOW_ZERO | FieldMask::CAPITALIZE_DEFAULT, // fees_amt
409 FieldMask::DISABLED, // dividend_amt
410 FieldMask::DISABLED, // capg_amt
411 // Translators: this is a stock transaction describing a
412 // reverse split when shorting stock.
413 N_("Reverse split"),
414 N_("Company redeems units, thereby increasing the stock price by a multiple, while "
415 "keeping the total monetary value of the overall investment constant.\n\nIf the "
416 "reverse split results in a cash in lieu for remainder units, please record the "
417 "cover buy using the Stock Transaction Assistant first, then record the reverse split.")
418 }
419};
420
421enum class LogMsgType
422{
423 info,
424 warning,
425 error
426};
427
428class LogMessage
429{
430 LogMsgType m_type;
431 const std::string m_message;
432public:
433 LogMessage(LogMsgType type, std::string&& message) :
434 m_type{type}, m_message(std::move(message)) {}
435 LogMessage(LogMsgType type, const char* message) :
436 m_type{type}, m_message(message) {}
437 LogMessage(const LogMessage&) = default;
438 LogMessage(LogMessage&&) = default;
439 ~LogMessage() = default;
440 LogMsgType type() { return m_type; }
441 const std::string& message() { return m_message; }
442};
443
449
450using Log = std::vector<LogMessage>;
451
453{
454 Log m_log;
455public: // compiler generated ctors & dtor are fine
456 void info(const char* message) { m_log.emplace_back(LogMsgType::info, message); }
457 void warn(const char* message) { m_log.emplace_back(LogMsgType::warning, message); }
458 void error(const char* message) { m_log.emplace_back(LogMsgType::error, message); }
459 void clear() { m_log.clear(); }
460 bool has_errors();
461 bool has_warnings();
462 void write_log(std::stringstream& stream, LogMsgType type);
463 void infos(std::stringstream& stream) { return write_log(stream, LogMsgType::info); }
464 void warnings(std::stringstream& stream) { return write_log(stream, LogMsgType::warning); }
465 void errors(std::stringstream& stream) { return write_log(stream, LogMsgType::error); }
471 std::string report();
472};
473
474void
475Logger::write_log(std::stringstream& stream, LogMsgType type)
476{
477 std::for_each(m_log.begin(), m_log.end(),
478 [&](auto& msg){
479 if (msg.type() == type)
480 stream << "\n * " << msg.message();
481 });
482}
483
484bool
485Logger::has_warnings()
486{
487 return std::any_of(m_log.begin(), m_log.end(),
488 [](auto& msg){ return msg.type() == LogMsgType::warning;
489 });
490}
491
492bool
493Logger::has_errors()
494{
495 return std::any_of(m_log.begin(), m_log.end(),
496 [](auto& msg){ return msg.type() == LogMsgType::error;
497 });
498}
499
500std::string
502{
503 std::stringstream summary;
504 if (!has_errors())
505 {
506 summary << _("No errors found. Click Apply to create transaction.");
507 infos(summary);
508 }
509 else
510 {
511 summary << _("The following errors must be fixed:");
512 errors(summary);
513 }
514 if (has_warnings())
515 {
516 summary << "\n\n" << _("The following warnings exist:");
517 warnings(summary);
518 }
519 return summary.str();
520}
521
522/* StockTransactionEntry QofEventHandler for accounts.
523 * Nulls the tranaction entry's account member if the account gets destroyed on
524 * us.
525 */
526static void account_destroyed_handler(QofInstance *inst, QofEventId event,
527 void* handler_data, [[maybe_unused]]void* event_data);
528
536
537class StockTransactionEntry
538{
539protected:
540 bool m_enabled;
541 bool m_debit_side;
542 bool m_fieldmask_debit_side = false;
543 bool m_allow_zero;
544 bool m_allow_negative = false;
545 bool m_input_new_balance = false;
546 Account *m_account;
547 gnc_numeric m_value;
548 const char* m_memo;
549 const char* m_action;
550 gnc_numeric m_balance = gnc_numeric_zero();
551 const char* m_kvp_tag;
552 int m_qof_event_handler;
553public:
554 StockTransactionEntry() :
555 m_enabled{false}, m_debit_side{false}, m_allow_zero{false}, m_account{nullptr},
556 m_value{gnc_numeric_error(GNC_ERROR_ARG)}, m_memo{nullptr}, m_action{nullptr},
557 m_kvp_tag{nullptr}, m_qof_event_handler{qof_event_register_handler(account_destroyed_handler, this)} {}
558 StockTransactionEntry(const char* action, const char* kvp_tag) :
559 m_enabled{false}, m_debit_side{false}, m_allow_zero{false}, m_account{nullptr},
560 m_value{gnc_numeric_error(GNC_ERROR_ARG)}, m_memo{nullptr}, m_action{action},
561 m_kvp_tag{kvp_tag}, m_qof_event_handler{qof_event_register_handler(account_destroyed_handler, this)} {}
562 StockTransactionEntry(const StockTransactionEntry&) = default;
563 virtual ~StockTransactionEntry() { qof_event_unregister_handler(m_qof_event_handler); }
568 virtual void set_fieldmask(FieldMask mask);
569 virtual bool enabled() const { return m_enabled; }
570 virtual bool debit_side() const { return m_debit_side; }
571 virtual void set_capitalize(bool capitalize) {}
572 virtual bool input_new_balance() const { return m_input_new_balance; }
573 virtual bool do_capitalize() const { return false; }
574 virtual void set_account(Account* account) { m_account = account; }
575 virtual Account* account() const { return m_account; }
576 virtual const char* print_account() const;
577 virtual void set_memo(const char* memo) { m_memo = memo; }
578 virtual const char* get_kvp_tag () { return m_kvp_tag; }
579 virtual const char* memo() const { return m_memo; }
580 virtual void set_value(gnc_numeric amount);
581 virtual GncNumeric value() { return (gnc_numeric_check(m_value) ? GncNumeric{} : GncNumeric(m_value)); }
582 virtual void set_amount(gnc_numeric) {}
583 virtual gnc_numeric amount() const { return m_value; }
584 virtual bool has_amount() const { return false; }
585 virtual bool marker_split() const { return false; }
586 /* Validates that the value and for stock entry the amount meet
587 * the criteria set for the entry by the field mask.
588 *
589 * @param logger collects any emitted diagnostics.
590 */
591 virtual void validate_amount(Logger&) const;
592 virtual void set_balance(gnc_numeric balance) { m_balance = balance; }
593 virtual gnc_numeric get_balance() const { return m_balance; }
594 /* Creates a GnuCash split from the data in the entry and adds it
595 * to the transaction, adding the account to the account vector so
596 * that it can be committed when the transaction is completed.
597 *
598 * @param trans the transaction to which to add the split
599 * @param commits the list of accounts to have edits committed later.
600 */
601 virtual void create_split(Transaction* trans, AccountVec& commits) const;
605 virtual const char* print_value() const;
609 virtual const char* print_amount(gnc_numeric amt) const;
617 virtual std::string amount_str_for_display() const { return ""; }
624 virtual gnc_numeric calculate_price() const { return gnc_numeric_error(GNC_ERROR_ARG); }
628 virtual const char* print_price() const;
629};
630
631static void
632account_destroyed_handler(QofInstance *inst, QofEventId event,
633 void* handler_data, [[maybe_unused]]void* event_data)
634{
635 auto entry{static_cast<StockTransactionEntry*>(handler_data)};
636 if ((inst && inst != QOF_INSTANCE(entry->account())) || (event & QOF_EVENT_DESTROY) == 0)
637 return;
638 entry->set_account(nullptr);
639}
640
641using StockTransactionEntryPtr = std::unique_ptr<StockTransactionEntry>;
642
643void
645{
646 m_enabled = mask != FieldMask::DISABLED;
647 m_debit_side = mask & FieldMask::ENABLED_DEBIT;
648 m_fieldmask_debit_side = m_debit_side;
649 m_allow_zero = mask & FieldMask::ALLOW_ZERO;
650 m_allow_negative = mask & FieldMask::ALLOW_NEGATIVE;
651}
652
653const char *
654StockTransactionEntry::print_account() const
655{
656 auto acct_required = m_enabled &&
657 !(m_allow_zero && (gnc_numeric_zero_p(m_value) ||
658 gnc_numeric_check(m_value)));
659 return m_account ? xaccAccountGetName(m_account) :
660 acct_required ? _("missing") : "";
661}
662
663void
664StockTransactionEntry::set_value(gnc_numeric amount)
665{
666 if (gnc_numeric_check (amount))
667 {
669 return;
670 }
671
672 m_value = gnc_numeric_abs(amount);
673 m_debit_side = m_fieldmask_debit_side != gnc_numeric_negative_p (amount);
674
675 PINFO("Set %s value to %" PRId64 "/%" PRId64, m_action, m_value.num, m_value.denom);
676}
677
678void
679StockTransactionEntry::validate_amount(Logger& logger) const
680{
681 auto add_error = [&logger](const char* format_str, const char* arg)
682 {
683 char *buf = g_strdup_printf (_(format_str),
684 g_dpgettext2 (nullptr, "Stock Assistant: Page name", arg));
685 logger.error(buf);
686 g_free (buf);
687 };
688
689
690 if (gnc_numeric_check (m_value))
691 {
692 if (!m_allow_zero)
693 add_error (N_("Amount for %s is missing."), m_action);
694 return;
695 }
696
697 if (gnc_numeric_negative_p (m_value) && !m_allow_negative && m_allow_zero)
698 add_error (N_("Amount for %s must not be negative."), m_action);
699
700 if (!m_allow_zero && !gnc_numeric_positive_p (m_value))
701 add_error (N_("Amount for %s must be positive."), m_action);
702
703 if (!gnc_numeric_zero_p(m_value) && !m_account)
704 add_error(N_("The %s amount has no associated account."), m_action);
705}
706
707const char *
709{
710 if (!m_enabled || (gnc_numeric_check(m_value) && m_allow_zero))
711 return nullptr;
712
713 if ((gnc_numeric_check(m_value) || gnc_numeric_zero_p(m_value))
714 && !m_allow_zero)
715 return _("missing");
716
717 /* Don't combine this with the first if, it would prevent showing
718 * "missing" when the value is required.
719 */
720 if (!m_account)
721 return nullptr;
722
723 auto currency{gnc_account_get_currency_or_parent(m_account)};
724 auto pinfo{gnc_commodity_print_info(currency, TRUE)};
725 return xaccPrintAmount(m_value, pinfo);
726}
727
728const char *
730{
731 if (!m_account || gnc_numeric_check(amt))
732 return nullptr;
733 auto commodity{xaccAccountGetCommodity(m_account)};
734 auto pinfo{gnc_commodity_print_info(commodity, TRUE)};
735 return xaccPrintAmount(amt, pinfo);
736}
737
738void
739StockTransactionEntry::create_split(Transaction *trans, AccountVec &account_commits) const
740{
741 g_return_if_fail(trans);
742 if (!m_account || gnc_numeric_check(m_value))
743 return;
744 auto split = xaccMallocSplit(qof_instance_get_book(trans));
745 xaccSplitSetParent(split, trans);
746 xaccAccountBeginEdit(m_account);
747 account_commits.push_back(m_account);
748 xaccSplitSetAccount(split, m_account);
749 xaccSplitSetMemo(split, m_memo);
750 if (m_enabled)
751 xaccSplitSetValue(split, m_debit_side ? m_value : gnc_numeric_neg(m_value));
752 xaccSplitSetAmount(split, amount());
753 PINFO("creating %s split in Acct(%s): Val(%s), Amt(%s) => Val(%s), Amt(%s)",
754 m_action, m_account ? xaccAccountGetName (m_account) : "Empty!",
755 gnc_num_dbg_to_string(m_value),
756 gnc_num_dbg_to_string(amount()),
759 gnc_set_num_action(nullptr, split, nullptr,
760 g_dpgettext2(nullptr, "Stock Assistant: Action field",
761 m_action));
762}
763
764const char *
766{
767 auto price{calculate_price()};
768 if (gnc_numeric_check(price))
769//Translators: "N/A" here means that a commodity doesn't have a valid price.
770 return _("N/A");
771 auto currency{gnc_account_get_currency_or_parent(m_account)};
772 auto pinfo{gnc_price_print_info(currency, TRUE)};
773 return xaccPrintAmount(price, pinfo);
774}
775
784class StockTransactionStockEntry : public StockTransactionEntry
785{
786 bool m_amount_enabled;
787 gnc_numeric m_amount;
788 bool m_marker = false;
789public:
790 StockTransactionStockEntry() :
791 StockTransactionEntry{}, m_amount{gnc_numeric_error(GNC_ERROR_ARG)}
792 {
793 PINFO("Stock Entry");
794 }
795 StockTransactionStockEntry(const char* action) :
796 StockTransactionEntry{action, nullptr}, m_amount{gnc_numeric_error(GNC_ERROR_ARG)}
797 {
798 PINFO("Stock Entry");
799 }
800 void set_fieldmask(FieldMask mask) override;
801 void set_amount(gnc_numeric amount) override;
802 gnc_numeric amount() const override { return m_amount; }
803 bool has_amount() const override { return m_amount_enabled; }
804 void validate_amount(Logger& logger) const override;
805 void create_split(Transaction *trans, AccountVec &account_commits) const override;
806 std::string amount_str_for_display() const override;
807 gnc_numeric calculate_price() const override;
808 bool marker_split() const override { return m_marker; }
809};
810
811void
813{
815 m_enabled = mask & (FieldMask::ENABLED_CREDIT | FieldMask::ENABLED_DEBIT);
816 m_amount_enabled = mask & (FieldMask::AMOUNT_CREDIT | FieldMask::AMOUNT_DEBIT);
817 m_debit_side = mask & (FieldMask::ENABLED_DEBIT | FieldMask::AMOUNT_DEBIT);
818 m_fieldmask_debit_side = m_debit_side;
819 m_input_new_balance = mask & FieldMask::INPUT_NEW_BALANCE;
820 m_marker = mask & FieldMask::MARKER_SPLIT;
821}
822
823
824void
825StockTransactionStockEntry::set_amount(gnc_numeric amount)
826{
827 if (!m_amount_enabled || gnc_numeric_check(amount))
828 {
830 return;
831 }
832
833 if (m_input_new_balance)
834 {
835 if (m_debit_side)
836 m_amount = gnc_numeric_sub_fixed(amount, m_balance);
837 else
838 m_amount = gnc_numeric_sub_fixed(m_balance, amount);
839
840 PINFO("%s set amount for new balance %s", m_memo, print_amount(m_amount));
841 }
842 else
843 {
844 m_amount = amount;
845 PINFO("%s set amount %s", m_memo, print_amount(m_amount));
846 }
847}
848
849void
850StockTransactionStockEntry::validate_amount(Logger& logger) const
851{
852 if (m_enabled)
853 StockTransactionEntry::validate_amount(logger);
854
855 if (!m_amount_enabled)
856 return;
857
858 auto add_error_str = [&logger]
859 (const char* str) { logger.error (_(str)); };
860
861 if (gnc_numeric_check(m_amount) || gnc_numeric_zero_p(m_amount))
862 {
863 add_error_str(_("Amount for stock value is missing."));
864 return;
865 }
866
867 if (m_input_new_balance)
868 {
869 auto amount = gnc_numeric_add_fixed(m_debit_side ? m_amount : gnc_numeric_neg(m_amount), m_balance);
870 auto delta = gnc_numeric_sub_fixed(amount, m_balance);
871 auto ratio = gnc_numeric_div(amount, m_balance,
873
874 if (gnc_numeric_check(ratio) || !gnc_numeric_positive_p(ratio))
875 add_error_str(N_("Invalid stock new balance."));
876 else if (gnc_numeric_negative_p(delta) && m_debit_side)
877 add_error_str(N_("New balance must be higher than old balance."));
878 else if (gnc_numeric_positive_p(delta) && !m_debit_side)
879 add_error_str(N_("New balance must be lower than old balance."));
880
881 PINFO("Delta %" PRId64 "/%" PRId64 ", Ratio %" PRId64 "/%" PRId64, delta.num, delta.denom, ratio.num, ratio.denom);
882 return;
883 }
884
885 if (!gnc_numeric_positive_p(m_amount))
886 add_error_str(N_("Stock amount must be positive."));
887
888 auto new_bal = gnc_numeric_add_fixed(m_balance, m_amount);
889 if (gnc_numeric_positive_p(m_balance) && gnc_numeric_negative_p(new_bal))
890 add_error_str(N_("Cannot sell more units than owned."));
891 else if (gnc_numeric_negative_p(m_balance) && gnc_numeric_positive_p(new_bal))
892 add_error_str(N_("Cannot cover buy more units than owed."));
893}
894
895std::string
897{
898 std::string rv{""};
899
900 if (gnc_numeric_check (m_amount))
901 return rv;
902
903 if (m_input_new_balance)
904 {
905 auto amount = gnc_numeric_add(m_debit_side ? m_amount : gnc_numeric_neg(m_amount), m_balance,
907 auto ratio = gnc_numeric_div (amount, m_balance,
909 PINFO("Computed ratio %" PRId64 "/%" PRId64 "; amount %" PRId64
910 "/%" PRId64 " and balance %" PRId64 "/%" PRId64,
911 ratio.num, ratio.denom, amount.num, amount.denom, m_balance.num, m_balance.denom);
912 if (gnc_numeric_check (ratio) || !gnc_numeric_positive_p (ratio))
913 return rv;
914
915 std::ostringstream ret;
916 ret << ratio.num << ':' << ratio.denom;
917 rv = ret.str();
918 }
919 else
920 {
921 auto amount = m_debit_side ? m_amount : gnc_numeric_neg (m_amount);
922 amount = gnc_numeric_add_fixed (amount, m_balance);
923 rv = print_amount(amount);
924 }
925
926 return rv;
927};
928
929
930void
931StockTransactionStockEntry::create_split(Transaction *trans, AccountVec &account_commits) const
932{
933 g_return_if_fail(trans);
934 if (!m_account)
935 return;
936 auto split = xaccMallocSplit(qof_instance_get_book(trans));
937 xaccSplitSetParent(split, trans);
938 xaccAccountBeginEdit(m_account);
939 account_commits.push_back(m_account);
940 xaccSplitSetAccount(split, m_account);
941 xaccSplitSetMemo(split, m_memo);
942 if (m_enabled)
943 xaccSplitSetValue(split, m_debit_side ? m_value : gnc_numeric_neg(m_value));
944 if (m_amount_enabled)
945 xaccSplitSetAmount(split, m_debit_side ? m_amount : gnc_numeric_neg(m_amount));
946 if (m_amount_enabled && !m_enabled) // It's a stock split
948 PINFO("creating %s split in Acct(%s): Val(%s), Amt(%s) => Val(%s), Amt(%s)",
949 m_action, m_account ? xaccAccountGetName (m_account) : "Empty!",
950 gnc_num_dbg_to_string(m_value),
951 gnc_num_dbg_to_string(amount()),
954 gnc_set_num_action(nullptr, split, nullptr,
955 g_dpgettext2(nullptr, "Stock Assistant: Action field",
956 m_action));
957}
958
959gnc_numeric
961{
962 if (m_input_new_balance ||
963 !m_amount_enabled || gnc_numeric_check(m_amount) ||
964 !m_enabled || gnc_numeric_check(m_value) ||
965 gnc_numeric_zero_p(m_amount) || gnc_numeric_zero_p(m_value))
967
968 auto price = gnc_numeric_div(m_value, m_amount,
970
971 auto comm{xaccAccountGetCommodity(m_account)};
972 auto curr{gnc_account_get_currency_or_parent(m_account)};
973 auto ainfo{gnc_commodity_print_info (comm, true)};
974 auto pinfo{gnc_price_print_info (curr, true)};
975 auto vinfo{gnc_commodity_print_info (curr, true)};
976
977 PINFO("Calculated price %s from value %s and amount %s",
978 xaccPrintAmount(price, pinfo), xaccPrintAmount(m_value, vinfo),
979 xaccPrintAmount(m_amount, ainfo));
980 return price;
981}
982
989class StockTransactionStockCapGainsEntry : public StockTransactionEntry
990{
991public:
992 StockTransactionStockCapGainsEntry(const StockTransactionEntry* cg_entry,
993 const StockTransactionEntry* stk_entry);
994 gnc_numeric amount() const { return gnc_numeric_zero(); }
995};
996
997StockTransactionStockCapGainsEntry::StockTransactionStockCapGainsEntry(const StockTransactionEntry *cg_entry,
998 const StockTransactionEntry *stk_entry) :
999 StockTransactionEntry(*cg_entry)
1000{
1001 m_debit_side = !m_debit_side;
1002 m_account = stk_entry->account();
1003}
1004
1009class StockTransactionFeesEntry : public StockTransactionEntry
1010{
1011 bool m_capitalize;
1012public:
1013 StockTransactionFeesEntry() : StockTransactionEntry{}, m_capitalize{false} {}
1014 StockTransactionFeesEntry(const char* action, const char *tag) : StockTransactionEntry{action, tag}, m_capitalize{false} {}
1015 void set_fieldmask(FieldMask mask) override;
1016 void set_capitalize(bool capitalize) override { m_capitalize = capitalize; }
1017 bool do_capitalize() const override { return m_capitalize; }
1018 void validate_amount(Logger &logger) const override;
1019 void create_split(Transaction *trans, AccountVec &commits) const override;
1020};
1021
1022void
1024{
1026 m_capitalize = mask & FieldMask::CAPITALIZE_DEFAULT;
1027}
1028
1029void
1030StockTransactionFeesEntry::validate_amount(Logger& logger) const
1031{
1032 auto add_error = [&logger](const char* format_str, const char* arg)
1033 {
1034 char *buf = g_strdup_printf (_(format_str),
1035 g_dpgettext2 (nullptr, "Stock Assistant: Page name", arg));
1036 logger.error(buf);
1037 g_free (buf);
1038 };
1039
1040
1041 if (gnc_numeric_check (m_value))
1042 {
1043 if (!m_allow_zero)
1044 add_error (N_("Amount for %s is missing."), m_action);
1045 return;
1046 }
1047
1048 if (gnc_numeric_negative_p (m_value) && !m_allow_negative && m_allow_zero)
1049 add_error (N_("Amount for %s must not be negative."), m_action);
1050
1051 if (!m_allow_zero && !gnc_numeric_positive_p (m_value))
1052 add_error (N_("Amount for %s must be positive."), m_action);
1053
1054 if (!gnc_numeric_zero_p(m_value) && !m_account && !m_capitalize)
1055 add_error(N_("The %s amount has no associated account."), m_action);
1056}
1057
1058void
1059StockTransactionFeesEntry::create_split(Transaction* trans, AccountVec& commits) const
1060{
1061 g_return_if_fail(trans);
1062 if ((!m_account && !m_capitalize) || gnc_numeric_check(m_value))
1063 return;
1064 auto split = xaccMallocSplit(qof_instance_get_book(trans));
1065 xaccSplitSetParent(split, trans);
1066 if (m_capitalize)
1067 {
1068 xaccSplitSetAccount(split, commits[0]); // Should be the stock account
1069 }
1070 else
1071 {
1072 xaccAccountBeginEdit(m_account);
1073 commits.push_back(m_account);
1074 xaccSplitSetAccount(split, m_account);
1075 xaccSplitSetAmount(split, amount());
1076 }
1077 xaccSplitSetMemo(split, m_memo);
1078 xaccSplitSetValue(split, m_debit_side ? m_value : gnc_numeric_neg(m_value));
1079 PINFO("creating %s split in Acct(%s): Val(%s), Amt(%s) => Val(%s), Amt(%s)",
1080 m_action, m_account ? xaccAccountGetName (m_account) : "Empty!",
1081 gnc_num_dbg_to_string(m_value),
1082 gnc_num_dbg_to_string(amount()),
1085 gnc_set_num_action(nullptr, split, nullptr,
1086 g_dpgettext2(nullptr, "Stock Assistant: Action field",
1087 m_action));
1088}
1089
1090using EntryVec = std::vector<StockTransactionEntry*>;
1091
1092static void stock_assistant_model_date_changed_cb(GtkWidget*, void*);
1093static void stock_assistant_model_description_changed_cb(GtkWidget *, void *);
1094
1100
1101class StockAssistantModel
1102{
1103 Account* m_acct;
1104 gnc_commodity* m_currency;
1105 time64 m_transaction_date;
1106 const char* m_transaction_description;
1107 std::optional<TxnTypeVec> m_txn_types;
1108
1109 std::optional<TxnTypeInfo> m_txn_type;
1110
1111 StockTransactionEntryPtr m_stock_entry;
1112 StockTransactionEntryPtr m_cash_entry;
1113 StockTransactionEntryPtr m_fees_entry;
1114 StockTransactionEntryPtr m_dividend_entry;
1115 StockTransactionEntryPtr m_capgains_entry;
1116 StockTransactionEntryPtr m_stock_cg_entry; // Required at this level for lifetime management
1117 Logger m_logger;
1118
1119 std::optional<time64> m_txn_types_date;
1120 bool m_ready_to_create = false;
1121
1122 EntryVec m_list_of_splits;
1123
1124public:
1125 StockAssistantModel(Account *account)
1126 : m_acct{account}, m_currency{gnc_account_get_currency_or_parent(
1127 account)},
1128 m_stock_entry{std::make_unique<StockTransactionStockEntry>(
1129 NC_("Stock Assistant: Page name", "Stock"))},
1130 m_cash_entry{std::make_unique<StockTransactionEntry>(
1131 NC_("Stock Assistant: Page name", "Cash"), PROCEEDS_KVP_TAG)},
1132 m_fees_entry{std::make_unique<StockTransactionFeesEntry>(
1133 NC_("Stock Assistant: Page name", "Fees"), FEES_KVP_TAG)},
1134 m_dividend_entry{std::make_unique<StockTransactionEntry>(
1135 NC_("Stock Assistant: Page name", "Dividend"), DIVIDEND_KVP_TAG)},
1136 m_capgains_entry{std::make_unique<StockTransactionEntry>(
1137 NC_("Stock Assistant: Page name", "Capital Gains"),
1138 CAPGAINS_KVP_TAG)} {
1139 DEBUG ("StockAssistantModel constructor\n");
1140 m_stock_entry->set_account(m_acct);
1141 };
1142
1143 ~StockAssistantModel()
1144 {
1145 DEBUG ("StockAssistantModel destructor\n");
1146 };
1147
1154 bool maybe_reset_txn_types ();
1159 const std::optional<TxnTypeVec>& get_txn_types() { return m_txn_types; }
1165 bool set_txn_type (guint type_idx);
1170 bool txn_type_valid() { return m_txn_type.has_value(); }
1175 void set_transaction_date(time64 date) { m_transaction_date = date;}
1180 void set_transaction_desc(const char* desc) { m_transaction_description = desc; }
1185 const std::optional<TxnTypeInfo>& txn_type() { return m_txn_type; }
1190 std::string get_new_amount_str () const;
1195 StockTransactionEntry* stock_entry() { return m_stock_entry.get(); }
1200 StockTransactionEntry* cash_entry() { return m_cash_entry.get(); }
1205 StockTransactionEntry* fees_entry() { return m_fees_entry.get(); }
1210 StockTransactionEntry* dividend_entry() { return m_dividend_entry.get(); }
1215 StockTransactionEntry* capgains_entry() { return m_capgains_entry.get(); }
1220 Logger& logger() { return m_logger; }
1231 std::tuple<bool, std::string, EntryVec> generate_list_of_splits ();
1237 std::tuple<bool, Transaction*> create_transaction ();
1238 Account* account() { return m_acct; }
1239private:
1243 void add_price (QofBook *book);
1244};
1245
1246bool
1248{
1249 auto old_bal = m_stock_entry->get_balance();
1250 auto new_bal = xaccAccountGetBalanceAsOfDate
1251 (m_acct, gnc_time64_get_day_end (m_transaction_date));
1252 if (m_txn_types_date && m_txn_types_date == m_transaction_date &&
1253 gnc_numeric_equal (old_bal, new_bal))
1254 return false;
1255 m_stock_entry->set_balance(new_bal);
1256 m_txn_types_date = m_transaction_date;
1257 m_txn_types = gnc_numeric_zero_p (new_bal) ? starting_types
1258 : gnc_numeric_positive_p (new_bal) ? long_types
1259 : short_types;
1260 return true;
1261};
1262
1263bool
1265{
1266 if (!m_txn_types_date || m_txn_types_date != m_transaction_date)
1267 {
1268 PERR ("transaction_date has changed. rerun maybe_reset_txn_types!");
1269 return false;
1270 }
1271 try
1272 {
1273 m_txn_type = m_txn_types->at (type_idx);
1274 }
1275 catch (const std::out_of_range&)
1276 {
1277 PERR ("out of range type_idx=%d", type_idx);
1278 return false;
1279 }
1280
1281 m_stock_entry->set_fieldmask(m_txn_type->stock_amount);
1282 m_fees_entry->set_fieldmask(m_txn_type->fees_value);
1283 m_capgains_entry->set_fieldmask(m_txn_type->capgains_value);
1284 m_dividend_entry->set_fieldmask(m_txn_type->dividend_value);
1285 m_cash_entry->set_fieldmask(m_txn_type->cash_value);
1286 return true;
1287};
1288
1289static void
1290check_txn_date(const Split* last_split, time64 txn_date, Logger& logger)
1291{
1292 auto last_split_date = xaccTransGetDate(xaccSplitGetParent(last_split));
1293 if (txn_date <= last_split_date) {
1294 auto last_split_date_str = qof_print_date(last_split_date);
1295 auto new_date_str = qof_print_date(txn_date);
1296 // Translators: the first %s is the new transaction date;
1297 // the second %s is the current stock account's latest
1298 // transaction date.
1299 auto warn_txt = g_strdup_printf(
1300 _("You will enter a transaction "
1301 "with date %s which is earlier than the latest transaction in this account, "
1302 "dated %s. Doing so may affect the cost basis, and therefore capital gains, "
1303 "of transactions dated after the new entry. Please review all transactions "
1304 "to ensure proper recording."),
1305 new_date_str, last_split_date_str);
1306 logger.warn(warn_txt);
1307 g_free(warn_txt);
1308 g_free(new_date_str);
1309 g_free(last_split_date_str);
1310 }
1311}
1312
1313std::tuple<bool, std::string, EntryVec>
1315 if (!m_txn_types || !m_txn_type)
1316 return { false, "Error: txn_type not initialized", {} };
1317
1318 m_logger.clear();
1319 m_list_of_splits.clear();
1320
1321 GncNumeric debit{};
1322 GncNumeric credit{};
1323
1324 // check the stock transaction date. If there are existing stock
1325 // transactions dated after the date specified, it is very likely
1326 // the later stock transactions will be invalidated. warn the user
1327 // to review them.
1328 if (const auto& splits = xaccAccountGetSplits (m_acct); !splits.empty())
1329 check_txn_date(splits.back(), m_transaction_date, m_logger);
1330
1331 if (m_stock_entry->enabled() || m_stock_entry->has_amount())
1332 {
1333 m_stock_entry->validate_amount(m_logger);
1334 m_list_of_splits.push_back(m_stock_entry.get());
1335
1336 auto price{m_stock_entry->calculate_price()};
1337 if (!gnc_numeric_check(price))
1338 {
1339 // Translators: %s refer to: stock mnemonic, broker currency,
1340 // date of transaction.
1341 auto tmpl = N_("A price of 1 %s = %s on %s will be recorded.");
1342 auto date_str = qof_print_date (m_transaction_date);
1343 auto price_msg = g_strdup_printf
1344 (_(tmpl),
1346 m_stock_entry->print_price(), date_str);
1347 m_logger.info(price_msg);
1348 g_free (date_str);
1349 g_free (price_msg);
1350 }
1351 }
1352
1353 if (m_stock_entry->marker_split())
1354 m_list_of_splits.push_back(m_stock_entry.get());
1355
1356 if (m_cash_entry->enabled())
1357 {
1358 m_cash_entry->validate_amount(m_logger);
1359 m_list_of_splits.push_back (m_cash_entry.get());
1360 }
1361
1362 if (m_fees_entry->enabled())
1363 {
1364 m_fees_entry->validate_amount(m_logger);
1365 if (m_fees_entry->do_capitalize())
1366 m_fees_entry->set_account(m_acct);
1367 m_list_of_splits.push_back (m_fees_entry.get());
1368 }
1369
1370 if (m_dividend_entry->enabled())
1371 {
1372 m_dividend_entry->validate_amount(m_logger);
1373 m_list_of_splits.push_back (m_dividend_entry.get());
1374 }
1375
1376 if (m_capgains_entry->enabled())
1377 {
1378 m_stock_cg_entry =
1379 std::make_unique<StockTransactionStockCapGainsEntry>(m_capgains_entry.get(),
1380 m_stock_entry.get());
1381 m_stock_cg_entry->validate_amount(m_logger);
1382 m_capgains_entry->validate_amount(m_logger);
1383 m_list_of_splits.push_back(m_stock_cg_entry.get());
1384 m_list_of_splits.push_back (m_capgains_entry.get());
1385 }
1386
1387 std::for_each(m_list_of_splits.begin(), m_list_of_splits.end(),
1388 [&debit, &credit](auto& entry) {
1389 if (entry->debit_side())
1390 debit += entry->value();
1391 else
1392 credit += entry->value();
1393 });
1394
1395 if (gnc_numeric_check(debit) || gnc_numeric_check(credit) ||!gnc_numeric_equal (debit, credit))
1396 {
1397 const char *err_act = NULL, *err_reason = NULL;
1398 if (gnc_numeric_check(debit))
1399 {
1400 err_act = "debit";
1402 }
1403 else if (gnc_numeric_check(credit))
1404 {
1405 err_act = "credit";
1407 }
1408
1409 if (err_act)
1410 {
1411 const char *balance_str = N_("Transaction can't balance, %s is error value %s");
1412 auto err_str = g_strdup_printf (_(balance_str), err_act, err_reason);
1413 m_logger.error(err_str);
1414 g_free (err_str);
1415 }
1416 else
1417 {
1418 auto imbalance_str = N_("Total Debits of %s does not balance with total Credits of %s.");
1419 auto pinfo{gnc_commodity_print_info (m_currency, true)};
1420 auto debit_str = g_strdup (xaccPrintAmount (debit, pinfo));
1421 auto credit_str = g_strdup (xaccPrintAmount (credit, pinfo));
1422 auto error_str = g_strdup_printf (_(imbalance_str), debit_str, credit_str);
1423 m_logger.error (error_str);
1424 g_free (error_str);
1425 g_free (credit_str);
1426 g_free (debit_str);
1427 }
1428 }
1429
1430 // generate final summary message. Collates a header, the errors
1431 // and warnings. Then allow completion if errors is empty.
1432 m_ready_to_create = !m_logger.has_errors();
1433 return { m_ready_to_create, m_logger.report(), m_list_of_splits };
1434}
1435
1436std::tuple<bool, Transaction*>
1438{
1439 if (!m_ready_to_create)
1440 {
1441 PERR ("errors exist. cannot create transaction.");
1442 m_list_of_splits.clear();
1443 return {false, nullptr};
1444 }
1445 auto book = qof_instance_get_book (m_acct);
1446 auto trans = xaccMallocTransaction (book);
1447 xaccTransBeginEdit (trans);
1448 xaccTransSetCurrency (trans, m_currency);
1449 xaccTransSetDescription (trans, m_transaction_description);
1450 xaccTransSetDatePostedSecsNormalized (trans, m_transaction_date);
1451 AccountVec accounts;
1452 std::for_each (m_list_of_splits.begin(), m_list_of_splits.end(),
1453 [&](auto& entry)
1454 {
1455 entry->create_split (trans, accounts);
1456 if (entry->get_kvp_tag() && entry->account())
1457 xaccAccountSetAssociatedAccount (m_acct, entry->get_kvp_tag(), entry->account());
1458 });
1459 add_price (book);
1460 xaccTransCommitEdit (trans);
1461 std::for_each (accounts.begin(), accounts.end(), xaccAccountCommitEdit);
1462 m_list_of_splits.clear();
1463 m_ready_to_create = false;
1464 return {true, trans};
1465}
1466
1467void
1468StockAssistantModel::add_price (QofBook *book)
1469{
1470 auto stock_price{m_stock_entry->calculate_price()};
1471 if (gnc_numeric_check(stock_price))
1472 return;
1473
1474 auto price = gnc_price_create (book);
1475 gnc_price_begin_edit (price);
1476 gnc_price_set_commodity (price, xaccAccountGetCommodity (m_acct));
1477 gnc_price_set_currency (price, m_currency);
1478 gnc_price_set_time64 (price, m_transaction_date);
1479 gnc_price_set_source (price, PRICE_SOURCE_STOCK_TRANSACTION);
1480 gnc_price_set_typestr (price, PRICE_TYPE_UNK);
1481 gnc_price_set_value (price, stock_price);
1482 gnc_price_commit_edit (price);
1483
1484 auto pdb = gnc_pricedb_get_db (book);
1485 if (!gnc_pricedb_add_price (pdb, price))
1486 PWARN ("error adding price");
1487
1488 gnc_price_unref (price);
1489}
1490
1491static void
1492stock_assistant_model_date_changed_cb(GtkWidget* widget, void* data)
1493{
1494 auto model{static_cast<StockAssistantModel*>(data)};
1495 model->set_transaction_date(gnc_date_edit_get_date_end(GNC_DATE_EDIT(widget)));
1496}
1497
1498static void
1499stock_assistant_model_description_changed_cb(GtkWidget* widget, void* data)
1500{
1501 auto model{static_cast<StockAssistantModel*>(data)};
1502 model->set_transaction_desc(gtk_entry_get_text(GTK_ENTRY(widget)));
1503}
1504
1505/* ********************* View Classes ************************/
1506
1507/* ***************** Generic Event Callbacks ****************/
1508static void
1509text_entry_changed_cb (GtkWidget *widget, StockTransactionEntry* entry)
1510{
1511 entry->set_memo(gtk_entry_get_text (GTK_ENTRY (widget)));
1512}
1513
1514
1515static inline GtkWidget*
1516get_widget (GtkBuilder *builder, const gchar * ID)
1517{
1518 g_return_val_if_fail (builder && ID, nullptr);
1519 auto obj = gtk_builder_get_object (builder, ID);
1520 if (!obj)
1521 PWARN ("get_widget ID '%s' not found. it may be a typo?", ID);
1522 return GTK_WIDGET (obj);
1523}
1524
1528
1529class GncDateEdit
1530{
1531 GtkWidget *m_edit;
1532public:
1533 GncDateEdit(GtkBuilder *builder) :
1534 m_edit{gnc_date_edit_new(gnc_time(nullptr), FALSE, FALSE)} {}
1535 void attach(GtkBuilder *builder, const char *table_ID, const char *label_ID,
1536 int row);
1537 time64 get_date_time() { return gnc_date_edit_get_date_end(GNC_DATE_EDIT(m_edit)); }
1538 void connect(GCallback, gpointer);
1539};
1540
1541void
1542GncDateEdit::attach(GtkBuilder *builder, const char *table_ID,
1543 const char *label_ID, int row)
1544{
1545 auto table = get_widget(builder, table_ID);
1546 auto label = get_widget (builder, label_ID);
1547 gtk_grid_attach(GTK_GRID(table), m_edit, 1, row, 1, 1);
1548 gtk_widget_show(m_edit);
1549 gnc_date_make_mnemonic_target (GNC_DATE_EDIT(m_edit), label);
1550}
1551
1552void
1553GncDateEdit::connect(GCallback cb, gpointer data)
1554{
1555 g_signal_connect(m_edit, "date_changed", cb, data);
1556}
1557
1561class GncAmountEdit
1562{
1563 GtkWidget *m_edit;
1564public:
1565 GncAmountEdit (GtkBuilder *builder, gnc_commodity *commodity);
1566 void attach (GtkBuilder *builder, const char *table_id,
1567 const char *label_ID, int row);
1568 GtkWidget* widget() {
1569 return gnc_amount_edit_gtk_entry(GNC_AMOUNT_EDIT(m_edit));
1570 }
1571 gnc_numeric get ();
1572 void connect (GCallback cb, gpointer data);
1573 void set_owner (gpointer obj);
1574};
1575
1576static void
1577value_changed_cb (GtkWidget* widget, StockTransactionEntry* entry)
1578{
1579 g_return_if_fail(GNC_IS_AMOUNT_EDIT(widget));
1580 gnc_numeric value;
1581 auto invalid{gnc_amount_edit_expr_is_valid(GNC_AMOUNT_EDIT(widget),
1582 &value, true, nullptr)};
1583 entry->set_value(invalid ? gnc_numeric_error(GNC_ERROR_ARG) : value);
1584}
1585
1586GncAmountEdit::GncAmountEdit (GtkBuilder *builder, gnc_commodity *commodity) :
1587 m_edit{gnc_amount_edit_new()}
1588{
1589 // shares amount
1590 auto info = gnc_commodity_print_info(commodity, true);
1591 gnc_amount_edit_set_evaluate_on_enter(GNC_AMOUNT_EDIT(m_edit), TRUE);
1592 gnc_amount_edit_set_print_info(GNC_AMOUNT_EDIT(m_edit), info);
1593}
1594
1595void
1596GncAmountEdit::attach (GtkBuilder *builder, const char *table_ID,
1597 const char* label_ID, int row)
1598{
1599 auto table = get_widget(builder, table_ID);
1600 auto label = get_widget(builder, label_ID);
1601 gtk_grid_attach(GTK_GRID(table), m_edit, 1, row, 1, 1);
1602 gtk_widget_show(m_edit);
1603 gnc_amount_edit_make_mnemonic_target(GNC_AMOUNT_EDIT(m_edit), label);
1604}
1605
1606gnc_numeric
1607GncAmountEdit::get ()
1608{
1609 gnc_numeric amt;
1610 if (!gnc_amount_edit_expr_is_valid (GNC_AMOUNT_EDIT(m_edit), &amt, true, nullptr))
1611 return amt;
1613}
1614
1615void
1616GncAmountEdit::connect (GCallback cb, gpointer data)
1617{
1618 g_signal_connect(m_edit, "changed", cb, data);
1619}
1620
1621void
1622GncAmountEdit::set_owner(gpointer obj)
1623{
1624 g_object_set_data(G_OBJECT (m_edit), "owner", obj);
1625}
1626
1627using AccountTypeList = std::vector<GNCAccountType>;
1628
1632class GncAccountSelector
1633{
1634 GtkWidget* m_selector;
1635public:
1636 GncAccountSelector (GtkBuilder *builder, AccountTypeList types,
1637 gnc_commodity *currency, Account *default_acct);
1638 void attach (GtkBuilder *builder, const char *table_id,
1639 const char *label_ID, int row);
1640 void connect (StockTransactionEntry*);
1641 void set (Account *acct) { gnc_account_sel_set_account (GNC_ACCOUNT_SEL (m_selector), acct, TRUE); }
1642 void set_sensitive(bool sensitive);
1643 Account *get () { return gnc_account_sel_get_account (GNC_ACCOUNT_SEL (m_selector)); }
1644};
1645
1646static void
1647gnc_account_sel_changed_cb (GtkWidget* widget, StockTransactionEntry* entry)
1648{
1649 g_return_if_fail (GNC_IS_ACCOUNT_SEL (widget));
1650 entry->set_account(gnc_account_sel_get_account (GNC_ACCOUNT_SEL (widget)));
1651}
1652
1653GncAccountSelector::GncAccountSelector (GtkBuilder *builder, AccountTypeList types,
1654 gnc_commodity *currency, Account *default_acct) :
1655 m_selector{gnc_account_sel_new ()}
1656{
1657 auto accum = [](auto a, auto b) { return g_list_prepend(a, (gpointer)b); };
1658 auto null_glist = static_cast<GList *>(nullptr);
1659 auto acct_list = std::accumulate(types.begin(), types.end(), null_glist, accum);
1660 auto curr_list = accum(null_glist, currency);
1661 gnc_account_sel_set_new_account_ability(GNC_ACCOUNT_SEL(m_selector), true);
1662 gnc_account_sel_set_acct_filters(GNC_ACCOUNT_SEL(m_selector), acct_list, curr_list);
1663 gnc_account_sel_set_default_new_commodity(GNC_ACCOUNT_SEL(m_selector), currency);
1664 gnc_account_sel_set_new_account_modal (GNC_ACCOUNT_SEL(m_selector), true);
1665 if (default_acct)
1666 gnc_account_sel_set_account (GNC_ACCOUNT_SEL(m_selector), default_acct, true);
1667 g_list_free(acct_list);
1668 g_list_free(curr_list);
1669}
1670
1671void
1672GncAccountSelector::attach (GtkBuilder *builder, const char *table_ID,
1673 const char *label_ID, int row)
1674{
1675 auto table = get_widget(builder, table_ID);
1676 auto label = get_widget(builder, label_ID);
1677 gtk_grid_attach(GTK_GRID(table), m_selector, 1, row, 1, 1);
1678 gtk_widget_show(m_selector);
1679 gtk_label_set_mnemonic_widget(GTK_LABEL(label), m_selector);
1680}
1681
1682void
1683GncAccountSelector::connect (StockTransactionEntry* entry)
1684{
1685 g_signal_connect(m_selector, "account_sel_changed", G_CALLBACK (gnc_account_sel_changed_cb), entry);
1686}
1687
1688void
1689GncAccountSelector::set_sensitive(bool sensitive)
1690{
1691 gtk_widget_set_sensitive(m_selector, sensitive);
1692}
1693
1694
1706static void
1707assistant_page_set_focus(GtkWidget* page, [[maybe_unused]]GtkDirectionType type, GtkWidget* entry)
1708{
1709 gtk_widget_grab_focus(entry);
1710 g_signal_handlers_disconnect_by_data(page, entry);
1711}
1737
1742class PageTransType {
1743 // transaction type page
1744 GtkWidget * m_page;
1745 GtkWidget * m_type;
1746 GtkWidget * m_explanation;
1747public:
1748 PageTransType(GtkBuilder *builder);
1749 void prepare(StockAssistantModel* model);
1750 int get_transaction_type_index ();
1751 void set_transaction_types (const TxnTypeVec& txn_types);
1758 void set_txn_type_explanation (const gchar *txt);
1759 void connect (StockAssistantModel *model);
1760 void change_txn_type (StockAssistantModel *model);
1761};
1762
1763PageTransType::PageTransType(GtkBuilder *builder)
1764 : m_page(get_widget(builder, "transaction_type_page")),
1765 m_type(get_widget(builder, "transaction_type_page_combobox")),
1766 m_explanation(get_widget(builder, "transaction_type_page_explanation"))
1767{
1768 g_object_set_data(G_OBJECT(m_type), "owner", this);
1769}
1770
1771static void
1772page_trans_type_changed_cb (GtkWidget* widget, StockAssistantModel *model)
1773{
1774 auto me = static_cast<PageTransType *>(g_object_get_data (G_OBJECT (widget), "owner"));
1775 g_return_if_fail (me);
1776 me->change_txn_type (model);
1777}
1778
1779void
1780PageTransType::prepare(StockAssistantModel *model)
1781{
1782 const auto& txn_types{model->get_txn_types()};
1783 if (!txn_types)
1784 return;
1785
1786 set_transaction_types(txn_types.value());
1787 change_txn_type (model);
1788 g_signal_connect(m_page, "focus", G_CALLBACK(assistant_page_set_focus), m_type);
1789}
1790
1791int
1792PageTransType::get_transaction_type_index ()
1793{
1794 return gtk_combo_box_get_active (GTK_COMBO_BOX (m_type));
1795}
1796
1797void
1798PageTransType::set_transaction_types (const TxnTypeVec& txn_types)
1799{
1800 auto combo = GTK_COMBO_BOX_TEXT (m_type);
1801 gtk_combo_box_text_remove_all (combo);
1802 std::for_each (txn_types.begin(), txn_types.end(),
1803 [&combo](const auto& it)
1804 { gtk_combo_box_text_append_text (combo, _(it.friendly_name)); });
1805 gtk_combo_box_set_active (GTK_COMBO_BOX (combo), 0);
1806}
1807
1808void
1810{
1811 gtk_label_set_text (GTK_LABEL (this->m_explanation), txt);
1812}
1813
1814void
1815PageTransType::change_txn_type (StockAssistantModel *model)
1816{
1817 auto type_idx = get_transaction_type_index();
1818 if (type_idx < 0) // combo isn't initialized yet.
1819 return;
1820
1821 if (!model->set_txn_type(type_idx))
1822 return;
1823 auto txn_type{model->txn_type()};
1824 set_txn_type_explanation (_(txn_type->explanation));
1825}
1826
1827void
1828PageTransType::connect(StockAssistantModel *model)
1829{
1830 g_signal_connect(m_type, "changed",
1831 G_CALLBACK (page_trans_type_changed_cb), model);
1832}
1833
1839class PageTransDeets
1840{
1841 // transaction details page
1842 GtkWidget *m_page;
1843 GncDateEdit m_date;
1844 GtkWidget *m_description;
1845public:
1846 PageTransDeets (GtkBuilder *builder);
1847 time64 get_date_time () { return m_date.get_date_time(); }
1848 const char* get_description () { return gtk_entry_get_text (GTK_ENTRY (m_description)); }
1849 void connect (StockAssistantModel*);
1850 void prepare(StockAssistantModel*);
1851};
1852
1853PageTransDeets::PageTransDeets (GtkBuilder *builder) :
1854 m_page (get_widget (builder, "transaction_details_page")),
1855 m_date (builder),
1856 m_description (get_widget (builder, "transaction_description_entry"))
1857{
1858 m_date.attach(builder, "transaction_details_table", "transaction_date_label", 0);
1859}
1860
1861void
1862PageTransDeets::connect(StockAssistantModel* model)
1863{
1864 m_date.connect(G_CALLBACK (stock_assistant_model_date_changed_cb),
1865 static_cast<void*>(model));
1866 g_signal_connect(m_description, "changed",
1867 G_CALLBACK (stock_assistant_model_description_changed_cb),
1868 static_cast<void*>(model));
1869}
1870
1871void
1872PageTransDeets::prepare(StockAssistantModel* model)
1873{
1874 model->set_transaction_date(get_date_time());
1875 model->set_transaction_desc(get_description());
1876 g_signal_connect(m_page, "focus", G_CALLBACK(assistant_page_set_focus), m_description);
1877}
1878
1888class PageStockAmount
1889{
1890 // stock amount page
1891 GtkWidget * m_page;
1892 GtkWidget * m_title;
1893 GtkWidget * m_prev_amount;
1894 GtkWidget * m_next_amount;
1895 GtkWidget * m_next_amount_label;
1896 GncAmountEdit m_amount;
1897 GtkWidget * m_amount_label;
1898public:
1899 PageStockAmount (GtkBuilder *builder, Account* account);
1900 void prepare (StockTransactionEntry*);
1901 gnc_numeric get_stock_amount () { return m_amount.get(); }
1902 void set_stock_amount (std::string new_amount_str);
1903 void connect(StockTransactionEntry* entry);
1904};
1905
1906PageStockAmount::PageStockAmount (GtkBuilder *builder, Account* account) :
1907 m_page (get_widget (builder, "stock_amount_page")),
1908 m_title (get_widget (builder, "stock_amount_title")),
1909 m_prev_amount (get_widget (builder, "prev_balance_amount")),
1910 m_next_amount (get_widget (builder, "next_balance_amount")),
1911 m_next_amount_label (get_widget (builder, "next_balance_label")),
1912 m_amount (builder, xaccAccountGetCommodity(account)),
1913 m_amount_label (get_widget (builder, "stock_amount_label"))
1914{
1915 m_amount.attach (builder, "stock_amount_table", "stock_amount_label", 1);
1916}
1917
1918void
1919PageStockAmount::prepare (StockTransactionEntry* entry)
1920{
1921 gtk_label_set_text_with_mnemonic
1922 (GTK_LABEL (m_amount_label),
1923 entry->input_new_balance() ? _("Ne_w Balance") : _("_Shares"));
1924 gtk_label_set_text
1925 (GTK_LABEL (m_next_amount_label),
1926 entry->input_new_balance() ? _("Ratio") : _("Next Balance"));
1927 gtk_label_set_text
1928 (GTK_LABEL (m_title),
1929 entry->input_new_balance() ?
1930 _("Enter the new balance of shares after the stock split.") :
1931 _("Enter the number of shares you gained or lost in the transaction."));
1932 gtk_label_set_text (GTK_LABEL (m_prev_amount), entry->print_amount(entry->get_balance()));
1933 if (!gnc_numeric_check(get_stock_amount()))
1934 entry->set_amount(get_stock_amount());
1935 set_stock_amount(entry->amount_str_for_display());
1936 g_signal_connect(m_page, "focus", G_CALLBACK(assistant_page_set_focus), m_amount.widget());
1937}
1938
1939static void
1940page_stock_amount_changed_cb(GtkWidget *widget, StockTransactionEntry* entry)
1941{
1942 auto me = static_cast<PageStockAmount*>(g_object_get_data (G_OBJECT (widget), "owner"));
1943 entry->set_amount(me->get_stock_amount());
1944 me->set_stock_amount(entry->amount_str_for_display());
1945}
1946
1947void
1948PageStockAmount::connect(StockTransactionEntry* entry)
1949{
1950 m_amount.connect(G_CALLBACK (page_stock_amount_changed_cb), entry);
1951 m_amount.set_owner(static_cast<gpointer>(this));
1952}
1953
1954void
1955PageStockAmount::set_stock_amount (std::string new_amount_str)
1956{
1957 gtk_label_set_text (GTK_LABEL(m_next_amount), new_amount_str.c_str());
1958}
1959
1964class PageStockValue
1965{
1966 // stock value page
1967 GtkWidget * m_page;
1968 GncAmountEdit m_value;
1969 GtkWidget * m_price;
1970 GtkWidget * m_memo;
1971public:
1972 PageStockValue (GtkBuilder *builder, Account* account);
1973 const char* get_memo ();
1974 void connect(StockTransactionEntry* entry);
1975 void prepare(StockTransactionEntry* entry);
1976 GncAmountEdit& value_edit() { return m_value; }
1977 void set_price(const gchar *val);
1978};
1979
1980static void
1981page_stock_value_changed_cb(GtkWidget *widget, StockTransactionEntry* entry)
1982{
1983 auto me = static_cast<PageStockValue*>(g_object_get_data (G_OBJECT (widget), "owner"));
1984 entry->set_value (me->value_edit().get());
1985 me->set_price(entry->print_price());
1986}
1987
1988PageStockValue::PageStockValue(GtkBuilder *builder, Account* account)
1989 : m_page(get_widget(builder, "stock_value_page")),
1990 m_value(builder, gnc_account_get_currency_or_parent(account)),
1991 m_price(get_widget(builder, "stock_price_amount")),
1992 m_memo(get_widget(builder, "stock_memo_entry"))
1993{
1994 m_value.attach(builder, "stock_value_table", "stock_value_label", 0);
1995}
1996
1997void
1998PageStockValue::connect(StockTransactionEntry* entry)
1999{
2000 m_value.connect(G_CALLBACK (page_stock_value_changed_cb), entry);
2001 m_value.set_owner (static_cast<gpointer>(this));
2002 g_signal_connect (m_memo, "changed", G_CALLBACK(text_entry_changed_cb), entry);
2003}
2004
2005void
2006PageStockValue::prepare(StockTransactionEntry* entry)
2007{
2008 entry->set_memo(get_memo());
2009 if (!gnc_numeric_check(m_value.get()))
2010 entry->set_value(m_value.get());
2011 set_price(entry->print_price());
2012 g_signal_connect(m_page, "focus", G_CALLBACK(assistant_page_set_focus), m_value.widget());
2013}
2014
2015const char *
2016PageStockValue::get_memo()
2017{
2018 return gtk_entry_get_text(GTK_ENTRY (m_memo));
2019}
2020
2021void
2022PageStockValue::set_price (const gchar *val)
2023{
2024 gtk_label_set_text(GTK_LABEL(this->m_price), val);
2025};
2026
2032class PageCash
2033{
2034 // cash page
2035 GtkWidget * m_page;
2036 GncAccountSelector m_account;
2037 GtkWidget * m_memo;
2038 GncAmountEdit m_value;
2039public:
2040 PageCash (GtkBuilder *builder, Account* account);
2041 void connect(StockTransactionEntry* entry);
2042 void prepare(StockTransactionEntry* entry);
2043 const char* get_memo();
2044};
2045
2046PageCash::PageCash(GtkBuilder *builder, Account* account)
2047 : m_page(get_widget(builder, "cash_details_page")),
2048 m_account(builder, {ACCT_TYPE_ASSET, ACCT_TYPE_BANK},
2050 xaccAccountGetAssociatedAccount (account, PROCEEDS_KVP_TAG)),
2051 m_memo(get_widget(builder, "cash_memo_entry")),
2052 m_value(builder, gnc_account_get_currency_or_parent(account))
2053{
2054 m_account.attach (builder, "cash_table", "cash_account_label", 0);
2055 m_value.attach (builder, "cash_table", "cash_label", 1);
2056}
2057
2058void
2059PageCash::connect(StockTransactionEntry* entry)
2060{
2061 m_account.connect(entry);
2062 g_signal_connect(m_memo, "changed", G_CALLBACK(text_entry_changed_cb), entry);
2063 m_value.connect(G_CALLBACK(value_changed_cb), entry);
2064}
2065
2066void
2067PageCash::prepare(StockTransactionEntry* entry)
2068{
2069 entry->set_memo(get_memo());
2070 if (!gnc_numeric_check(m_value.get()))
2071 entry->set_value(m_value.get());
2072 entry->set_account(m_account.get());
2073 g_signal_connect(m_page, "focus", G_CALLBACK(assistant_page_set_focus), m_value.widget());
2074}
2075
2076const char *
2077PageCash::get_memo()
2078{
2079 return gtk_entry_get_text(GTK_ENTRY (m_memo));
2080}
2081
2087class PageFees
2088{
2089 // fees page
2090 GtkWidget * m_page;
2091 GtkWidget * m_capitalize;
2092 GncAccountSelector m_account;
2093 GtkWidget * m_memo;
2094 GncAmountEdit m_value;
2095 Account* m_stock_account;
2096public:
2097 PageFees (GtkBuilder *builder, Account* account);
2098 void connect(StockTransactionEntry*);
2099 bool get_capitalize_fees ();
2100 const char* get_memo();
2101 void set_capitalize_fees (bool state);
2102 void set_account (Account *acct) { m_account.set(acct); }
2103 Account* stock_account() { return m_stock_account; }
2104 void update_fees_acct_sensitive (bool sensitive);
2105 void prepare(StockTransactionEntry*);
2106};
2107
2108PageFees::PageFees(GtkBuilder *builder, Account* account)
2109 : m_page(get_widget(builder, "fees_details_page")),
2110 m_capitalize(
2111 get_widget(builder, "capitalize_fees_checkbutton")),
2112 m_account(builder, {ACCT_TYPE_EXPENSE}, gnc_account_get_currency_or_parent(account),
2113 xaccAccountGetAssociatedAccount (account, FEES_KVP_TAG)),
2114 m_memo(get_widget(builder, "fees_memo_entry")),
2115 m_value(builder, gnc_account_get_currency_or_parent(account)),
2116 m_stock_account(account)
2117{
2118 m_account.attach (builder, "fees_table", "fees_account_label", 1);
2119 m_value.attach(builder, "fees_table", "fees_label", 2);
2120}
2121
2122bool
2123PageFees::get_capitalize_fees()
2124{
2125 return gtk_toggle_button_get_active(
2126 GTK_TOGGLE_BUTTON(m_capitalize));
2127}
2128
2129const char *
2130PageFees::get_memo()
2131{
2132 return gtk_entry_get_text(GTK_ENTRY (m_memo));
2133}
2134
2135void
2136PageFees::set_capitalize_fees(bool state)
2137{
2138 gtk_toggle_button_set_active(
2139 GTK_TOGGLE_BUTTON(m_capitalize), state);
2140}
2141
2142void
2143PageFees::update_fees_acct_sensitive(bool sensitive)
2144{
2145 m_account.set_sensitive(sensitive);
2146}
2147
2148static void
2149capitalize_fees_toggled_cb (GtkWidget *widget, StockTransactionEntry *entry)
2150{
2151 g_return_if_fail (entry);
2152 auto me = static_cast<PageFees *>(g_object_get_data (G_OBJECT (widget), "owner"));
2153 g_return_if_fail (me);
2154 bool cap = me->get_capitalize_fees();
2155 entry->set_capitalize(cap);
2156 if (cap)
2157 entry->set_account(me->stock_account());
2158 me->update_fees_acct_sensitive(!cap);
2159}
2160
2161void
2162PageFees::connect(StockTransactionEntry* entry)
2163{
2164 m_account.connect(entry);
2165 g_signal_connect(m_memo, "changed", G_CALLBACK(text_entry_changed_cb), entry);
2166 m_value.connect(G_CALLBACK(value_changed_cb), entry);
2167 g_object_set_data(G_OBJECT (m_capitalize), "owner", this);
2168 g_signal_connect (m_capitalize, "toggled", G_CALLBACK (capitalize_fees_toggled_cb), entry);
2169}
2170
2171void
2172PageFees::prepare(StockTransactionEntry* entry)
2173{
2174 set_capitalize_fees (entry->do_capitalize());
2175 entry->set_memo(get_memo());
2176 if (!gnc_numeric_check(m_value.get()))
2177 entry->set_value (m_value.get());
2178 entry->set_account(m_account.get());
2179 g_signal_connect(m_page, "focus", G_CALLBACK(assistant_page_set_focus), m_value.widget());
2180}
2181
2184class PageDividend
2185{
2186 // dividend page
2187 GtkWidget *m_page;
2188 GncAccountSelector m_account;
2189 GtkWidget *m_memo;
2190 GncAmountEdit m_value;
2191public:
2192 PageDividend (GtkBuilder *builder, Account* account);
2193 void connect(StockTransactionEntry*);
2194 void prepare(StockTransactionEntry*);
2195 const char* get_memo();
2196};
2197
2198PageDividend::PageDividend(GtkBuilder *builder, Account* account)
2199 : m_page(get_widget(builder, "dividend_details_page")),
2200 m_account(builder, {ACCT_TYPE_INCOME}, gnc_account_get_currency_or_parent(account),
2201 xaccAccountGetAssociatedAccount (account, DIVIDEND_KVP_TAG)),
2202 m_memo(get_widget(builder, "dividend_memo_entry")),
2203 m_value(builder, gnc_account_get_currency_or_parent(account))
2204{
2205 m_account.attach(builder, "dividend_table", "dividend_account_label", 0);
2206 m_value.attach(builder, "dividend_table", "dividend_label", 1);
2207}
2208
2209
2210void
2211PageDividend::connect(StockTransactionEntry* entry)
2212{
2213 m_account.connect(entry);
2214 g_signal_connect(m_memo, "changed", G_CALLBACK(text_entry_changed_cb), entry);
2215 m_value.connect(G_CALLBACK(value_changed_cb), entry);
2216}
2217
2218void
2219PageDividend::prepare(StockTransactionEntry* entry)
2220{
2221 entry->set_memo(get_memo());
2222 if (!gnc_numeric_check(m_value.get()))
2223 entry->set_value(m_value.get());
2224 entry->set_account(m_account.get());
2225 g_signal_connect(m_page, "focus", G_CALLBACK(assistant_page_set_focus), m_value.widget());
2226}
2227
2228const char *
2229PageDividend::get_memo()
2230{
2231 return gtk_entry_get_text(GTK_ENTRY (m_memo));
2232}
2233
2234class PageCapGain
2235{
2236 // capgains page
2237 GtkWidget * m_page;
2238 GncAccountSelector m_account;
2239 GtkWidget * m_memo;
2240 GncAmountEdit m_value;
2241public:
2242 PageCapGain (GtkBuilder *builder, Account* account);
2243 void connect(StockTransactionEntry* entry);
2244 void prepare(StockTransactionEntry* entry);
2245 const char* get_memo();
2246};
2247
2248PageCapGain::PageCapGain (GtkBuilder *builder, Account* account) :
2249 m_page (get_widget (builder, "capgains_details_page")),
2250 m_account (builder, { ACCT_TYPE_INCOME }, gnc_account_get_currency_or_parent(account),
2251 xaccAccountGetAssociatedAccount (account, CAPGAINS_KVP_TAG)),
2252 m_memo (get_widget (builder, "capgains_memo_entry")),
2253 m_value (builder, gnc_account_get_currency_or_parent(account))
2254{
2255 m_account.attach(builder, "capgains_table", "capgains_account_label", 0);
2256 m_value.attach(builder, "capgains_table", "capgains_label", 1);
2257}
2258
2259const char *
2260PageCapGain::get_memo()
2261{
2262 return gtk_entry_get_text(GTK_ENTRY (m_memo));
2263}
2264
2265
2266void
2267PageCapGain::connect(StockTransactionEntry*entry)
2268{
2269 m_account.connect(entry);
2270 g_signal_connect(m_memo, "changed", G_CALLBACK(text_entry_changed_cb), entry);
2271 m_value.connect(G_CALLBACK(value_changed_cb), entry);
2272}
2273
2274void
2275PageCapGain::prepare(StockTransactionEntry* entry)
2276{
2277 entry->set_memo(get_memo());
2278 if (!gnc_numeric_check(m_value.get()))
2279 entry->set_value(m_value.get());
2280 entry->set_account(m_account.get());
2281 g_signal_connect(m_page, "focus", G_CALLBACK(assistant_page_set_focus), m_value.widget());
2282}
2283
2284
2285enum split_cols
2286{
2287 SPLIT_COL_ACCOUNT = 0,
2288 SPLIT_COL_MEMO,
2289 SPLIT_COL_TOOLTIP,
2290 SPLIT_COL_DEBIT,
2291 SPLIT_COL_CREDIT,
2292 SPLIT_COL_UNITS,
2293 SPLIT_COL_UNITS_COLOR,
2294 NUM_SPLIT_COLS
2295};
2296
2297/* Displays a summary of the transactions as a list. */
2298class GncFinishTreeview
2299{
2300 GtkWidget *m_treeview;
2301public:
2302 GncFinishTreeview(GtkBuilder *builder);
2307 void load(const EntryVec& list_of_splits);
2308};
2309
2310GncFinishTreeview::GncFinishTreeview (GtkBuilder *builder) :
2311 m_treeview{get_widget (builder, "transaction_view")}
2312{
2313 auto view = GTK_TREE_VIEW (m_treeview);
2314 gtk_tree_view_set_grid_lines (GTK_TREE_VIEW(view), gnc_tree_view_get_grid_lines_pref ());
2315
2316 auto store = gtk_list_store_new (NUM_SPLIT_COLS, G_TYPE_STRING, G_TYPE_STRING,
2317 G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING,
2318 G_TYPE_STRING, G_TYPE_STRING);
2319 gtk_tree_view_set_model(view, GTK_TREE_MODEL(store));
2320 gtk_tree_selection_set_mode (gtk_tree_view_get_selection (view),
2321 GTK_SELECTION_NONE);
2322 g_object_unref(store);
2323
2324 auto renderer = gtk_cell_renderer_text_new();
2325 auto column = gtk_tree_view_column_new_with_attributes
2326 (_("Account"), renderer, "text", SPLIT_COL_ACCOUNT, nullptr);
2327 gtk_tree_view_append_column(view, column);
2328
2329 renderer = gtk_cell_renderer_text_new();
2330 g_object_set (renderer, "ellipsize", PANGO_ELLIPSIZE_END, nullptr);
2331 column = gtk_tree_view_column_new_with_attributes
2332 (_("Memo"), renderer, "text", SPLIT_COL_MEMO, nullptr);
2333 gtk_tree_view_column_set_expand (column, true);
2334 gtk_tree_view_append_column(view, column);
2335
2336 renderer = gtk_cell_renderer_text_new();
2337 gtk_cell_renderer_set_alignment (renderer, 1.0, 0.5);
2338 gtk_cell_renderer_set_padding (renderer, 5, 0);
2339 column = gtk_tree_view_column_new_with_attributes
2340 (_("Debit"), renderer, "text", SPLIT_COL_DEBIT, nullptr);
2341 gtk_tree_view_append_column(view, column);
2342
2343 renderer = gtk_cell_renderer_text_new();
2344 gtk_cell_renderer_set_alignment (renderer, 1.0, 0.5);
2345 gtk_cell_renderer_set_padding (renderer, 5, 0);
2346 column = gtk_tree_view_column_new_with_attributes
2347 (_("Credit"), renderer, "text", SPLIT_COL_CREDIT, nullptr);
2348 gtk_tree_view_append_column(view, column);
2349
2350 renderer = gtk_cell_renderer_text_new();
2351 gtk_cell_renderer_set_alignment (renderer, 1.0, 0.5);
2352 gtk_cell_renderer_set_padding (renderer, 5, 0);
2353 column = gtk_tree_view_column_new_with_attributes
2354 (_("Units"), renderer,
2355 "text", SPLIT_COL_UNITS,
2356 "foreground", SPLIT_COL_UNITS_COLOR,
2357 nullptr);
2358 gtk_tree_view_append_column(view, column);
2359 gtk_tree_view_set_tooltip_column(GTK_TREE_VIEW(m_treeview),
2360 SPLIT_COL_TOOLTIP);}
2361
2362void
2363GncFinishTreeview::load(const EntryVec& list_of_splits)
2364{
2365 auto gtv = GTK_TREE_VIEW(m_treeview);
2366 bool negative_in_red = gnc_prefs_get_bool (GNC_PREFS_GROUP_GENERAL,
2367 GNC_PREF_NEGATIVE_IN_RED);
2368 auto list = GTK_LIST_STORE(gtk_tree_view_get_model(gtv));
2369 gtk_list_store_clear(list);
2370 for (const auto &entry : list_of_splits) {
2371 GtkTreeIter iter;
2372 auto memo{entry->memo()};
2373 auto tooltip = (memo && *memo ?
2374 g_markup_escape_text(memo, -1) : strdup(""));
2375 /* print_value and print_amount rely on xaccPrintAmount that
2376 * uses static memory so the result needs to be copied
2377 * immediately or the second call overwrites the results of
2378 * the first one.
2379 */
2380 auto char2str{[](const char* str) -> std::string {
2381 return std::string{ str ? str : "" }; }};
2382 auto amount{char2str(entry->print_value())};
2383 auto units{char2str(entry->has_amount() ?
2384 entry->print_amount(entry->debit_side() ? entry->amount() :
2385 gnc_numeric_neg(entry->amount())) : "")};
2386 auto units_in_red{negative_in_red && !entry->debit_side()};
2387 gtk_list_store_append(list, &iter);
2388 gtk_list_store_set(
2389 list, &iter,
2390 SPLIT_COL_ACCOUNT,
2391 entry->print_account(), SPLIT_COL_MEMO,
2392 entry->memo(), SPLIT_COL_TOOLTIP, tooltip, SPLIT_COL_DEBIT,
2393 entry->debit_side() ? amount.c_str() : nullptr,
2394 SPLIT_COL_CREDIT,
2395 entry->debit_side() ? nullptr : amount.c_str(),
2396 SPLIT_COL_UNITS, units.c_str(),
2397 SPLIT_COL_UNITS_COLOR, units_in_red ? "red" : nullptr, -1);
2398 g_free(tooltip);
2399 }
2400}
2401
2405class PageFinish
2406{
2407 // finish page
2408 GtkWidget * m_page;
2409 GncFinishTreeview m_view;
2410 GtkWidget * m_summary;
2411public:
2412 PageFinish (GtkBuilder *builder);
2413 void prepare (GtkWidget *window, StockAssistantModel *model);
2414};
2415
2416PageFinish::PageFinish (GtkBuilder *builder) :
2417 m_page (get_widget (builder, "finish_page")), m_view (builder),
2418 m_summary (get_widget (builder, "finish_summary")) {}
2419
2420
2421void
2422PageFinish::prepare (GtkWidget *window, StockAssistantModel *model)
2423{
2424 auto [success, summary, list_of_splits] = model->generate_list_of_splits ();
2425 m_view.load(list_of_splits);
2426 gtk_label_set_text(GTK_LABEL(m_summary), summary.c_str());
2427 gtk_assistant_set_page_complete(GTK_ASSISTANT(window), m_page, success);
2428}
2429
2430enum assistant_pages
2431{
2432 PAGE_INTRO = 0,
2433 PAGE_TRANSACTION_DETAILS,
2434 PAGE_TRANSACTION_TYPE,
2435 PAGE_STOCK_AMOUNT,
2436 PAGE_STOCK_VALUE,
2437 PAGE_CASH,
2438 PAGE_FEES,
2439 PAGE_DIVIDEND,
2440 PAGE_CAPGAINS,
2441 PAGE_FINISH
2442};
2443
2445class StockAssistantView {
2446 GtkWidget * m_window;
2447
2448 PageTransType m_type_page;
2449 PageTransDeets m_deets_page;
2450 PageStockAmount m_stock_amount_page;
2451 PageStockValue m_stock_value_page;
2452 PageCash m_cash_page;
2453 PageFees m_fees_page;
2454 PageDividend m_dividend_page;
2455 PageCapGain m_capgain_page;
2456 PageFinish m_finish_page;
2457public:
2458 StockAssistantView(GtkBuilder *builder, Account* account, GtkWidget *parent);
2459 ~StockAssistantView();
2472 void prepare(int page, StockAssistantModel*);
2473 GtkWidget* window() { return m_window; }
2474};
2475
2476StockAssistantView::StockAssistantView (GtkBuilder *builder, Account* account, GtkWidget *parent) :
2477 m_window (get_widget (builder, "stock_transaction_assistant")), m_type_page(builder), m_deets_page(builder),
2478 m_stock_amount_page (builder, account), m_stock_value_page (builder, account), m_cash_page (builder, account),
2479 m_fees_page (builder, account), m_dividend_page (builder, account), m_capgain_page (builder, account),
2480 m_finish_page (builder)
2481{
2482 // Set the name for this assistant so it can be easily manipulated with css
2483 gtk_widget_set_name (GTK_WIDGET(m_window), "gnc-id-assistant-stock-transaction");
2484 gtk_window_set_transient_for (GTK_WINDOW (m_window), GTK_WINDOW(parent));
2485 gnc_window_adjust_for_screen (GTK_WINDOW(m_window));
2486 gnc_restore_window_size (GNC_PREFS_GROUP, GTK_WINDOW(m_window),
2487 GTK_WINDOW(parent));
2488 gtk_widget_show_all (m_window);
2489 DEBUG ("StockAssistantView constructor\n");
2490};
2491
2492StockAssistantView::~StockAssistantView()
2493{
2494 gnc_save_window_size (GNC_PREFS_GROUP, GTK_WINDOW(m_window));
2495 gtk_widget_destroy (m_window);
2496 DEBUG ("StockAssistantView destructor\n");
2497};
2498
2504
2505static gint
2506forward_page_func (gint current_page, void* data)
2507{
2508 auto model{static_cast<StockAssistantModel*>(data)};
2509 current_page++;
2510 if (!model->txn_type_valid())
2511 return current_page;
2512
2513 if (!model->stock_entry()->has_amount() && current_page == PAGE_STOCK_AMOUNT)
2514 current_page++;
2515 if (!model->stock_entry()->enabled() && current_page == PAGE_STOCK_VALUE)
2516 current_page++;
2517 if (!model->cash_entry()->enabled() && current_page == PAGE_CASH)
2518 current_page++;
2519 if (!model->fees_entry()->enabled() && current_page == PAGE_FEES)
2520 current_page++;
2521 if (!model->dividend_entry()->enabled() && current_page == PAGE_DIVIDEND)
2522 current_page++;
2523 if (!model->capgains_entry()->enabled() && current_page == PAGE_CAPGAINS)
2524 current_page++;
2525
2526 return current_page;
2527}
2528
2529void
2531{
2532 m_type_page.connect(model);
2533 m_deets_page.connect(model);
2534 m_stock_amount_page.connect(model->stock_entry());
2535 m_stock_value_page.connect(model->stock_entry());
2536 m_cash_page.connect(model->cash_entry());
2537 m_fees_page.connect(model->fees_entry());
2538 m_dividend_page.connect(model->dividend_entry());
2539 m_capgain_page.connect(model->capgains_entry());
2540
2541 gtk_assistant_set_forward_page_func (GTK_ASSISTANT(m_window),
2542 (GtkAssistantPageFunc)forward_page_func,
2543 model, nullptr);
2544}
2545
2546void
2548{
2549 g_return_if_fail (page < PAGE_STOCK_AMOUNT || model->txn_type_valid());
2550 switch (page)
2551 {
2552 case PAGE_TRANSACTION_TYPE:
2553 if (!model->maybe_reset_txn_types())
2554 break;
2555 m_type_page.prepare(model);
2556 break;
2557 case PAGE_TRANSACTION_DETAILS:
2558 m_deets_page.prepare(model);
2559 break;
2560 case PAGE_STOCK_AMOUNT:
2561 {
2562 m_stock_amount_page.prepare(model->stock_entry());
2563 break;
2564 }
2565 case PAGE_STOCK_VALUE:
2566 m_stock_value_page.prepare(model->stock_entry());
2567 break;
2568 case PAGE_CASH:
2569 m_cash_page.prepare(model->cash_entry());
2570 break;
2571 case PAGE_FEES:
2572 {
2573 m_fees_page.prepare(model->fees_entry());
2574 break;
2575 }
2576 case PAGE_DIVIDEND:
2577 m_dividend_page.prepare(model->dividend_entry());
2578 break;
2579 case PAGE_CAPGAINS:
2580 {
2581 m_capgain_page.prepare(model->capgains_entry());
2582 break;
2583 }
2584 case PAGE_FINISH:
2585 {
2586 m_finish_page.prepare (m_window, model);
2587 break;
2588 }
2589 default:
2590 break;
2591 }
2592}
2593
2598
2599static void stock_account_destroyed_handler(QofInstance *inst, QofEventId event,
2600 void* handler_data, [[maybe_unused]]void* event_data);
2601
2602class StockAssistantController
2603{
2604 std::unique_ptr<StockAssistantModel> m_model;
2605 StockAssistantView m_view;
2606 bool m_destroying = false;
2607 int m_qof_event_handler;
2608public:
2609 StockAssistantController (GtkWidget *parent, GtkBuilder* builder, Account* acct)
2610 : m_model{std::make_unique<StockAssistantModel>(acct)},
2611 m_view{builder, acct, parent},
2612 m_qof_event_handler{qof_event_register_handler(stock_account_destroyed_handler, this)}
2613 {
2614 connect_signals (builder);
2615 DEBUG ("StockAssistantController constructor\n");
2616 };
2617 ~StockAssistantController ();
2618 void connect_signals(GtkBuilder *builder);
2619 void prepare(GtkAssistant* assistant, GtkWidget *page);
2620 void finish();
2621 bool destroying() { return m_destroying; }
2622 Account* model_account() { return m_model->account(); }
2623};
2624
2625static void stock_assistant_window_destroy_cb(GtkWidget *object, gpointer user_data);
2626static void close_handler (gpointer user_data);
2627
2628StockAssistantController::~StockAssistantController()
2629{
2630 m_destroying = true;
2631 gnc_unregister_gui_component_by_data (ASSISTANT_STOCK_TRANSACTION_CM_CLASS, this);
2632 qof_event_unregister_handler(m_qof_event_handler);
2633}
2634
2635void
2636StockAssistantController::connect_signals (GtkBuilder *builder)
2637{
2638 m_view.connect(m_model.get());
2639 gtk_builder_connect_signals (builder, this); //Stock Assistant View: cancel, close, prepare
2640 g_signal_connect (m_view.window(), "destroy",
2641 G_CALLBACK (stock_assistant_window_destroy_cb), this);
2642
2643
2644 auto component_id = gnc_register_gui_component
2645 (ASSISTANT_STOCK_TRANSACTION_CM_CLASS, nullptr, close_handler, this);
2646 gnc_gui_component_watch_entity_type (component_id, GNC_ID_ACCOUNT,
2647 QOF_EVENT_MODIFY | QOF_EVENT_DESTROY);
2648}
2649
2650void
2651StockAssistantController::prepare(GtkAssistant* assistant, GtkWidget* page)
2652{
2653 auto currentpage = gtk_assistant_get_current_page(assistant);
2654 m_view.prepare(currentpage, m_model.get());
2655}
2656
2657void
2658StockAssistantController::finish()
2659{
2660 g_return_if_fail (m_model->txn_type_valid());
2661
2662 gnc_suspend_gui_refresh ();
2663 auto [success, trans] = m_model->create_transaction();
2664 gnc_resume_gui_refresh ();
2665
2666 if (success && trans)
2667 {
2668 auto split = xaccTransFindSplitByAccount (trans, m_model->account());
2669 if (split)
2670 {
2671 auto page = gnc_plugin_page_register_new (m_model->account(), FALSE);
2672 gnc_main_window_open_page (nullptr, page);
2673 auto gsr = gnc_plugin_page_register_get_gsr (page);
2674 gnc_split_reg_raise (gsr);
2675
2676 if (gnc_split_reg_clear_filter_for_split (gsr, split))
2678
2679 gnc_split_reg_jump_to_split (gsr, split);
2680 }
2681 }
2682
2683 gnc_close_gui_component_by_data (ASSISTANT_STOCK_TRANSACTION_CM_CLASS, this);
2684}
2685
2686static void
2687stock_account_destroyed_handler(QofInstance *inst, QofEventId event,
2688 void* handler_data, [[maybe_unused]]void* event_data)
2689{
2690 auto controller{static_cast<StockAssistantController*>(handler_data)};
2691 if ((inst && inst != QOF_INSTANCE(controller->model_account())) || (event & QOF_EVENT_DESTROY) == 0 ||
2692 controller->destroying())
2693 return;
2694 delete controller;
2695}
2696
2697// These callbacks must be registered with the GtkAssistant so they can't be member functions.
2698/* The StockAssistantController manages the event handlers and user input. */
2699void
2700stock_assistant_prepare_cb (GtkAssistant *assistant, GtkWidget *page,
2701 gpointer user_data)
2702{
2703 auto info = static_cast<StockAssistantController*>(user_data);
2704 info->prepare(assistant, page);
2705}
2706
2707
2708static void
2709stock_assistant_window_destroy_cb (GtkWidget *object, gpointer user_data) //crashes before this gets called.
2710{
2711 auto controller = static_cast<StockAssistantController*>(user_data);
2712 if (controller->destroying())
2713 return;
2714
2715 gnc_close_gui_component_by_data (ASSISTANT_STOCK_TRANSACTION_CM_CLASS, controller);
2716}
2717
2718
2719void
2720stock_assistant_finish_cb (GtkAssistant *assistant, gpointer user_data)
2721{
2722 auto controller = static_cast<StockAssistantController*>(user_data);
2723 controller->finish();
2724}
2725
2726
2727void
2728stock_assistant_cancel_cb (GtkAssistant *assistant, gpointer user_data)
2729{
2730 auto controller = static_cast<StockAssistantController*>(user_data);
2731 if (controller->destroying())
2732 return;
2733 gnc_close_gui_component_by_data (ASSISTANT_STOCK_TRANSACTION_CM_CLASS, controller);
2734}
2735
2736
2737static void
2738close_handler (gpointer user_data)
2739{
2740 auto controller = static_cast<StockAssistantController*>(user_data);
2741 if (controller->destroying())
2742 return;
2743 delete controller;
2744}
2745
2746/********************************************************************\
2747 * gnc_stock_transaction_assistant *
2748 * opens up a assistant to record a stock transaction *
2749 * *
2750 * Args: parent - the parent ofthis window *
2751 * initial - the initial account to use *
2752 * Return: nothing *
2753\********************************************************************/
2754void
2755gnc_stock_transaction_assistant (GtkWidget *parent, Account *account)
2756{
2757 auto builder = gtk_builder_new();
2758 gnc_builder_add_from_file(builder, "assistant-stock-transaction.glade",
2759 "stock_transaction_assistant");
2760
2761 [[maybe_unused]] auto info = new StockAssistantController(parent, builder, account);
2762 g_object_unref(builder);
2763}
Account handling public routines.
Account public routines (C++ api).
API for Transactions and Splits (journal entries).
C++ wrapper for GncAccounSel, see gnucash/gnome-utils/gnc-account-sel.h.
C++ wrapper for GncAmountEdit, see gnucash/gnome-utils/gnc-amount-edit.h.
C++ wrapper for the GncDateEdit control (see gnucash/gnome-utils/gnc-date-edit.h).
void load(const EntryVec &list_of_splits)
Extract the information from the StockTransactionEntries in the vector created by the model's make_li...
The primary numeric class for representing amounts and values.
messages for later display to the user.
std::string report()
Compose all of the logged messages into a bullet list, errors first, then warnings,...
The Cash page collects the cash account (usually corresponds the broker's cash management account),...
Dividend page, collects an amount, an INCOME account, and a memo.
Transaction Details page.
Page classes generate the several pages of the assistant.
void set_txn_type_explanation(const gchar *txt)
Sets the explanation text for the selected transaction type, allowing the user to make sure that the ...
available transaction types based on the state of the account, the collection and validation of input...
bool maybe_reset_txn_types()
Selects a TxnTypevec for the user to pick from depending on whether the account has a positive,...
const std::optional< TxnTypeVec > & get_txn_types()
Accessor function.
void set_transaction_desc(const char *desc)
Setter.
std::string get_new_amount_str() const
Accessor.
StockTransactionEntry * dividend_entry()
Accessor.
StockTransactionEntry * cash_entry()
Accessor.
std::tuple< bool, std::string, EntryVec > generate_list_of_splits()
Generate the proposed list of splits.
const std::optional< TxnTypeInfo > & txn_type()
Accessor.
StockTransactionEntry * stock_entry()
Accessor.
StockTransactionEntry * fees_entry()
Accessor.
bool set_txn_type(guint type_idx)
Setter.
std::tuple< bool, Transaction * > create_transaction()
Generate a GnuCash transaction from the active entries.
void set_transaction_date(time64 date)
Setter.
StockTransactionEntry * capgains_entry()
Accessor.
Contains the pages and manages displaying them one at a time.
void prepare(int page, StockAssistantModel *)
Calls the specified page's prepare function.
void connect(StockAssistantModel *)
Calls each page's connect function.
Holds the configuration information from the fieldmask and the data to create a single split.
virtual const char * print_amount(gnc_numeric amt) const
virtual const char * print_value() const
virtual void set_fieldmask(FieldMask mask)
Set up the state variables from the FieldMask.
virtual std::string amount_str_for_display() const
Generate a string representation of the value.
virtual gnc_numeric calculate_price() const
Calculate the price (amount/value) for non-currency accounts.
virtual const char * print_price() const
void set_fieldmask(FieldMask mask) override
Set up the state variables from the FieldMask.
void set_fieldmask(FieldMask mask) override
Set up the state variables from the FieldMask.
gnc_numeric calculate_price() const override
Calculate the price (amount/value) for non-currency accounts.
std::string amount_str_for_display() const override
Generate a string representation of the value.
Date and Time handling routines.
All type declarations for the whole Gnucash engine.
Functions for adding content to a window.
An exact-rational-number library for gnucash.
Functions providing a register page for the GnuCash UI.
Generic api to store and retrieve preferences.
GtkTreeView implementation for gnucash account tree.
utility functions for the GnuCash UI
const char * xaccAccountGetName(const Account *acc)
Get the account's name.
Definition Account.cpp:3270
void xaccAccountCommitEdit(Account *acc)
ThexaccAccountCommitEdit() subroutine is the second phase of a two-phase-commit wrapper for account u...
Definition Account.cpp:1505
void xaccAccountBeginEdit(Account *acc)
The xaccAccountBeginEdit() subroutine is the first phase of a two-phase-commit wrapper for account up...
Definition Account.cpp:1464
gnc_commodity * gnc_account_get_currency_or_parent(const Account *account)
Returns a gnc_commodity that is a currency, suitable for being a Transaction's currency.
Definition Account.cpp:3396
gnc_numeric xaccAccountGetBalanceAsOfDate(Account *acc, time64 date)
Get the balance of the account at the end of the day before the date specified.
Definition Account.cpp:3514
Account * xaccAccountGetAssociatedAccount(const Account *acc, const char *tag)
Get the account's associated account e.g.
Definition Account.cpp:3368
gnc_commodity * xaccAccountGetCommodity(const Account *acc)
Get the account's commodity.
Definition Account.cpp:3389
@ ACCT_TYPE_INCOME
Income accounts are used to denote income.
Definition Account.h:140
@ ACCT_TYPE_EXPENSE
Expense accounts are used to denote expenses.
Definition Account.h:143
@ ACCT_TYPE_BANK
The bank account type denotes a savings or checking account held at a bank.
Definition Account.h:107
@ ACCT_TYPE_ASSET
asset (and liability) accounts indicate generic, generalized accounts that are none of the above.
Definition Account.h:116
const char * gnc_commodity_get_mnemonic(const gnc_commodity *cm)
Retrieve the mnemonic for the specified commodity.
gint64 time64
Most systems that are currently maintained, including Microsoft Windows, BSD-derived Unixes and Linux...
Definition gnc-date.h:87
char * qof_print_date(time64 t)
Convenience; calls through to qof_print_date_dmy_buff().
Definition gnc-date.cpp:610
time64 gnc_time64_get_day_end(time64 time_val)
The gnc_time64_get_day_end() routine will take the given time in seconds and adjust it to the last se...
time64 gnc_time(time64 *tbuf)
get the current time
Definition gnc-date.cpp:262
void xaccTransSetDescription(Transaction *trans, const char *desc)
Sets the transaction Description.
void xaccTransCommitEdit(Transaction *trans)
The xaccTransCommitEdit() method indicates that the changes to the transaction and its splits are com...
Transaction * xaccMallocTransaction(QofBook *book)
The xaccMallocTransaction() will malloc memory and initialize it.
void xaccTransSetDatePostedSecsNormalized(Transaction *trans, time64 time)
This function sets the posted date of the transaction, specified by a time64 (see ctime(3)).
void xaccTransSetCurrency(Transaction *trans, gnc_commodity *curr)
Set a new currency on a transaction.
void xaccTransBeginEdit(Transaction *trans)
The xaccTransBeginEdit() method must be called before any changes are made to a transaction or any of...
time64 xaccTransGetDate(const Transaction *trans)
Retrieve the posted date of the transaction.
void qof_event_unregister_handler(gint handler_id)
Unregister an event handler.
Definition qofevent.cpp:103
gint qof_event_register_handler(QofEventHandler handler, gpointer user_data)
Register a handler for events.
Definition qofevent.cpp:73
gint QofEventId
Define the type of events allowed.
Definition qofevent.h:45
void gnc_main_window_open_page(GncMainWindow *window, GncPluginPage *page)
Display a data plugin page in a window.
const char * xaccPrintAmount(gnc_numeric val, GNCPrintAmountInfo info)
Make a string representation of a gnc_numeric.
QofBook * qof_instance_get_book(gconstpointer inst)
Return the book pointer.
#define PINFO(format, args...)
Print an informational note.
Definition qoflog.h:256
#define DEBUG(format, args...)
Print a debugging message.
Definition qoflog.h:264
#define PERR(format, args...)
Log a serious error.
Definition qoflog.h:244
#define PWARN(format, args...)
Log a warning.
Definition qoflog.h:250
const char * gnc_numeric_errorCode_to_string(GNCNumericErrorCode error_code)
Returns a string representation of the given GNCNumericErrorCode.
#define GNC_DENOM_AUTO
Values that can be passed as the 'denom' argument.
gnc_numeric gnc_numeric_div(gnc_numeric a, gnc_numeric b, gint64 denom, gint how)
Division.
gnc_numeric gnc_numeric_error(GNCNumericErrorCode error_code)
Create a gnc_numeric object that signals the error condition noted by error_code, rather than a numbe...
GNCNumericErrorCode gnc_numeric_check(gnc_numeric in)
Check for error signal in value.
gnc_numeric gnc_numeric_abs(gnc_numeric a)
Returns a newly created gnc_numeric that is the absolute value of the given gnc_numeric value.
gboolean gnc_numeric_negative_p(gnc_numeric a)
Returns 1 if a < 0, otherwise returns 0.
gboolean gnc_numeric_zero_p(gnc_numeric a)
Returns 1 if the given gnc_numeric is 0 (zero), else returns 0.
gnc_numeric gnc_numeric_neg(gnc_numeric a)
Returns a newly created gnc_numeric that is the negative of the given gnc_numeric value.
gboolean gnc_numeric_equal(gnc_numeric a, gnc_numeric b)
Equivalence predicate: Returns TRUE (1) if a and b represent the same number.
gchar * gnc_num_dbg_to_string(gnc_numeric n)
Convert to string.
gboolean gnc_numeric_positive_p(gnc_numeric a)
Returns 1 if a > 0, otherwise returns 0.
gnc_numeric gnc_numeric_add(gnc_numeric a, gnc_numeric b, gint64 denom, gint how)
Return a+b.
@ GNC_ERROR_ARG
Argument is not a valid number.
@ GNC_HOW_DENOM_REDUCE
Reduce the result value by common factor elimination, using the smallest possible value for the denom...
@ GNC_HOW_DENOM_EXACT
Use any denominator which gives an exactly correct ratio of numerator to denominator.
gboolean gnc_prefs_get_bool(const gchar *group, const gchar *pref_name)
Get a boolean value from the preferences backend.
GNCPriceDB * gnc_pricedb_get_db(QofBook *book)
Return the pricedb associated with the book.
gboolean gnc_pricedb_add_price(GNCPriceDB *db, GNCPrice *p)
Add a price to the pricedb.
GNCPrice * gnc_price_create(QofBook *book)
gnc_price_create - returns a newly allocated and initialized price with a reference count of 1.
void gnc_price_unref(GNCPrice *p)
gnc_price_unref - indicate you're finished with a price (i.e.
void gnc_plugin_page_register_clear_current_filter(GncPluginPage *plugin_page)
This function clears the registers current filter.
GncPluginPage * gnc_plugin_page_register_new(Account *account, gboolean subaccounts)
Create a new "register" plugin page, given a pointer to an account.
GNCSplitReg * gnc_plugin_page_register_get_gsr(GncPluginPage *plugin_page)
Get the GNCSplitReg data structure associated with this register page.
Transaction * xaccSplitGetParent(const Split *split)
Returns the parent transaction of the split.
void xaccSplitSetMemo(Split *split, const char *memo)
The memo is an arbitrary string associated with a split.
void xaccSplitSetValue(Split *split, gnc_numeric val)
The xaccSplitSetValue() method sets the value of this split in the transaction's commodity.
Split * xaccMallocSplit(QofBook *book)
Constructor.
void xaccSplitSetAmount(Split *split, gnc_numeric amt)
The xaccSplitSetAmount() method sets the amount in the account's commodity that the split should have...
gnc_numeric xaccSplitGetValue(const Split *split)
Returns the value of this split in the transaction's commodity.
gnc_numeric xaccSplitGetAmount(const Split *split)
Returns the amount of the split in the account's commodity.
void xaccSplitMakeStockSplit(Split *s)
Mark a split to be of type stock split - after this, you shouldn't modify the value anymore,...
Definition Split.cpp:2074
STRUCTS.
QofBook reference.
Definition qofbook-p.hpp:47
class TxnTypeinfo has no functions.