diff --git a/Directory.Build.props b/Directory.Build.props index 3d4e34fc..975c37ed 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,7 +1,8 @@ - 2026.07.01.1 + 2026.09.01.1 vov4uk Copyright (C) vov4uk + true diff --git a/Directory.Packages.props b/Directory.Packages.props index 6860619f..909958ae 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -10,18 +10,15 @@ - - + + + - + - - - - - + @@ -30,18 +27,18 @@ - + - + - - - + + + - + \ No newline at end of file diff --git a/global.json b/global.json new file mode 100644 index 00000000..8f73781c --- /dev/null +++ b/global.json @@ -0,0 +1,5 @@ +{ + "test": { + "runner": "Microsoft.Testing.Platform" + } +} \ No newline at end of file diff --git a/src/Financier.Adapter/EntityReader.cs b/src/Financier.Adapter/EntityReader.cs index 1207e659..12675191 100644 --- a/src/Financier.Adapter/EntityReader.cs +++ b/src/Financier.Adapter/EntityReader.cs @@ -26,8 +26,8 @@ public class EntityReader : IEntityReader List entities = new List(); var entityTypes = _entityTypes.Value; - Entity entity = null!; - EntityInfo entityInfo = null!; + Entity entity = null; + EntityInfo entityInfo = null; string prevField = string.Empty; string entityType = string.Empty; @@ -38,7 +38,7 @@ public class EntityReader : IEntityReader { prevField = string.Empty; entityType = line.Value!; - if (!string.IsNullOrEmpty(line.Value) && entityTypes.TryGetValue(line.Value, out entityInfo!)) + if (!string.IsNullOrEmpty(line.Value) && entityTypes.TryGetValue(line.Value, out entityInfo)) { entity = entityInfo.Factory(); } @@ -57,7 +57,7 @@ public class EntityReader : IEntityReader } else if (entity != null && line.Value != null) { - if (entityInfo.Properties.TryGetValue(line.Key!, out var property)) + if (entityInfo.Properties.TryGetValue(line.Key, out var property)) { property.SetValue(entity, line.Value); } @@ -65,9 +65,9 @@ public class EntityReader : IEntityReader var order = EntityColumnsOrder[entityType]; if (columnsSeen[entityType].Add(line.Key!)) { - order.Insert(order.IndexOf(prevField) + 1, line.Key!); + order.Insert(order.IndexOf(prevField) + 1, line.Key); } - prevField = line.Key!; + prevField = line.Key; } } @@ -116,7 +116,7 @@ private static IReadOnlyDictionary BuildEntityTypes() private static Func BuildFactory(Type type) { - var ctor = type.GetConstructor(Type.EmptyTypes)!; + var ctor = type.GetConstructor(Type.EmptyTypes); var newExpr = Expression.New(ctor); var cast = Expression.Convert(newExpr, typeof(Entity)); return Expression.Lambda>(cast).Compile(); diff --git a/src/Financier.Common/Entities/DbManual.cs b/src/Financier.Common/Entities/DbManual.cs index 9c380b85..910e0c24 100644 --- a/src/Financier.Common/Entities/DbManual.cs +++ b/src/Financier.Common/Entities/DbManual.cs @@ -31,6 +31,7 @@ public static class DbManual private static Dictionary _mccTitles; private static Dictionary _mccCodes; private static Dictionary _projectIds; + private static Dictionary _currencyIds; private static List> _allCurrencies; public static async Task SetupAsync(IFinancierDatabase financierDatabase) @@ -111,6 +112,8 @@ FROM category ctx { Name = Localization.LocalizationService.Instance.all_currencies }); + + _currencyIds = _currencies.Where(c => c.Id.HasValue).ToDictionary(c => c.Id.Value, c => c); } if (_payee == null) @@ -181,6 +184,8 @@ FROM v_report_transactions public static Dictionary ProjectIds => _projectIds ?? new(); + public static Dictionary CurrencyIds => _currencyIds ?? new(); + public static List YearMonths => _yearMonths ?? new(); public static List Years => _years ?? new(); @@ -282,6 +287,7 @@ public static void ResetAllDatabaseManuals() _category = null; _topCategory = null; _currencies = null; + _currencyIds = null; _payee = null; _project = null; _yearMonths = null; @@ -299,7 +305,7 @@ public static void ResetManuals(string manual) case nameof(Account): _accounts = null; break; case nameof(MCCEnums): _mccEnums = null; break; case nameof(MCCTitles): _mccTitles = null; break; - case nameof(Currencies): _currencies = null; break; + case nameof(Currencies): _currencies = null; _currencyIds = null; break; case nameof(Category): _category = null; _topCategory = null; break; default: break; @@ -359,6 +365,7 @@ internal static void SetupTests(List loc) internal static void SetupTests(List cur) { _currencies = cur; + _currencyIds = cur.Where(c => c.Id.HasValue).ToDictionary(c => c.Id.Value, c => c); } internal static void SetupTests(List acc) diff --git a/src/Financier.Common/Localization/LocalizationService.cs b/src/Financier.Common/Localization/LocalizationService.cs index 9efeba74..9dfede9f 100644 --- a/src/Financier.Common/Localization/LocalizationService.cs +++ b/src/Financier.Common/Localization/LocalizationService.cs @@ -140,7 +140,7 @@ private string Get([CallerMemberName] string key = null) // RecipesWizard Page1 public string recipe_wizard_total_format => Get(); // MainWindow Messages - public string backup_done => Get(); + public string import_result => Get(); public string import_result_with_duplicates => Get(); public string saved_message => Get(); diff --git a/src/Financier.Common/Localization/Resources.Designer.cs b/src/Financier.Common/Localization/Resources.Designer.cs index 15e3269d..ca65bdcc 100644 --- a/src/Financier.Common/Localization/Resources.Designer.cs +++ b/src/Financier.Common/Localization/Resources.Designer.cs @@ -87,6 +87,24 @@ public static string account { } } + /// + /// Looks up a localized string similar to Account Details. + /// + public static string account_details { + get { + return ResourceManager.GetString("account_details", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account Type. + /// + public static string account_type { + get { + return ResourceManager.GetString("account_type", resourceCulture); + } + } + /// /// Looks up a localized string similar to Asset. /// @@ -366,15 +384,6 @@ public static string back { } } - /// - /// Looks up a localized string similar to Backup done.. - /// - public static string backup_done { - get { - return ResourceManager.GetString("backup_done", resourceCulture); - } - } - /// /// Looks up a localized string similar to Balance. /// @@ -420,6 +429,24 @@ public static string cancel { } } + /// + /// Looks up a localized string similar to Card Issuer. + /// + public static string card_issuer { + get { + return ResourceManager.GetString("card_issuer", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Card Number. + /// + public static string card_number { + get { + return ResourceManager.GetString("card_number", resourceCulture); + } + } + /// /// Looks up a localized string similar to Cashback. /// @@ -447,6 +474,15 @@ public static string category { } } + /// + /// Looks up a localized string similar to Category details. + /// + public static string category_details { + get { + return ResourceManager.GetString("category_details", resourceCulture); + } + } + /// /// Looks up a localized string similar to Check for Updates. /// @@ -492,6 +528,15 @@ public static string clear_notes_tooltip { } } + /// + /// Looks up a localized string similar to Closing Day. + /// + public static string closing_day { + get { + return ResourceManager.GetString("closing_day", resourceCulture); + } + } + /// /// Looks up a localized string similar to Commission. /// @@ -519,6 +564,24 @@ public static string conditions { } } + /// + /// Looks up a localized string similar to Mark this account as inactive?. + /// + public static string confirm_delete_account { + get { + return ResourceManager.GetString("confirm_delete_account", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete this currency?. + /// + public static string confirm_delete_currency { + get { + return ResourceManager.GetString("confirm_delete_currency", resourceCulture); + } + } + /// /// Looks up a localized string similar to Are you sure you want to delete transaction?. /// @@ -591,6 +654,15 @@ public static string currency_details { } } + /// + /// Looks up a localized string similar to This currency is used by accounts or transactions and cannot be deleted.. + /// + public static string currency_is_used { + get { + return ResourceManager.GetString("currency_is_used", resourceCulture); + } + } + /// /// Looks up a localized string similar to Currency name. /// @@ -744,6 +816,15 @@ public static string edit { } } + /// + /// Looks up a localized string similar to Electronic Payment. + /// + public static string electronic_payment_type { + get { + return ResourceManager.GetString("electronic_payment_type", resourceCulture); + } + } + /// /// Looks up a localized string similar to Entities. /// @@ -1014,6 +1095,24 @@ public static string is_default { } } + /// + /// Looks up a localized string similar to Include in Totals. + /// + public static string is_include_into_totals { + get { + return ResourceManager.GetString("is_include_into_totals", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Issuer. + /// + public static string issuer { + get { + return ResourceManager.GetString("issuer", resourceCulture); + } + } + /// /// Looks up a localized string similar to Language. /// @@ -1104,6 +1203,15 @@ public static string liabilities_usd { } } + /// + /// Looks up a localized string similar to Limit Amount. + /// + public static string limit_amount { + get { + return ResourceManager.GetString("limit_amount", resourceCulture); + } + } + /// /// Looks up a localized string similar to Location. /// @@ -1150,20 +1258,20 @@ public static string mcc { } /// - /// Looks up a localized string similar to Monobank. + /// Looks up a localized string similar to Menu. /// - public static string monobank { + public static string menu { get { - return ResourceManager.GetString("monobank", resourceCulture); + return ResourceManager.GetString("menu", resourceCulture); } } /// - /// Looks up a localized string similar to Monobank CSV. + /// Looks up a localized string similar to Monobank. /// - public static string monobank_csv { + public static string monobank { get { - return ResourceManager.GetString("monobank_csv", resourceCulture); + return ResourceManager.GetString("monobank", resourceCulture); } } @@ -1176,6 +1284,15 @@ public static string month { } } + /// + /// Looks up a localized string similar to Name. + /// + public static string name { + get { + return ResourceManager.GetString("name", resourceCulture); + } + } + /// /// Looks up a localized string similar to Net Worth. /// @@ -1275,6 +1392,15 @@ public static string open_recipes_wizard { } } + /// + /// Looks up a localized string similar to Opening Amount. + /// + public static string opening_amount { + get { + return ResourceManager.GetString("opening_amount", resourceCulture); + } + } + /// /// Looks up a localized string similar to Operation amount. /// @@ -1311,6 +1437,15 @@ public static string others { } } + /// + /// Looks up a localized string similar to Parent category. + /// + public static string parent_category { + get { + return ResourceManager.GetString("parent_category", resourceCulture); + } + } + /// /// Looks up a localized string similar to Paste. /// @@ -1347,6 +1482,15 @@ public static string payees { } } + /// + /// Looks up a localized string similar to Payment Day. + /// + public static string payment_day { + get { + return ResourceManager.GetString("payment_day", resourceCulture); + } + } + /// /// Looks up a localized string similar to PDF. /// @@ -1473,15 +1617,6 @@ public static string pireus { } } - /// - /// Looks up a localized string similar to Pireus PDF. - /// - public static string pireus_pdf { - get { - return ResourceManager.GetString("pireus_pdf", resourceCulture); - } - } - /// /// Looks up a localized string similar to PKO. /// @@ -1491,15 +1626,6 @@ public static string pko { } } - /// - /// Looks up a localized string similar to PKO PDF. - /// - public static string pko_pdf { - get { - return ResourceManager.GetString("pko_pdf", resourceCulture); - } - } - /// /// Looks up a localized string similar to Please select account. /// @@ -1555,20 +1681,47 @@ public static string please_select_transaction_title { } /// - /// Looks up a localized string similar to Privat. + /// Looks up a localized string similar to Move to the bottom. /// - public static string privat { + public static string position_move_bottom { get { - return ResourceManager.GetString("privat", resourceCulture); + return ResourceManager.GetString("position_move_bottom", resourceCulture); } } /// - /// Looks up a localized string similar to Privat XLSX. + /// Looks up a localized string similar to Move down. /// - public static string privat_xlsx { + public static string position_move_down { get { - return ResourceManager.GetString("privat_xlsx", resourceCulture); + return ResourceManager.GetString("position_move_down", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Move to the top. + /// + public static string position_move_top { + get { + return ResourceManager.GetString("position_move_top", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Move up. + /// + public static string position_move_up { + get { + return ResourceManager.GetString("position_move_up", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Privat. + /// + public static string privat { + get { + return ResourceManager.GetString("privat", resourceCulture); } } @@ -1608,15 +1761,6 @@ public static string pumb { } } - /// - /// Looks up a localized string similar to PUMB PDF. - /// - public static string pumb_pdf { - get { - return ResourceManager.GetString("pumb_pdf", resourceCulture); - } - } - /// /// Looks up a localized string similar to Rate. /// @@ -1815,15 +1959,6 @@ public static string revolut { } } - /// - /// Looks up a localized string similar to Revolut CSV. - /// - public static string revolut_csv { - get { - return ResourceManager.GetString("revolut_csv", resourceCulture); - } - } - /// /// Looks up a localized string similar to Rule. /// @@ -2031,6 +2166,24 @@ public static string settings_corrupted { } } + /// + /// Looks up a localized string similar to Sort by title. + /// + public static string sort_by_title { + get { + return ResourceManager.GetString("sort_by_title", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Sort Order. + /// + public static string sort_order { + get { + return ResourceManager.GetString("sort_order", resourceCulture); + } + } + /// /// Looks up a localized string similar to Split-transfers with a currency differ from account's currency are not yet supported. /// @@ -2175,6 +2328,15 @@ public static string transaction_details { } } + /// + /// Looks up a localized string similar to Transfer. + /// + public static string transfer { + get { + return ResourceManager.GetString("transfer", resourceCulture); + } + } + /// /// Looks up a localized string similar to Transfer details. /// @@ -2184,6 +2346,15 @@ public static string transfer_details { } } + /// + /// Looks up a localized string similar to Open transfer dialog for the selected row (enabled when From/To account currency differs from the imported account). + /// + public static string transfer_tooltip { + get { + return ResourceManager.GetString("transfer_tooltip", resourceCulture); + } + } + /// /// Looks up a localized string similar to Type. /// diff --git a/src/Financier.Common/Localization/Resources.pl.resx b/src/Financier.Common/Localization/Resources.pl.resx index 55ef224b..05a258d0 100644 --- a/src/Financier.Common/Localization/Resources.pl.resx +++ b/src/Financier.Common/Localization/Resources.pl.resx @@ -144,6 +144,9 @@ Główna + + Menu + Jednostki @@ -180,9 +183,6 @@ Import - - Monobank CSV - Monobank @@ -195,33 +195,18 @@ XLSX - - PUMB PDF - PUMB - - Pireus PDF - Pireus - - Privat XLSX - Privat - - PKO PDF - PKO - - Revolut CSV - Revolut @@ -318,6 +303,9 @@ Notatka + + Tytuł + Zapisz @@ -564,9 +552,6 @@ Dodaj nową transakcję - - Kopia zapasowa wykonana. - Zaimportowano {0} transakcji. diff --git a/src/Financier.Common/Localization/Resources.resx b/src/Financier.Common/Localization/Resources.resx index 9bbad9bd..80346fc1 100644 --- a/src/Financier.Common/Localization/Resources.resx +++ b/src/Financier.Common/Localization/Resources.resx @@ -144,6 +144,9 @@ Main + + Menu + Entities @@ -180,9 +183,6 @@ Import - - Monobank CSV - Monobank @@ -195,33 +195,18 @@ XLSX - - PUMB PDF - PUMB - - Pireus PDF - Pireus - - Privat XLSX - Privat - - PKO PDF - PKO - - Revolut CSV - Revolut @@ -318,6 +303,9 @@ Note + + Name + Save @@ -564,9 +552,6 @@ Add new transaction - - Backup done. - Imported {0} transactions. diff --git a/src/Financier.Common/Localization/Resources.uk.resx b/src/Financier.Common/Localization/Resources.uk.resx index d44f0874..ba2057a6 100644 --- a/src/Financier.Common/Localization/Resources.uk.resx +++ b/src/Financier.Common/Localization/Resources.uk.resx @@ -144,6 +144,9 @@ Головна + + Меню + Сутності @@ -180,9 +183,6 @@ Імпорт - - Монобанк CSV - Монобанк @@ -195,33 +195,18 @@ XLSX - - ПУМБ PDF - ПУМБ - - Піреус PDF - Піреус - - Приват XLSX - Приват - - PKO PDF - PKO - - Revolut CSV - Revolut @@ -318,6 +303,9 @@ Примітка + + Назва + Зберегти @@ -564,9 +552,6 @@ Додати нову операцію - - Резервну копію збережено. - Імпортовано {0} операцій. diff --git a/src/Financier.Common/Model/BlotterModel.cs b/src/Financier.Common/Model/BlotterModel.cs index 9ba7a18f..7c1109b0 100644 --- a/src/Financier.Common/Model/BlotterModel.cs +++ b/src/Financier.Common/Model/BlotterModel.cs @@ -35,6 +35,14 @@ public string AmountTitle } } + public string AmountClipboardText + { + get + { + return BlotterUtils.SetAmountText(FromAccountCurrency, FromAmount, true); + } + } + public string BalanceTitle { get diff --git a/src/Financier.DataAccess/DataBase/Scripts/SQL_alter_files.Designer.cs b/src/Financier.DataAccess/DataBase/Scripts/SQL_alter_files.Designer.cs index 5bdc5496..4ff777cf 100644 --- a/src/Financier.DataAccess/DataBase/Scripts/SQL_alter_files.Designer.cs +++ b/src/Financier.DataAccess/DataBase/Scripts/SQL_alter_files.Designer.cs @@ -66,7 +66,8 @@ internal SQL_alter_files() { ///INSERT INTO project (_id, title) VALUES (0, '<NO_PROJECT>'); /// ///INSERT INTO locations(_id, name, datetime, provider, accuracy, latitude, longitude, is_payee, resolved_address) - ///VALUES (0, '<CURRENT_LOCATION>', 0, "?", "?", 0, 0, 0, "?");. + ///VALUES (0, '<CURRENT_LOCATION>', 0, '?', '?', 0, 0, 0, '?'); + ///. /// internal static string _20090723_0035_initial_data { get { @@ -933,5 +934,69 @@ internal static string _20260613_0251_alter_sms_template_add_description { return ResourceManager.GetString("_20260613_0251_alter_sms_template_add_description", resourceCulture); } } + + /// + /// Looks up a localized string similar to ALTER TABLE currency ADD trading_currency_id LONG NOT NULL DEFAULT 0. + /// + internal static string _20260628_0122_add_currency_trading_currency { + get { + return ResourceManager.GetString("_20260628_0122_add_currency_trading_currency", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ALTER TABLE transactions ADD parent_account_id INTEGER NOT NULL DEFAULT 0. + /// + internal static string _20260711_0458_add_transaction_parent_account_id { + get { + return ResourceManager.GetString("_20260711_0458_add_transaction_parent_account_id", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DROP INDEX IF EXISTS transaction_pid_idx; + /// + ///CREATE INDEX IF NOT EXISTS transaction_pid_idx ON transactions (parent_id, _id);. + /// + internal static string _20260712_0855_recreate_transactions_parent_id_idx { + get { + return ResourceManager.GetString("_20260712_0855_recreate_transactions_parent_id_idx", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ALTER TABLE account ADD COLUMN is_include_into_reports boolean not null default 1; + ///. + /// + internal static string _20260719_0330_add_is_include_into_reports_to_account { + get { + return ResourceManager.GetString("_20260719_0330_add_is_include_into_reports_to_account", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ALTER TABLE payee ADD COLUMN aliases TEXT; + ///ALTER TABLE locations ADD COLUMN aliases TEXT; + /// + ///CREATE TABLE IF NOT EXISTS payee_aliases ( + /// _id INTEGER NOT NULL, + /// alias TEXT NOT NULL + ///); + /// + ///CREATE TABLE IF NOT EXISTS locations_aliases ( + /// _id INTEGER NOT NULL, + /// alias TEXT NOT NULL + ///); + /// + ///CREATE INDEX IF NOT EXISTS payee_aliases_id_idx ON payee_aliases (_id); + ///CREATE INDEX IF NOT EXISTS payee_aliases_alias_idx ON payee_aliases (alias); + /// + ///CREATE INDEX IF NOT EXISTS locations_aliases_id_idx ON lo [rest of string was truncated]";. + /// + internal static string _20260905_0241_add_payee_locations_alias { + get { + return ResourceManager.GetString("_20260905_0241_add_payee_locations_alias", resourceCulture); + } + } } } diff --git a/src/Financier.DataAccess/DataBase/Scripts/SQL_alter_files.resx b/src/Financier.DataAccess/DataBase/Scripts/SQL_alter_files.resx index d6edaaa3..73db2dea 100644 --- a/src/Financier.DataAccess/DataBase/Scripts/SQL_alter_files.resx +++ b/src/Financier.DataAccess/DataBase/Scripts/SQL_alter_files.resx @@ -119,16 +119,16 @@ - alter\20241228_0500_alter_sms_template_add_payee_project.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + alter\20241228_0500_alter_sms_template_add_payee_project.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 - alter\20250709_1950_account_icon_color_separator.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + alter\20250709_1950_account_icon_color_separator.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 - alter\20250802_0155_add_currency_number_format.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + alter\20250802_0155_add_currency_number_format.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 - alter\20260613_0251_alter_sms_template_add_description.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + alter\20260613_0251_alter_sms_template_add_description.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 alter\20090723_0035_initial_data.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 @@ -343,4 +343,19 @@ alter\20240221_0135_alter_location_drop_name_is_payee.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 + + alter\20260628_0122_add_currency_trading_currency.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 + + + alter\20260711_0458_add_transaction_parent_account_id.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 + + + alter\20260712_0855_recreate_transactions_parent_id_idx.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 + + + alter\20260719_0330_add_is_include_into_reports_to_account.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 + + + alter\20260905_0241_add_payee_locations_alias.sql;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;windows-1251 + \ No newline at end of file diff --git a/src/Financier.DataAccess/DataBase/Scripts/SQL_create_files.Designer.cs b/src/Financier.DataAccess/DataBase/Scripts/SQL_create_files.Designer.cs index 67b88fdf..faa79f41 100644 --- a/src/Financier.DataAccess/DataBase/Scripts/SQL_create_files.Designer.cs +++ b/src/Financier.DataAccess/DataBase/Scripts/SQL_create_files.Designer.cs @@ -19,7 +19,7 @@ namespace Financier.DataAccess.DataBase.Scripts { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "18.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SQL_create_files { @@ -97,8 +97,6 @@ internal static string account { /// attribute_id integer not null, /// value text ///); - /// - ///cre [rest of string was truncated]";. /// internal static string attributes { get { @@ -209,8 +207,6 @@ internal static string project { /// latitude double, /// longitude double ///); - /// - ///create index if not exists transaction_from_act_idx O [rest of string was truncated]";. /// internal static string transaction { get { diff --git a/src/Financier.DataAccess/DataBase/Scripts/SQL_views_files.Designer.cs b/src/Financier.DataAccess/DataBase/Scripts/SQL_views_files.Designer.cs index d11c51d7..fb0c758b 100644 --- a/src/Financier.DataAccess/DataBase/Scripts/SQL_views_files.Designer.cs +++ b/src/Financier.DataAccess/DataBase/Scripts/SQL_views_files.Designer.cs @@ -19,7 +19,7 @@ namespace Financier.DataAccess.DataBase.Scripts { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "18.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SQL_views_files { @@ -63,20 +63,18 @@ internal SQL_views_files() { /// /// Looks up a localized string similar to CREATE VIEW v_all_transactions AS ///SELECT - /// t._id as _id, - /// t.parent_id as parent_id, - /// a1._id as from_account_id, - /// a1.title as from_account_title, - /// a1.is_include_into_totals as from_account_is_include_into_totals, - /// c1._id as from_account_currency_id, - /// a2._id as to_account_id, - /// a2.title as to_account_title, - /// c2._id as to_account_currency_id, - /// cat._id as category_id, - /// cat.title as category_title, - /// cat.left as category_left, - /// cat.right as category_right, - /// [rest of string was truncated]";. + /// t._id as _id, + /// t.parent_id as parent_id, + /// t.parent_account_id as parent_account_id, + /// a1._id as from_account_id, + /// a1.title as from_account_title, + /// a1.is_include_into_totals as from_account_is_include_into_totals, + /// a1.is_include_into_reports as from_account_is_include_into_reports, + /// c1._id as from_account_currency_id, + /// a2._id as to_account_id, + /// a2.title as to_account_title, + /// a2.is_include_into_reports as to_account_is_include_into_reports, + /// c2._id as t [rest of string was truncated]";. /// internal static string _010_v_all_transactions_ { get { @@ -87,19 +85,18 @@ internal static string _010_v_all_transactions_ { /// /// Looks up a localized string similar to CREATE VIEW v_blotter_for_account_with_splits AS ///SELECT - /// t._id as _id, - /// t.parent_id as parent_id, - /// a._id as from_account_id, - /// a.title as from_account_title, - /// a.is_include_into_totals as from_account_is_include_into_totals, - /// c._id as from_account_currency_id, - /// a2._id as to_account_id, - /// a2.title as to_account_title, - /// a2.currency_id as to_account_currency_id, - /// cat._id as category_id, - /// cat.title as category_title, - /// cat.left as category_left, - /// cat.right as cat [rest of string was truncated]";. + /// t._id as _id, + /// t.parent_id as parent_id, + /// t.parent_account_id as parent_account_id, + /// a._id as from_account_id, + /// a.title as from_account_title, + /// a.is_include_into_totals as from_account_is_include_into_totals, + /// a.is_include_into_reports as from_account_is_include_into_reports, + /// c._id as from_account_currency_id, + /// a2._id as to_account_id, + /// a2.title as to_account_title, + /// a2.is_include_into_reports as to_account_is_include_into_reports, + /// a2.c [rest of string was truncated]";. /// internal static string _015_v_blotter_for_account_with_splits_ { get { @@ -132,15 +129,10 @@ internal static string _021_v_blotter_for_account_ { } /// - /// Looks up a localized string similar to CREATE VIEW v_blotter_flatsplits - ///AS - /// SELECT * - /// FROM v_all_transactions - /// WHERE is_template = 0 - /// AND _id NOT IN (SELECT DISTINCT parent_id - /// FROM transactions - /// WHERE is_template = 0 - /// AND parent_id > 0); . + /// Looks up a localized string similar to CREATE VIEW v_blotter_flatsplits AS + ///SELECT * + ///FROM v_all_transactions + ///WHERE is_template = 0 and _id not in (SELECT DISTINCT parent_id FROM transactions WHERE is_template=0 AND parent_id > 0);. /// internal static string _022_v_blotter_flatsplits_ { get { @@ -151,20 +143,22 @@ internal static string _022_v_blotter_flatsplits_ { /// /// Looks up a localized string similar to create view v_category AS ///SELECT - /// node._id as _id, - /// node.title as title, - /// node.left as left, - /// node.right as right, - /// node.type as type, - /// node.last_location_id as last_location_id, - /// node.last_project_id as last_project_id, - /// node.sort_order as sort_order, - /// count(parent._id)-1 as level + /// node._id as _id, + /// node.title as title, + /// node.left as left, + /// node.right as right, + /// node.type as type, + /// node.last_location_id as last_location_id, + /// node.last_project_id as last_project_id, + /// node.sort_order as sort_order, + /// count(parent._id)-1 as level ///FROM - /// category as node, - /// category as parent + /// category as node, + /// category as parent ///WHERE node.left BETWEEN parent.left AND parent.right - ///GROUP BY node._id ORDER BY node.left;. + ///GROUP BY node._id ORDER BY node.left; + /// + ///. /// internal static string _030_v_category_ { get { @@ -175,16 +169,16 @@ internal static string _030_v_category_ { /// /// Looks up a localized string similar to CREATE VIEW v_category_list AS ///SELECT - /// B._id AS parent_id, - /// B.title AS parent_title, - /// B.left AS parent_left, - /// B.right AS parent_right, - /// B.type AS parent_type, - /// P._id as _id, - /// P.title AS title, - /// P.left as left, - /// P.right as right, - /// P.type as type + /// B._id AS parent_id, + /// B.title AS parent_title, + /// B.left AS parent_left, + /// B.right AS parent_right, + /// B.type AS parent_type, + /// P._id as _id, + /// P.title AS title, + /// P.left as left, + /// P.right as right, + /// P.type as type ///FROM category AS B, category AS P ///WHERE P.left BETWEEN B.left AND B.right ///AND B._id = (SELECT MAX(S._id) @@ -202,21 +196,23 @@ internal static string _035_v_category_list_ { /// /// Looks up a localized string similar to create view v_attributes AS ///SELECT - /// a._id as _id, - /// a.title as title, - /// a.type as type, - /// a.list_values as list_values, - /// a.default_value as default_value, - /// c._id as category_id, - /// c.left as category_left, - /// c.right as category_right + /// a._id as _id, + /// a.title as title, + /// a.type as type, + /// a.list_values as list_values, + /// a.default_value as default_value, + /// c._id as category_id, + /// c.left as category_left, + /// c.right as category_right ///FROM - /// attributes as a, - /// category_attribute as ca, - /// category c + /// attributes as a, + /// category_attribute as ca, + /// category c ///WHERE - /// ca.attribute_id=a._id - /// AND ca.category_id=c._id;. + /// ca.attribute_id=a._id + /// AND ca.category_id=c._id; + /// + ///. /// internal static string _050_v_attributes_ { get { @@ -226,19 +222,19 @@ internal static string _050_v_attributes_ { /// /// Looks up a localized string similar to create view v_report_category AS - ///select - /// c._id as _id, - /// c.parent_id as parent_id, + ///select + /// c._id as _id, + /// c.parent_id as parent_id, /// c.title as name, /// t.datetime as datetime, /// t.from_account_currency_id as from_account_currency_id, /// t.from_amount as from_amount, /// t.to_account_currency_id as to_account_currency_id, /// t.to_amount as to_amount, - /// t.original_currency_id as original_currency_id, - /// t.original_from_amount as original_from_amount, + /// t.original_currency_id as original_currency_id, + /// t.original_from_amount as original_from_amount, /// t.is_transfer as is_transfer, - /// t.f [rest of string was truncated]";. + /// t.from_account [rest of string was truncated]";. /// internal static string _060_v_report_category_ { get { @@ -249,18 +245,19 @@ internal static string _060_v_report_category_ { /// /// Looks up a localized string similar to create view v_report_sub_category AS ///select - /// c._id as _id, - /// c.left as left, - /// c.right as right, - /// c.title as name, + /// c._id as _id, + /// c.left as left, + /// c.right as right, + /// c.title as name, /// t.datetime as datetime, /// t.from_account_currency_id as from_account_currency_id, /// t.from_amount as from_amount, /// t.to_account_currency_id as to_account_currency_id, /// t.to_amount as to_amount, - /// t.original_currency_id as original_currency_id, - /// t.original_from_amount as original_from_amount, - /// t.is_transfer as is_ [rest of string was truncated]";. + /// t.original_currency_id as original_currency_id, + /// t.original_from_amount as original_from_amount, + /// t.is_transfer as is_transfer, + /// [rest of string was truncated]";. /// internal static string _060_v_report_sub_category_ { get { @@ -279,10 +276,10 @@ internal static string _060_v_report_sub_category_ { /// t.to_account_currency_id as to_account_currency_id, /// t.to_amount as to_amount, /// t.is_transfer as is_transfer, - /// t.original_currency_id as original_currency_id, - /// t.original_from_amount as original_from_amount, + /// t.original_currency_id as original_currency_id, + /// t.original_from_amount as original_from_amount, /// t.from_account_id as from_account_id, - /// [rest of string was truncated]";. + /// t.to_ [rest of string was truncated]";. /// internal static string _061_v_report_period_ { get { @@ -293,17 +290,18 @@ internal static string _061_v_report_period_ { /// /// Looks up a localized string similar to create view v_report_location AS ///select - /// l._id as _id, + /// l._id as _id, /// l.title as name, /// t.datetime as datetime, /// t.from_account_currency_id as from_account_currency_id, /// t.from_amount as from_amount, /// t.to_account_currency_id as to_account_currency_id, /// t.to_amount as to_amount, - /// t.original_currency_id as original_currency_id, - /// t.original_from_amount as original_from_amount, + /// t.original_currency_id as original_currency_id, + /// t.original_from_amount as original_from_amount, /// t.is_transfer as is_transfer, - /// t.from_account_id as from_account_id [rest of string was truncated]";. + /// t.from_account_id as from_account_id, + /// [rest of string was truncated]";. /// internal static string _062_v_report_location_ { get { @@ -314,17 +312,18 @@ internal static string _062_v_report_location_ { /// /// Looks up a localized string similar to create view v_report_project AS ///select - /// p._id as _id, - /// p.title as name, + /// p._id as _id, + /// p.title as name, /// t.datetime as datetime, /// t.from_account_currency_id as from_account_currency_id, /// t.from_amount as from_amount, /// t.to_account_currency_id as to_account_currency_id, /// t.to_amount as to_amount, - /// t.original_currency_id as original_currency_id, - /// t.original_from_amount as original_from_amount, + /// t.original_currency_id as original_currency_id, + /// t.original_from_amount as original_from_amount, /// t.is_transfer as is_transfer, - /// t.from_account_id as from_account_id, [rest of string was truncated]";. + /// t.from_account_id as from_account_id, + /// [rest of string was truncated]";. /// internal static string _063_v_report_project_ { get { @@ -334,19 +333,19 @@ internal static string _063_v_report_project_ { /// /// Looks up a localized string similar to create view v_report_payee AS - ///select - /// p._id as _id, - /// p.title as name, + ///select + /// p._id as _id, + /// p.title as name, /// t.datetime as datetime, /// t.from_account_currency_id as from_account_currency_id, /// t.from_amount as from_amount, /// t.to_account_currency_id as to_account_currency_id, /// t.to_amount as to_amount, /// t.is_transfer as is_transfer, - /// t.original_currency_id as original_currency_id, - /// t.original_from_amount as original_from_amount, + /// t.original_currency_id as original_currency_id, + /// t.original_from_amount as original_from_amount, /// t.from_account_id as from_account_id, - /// [rest of string was truncated]";. + /// [rest of string was truncated]";. /// internal static string _064_v_report_payee_ { get { @@ -357,20 +356,20 @@ internal static string _064_v_report_payee_ { /// /// Looks up a localized string similar to create view v_transaction_attributes AS ///SELECT - /// t._id as _id, - /// t.parent_id as parent_id, - /// a._id as attribute_id, - /// a.type as attribute_type, - /// a.title as attribute_name, - /// a.list_values as attribute_list_values, - /// a.default_value as attribute_default_value, - /// ta.value as attribute_value + /// t._id as _id, + /// t.parent_id as parent_id, + /// a._id as attribute_id, + /// a.type as attribute_type, + /// a.title as attribute_name, + /// a.list_values as attribute_list_values, + /// a.default_value as attribute_default_value, + /// ta.value as attribute_value ///FROM - /// transactions t - /// INNER JOIN transaction_attribute ta ON ta.transaction_id=t._id - /// INNER JOIN attributes a ON a._id=ta.attribute_id + /// transactions t + /// INNER JOIN transaction_attribute ta ON ta.transaction_id=t._id + /// INNER JOIN attributes a ON a._id=ta.attribute_id ///ORDER BY - /// a.title;. + /// a.title;. /// internal static string _080_v_transaction_attributes_ { get { @@ -400,37 +399,6 @@ internal static string _081_v_currency_exchange_rate_ { } } - /// - /// Looks up a localized string similar to CREATE VIEW v_account AS - ///SELECT _id, - /// title, - /// creation_date, - /// currency_id, - /// type, - /// issuer, - /// number, - /// sort_order, - /// is_active, - /// is_include_into_totals, - /// last_category_id, - /// last_account_id, - /// total_limit, - /// card_issuer, - /// closing_day, - /// payment_day note, - /// last_transaction_date, - /// updated_on, - /// remote_key, - /// total_amount, - /// CASE (SELECT _id FROM currency WHERE is_default = 1) - /// [rest of string was truncated]";. - /// - internal static string _083_v_account_ { - get { - return ResourceManager.GetString("_083_v_account_", resourceCulture); - } - } - /// /// Looks up a localized string similar to CREATE VIEW v_report_transactions AS ///SELECT t._id, @@ -459,5 +427,60 @@ internal static string _084_v_report_transactions_ { return ResourceManager.GetString("_084_v_report_transactions_", resourceCulture); } } + + /// + /// Looks up a localized string similar to CREATE VIEW v_exchange_rate AS + ///SELECT + /// from_currency_id, + /// to_currency_id, + /// rate_date, + /// rate, + /// is_flip + ///FROM ( + /// SELECT from_currency_id, to_currency_id, rate_date, rate, 0 AS is_flip FROM currency_exchange_rate + /// UNION + /// SELECT to_currency_id AS from_currency_id, from_currency_id AS to_currency_id, rate_date, 1/rate AS rate, 1 AS is_flip FROM currency_exchange_rate + ///) + ///GROUP BY from_currency_id, to_currency_id, rate_date. + /// + internal static string _090_v_exchange_rate_ { + get { + return ResourceManager.GetString("_090_v_exchange_rate_", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to CREATE VIEW v_account AS + ///SELECT + /// a.*, + /// c.name AS currency_name + ///FROM account a + ///LEFT JOIN currency c ON a.currency_id=c._id. + /// + internal static string _091_v_account_ { + get { + return ResourceManager.GetString("_091_v_account_", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to CREATE VIEW v_account_with_separator AS + ///SELECT + /// _id, icon, accent_color, title, creation_date, currency_id, total_amount, + /// type, issuer, number, is_active, is_include_into_totals, last_category_id, + /// last_account_id, total_limit, card_issuer, closing_day, payment_day, note, + /// last_transaction_date, updated_on, remote_key, currency_name, sort_order, + /// 0 AS is_separator + ///FROM v_account + ///UNION + ///SELECT + /// _id, '' AS icon, accent_color, title, 0 AS creation_date, 0 AS currency_id, + /// 0 AS t [rest of string was truncated]";. + /// + internal static string _092_v_account_with_separator_ { + get { + return ResourceManager.GetString("_092_v_account_with_separator_", resourceCulture); + } + } } } diff --git a/src/Financier.DataAccess/DataBase/Scripts/SQL_views_files.resx b/src/Financier.DataAccess/DataBase/Scripts/SQL_views_files.resx index 80f1e6ea..5a231c99 100644 --- a/src/Financier.DataAccess/DataBase/Scripts/SQL_views_files.resx +++ b/src/Financier.DataAccess/DataBase/Scripts/SQL_views_files.resx @@ -1,4 +1,4 @@ - + - - - - - - - - - - - - - - - @@ -283,9 +227,6 @@ - + + + + + + + + + + + + + + + + + + + + + + ?? entities.ToList(); _backupVersion = backupVersion; _entityColumnsOrder = columnsOrder; @@ -233,11 +234,12 @@ public async Task OpenBackup(string backupPath) await DbManual.LoadRulesAsync(); stopwatch.Stop(); - Logger.Info($"Backup loaded in {stopwatch.ElapsedMilliseconds} ms. Backup version : {_backupVersion}. Entities count : {entities?.Count()}"); + int entitiesCount = entities?.Count() ?? 0; + Logger.Info($"Backup loaded in {stopwatch.ElapsedMilliseconds} ms. Backup version : {_backupVersion}. Entities count : {entitiesCount}"); await NavigateToType(typeof(BlotterModel)); - notifier?.ShowMessage(string.Format(LocalizationService.Instance.entities_loaded, entities?.Count())); + notifier?.ShowMessage(string.Format(LocalizationService.Instance.entities_loaded, entitiesCount)); if (SettingsService.Current.Settings?.ExchangeRates.UpdateOnStart == true) { @@ -279,8 +281,9 @@ public async Task SaveBackup(string backupPath) private void AddKeylessEntities(IEnumerable entities) where T : Entity { - Logger.Info($"Imported {typeof(T).Name} {entities.Count()}"); - keyLessEntities.AddRange(entities); + List materialized = entities as List ?? entities.ToList(); + Logger.Info($"Imported {typeof(T).Name} {materialized.Count}"); + keyLessEntities.AddRange(materialized); } private void ClearPages() @@ -340,13 +343,7 @@ private BindableBase GetOrCreatePage(Type type) case nameof(RuleModel): return Rules ??= GetOrCreatePage(); case nameof(ReportsControlVM): - { - if (!_pages.ContainsKey(type)) - { - _pages.TryAdd(type, new ReportsControlVM(db)); - } - return _pages[type]; - } + return _pages.GetOrAdd(type, _ => new ReportsControlVM(db)); default: throw new NotSupportedException($"{type.FullName} not supported"); } @@ -357,14 +354,7 @@ private VMType GetOrCreatePage() where TEntity : BaseModel, new() { var type = typeof(TEntity); - if (!_pages.ContainsKey(type)) - { - var viewModel = Activator.CreateInstance(typeof(VMType), db, dialogWrapper) as VMType; - - _pages.TryAdd(type, viewModel!); - } - - return (VMType)_pages[type]; + return (VMType)_pages.GetOrAdd(type, _ => Activator.CreateInstance(typeof(VMType), db, dialogWrapper) as VMType); } private async Task NavigateToType(Type type) @@ -395,10 +385,11 @@ private async Task OpenImportWizardAsync(WizardTypes bankType) var sourceData = importHelper.ParseReport(fileName); Dictionary lastTransactions = new(); + var blotterEntitiesById = Blotter.Entities.ToDictionary(x => x.Id); foreach (var acc in DbManual.Account.Where(x => x.Id.HasValue)) { - var last = Blotter.Entities.FirstOrDefault(x => x.Id == acc.LastTransactionId); - lastTransactions.Add(acc.Id!.Value, last!); + blotterEntitiesById.TryGetValue(acc.LastTransactionId, out var last); + lastTransactions.Add(acc.Id.Value, last); } var vm = new MonoWizardVM(importHelper.BankTitle, sourceData, lastTransactions, dialogWrapper); @@ -413,11 +404,12 @@ private async Task OpenImportWizardAsync(WizardTypes bankType) var transactionRepo = blotter.GetRepository(); List accTransactions = await transactionRepo.FindManyAsync(predicate: x => times.Contains(x.DateTime)); + var accTransactionKeys = accTransactions + .Select(x => (x.FromAccountId, x.DateTime, x.FromAmount)) + .ToHashSet(); + List monoToImport = outputTransactions.Where(item => - !accTransactions.Any(x => - x.FromAccountId == item.FromAccountId && - x.DateTime == item.DateTime && - x.FromAmount == item.FromAmount)).ToList(); + !accTransactionKeys.Contains((item.FromAccountId, item.DateTime, item.FromAmount))).ToList(); var duplicatesCount = outputTransactions.Count - monoToImport.Count; @@ -476,7 +468,7 @@ private async Task SaveBackup_Click() { await SaveBackup(backupPath); - dialogWrapper.ShowMessageBox(string.Format(LocalizationService.Instance.saved_message, backupPath), LocalizationService.Instance.backup_done); + notifier.ShowMessage(string.Format(LocalizationService.Instance.saved_message, backupPath)); Logger.Info($"Backup done. Saved {backupPath}"); } } @@ -484,14 +476,14 @@ private async Task SaveBackup_Click() private async Task SaveBackupAsDb() { string fileName = Path.ChangeExtension(BackupWriter.GenerateFileName(), "db"); - string defaultPath = !string.IsNullOrEmpty(OpenBackupPath) ? Path.Combine(Path.GetDirectoryName(OpenBackupPath ?? string.Empty)!, fileName) : fileName; + string defaultPath = !string.IsNullOrEmpty(OpenBackupPath) ? Path.Combine(Path.GetDirectoryName(OpenBackupPath ?? string.Empty), fileName) : fileName; var backupPath = dialogWrapper.SaveFileDialog("db", defaultPath); if (!string.IsNullOrEmpty(backupPath)) { await db.SaveAsFile(backupPath); - dialogWrapper.ShowMessageBox(string.Format(LocalizationService.Instance.saved_message, backupPath), LocalizationService.Instance.backup_done); + notifier.ShowMessage(string.Format(LocalizationService.Instance.saved_message, backupPath)); Logger.Info($"Backup done. Saved {backupPath}"); } } @@ -552,7 +544,7 @@ private async Task RefreshExchangeRates_Click() } catch (DbUpdateException ex) { - string msg = ex?.InnerException?.Message!; + string msg = ex?.InnerException?.Message; if (!string.IsNullOrEmpty(msg) && msg.Contains("UNIQUE constraint failed", StringComparison.OrdinalIgnoreCase)) { notifier?.ShowWarning(LocalizationService.Instance.exchange_rates_exist); diff --git a/src/Financier.Desktop/Pages/BlotterVM.cs b/src/Financier.Desktop/Pages/BlotterVM.cs index 76171627..e3e1f306 100644 --- a/src/Financier.Desktop/Pages/BlotterVM.cs +++ b/src/Financier.Desktop/Pages/BlotterVM.cs @@ -3,10 +3,12 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using System.Windows.Controls; using Financier.Common; using Financier.Common.Entities; using Financier.Common.Localization; using Financier.Common.Model; +using Financier.Common.Utils; using Financier.Converters; using Financier.DataAccess.Abstractions; using Financier.DataAccess.Data; @@ -27,6 +29,8 @@ public class BlotterVM : EntityBaseVM private IAsyncCommand _duplicateCommand; private IAsyncCommand _clearFiltersCommand; private IAsyncCommand _infoCommand; + private Prism.Commands.DelegateCommand> _selectionChangedCommand; + private string _selectionSummary; private DateTime? _from; private DateTime? _to; private PeriodType _periodType; @@ -79,7 +83,7 @@ public PeriodType PeriodType public AccountFilterModel Account { - get => _account ??= DbManual.Account.Find(p => !p.Id.HasValue)!; + get => _account ??= DbManual.Account.Find(p => !p.Id.HasValue); set { _account = value; @@ -89,7 +93,7 @@ public AccountFilterModel Account public CategoryModel Category { - get => _category ??= DbManual.Category.Find(p => !p.Id.HasValue)!; + get => _category ??= DbManual.Category.Find(p => !p.Id.HasValue); set { _category = value; @@ -99,7 +103,7 @@ public CategoryModel Category public PayeeModel Payee { - get => _payee ??= DbManual.Payee.Find(p => !p.Id.HasValue)!; + get => _payee ??= DbManual.Payee.Find(p => !p.Id.HasValue); set { _payee = value; @@ -109,7 +113,7 @@ public PayeeModel Payee public ProjectModel Project { - get => _project ??= DbManual.Project.Find(p => !p.Id.HasValue)!; + get => _project ??= DbManual.Project.Find(p => !p.Id.HasValue); set { _project = value; @@ -119,7 +123,7 @@ public ProjectModel Project public LocationModel Location { - get => _location ??= DbManual.Location.Find(p => !p.Id.HasValue)!; + get => _location ??= DbManual.Location.Find(p => !p.Id.HasValue); set { _location = value; @@ -137,6 +141,37 @@ public LocationModel Location public IAsyncCommand InfoCommand => _infoCommand ??= new AsyncCommand(() => Task.CompletedTask, () => false); + public string SelectionSummary + { + get => _selectionSummary; + private set => SetProperty(ref _selectionSummary, value); + } + + public Prism.Commands.DelegateCommand> SelectionChangedCommand => + _selectionChangedCommand ??= new Prism.Commands.DelegateCommand>(OnSelectionChanged); + + private void OnSelectionChanged(IList selectedCells) + { + var selectedItems = (selectedCells ?? Array.Empty()) + .Select(c => c.Item) + .OfType() + .Distinct() + .ToList(); + + if (selectedItems.Count < 2) + { + SelectionSummary = string.Empty; + return; + } + + var totalsByCurrency = selectedItems + .Where(item => item.ToAccountId == null || item.ToAccountId == 0) + .GroupBy(item => item.FromAccountCurrency) + .Select(g => BlotterUtils.SetAmountText(g.Key, g.Sum(i => i.FromAmount), true)); + + SelectionSummary = string.Join(" ", totalsByCurrency); + } + private async Task ClearFilters() { PeriodType = PeriodType.AllTime; @@ -376,7 +411,7 @@ private async Task GetSubTransaction(Transaction transaction, Trans subTransaction.Parent = transaction; subTransaction.FromAccountId = transaction.FromAccountId; subTransaction.OriginalCurrencyId = transaction.OriginalCurrencyId ?? transaction.FromAccount.CurrencyId; - subTransaction.Category = default!; + subTransaction.Category = default; return subTransaction; } @@ -438,28 +473,10 @@ protected override async Task RefreshData() OriginalFromAmount = x.OriginalFromAmount, FromAccountBalance = x.FromAccountBalance, ToAccountBalance = x.ToAccountBalance, - FromAccountCurrency = new CurrencyModel - { - Id = x.FromAccountCurrency.Id, - Name = x.FromAccountCurrency.Name, - Symbol = x.FromAccountCurrency.Symbol, - }, - ToAccountCurrency = x.ToAccountCurrency == null ? default : new CurrencyModel - { - Id = x.ToAccountCurrency.Id, - Name = x.ToAccountCurrency.Name, - Symbol = x.ToAccountCurrency.Symbol, - }, - OriginalCurrency = x.OriginalCurrency == null ? default : new CurrencyModel - { - Id = x.OriginalCurrency.Id, - Name = x.OriginalCurrency.Name, - Symbol = x.OriginalCurrency.Symbol, - } - }, - x => x.FromAccountCurrency, - x => x.ToAccountCurrency, - x => x.OriginalCurrency); + FromAccountCurrency = DbManual.CurrencyIds.GetValueOrDefault(x.FromAccountCurrencyId), + ToAccountCurrency = x.ToAccountCurrency == null ? default : DbManual.CurrencyIds.GetValueOrDefault(x.ToAccountCurrencyId.Value), + OriginalCurrency = x.OriginalCurrency == null ? default : DbManual.CurrencyIds.GetValueOrDefault(x.OriginalCurrencyId.Value) + }); if (items != null) { diff --git a/src/Financier.Desktop/Pages/BlotterView.xaml b/src/Financier.Desktop/Pages/BlotterView.xaml index 75a5045f..5b40c18f 100644 --- a/src/Financier.Desktop/Pages/BlotterView.xaml +++ b/src/Financier.Desktop/Pages/BlotterView.xaml @@ -8,6 +8,7 @@ xmlns:loc="clr-namespace:Financier.Common.Localization;assembly=Financier.Common" xmlns:filters="clr-namespace:Financier.Common.Filters;assembly=Financier.Common" xmlns:converters="clr-namespace:Financier.Converters;assembly=Financier.Common" + xmlns:i="http://schemas.microsoft.com/xaml/behaviors" mc:Ignorable="d" d:DesignHeight="480" d:DesignWidth="1000"> @@ -20,12 +21,18 @@ + + + + @@ -68,17 +75,28 @@ - + + + + + @@ -112,7 +131,8 @@ Binding="{Binding Path=Datetime, Converter= {StaticResource DatetimeConverter}}" /> - + @@ -137,7 +157,8 @@ + dgx:DataGridFilterColumn.IsFilterVisible="False" + ClipboardContentBinding="{Binding Path=AmountClipboardText}"> + + + diff --git a/src/Financier.Desktop/Pages/CategoriesVM.cs b/src/Financier.Desktop/Pages/CategoriesVM.cs index f083de67..f9f90602 100644 --- a/src/Financier.Desktop/Pages/CategoriesVM.cs +++ b/src/Financier.Desktop/Pages/CategoriesVM.cs @@ -35,19 +35,35 @@ public CategoriesVM(IFinancierDatabase db, IDialogWrapper dialogWrapper) } public IAsyncCommand MoveBottomCommand => _moveBottomCommand ??= new AsyncCommand( - () => MoveAsync((siblings, pos) => { if (pos >= siblings.Count - 1) return; var n = siblings[pos]; siblings.RemoveAt(pos); siblings.Add(n); }), + () => MoveAsync((siblings, pos) => + { + if (pos >= siblings.Count - 1) return; + var n = siblings[pos]; siblings.RemoveAt(pos); siblings.Add(n); + }), () => IsAtPosition(SelectedValue, atStart: true)); public IAsyncCommand MoveDownCommand => _moveDownCommand ??= new AsyncCommand( - () => MoveAsync((siblings, pos) => { if (pos >= siblings.Count - 1) return; (siblings[pos], siblings[pos + 1]) = (siblings[pos + 1], siblings[pos]); }), + () => MoveAsync((siblings, pos) => + { + if (pos >= siblings.Count - 1) return; + (siblings[pos], siblings[pos + 1]) = (siblings[pos + 1], siblings[pos]); + }), () => IsAtPosition(SelectedValue, atStart: true)); public IAsyncCommand MoveTopCommand => _moveTopCommand ??= new AsyncCommand( - () => MoveAsync((siblings, pos) => { if (pos <= 0) return; var n = siblings[pos]; siblings.RemoveAt(pos); siblings.Insert(0, n); }), + () => MoveAsync((siblings, pos) => + { + if (pos <= 0) return; + var n = siblings[pos]; siblings.RemoveAt(pos); siblings.Insert(0, n); + }), () => IsAtPosition(SelectedValue, atStart: false)); public IAsyncCommand MoveUpCommand => _moveUpCommand ??= new AsyncCommand( - () => MoveAsync((siblings, pos) => { if (pos <= 0) return; (siblings[pos], siblings[pos - 1]) = (siblings[pos - 1], siblings[pos]); }), + () => MoveAsync((siblings, pos) => + { + if (pos <= 0) return; + (siblings[pos], siblings[pos - 1]) = (siblings[pos - 1], siblings[pos]); + }), () => IsAtPosition(SelectedValue, atStart: false)); public IAsyncCommand SortByTitleCommand => _sortByTitleCommand ??= new AsyncCommand( @@ -116,9 +132,10 @@ private static CategoryTreeModel FindAndMarkSelected(List nod private static (List siblings, int pos) FindSiblingsInSubTree(List nodes, CategoryTreeModel target) { - foreach (var node in nodes) + foreach (var (node, pos) in from node in nodes + let pos = node.SubCategoties?.IndexOf(target) ?? -1 + select (node, pos)) { - var pos = node.SubCategoties?.IndexOf(target) ?? -1; if (pos >= 0) return (node.SubCategoties, pos); if (node.SubCategoties?.Count > 0) { @@ -126,6 +143,7 @@ private static (List siblings, int pos) FindSiblingsInSubTree if (result.siblings != null) return result; } } + return (null, -1); } diff --git a/src/Financier.Desktop/Pages/CategoriesView.xaml.cs b/src/Financier.Desktop/Pages/CategoriesView.xaml.cs index 17c56f1f..1bfd2ff7 100644 --- a/src/Financier.Desktop/Pages/CategoriesView.xaml.cs +++ b/src/Financier.Desktop/Pages/CategoriesView.xaml.cs @@ -32,15 +32,13 @@ private static T FindAncestor(DependencyObject obj) where T : DependencyObjec while (obj != null) { if (obj is T t) return t; - if (obj is FrameworkContentElement) + if (obj is FrameworkContentElement element) { - obj = ((FrameworkContentElement)obj).Parent; - continue; + obj = element.Parent; } else if (obj is Visual || obj is Visual3D) { obj = VisualTreeHelper.GetParent(obj); - continue; } else { return null; diff --git a/src/Financier.Desktop/Pages/Controls/CustomDisplayPart.xaml.cs b/src/Financier.Desktop/Pages/Controls/CustomDisplayPart.xaml.cs index 3fe3c72f..4bbc768a 100644 --- a/src/Financier.Desktop/Pages/Controls/CustomDisplayPart.xaml.cs +++ b/src/Financier.Desktop/Pages/Controls/CustomDisplayPart.xaml.cs @@ -50,7 +50,7 @@ public CustomNotification(string message, MessageOptions messageOptions) #nullable enable public event PropertyChangedEventHandler? PropertyChanged; #nullable disable - protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null!) + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) diff --git a/src/Financier.Desktop/Pages/CurrenciesVM.cs b/src/Financier.Desktop/Pages/CurrenciesVM.cs index 359e1e9f..b3837d6f 100644 --- a/src/Financier.Desktop/Pages/CurrenciesVM.cs +++ b/src/Financier.Desktop/Pages/CurrenciesVM.cs @@ -131,6 +131,7 @@ private async Task SaveFromTemplateAsync(System.Collections.Generic.List entity.DecimalSeparator = template[4]; entity.GroupSeparator = template[5]; entity.IsActive = true; + entity.SymbolFormat = SymbolFormat.RS.ToString(); entity.IsDefault = !DbManual.Currencies.Any(x => x.Id.HasValue); await db.InsertOrUpdateAsync(new[] { entity }); diff --git a/src/Financier.Desktop/Pages/Dialogs/AccountControl.xaml b/src/Financier.Desktop/Pages/Dialogs/AccountControl.xaml index 1346bf65..856add8f 100644 --- a/src/Financier.Desktop/Pages/Dialogs/AccountControl.xaml +++ b/src/Financier.Desktop/Pages/Dialogs/AccountControl.xaml @@ -58,6 +58,7 @@ @@ -65,6 +66,7 @@ @@ -80,6 +82,7 @@ @@ -116,6 +120,7 @@ @@ -141,6 +146,7 @@ @@ -149,6 +155,7 @@ @@ -157,6 +164,7 @@ @@ -165,6 +173,7 @@ @@ -173,6 +182,7 @@ @@ -181,6 +191,7 @@ @@ -188,6 +199,7 @@ diff --git a/src/Financier.Desktop/Pages/Dialogs/AccountControlVM.cs b/src/Financier.Desktop/Pages/Dialogs/AccountControlVM.cs index 8e268ae4..884a92ab 100644 --- a/src/Financier.Desktop/Pages/Dialogs/AccountControlVM.cs +++ b/src/Financier.Desktop/Pages/Dialogs/AccountControlVM.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using Financier.Common.Entities; using Financier.Common.Model; using Financier.Desktop.Data; @@ -19,7 +20,7 @@ public AccountControlVM(AccountDto entity, bool isNew) { Entity = entity; IsNew = isNew; - Currencies = DbManual.Currencies; + Currencies = DbManual.Currencies.Where(x => x.Id > 0).ToList(); InitSelections(); @@ -31,7 +32,7 @@ public AccountControlVM(AccountDto entity, bool isNew) } public DelegateCommand ClearTitleCommand => - _clearTitleCommand ??= new DelegateCommand(() => { Entity.Title = default!; SaveCommand.RaiseCanExecuteChanged(); }); + _clearTitleCommand ??= new DelegateCommand(() => { Entity.Title = default; SaveCommand.RaiseCanExecuteChanged(); }); public AccountDto Entity { get; } diff --git a/src/Financier.Desktop/Pages/Dialogs/CategoryControlVM.cs b/src/Financier.Desktop/Pages/Dialogs/CategoryControlVM.cs index 1ad29129..46b0e489 100644 --- a/src/Financier.Desktop/Pages/Dialogs/CategoryControlVM.cs +++ b/src/Financier.Desktop/Pages/Dialogs/CategoryControlVM.cs @@ -14,9 +14,15 @@ public CategoryControlVM(CategoryDto entity, List availableParent { Entity = entity; AvailableParents = availableParents; - _selectedParent = entity.ParentId > 0 - ? availableParents.Find(x => x.Id == entity.ParentId) - : availableParents.Count > 0 ? availableParents[0] : null; + + if (entity.ParentId > 0) + { + _selectedParent = availableParents.Find(x => x.Id == entity.ParentId); + } + else + { + _selectedParent = availableParents.Count > 0 ? availableParents[0] : null; + } } public CategoryDto Entity { get; } @@ -40,7 +46,7 @@ public CategoryModel SelectedParent public bool IsTypeEnabled => Entity.ParentId <= 0; - public DelegateCommand ClearTitleCommand => _clearTitleCommand ??= new DelegateCommand(() => Entity.Title = default!); + public DelegateCommand ClearTitleCommand => _clearTitleCommand ??= new DelegateCommand(() => Entity.Title = default); public override object OnRequestSave() => Entity; } diff --git a/src/Financier.Desktop/Pages/Dialogs/LocationControlVM.cs b/src/Financier.Desktop/Pages/Dialogs/LocationControlVM.cs index 987757b0..92c70f00 100644 --- a/src/Financier.Desktop/Pages/Dialogs/LocationControlVM.cs +++ b/src/Financier.Desktop/Pages/Dialogs/LocationControlVM.cs @@ -12,7 +12,7 @@ public LocationControlVM(LocationDto location) : base(location) Entity = location; } - public DelegateCommand ClearAddressCommand => _clearAddressCommand ??= new DelegateCommand(() => { Entity.Address = default!; }); + public DelegateCommand ClearAddressCommand => _clearAddressCommand ??= new DelegateCommand(() => { Entity.Address = default; }); public new LocationDto Entity { get; } } diff --git a/src/Financier.Desktop/Pages/Dialogs/SubTransactionControlVM.cs b/src/Financier.Desktop/Pages/Dialogs/SubTransactionControlVM.cs index 8556beb0..1e53b5db 100644 --- a/src/Financier.Desktop/Pages/Dialogs/SubTransactionControlVM.cs +++ b/src/Financier.Desktop/Pages/Dialogs/SubTransactionControlVM.cs @@ -17,7 +17,7 @@ public class SubTransactionControlVM : DialogBaseVM public SubTransactionControlVM(TransactionDto transaction) { Transaction = transaction; - Transaction.PropertyChanged += Transaction_PropertyChanged!; + Transaction.PropertyChanged += Transaction_PropertyChanged; Transaction.RecalculateRate(); } @@ -33,7 +33,7 @@ public DelegateCommand ClearFromAmountCommand => _clearFromAmountCommand ??= new DelegateCommand(() => { Transaction.FromAmount = 0; }); public DelegateCommand ClearNotesCommand - => _clearNotesCommand ??= new DelegateCommand(() => { Transaction.Note = default!; }); + => _clearNotesCommand ??= new DelegateCommand(() => { Transaction.Note = default; }); public DelegateCommand ClearOriginalFromAmountCommand => _clearOriginalFromAmountCommand ??= new DelegateCommand(() => { Transaction.OriginalFromAmount = 0; }); diff --git a/src/Financier.Desktop/Pages/Dialogs/TagControlVM.cs b/src/Financier.Desktop/Pages/Dialogs/TagControlVM.cs index 03269d5f..632178e5 100644 --- a/src/Financier.Desktop/Pages/Dialogs/TagControlVM.cs +++ b/src/Financier.Desktop/Pages/Dialogs/TagControlVM.cs @@ -12,7 +12,7 @@ public TagControlVM(TagDto entity) this.Entity = entity; } - public DelegateCommand ClearTitleCommand => _clearTitleCommand ??= new DelegateCommand(() => { Entity.Title = default!; }); + public DelegateCommand ClearTitleCommand => _clearTitleCommand ??= new DelegateCommand(() => { Entity.Title = default; }); public TagDto Entity { get; } public override object OnRequestSave() diff --git a/src/Financier.Desktop/Pages/Dialogs/TransactionControlVM.cs b/src/Financier.Desktop/Pages/Dialogs/TransactionControlVM.cs index 34713fd5..9bd3f63e 100644 --- a/src/Financier.Desktop/Pages/Dialogs/TransactionControlVM.cs +++ b/src/Financier.Desktop/Pages/Dialogs/TransactionControlVM.cs @@ -51,7 +51,7 @@ public TransactionControlVM( private static void CopySubTransaction(TransactionDto original, TransactionDto modifiedCopy) { original.CategoryId = modifiedCopy.CategoryId; - original.Category = DbManual.Category?.Find(x => x.Id == modifiedCopy.CategoryId)!; + original.Category = DbManual.Category?.Find(x => x.Id == modifiedCopy.CategoryId); original.FromAmount = modifiedCopy.RealFromAmount; original.IsAmountNegative = modifiedCopy.IsAmountNegative; original.Note = modifiedCopy.Note; @@ -83,7 +83,7 @@ private void ShowRecepiesDialog() { foreach (var item in outputTransactions) { - item.Category = DbManual.Category?.Find(x => x.Id == item.CategoryId)!; + item.Category = DbManual.Category?.Find(x => x.Id == item.CategoryId); Transaction.SubTransactions.Add(item); } Transaction.RecalculateUnSplitAmount(); diff --git a/src/Financier.Desktop/Pages/Dialogs/TransferControlVM.cs b/src/Financier.Desktop/Pages/Dialogs/TransferControlVM.cs index 24e4a45c..4ead30aa 100644 --- a/src/Financier.Desktop/Pages/Dialogs/TransferControlVM.cs +++ b/src/Financier.Desktop/Pages/Dialogs/TransferControlVM.cs @@ -17,13 +17,13 @@ public class TransferControlVM : DialogBaseVM public TransferControlVM(TransferDto transfer) { Transfer = transfer; - Transfer.PropertyChanged += TransferPropertyChanged!; + Transfer.PropertyChanged += TransferPropertyChanged; transfer.RecalculateRate(); } public TransferDto Transfer { get; } - public DelegateCommand ClearNotesCommand => _clearNotesCommand ??= new DelegateCommand(() => { Transfer.Note = default!; }); + public DelegateCommand ClearNotesCommand => _clearNotesCommand ??= new DelegateCommand(() => { Transfer.Note = default; }); public override object OnRequestSave() => Transfer; diff --git a/src/Financier.Desktop/Pages/RulesVM.cs b/src/Financier.Desktop/Pages/RulesVM.cs index 444addbd..e9a7f71c 100644 --- a/src/Financier.Desktop/Pages/RulesVM.cs +++ b/src/Financier.Desktop/Pages/RulesVM.cs @@ -40,14 +40,14 @@ protected override async Task RefreshData() private async Task OnRuleDelete(int id) { - DbManual.Rules.Remove(DbManual.Rules.FirstOrDefault(r => r.Id == id)!); + DbManual.Rules.Remove(DbManual.Rules.FirstOrDefault(r => r.Id == id)); await RefreshData(); } private async Task OpenRulesDialogAsync(int id) { - RuleDto rule = null!; + RuleDto rule = null; if (id != 0) { @@ -99,7 +99,7 @@ private async Task OpenRulesDialogAsync(int id) else { var existingRule = DbManual.Rules.FirstOrDefault(r => r.Id == id); - DbManual.Rules?.Remove(existingRule!); + DbManual.Rules?.Remove(existingRule); newId = id; } DbManual.Rules?.Add(new RuleModel diff --git a/src/Financier.Desktop/Services/ExchangeRatesService.cs b/src/Financier.Desktop/Services/ExchangeRatesService.cs index a23f891f..9516ee61 100644 --- a/src/Financier.Desktop/Services/ExchangeRatesService.cs +++ b/src/Financier.Desktop/Services/ExchangeRatesService.cs @@ -385,13 +385,13 @@ private static string buildFreeCurrencyUrl(string fromCurrency, string toCurrenc public static (long UpdatedOn, float Rate) ParseExchangeRateJson(string json) { var obj = JObject.Parse(json); - var updated = long.Parse(obj["updated"]!.Value()!); + var updated = long.Parse(obj["updated"].Value()); // Find the currency key (any key that's not "updated") var currencyProperty = obj.Properties() .FirstOrDefault(p => p.Name != "updated"); - return (updated, currencyProperty!.Value.Value()); + return (updated, currencyProperty.Value.Value()); } private sealed class OpenExchangeCurrencyRates diff --git a/src/Financier.Desktop/Services/UpdateService.cs b/src/Financier.Desktop/Services/UpdateService.cs index bc39fe12..d9c97bef 100644 --- a/src/Financier.Desktop/Services/UpdateService.cs +++ b/src/Financier.Desktop/Services/UpdateService.cs @@ -7,7 +7,7 @@ namespace Financier.Desktop.Services { - public class UpdateService() : IDisposable + public sealed class UpdateService() : IDisposable { #nullable enable private readonly IUpdateManager? _updateManager = new UpdateManager( @@ -19,10 +19,9 @@ public class UpdateService() : IDisposable new ZipPackageExtractor() ); - private Version? _updateVersion; private bool _isUpdatePrepared; private bool _isUpdaterLaunched; - + private Version? _updateVersion; public async Task CheckForUpdatesAsync() { if (_updateManager is null) @@ -33,15 +32,24 @@ public class UpdateService() : IDisposable } #nullable disable - public async Task PrepareUpdateAsync(Version version) + public void Dispose() + { + _updateManager?.Dispose(); + GC.SuppressFinalize(this); + } + + public void FinalizeUpdate(bool needRestart) { if (_updateManager is null) return; + if (_updateVersion is null || !_isUpdatePrepared || _isUpdaterLaunched) + return; + try { - await _updateManager.PrepareUpdateAsync(_updateVersion = version); - _isUpdatePrepared = true; + _updateManager.LaunchUpdater(_updateVersion, needRestart); + _isUpdaterLaunched = true; } catch (UpdaterAlreadyLaunchedException) { @@ -53,18 +61,16 @@ public async Task PrepareUpdateAsync(Version version) } } - public void FinalizeUpdate(bool needRestart) + public async Task PrepareUpdateAsync(Version version) { if (_updateManager is null) return; - if (_updateVersion is null || !_isUpdatePrepared || _isUpdaterLaunched) - return; - try { - _updateManager.LaunchUpdater(_updateVersion, needRestart); - _isUpdaterLaunched = true; + _updateVersion = version; + await _updateManager.PrepareUpdateAsync(_updateVersion); + _isUpdatePrepared = true; } catch (UpdaterAlreadyLaunchedException) { @@ -75,7 +81,5 @@ public void FinalizeUpdate(bool needRestart) // Ignore race conditions } } - - public void Dispose() => _updateManager?.Dispose(); } } diff --git a/src/Financier.Desktop/Wizards/MonoWizard/MonoWizardVM.cs b/src/Financier.Desktop/Wizards/MonoWizard/MonoWizardVM.cs index 045c9c90..a4c39478 100644 --- a/src/Financier.Desktop/Wizards/MonoWizard/MonoWizardVM.cs +++ b/src/Financier.Desktop/Wizards/MonoWizard/MonoWizardVM.cs @@ -77,7 +77,7 @@ public override object OnRequestClose(bool save) .Select(TransformMonoTransaction) .ToList(); } - return null!; + return null; } private Transaction TransformMonoTransaction(FinancierTransactionDto x) @@ -93,7 +93,7 @@ private Transaction TransformMonoTransaction(FinancierTransactionDto x) ProjectId = x.ProjectId, PayeeId = x.PayeeId, CategoryId = 0, - Category = default!, + Category = default, DateTime = x.DateTime, ToAmount = 0 }; @@ -116,7 +116,7 @@ private Transaction TransformMonoTransaction(FinancierTransactionDto x) result.FromAccountId = x.MonoAccountId ?? 0; result.CategoryId = x.CategoryId; result.ToAccountId = 0; - result.ToAccount = default!; + result.ToAccount = default; result.ToAmount = 0; } diff --git a/src/Financier.Desktop/Wizards/MonoWizard/Page1VM.cs b/src/Financier.Desktop/Wizards/MonoWizard/Page1VM.cs index b19468bb..ff4db966 100644 --- a/src/Financier.Desktop/Wizards/MonoWizard/Page1VM.cs +++ b/src/Financier.Desktop/Wizards/MonoWizard/Page1VM.cs @@ -12,7 +12,7 @@ public class Page1VM : WizardPageBaseVM public Page1VM(string bank) { - MonoAccount = DbManual.Account.FirstOrDefault(x => x.IsActive && x.Title.Contains(bank, System.StringComparison.OrdinalIgnoreCase)) ?? DbManual.Account.FirstOrDefault(x => x.Id != null)!; + MonoAccount = DbManual.Account.FirstOrDefault(x => x.IsActive && x.Title.Contains(bank, System.StringComparison.OrdinalIgnoreCase)) ?? DbManual.Account.FirstOrDefault(x => x.Id != null); } public AccountFilterModel MonoAccount diff --git a/src/Financier.Desktop/Wizards/MonoWizard/Page2VM.cs b/src/Financier.Desktop/Wizards/MonoWizard/Page2VM.cs index 72826f8a..bd0db3d2 100644 --- a/src/Financier.Desktop/Wizards/MonoWizard/Page2VM.cs +++ b/src/Financier.Desktop/Wizards/MonoWizard/Page2VM.cs @@ -50,8 +50,8 @@ public AccountFilterModel MonoAccount _monoAccount = value; RaisePropertyChanged(nameof(MonoAccount)); double balance = _monoAccount.TotalAmount / 100.0; - StartTransaction = allTransactions.FirstOrDefault(x => Math.Abs(x.Balance - balance) < 0.01)!; - LastAccountTransaction = (_monoAccount?.Id != null && lastTransactions.ContainsKey(_monoAccount.Id.Value)) ? lastTransactions[_monoAccount.Id.Value] : null!; + StartTransaction = allTransactions.FirstOrDefault(x => Math.Abs(x.Balance - balance) < 0.01); + LastAccountTransaction = (_monoAccount?.Id != null && lastTransactions.ContainsKey(_monoAccount.Id.Value)) ? lastTransactions[_monoAccount.Id.Value] : null; } } diff --git a/src/Financier.Desktop/Wizards/RecipesWizard/Page2VM.cs b/src/Financier.Desktop/Wizards/RecipesWizard/Page2VM.cs index 96a70b32..e1328c0e 100644 --- a/src/Financier.Desktop/Wizards/RecipesWizard/Page2VM.cs +++ b/src/Financier.Desktop/Wizards/RecipesWizard/Page2VM.cs @@ -88,7 +88,7 @@ private void ClearAllNotes() { foreach (var item in FinancierTransactions) { - item.Note = null!; + item.Note = null; } } } diff --git a/src/Financier.Desktop/Wizards/RecipesWizard/RecipesVM.cs b/src/Financier.Desktop/Wizards/RecipesWizard/RecipesVM.cs index 3902e805..3de00bc8 100644 --- a/src/Financier.Desktop/Wizards/RecipesWizard/RecipesVM.cs +++ b/src/Financier.Desktop/Wizards/RecipesWizard/RecipesVM.cs @@ -63,7 +63,7 @@ public override object OnRequestClose(bool save) .Select(TransformMonoTransaction) .ToList(); } - return null!; + return null; } private TransactionDto TransformMonoTransaction(FinancierTransactionDto x) @@ -79,7 +79,7 @@ private TransactionDto TransformMonoTransaction(FinancierTransactionDto x) LocationId = x.LocationId, ProjectId = x.ProjectId, CategoryId = x.CategoryId, - Category = default!, + Category = default, }; return result; diff --git a/src/Financier.Desktop/Wizards/WizardBaseVM.cs b/src/Financier.Desktop/Wizards/WizardBaseVM.cs index 0e56a6dd..ed3bfdf4 100644 --- a/src/Financier.Desktop/Wizards/WizardBaseVM.cs +++ b/src/Financier.Desktop/Wizards/WizardBaseVM.cs @@ -79,7 +79,7 @@ int CurrentPageIndex { Logger.Error("Why is the current page null?"); } - return Pages.IndexOf(CurrentPage!); + return Pages.IndexOf(CurrentPage); } } diff --git a/src/Financier.Reports/BaseReportVM.cs b/src/Financier.Reports/BaseReportVM.cs index db6d61ad..fc3e8535 100644 --- a/src/Financier.Reports/BaseReportVM.cs +++ b/src/Financier.Reports/BaseReportVM.cs @@ -50,7 +50,7 @@ protected BaseReportVM(IFinancierDatabase financierDatabase) public ProjectModel Project { - get => _project ??= DbManual.Project.FirstOrDefault(p => !p.Id.HasValue)!; + get => _project ??= DbManual.Project.FirstOrDefault(p => !p.Id.HasValue); set { _project = value; @@ -60,7 +60,7 @@ public ProjectModel Project public CategoryModel Category { - get => _category ??= DbManual.Category.FirstOrDefault(p => !p.Id.HasValue)!; + get => _category ??= DbManual.Category.FirstOrDefault(p => !p.Id.HasValue); set { _category = value; @@ -70,7 +70,7 @@ public CategoryModel Category public CategoryModel TopCategory { - get => _topCategory ??= DbManual.TopCategories.FirstOrDefault(p => !p.Id.HasValue)!; + get => _topCategory ??= DbManual.TopCategories.FirstOrDefault(p => !p.Id.HasValue); set { _topCategory = value; @@ -80,7 +80,7 @@ public CategoryModel TopCategory public AccountFilterModel Account { - get => _account ??= DbManual.Account.FirstOrDefault(p => !p.Id.HasValue)!; + get => _account ??= DbManual.Account.FirstOrDefault(p => !p.Id.HasValue); set { _account = value; @@ -90,7 +90,7 @@ public AccountFilterModel Account public PayeeModel Payee { - get => _payee ??= DbManual.Payee.FirstOrDefault(p => !p.Id.HasValue)!; + get => _payee ??= DbManual.Payee.FirstOrDefault(p => !p.Id.HasValue); set { _payee = value; @@ -100,7 +100,7 @@ public PayeeModel Payee public CurrencyModel CurentCurrency { - get => _curentCurrency ??= DbManual.Currencies.FirstOrDefault(p => !p.Id.HasValue)!; + get => _curentCurrency ??= DbManual.Currencies.FirstOrDefault(p => !p.Id.HasValue); set { _curentCurrency = value; @@ -110,7 +110,7 @@ public CurrencyModel CurentCurrency public YearMonths StartYearMonths { - get => _startYearMonths ??= DbManual.YearMonths.FirstOrDefault(p => !p.Year.HasValue && !p.Month.HasValue)!; + get => _startYearMonths ??= DbManual.YearMonths.FirstOrDefault(p => !p.Year.HasValue && !p.Month.HasValue); set { _startYearMonths = value; @@ -120,7 +120,7 @@ public YearMonths StartYearMonths public YearMonths EndYearMonths { - get => _endYearMonths ??= DbManual.YearMonths.FirstOrDefault(p => !p.Year.HasValue && !p.Month.HasValue)!; + get => _endYearMonths ??= DbManual.YearMonths.FirstOrDefault(p => !p.Year.HasValue && !p.Month.HasValue); set { _endYearMonths = value; diff --git a/src/Financier.Reports/ReportsControlVM.cs b/src/Financier.Reports/ReportsControlVM.cs index c1e7fb8c..91c93669 100644 --- a/src/Financier.Reports/ReportsControlVM.cs +++ b/src/Financier.Reports/ReportsControlVM.cs @@ -123,24 +123,24 @@ public void CloseReport(BindableBase selected) public void OpenReport(string reportType) { - BindableBase existingReport = ReportsVM.FirstOrDefault(p => p.GetType().ToString() == reportType)!; + BindableBase existingReport = ReportsVM.FirstOrDefault(p => p.GetType().ToString() == reportType); if (existingReport != null) { SelectedReport = existingReport; } else { - Type type = Type.GetType(reportType, false, true)!; + Type type = Type.GetType(reportType, false, true); if (type != null) { - ConstructorInfo constructor = type.GetConstructors().FirstOrDefault()!; + ConstructorInfo constructor = type.GetConstructors().FirstOrDefault(); if (constructor != null) { BindableBase newReport = (BindableBase)constructor.Invoke(new[] { financierDatabase }); - HeaderAttribute customAttribute = (HeaderAttribute)Attribute.GetCustomAttribute(type, typeof(HeaderAttribute))!; + HeaderAttribute customAttribute = (HeaderAttribute)Attribute.GetCustomAttribute(type, typeof(HeaderAttribute)); string header = LocalizationService.Instance[customAttribute.Header]; - newReport.GetType().GetProperty("Header")!.SetValue(newReport, header, null); + newReport.GetType().GetProperty("Header").SetValue(newReport, header, null); ReportsVM.Add(newReport); SelectedReport = newReport; } diff --git a/src/Financier.Reports/SafePlotModel.cs b/src/Financier.Reports/SafePlotModel.cs index 75edfbf9..2ac808f0 100644 --- a/src/Financier.Reports/SafePlotModel.cs +++ b/src/Financier.Reports/SafePlotModel.cs @@ -7,11 +7,11 @@ namespace Financier.Reports { public class SafePlotModel : PlotModel, IPlotModel { - private static readonly Type BaseType = typeof(SafePlotModel).BaseType!; + private static readonly Type BaseType = typeof(SafePlotModel).BaseType; private static readonly MethodInfo BaseAttachMethod = BaseType .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(methodInfo => methodInfo.IsFinal && methodInfo.IsPrivate) - .FirstOrDefault(methodInfo => methodInfo.Name.EndsWith(nameof(IPlotModel.AttachPlotView)))!; + .FirstOrDefault(methodInfo => methodInfo.Name.EndsWith(nameof(IPlotModel.AttachPlotView))); void IPlotModel.AttachPlotView(IPlotView plotView) { @@ -20,12 +20,12 @@ void IPlotModel.AttachPlotView(IPlotView plotView) //we have to force detach previous view and then attach new one if (plotView != null && PlotView != null && !Equals(plotView, PlotView)) { - BaseAttachMethod.Invoke(this, new object[] { null! }); + BaseAttachMethod.Invoke(this, new object[] { null }); BaseAttachMethod.Invoke(this, new object[] { plotView }); } else { - BaseAttachMethod.Invoke(this, new object[] { plotView! }); + BaseAttachMethod.Invoke(this, new object[] { plotView }); } } } diff --git a/src/Tests/Financier.Adapter.Tests/BackupReaderTests.cs b/src/Tests/Financier.Adapter.Tests/BackupReaderTests.cs index 53ac1f27..1c485b2e 100644 --- a/src/Tests/Financier.Adapter.Tests/BackupReaderTests.cs +++ b/src/Tests/Financier.Adapter.Tests/BackupReaderTests.cs @@ -16,7 +16,9 @@ public async Task GetLines_ReadLinesFromArchive_ReadCorrectCount() int count = 0; await foreach (var _ in backupReader.GetLinesAsync()) + { count++; + } Assert.Equal(343, count); Assert.Equal(211, backupReader.BackupVersion.DatabaseVersion); @@ -25,4 +27,4 @@ public async Task GetLines_ReadLinesFromArchive_ReadCorrectCount() Assert.Equal(100, backupReader.BackupVersion.VersionCode); } } -} \ No newline at end of file +} diff --git a/src/Tests/Financier.Adapter.Tests/Financier.Adapter.Tests.csproj b/src/Tests/Financier.Adapter.Tests/Financier.Adapter.Tests.csproj index 4307a5eb..36cd4ed1 100644 --- a/src/Tests/Financier.Adapter.Tests/Financier.Adapter.Tests.csproj +++ b/src/Tests/Financier.Adapter.Tests/Financier.Adapter.Tests.csproj @@ -29,6 +29,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + all diff --git a/src/Tests/Financier.Converter.Test/Financier.Common.Test.csproj b/src/Tests/Financier.Converter.Test/Financier.Common.Test.csproj index 941efa4e..5afb918e 100644 --- a/src/Tests/Financier.Converter.Test/Financier.Common.Test.csproj +++ b/src/Tests/Financier.Converter.Test/Financier.Common.Test.csproj @@ -23,6 +23,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Tests/Financier.DataAccess.Tests/Financier.DataAccess.Tests.csproj b/src/Tests/Financier.DataAccess.Tests/Financier.DataAccess.Tests.csproj index 7442de67..935b375a 100644 --- a/src/Tests/Financier.DataAccess.Tests/Financier.DataAccess.Tests.csproj +++ b/src/Tests/Financier.DataAccess.Tests/Financier.DataAccess.Tests.csproj @@ -16,6 +16,7 @@ + all diff --git a/src/Tests/Financier.Desktop.Tests/Financier.Desktop.Tests.csproj b/src/Tests/Financier.Desktop.Tests/Financier.Desktop.Tests.csproj index f843b385..8d5a04a4 100644 --- a/src/Tests/Financier.Desktop.Tests/Financier.Desktop.Tests.csproj +++ b/src/Tests/Financier.Desktop.Tests/Financier.Desktop.Tests.csproj @@ -20,6 +20,7 @@ + all diff --git a/src/Tests/Financier.Desktop.Tests/Pages/BlotterVMIntegrationTests.cs b/src/Tests/Financier.Desktop.Tests/Pages/BlotterVMIntegrationTests.cs index 3cf521fd..5c070d2e 100644 --- a/src/Tests/Financier.Desktop.Tests/Pages/BlotterVMIntegrationTests.cs +++ b/src/Tests/Financier.Desktop.Tests/Pages/BlotterVMIntegrationTests.cs @@ -20,109 +20,8 @@ public class BlotterVMIntegrationTests { - [Fact] - public void DuplicateCommand_WithoutSelectedValue_CannotExecute() - { - var db = new FinancierDatabase(); - var dialogMock = new Mock(); - var vm = new BlotterVM(db, dialogMock.Object); - - Assert.False(vm.DuplicateCommand.CanExecute()); - } - - [Fact] - public void DuplicateCommand_WithSelectedValue_CanExecute() - { - var db = new FinancierDatabase(); - var dialogMock = new Mock(); - var vm = new BlotterVM(db, dialogMock.Object); - - vm.SelectedValue = new Common.Model.BlotterModel { Id = 1, CategoryId = 37, FromAccountId = 2, ToAccountId = 0 }; - - Assert.True(vm.DuplicateCommand.CanExecute()); - } - - [Fact] - public void PropertySetters_Account_RaisesPropertyChanged() - { - var db = new FinancierDatabase(); - var dialogMock = new Mock(); - var vm = new BlotterVM(db, dialogMock.Object); - var changedProperties = new List(); - - var inpc = vm as System.ComponentModel.INotifyPropertyChanged; - inpc.PropertyChanged += (s, e) => changedProperties.Add(e.PropertyName); - - var mockAccount = new AccountFilterModel { Id = 1, Title = "Test" }; - vm.Account = mockAccount; - - Assert.Contains("Account", changedProperties); - } - - [Fact] - public void PropertySetters_Category_RaisesPropertyChanged() - { - var db = new FinancierDatabase(); - var dialogMock = new Mock(); - var vm = new BlotterVM(db, dialogMock.Object); - var changedProperties = new List(); - - var inpc = vm as System.ComponentModel.INotifyPropertyChanged; - inpc.PropertyChanged += (s, e) => changedProperties.Add(e.PropertyName); - - var mockCategory = new CategoryModel { Id = 1, Title = "Test" }; - vm.Category = mockCategory; - - Assert.Contains("Category", changedProperties); - } - - [Fact] - public void PropertySetters_From_RaisesPropertyChanged() - { - var db = new FinancierDatabase(); - var dialogMock = new Mock(); - var vm = new BlotterVM(db, dialogMock.Object); - var changedProperties = new List(); - - var inpc = vm as System.ComponentModel.INotifyPropertyChanged; - inpc.PropertyChanged += (s, e) => changedProperties.Add(e.PropertyName); - - vm.From = System.DateTime.Now; - - Assert.Contains("From", changedProperties); - } - - [Fact] - public void PropertySetters_To_RaisesPropertyChanged() - { - var db = new FinancierDatabase(); - var dialogMock = new Mock(); - var vm = new BlotterVM(db, dialogMock.Object); - var changedProperties = new List(); - - var inpc = vm as System.ComponentModel.INotifyPropertyChanged; - inpc.PropertyChanged += (s, e) => changedProperties.Add(e.PropertyName); - - vm.To = System.DateTime.Now; - - Assert.Contains("To", changedProperties); - } - - [Fact] - public void PropertySetters_PeriodType_RaisesPropertyChanged() - { - var db = new FinancierDatabase(); - var dialogMock = new Mock(); - var vm = new BlotterVM(db, dialogMock.Object); - var changedProperties = new List(); - - var inpc = vm as System.ComponentModel.INotifyPropertyChanged; - inpc.PropertyChanged += (s, e) => changedProperties.Add(e.PropertyName); - - vm.PeriodType = PeriodType.Today; - - Assert.Contains("PeriodType", changedProperties); - } + private const string CreateSplitHomeCurrencyOnlySubTransactionsRunningBalancesJson = +"[{\"TransactionId\":1,\"AccountId\":1,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":-5000}]"; private const string CreateSplitTransactionDifferentCurrenciesRunningBalancesJson = "[{\"TransactionId\":1,\"AccountId\":2,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":-54703}]"; @@ -209,13 +108,6 @@ public void PropertySetters_PeriodType_RaisesPropertyChanged() "{\"TransactionId\":2,\"AccountId\":2,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":56000}" + "]"; - private const string EditSplitTransactionRunningBalancesJson = -"[{\"TransactionId\":27160,\"AccountId\":2,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":-24230}," + -"{\"TransactionId\":27173,\"AccountId\":1,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":834}]"; - - private const string EditSimpleTransactionJson = -"[{\"_id\":1,\"from_account_id\":2,\"to_account_id\":0,\"category_id\":37,\"project_id\":0,\"location_id\":0,\"note\":null,\"from_amount\":-10000,\"to_amount\":0,\"datetime\":1644060576000,\"provider\":null,\"accuracy\":0.0,\"latitude\":0.0,\"longitude\":0.0,\"payee\":null,\"is_template\":0,\"template_name\":null,\"recurrence\":null,\"notification_options\":null,\"status\":\"UR\",\"attached_picture\":null,\"is_ccard_payment\":0,\"last_recurrence\":0,\"payee_id\":0,\"parent_id\":0,\"updated_on\":0,\"remote_key\":null,\"original_currency_id\":0,\"original_from_amount\":0,\"blob_key\":null}]"; - private const string EditSimpleTransactionDtoJson = "{\"Date\":\"2022-02-15T00:00:00+02:00\",\"Time\":\"2022-02-15T23:05:49.208+02:00\"," + "\"FromAccount\":{\"Id\":2,\"IsActive\":true,\"SortOrder\":1,\"Title\":\"\\u041c\\u0456\\u0439 \\u0413\\u0430\\u043c\\u0430\\u043d\\u0435\\u0446\\u044c\",\"Type\":\"CASH\",\"CurrencyName\":\"UAH\",\"CurrencyId\":1,\"TotalAmount\":0}," + @@ -223,16 +115,14 @@ public void PropertySetters_PeriodType_RaisesPropertyChanged() "\"FromAccountCurrency\":{\"Id\":1,\"Name\":\"UAH\",\"Title\":\"Ukrainian hryvnia\",\"Symbol\":\"\\u20b4\",\"IsDefault\":true}," + "\"FromAmount\":20000,\"Rate\":0.0,\"RealFromAmount\":-20000,\"SplitAmount\":0,\"DateTime\":\"2022-02-15T23:05:49\",\"Id\":1,\"IsSubTransaction\":false}"; + private const string EditSimpleTransactionJson = +"[{\"_id\":1,\"from_account_id\":2,\"to_account_id\":0,\"category_id\":37,\"project_id\":0,\"location_id\":0,\"note\":null,\"from_amount\":-10000,\"to_amount\":0,\"datetime\":1644060576000,\"provider\":null,\"accuracy\":0.0,\"latitude\":0.0,\"longitude\":0.0,\"payee\":null,\"is_template\":0,\"template_name\":null,\"recurrence\":null,\"notification_options\":null,\"status\":\"UR\",\"attached_picture\":null,\"is_ccard_payment\":0,\"last_recurrence\":0,\"payee_id\":0,\"parent_id\":0,\"updated_on\":0,\"remote_key\":null,\"original_currency_id\":0,\"original_from_amount\":0,\"blob_key\":null}]"; + private const string EditSimpleTransactionRunningBalancesJson = "[{\"TransactionId\":1,\"AccountId\":2,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":-20000}]"; - private const string CreateSplitHomeCurrencyOnlySubTransactionsRunningBalancesJson = -"[{\"TransactionId\":1,\"AccountId\":1,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":-5000}]"; - - private const string EditSplitToSimpleTransactionJson = -"[{\"_id\":27160,\"from_account_id\":2,\"to_account_id\":0,\"category_id\":-1,\"project_id\":0,\"location_id\":0,\"note\":null,\"from_amount\":-10000,\"to_amount\":0,\"datetime\":1644745608000,\"provider\":null,\"accuracy\":0.0,\"latitude\":0.0,\"longitude\":0.0,\"payee\":null,\"is_template\":0,\"template_name\":null,\"recurrence\":null,\"notification_options\":null,\"status\":\"UR\",\"attached_picture\":null,\"is_ccard_payment\":0,\"last_recurrence\":0,\"payee_id\":0,\"parent_id\":0,\"updated_on\":0,\"remote_key\":null,\"original_currency_id\":0,\"original_from_amount\":0,\"blob_key\":null}," + -"{\"_id\":27165,\"from_account_id\":2,\"to_account_id\":0,\"category_id\":37,\"project_id\":0,\"location_id\":0,\"note\":null,\"from_amount\":-6000,\"to_amount\":0,\"datetime\":1644745608000,\"provider\":null,\"accuracy\":0.0,\"latitude\":0.0,\"longitude\":0.0,\"payee\":null,\"is_template\":0,\"template_name\":null,\"recurrence\":null,\"notification_options\":null,\"status\":\"UR\",\"attached_picture\":null,\"is_ccard_payment\":0,\"last_recurrence\":0,\"payee_id\":0,\"parent_id\":27160,\"updated_on\":0,\"remote_key\":null,\"original_currency_id\":0,\"original_from_amount\":0,\"blob_key\":null}," + -"{\"_id\":27166,\"from_account_id\":2,\"to_account_id\":0,\"category_id\":43,\"project_id\":0,\"location_id\":0,\"note\":null,\"from_amount\":-4000,\"to_amount\":0,\"datetime\":1644745608000,\"provider\":null,\"accuracy\":0.0,\"latitude\":0.0,\"longitude\":0.0,\"payee\":null,\"is_template\":0,\"template_name\":null,\"recurrence\":null,\"notification_options\":null,\"status\":\"UR\",\"attached_picture\":null,\"is_ccard_payment\":0,\"last_recurrence\":0,\"payee_id\":0,\"parent_id\":27160,\"updated_on\":0,\"remote_key\":null,\"original_currency_id\":0,\"original_from_amount\":0,\"blob_key\":null}]"; + private const string EditSplitToSimpleRunningBalancesJson = +"[{\"TransactionId\":27160,\"AccountId\":2,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":-10000}]"; private const string EditSplitToSimpleTransactionDtoJson = "{\"Date\":\"2022-02-13T00:00:00+02:00\",\"Time\":\"2022-02-13T11:46:48+02:00\"," + @@ -241,10 +131,17 @@ public void PropertySetters_PeriodType_RaisesPropertyChanged() "\"FromAccountCurrency\":{\"Id\":1,\"Name\":\"UAH\",\"Title\":\"Ukrainian hryvnia\",\"Symbol\":\"\\u20b4\",\"IsDefault\":true}," + "\"FromAmount\":10000,\"Rate\":0.0,\"RealFromAmount\":-10000,\"SplitAmount\":0,\"DateTime\":\"2022-02-13T11:46:48\",\"Id\":27160,\"IsSubTransaction\":false}"; - private const string EditSplitToSimpleRunningBalancesJson = -"[{\"TransactionId\":27160,\"AccountId\":2,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":-10000}]"; + private const string EditSplitToSimpleTransactionJson = +"[{\"_id\":27160,\"from_account_id\":2,\"to_account_id\":0,\"category_id\":-1,\"project_id\":0,\"location_id\":0,\"note\":null,\"from_amount\":-10000,\"to_amount\":0,\"datetime\":1644745608000,\"provider\":null,\"accuracy\":0.0,\"latitude\":0.0,\"longitude\":0.0,\"payee\":null,\"is_template\":0,\"template_name\":null,\"recurrence\":null,\"notification_options\":null,\"status\":\"UR\",\"attached_picture\":null,\"is_ccard_payment\":0,\"last_recurrence\":0,\"payee_id\":0,\"parent_id\":0,\"updated_on\":0,\"remote_key\":null,\"original_currency_id\":0,\"original_from_amount\":0,\"blob_key\":null}," + +"{\"_id\":27165,\"from_account_id\":2,\"to_account_id\":0,\"category_id\":37,\"project_id\":0,\"location_id\":0,\"note\":null,\"from_amount\":-6000,\"to_amount\":0,\"datetime\":1644745608000,\"provider\":null,\"accuracy\":0.0,\"latitude\":0.0,\"longitude\":0.0,\"payee\":null,\"is_template\":0,\"template_name\":null,\"recurrence\":null,\"notification_options\":null,\"status\":\"UR\",\"attached_picture\":null,\"is_ccard_payment\":0,\"last_recurrence\":0,\"payee_id\":0,\"parent_id\":27160,\"updated_on\":0,\"remote_key\":null,\"original_currency_id\":0,\"original_from_amount\":0,\"blob_key\":null}," + +"{\"_id\":27166,\"from_account_id\":2,\"to_account_id\":0,\"category_id\":43,\"project_id\":0,\"location_id\":0,\"note\":null,\"from_amount\":-4000,\"to_amount\":0,\"datetime\":1644745608000,\"provider\":null,\"accuracy\":0.0,\"latitude\":0.0,\"longitude\":0.0,\"payee\":null,\"is_template\":0,\"template_name\":null,\"recurrence\":null,\"notification_options\":null,\"status\":\"UR\",\"attached_picture\":null,\"is_ccard_payment\":0,\"last_recurrence\":0,\"payee_id\":0,\"parent_id\":27160,\"updated_on\":0,\"remote_key\":null,\"original_currency_id\":0,\"original_from_amount\":0,\"blob_key\":null}]"; + + private const string EditSplitTransactionRunningBalancesJson = +"[{\"TransactionId\":27160,\"AccountId\":2,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":-24230}," + +"{\"TransactionId\":27173,\"AccountId\":1,\"Account\":null,\"Transaction\":null,\"Datetime\":0,\"Balance\":834}]"; private readonly Mock dialogMock; + private FinancierDatabase db; public BlotterVMIntegrationTests() @@ -273,6 +170,27 @@ public async Task CreateSplitTransaction_DifferentCurrencies_BalancesUpdated() Assert.Equal(-1933, result.Transactions.Where(x => x.ParentId > 0).Sum(x => x.OriginalFromAmount)); } + [Fact] + public async Task CreateSplitTransaction_HomeCurrency_OnlySubTransactions_BalancesUpdated() + { + await SetupDb(); + + var resultVm = CreateSplitTransactionHomeCurrencyOnlySubTransactionsDto(); + this.dialogMock.Setup(x => x.ShowDialog(It.IsAny(), 640, 340, nameof(Transaction))) + .Returns(resultVm); + + var vm = new BlotterVM(db, dialogMock.Object); + await vm.AddCommand.ExecuteAsync(); + + var result = await GetResults(); + + Assert.Equal(CreateSplitHomeCurrencyOnlySubTransactionsRunningBalancesJson, JsonConvert.SerializeObject(result.Balances)); + Assert.Equal(-5000, result.Accounts.FirstOrDefault(x => x.Id == 1).TotalAmount); + Assert.Equal(3, result.Transactions.Count); + Assert.Equal(-3000, result.Transactions.First(x => x.ParentId > 0 && x.CategoryId == 37).FromAmount); + Assert.Equal(-2000, result.Transactions.First(x => x.ParentId > 0 && x.CategoryId == 43).FromAmount); + } + [Fact] public async Task CreateSplitTransaction_SubTransactionWithSubTransfer_BalancesUpdated() { @@ -337,6 +255,28 @@ public async Task CreateTransfer_HomeCurrency_BalancesUpdated(string resultVmJso Assert.Equal(toAmount, result.Transactions[0].ToAmount); } + [Fact] + public void DuplicateCommand_WithoutSelectedValue_CannotExecute() + { + var db = new FinancierDatabase(); + var dialogMock = new Mock(); + var vm = new BlotterVM(db, dialogMock.Object); + + Assert.False(vm.DuplicateCommand.CanExecute()); + } + + [Fact] + public void DuplicateCommand_WithSelectedValue_CanExecute() + { + var db = new FinancierDatabase(); + var dialogMock = new Mock(); + var vm = new BlotterVM(db, dialogMock.Object); + + vm.SelectedValue = new Common.Model.BlotterModel { Id = 1, CategoryId = 37, FromAccountId = 2, ToAccountId = 0 }; + + Assert.True(vm.DuplicateCommand.CanExecute()); + } + [Theory] [InlineData(DuplicateTransactionDiffCurrency, CreateTransactionDiffCurrencyDto, DuplicateTransactionDiffCurrencyRunningBalancesJson, -54703, -1933)] [InlineData(DuplicateTransactionHomeCurrency, CreateTransactionHomeCurrencyDto, DuplicateTransactionHomeCurrencyRunningBalancesJson, -10000, 0)] @@ -408,27 +348,6 @@ public async Task EditSimpleTransaction_HomeCurrency_BalancesUpdated() Assert.Equal(-20000, result.Transactions[0].FromAmount); } - [Fact] - public async Task CreateSplitTransaction_HomeCurrency_OnlySubTransactions_BalancesUpdated() - { - await SetupDb(); - - var resultVm = CreateSplitTransactionHomeCurrencyOnlySubTransactionsDto(); - this.dialogMock.Setup(x => x.ShowDialog(It.IsAny(), 640, 340, nameof(Transaction))) - .Returns(resultVm); - - var vm = new BlotterVM(db, dialogMock.Object); - await vm.AddCommand.ExecuteAsync(); - - var result = await GetResults(); - - Assert.Equal(CreateSplitHomeCurrencyOnlySubTransactionsRunningBalancesJson, JsonConvert.SerializeObject(result.Balances)); - Assert.Equal(-5000, result.Accounts.FirstOrDefault(x => x.Id == 1).TotalAmount); - Assert.Equal(3, result.Transactions.Count); - Assert.Equal(-3000, result.Transactions.First(x => x.ParentId > 0 && x.CategoryId == 37).FromAmount); - Assert.Equal(-2000, result.Transactions.First(x => x.ParentId > 0 && x.CategoryId == 43).FromAmount); - } - [Fact] public async Task EditSplitTransaction_RemoveAllSubTransactions_SubTransactionsDeleted() { @@ -497,7 +416,7 @@ public async Task Filter_ApplyFilter_ReturnFilteredTransaction() var vm = new BlotterVM(db, dialogMock.Object); - // await db.SaveAsFile(@"c:\\test.db"); + // await db.SaveAsFile(@"c:\\test.db"); await vm.RefreshDataCommand.ExecuteAsync(); Assert.Equal(18, vm.Entities.Count); @@ -548,6 +467,88 @@ public async Task Filter_ApplyFilter_ReturnFilteredTransaction() Assert.Single(vm.Entities); } + [Fact] + public void PropertySetters_Account_RaisesPropertyChanged() + { + var db = new FinancierDatabase(); + var dialogMock = new Mock(); + var vm = new BlotterVM(db, dialogMock.Object); + var changedProperties = new List(); + + var inpc = vm as System.ComponentModel.INotifyPropertyChanged; + inpc.PropertyChanged += (s, e) => changedProperties.Add(e.PropertyName); + + var mockAccount = new AccountFilterModel { Id = 1, Title = "Test" }; + vm.Account = mockAccount; + + Assert.Contains("Account", changedProperties); + } + + [Fact] + public void PropertySetters_Category_RaisesPropertyChanged() + { + var db = new FinancierDatabase(); + var dialogMock = new Mock(); + var vm = new BlotterVM(db, dialogMock.Object); + var changedProperties = new List(); + + var inpc = vm as System.ComponentModel.INotifyPropertyChanged; + inpc.PropertyChanged += (s, e) => changedProperties.Add(e.PropertyName); + + var mockCategory = new CategoryModel { Id = 1, Title = "Test" }; + vm.Category = mockCategory; + + Assert.Contains("Category", changedProperties); + } + + [Fact] + public void PropertySetters_From_RaisesPropertyChanged() + { + var db = new FinancierDatabase(); + var dialogMock = new Mock(); + var vm = new BlotterVM(db, dialogMock.Object); + var changedProperties = new List(); + + var inpc = vm as System.ComponentModel.INotifyPropertyChanged; + inpc.PropertyChanged += (s, e) => changedProperties.Add(e.PropertyName); + + vm.From = System.DateTime.Now; + + Assert.Contains("From", changedProperties); + } + + [Fact] + public void PropertySetters_PeriodType_RaisesPropertyChanged() + { + var db = new FinancierDatabase(); + var dialogMock = new Mock(); + var vm = new BlotterVM(db, dialogMock.Object); + var changedProperties = new List(); + + var inpc = vm as System.ComponentModel.INotifyPropertyChanged; + inpc.PropertyChanged += (s, e) => changedProperties.Add(e.PropertyName); + + vm.PeriodType = PeriodType.Today; + + Assert.Contains("PeriodType", changedProperties); + } + + [Fact] + public void PropertySetters_To_RaisesPropertyChanged() + { + var db = new FinancierDatabase(); + var dialogMock = new Mock(); + var vm = new BlotterVM(db, dialogMock.Object); + var changedProperties = new List(); + + var inpc = vm as System.ComponentModel.INotifyPropertyChanged; + inpc.PropertyChanged += (s, e) => changedProperties.Add(e.PropertyName); + + vm.To = System.DateTime.Now; + + Assert.Contains("To", changedProperties); + } + private List Accounts() { return JsonDeserializer.Deserialize( @@ -594,6 +595,28 @@ private TransactionDto CreateSplitTransactionDifferentCurrencyDto() return transaction; } + private TransactionDto CreateSplitTransactionHomeCurrencyOnlySubTransactionsDto() + { + var transaction = JsonConvert.DeserializeObject( +"{\"Date\":\"2022-02-15T00:00:00+02:00\",\"Time\":\"2022-02-15T17:47:19.515+02:00\"," + +"\"FromAccount\":{\"Id\":1,\"IsActive\":true,\"SortOrder\":1,\"Title\":\"\\u041c\\u0456\\u0439 \\u0413\\u0430\\u043c\\u0430\\u043d\\u0435\\u0446\\u044c\",\"Type\":\"CASH\",\"CurrencyName\":\"UAH\",\"CurrencyId\":1,\"TotalAmount\":0}," + +"\"FromAccountId\":1,\"CategoryId\":-1,\"OriginalCurrencyId\":null,\"IsSplitCategory\":true,\"LocationId\":0,\"Note\":null,\"ProjectId\":0,\"IsOriginalFromAmountVisible\":false,\"IsAmountNegative\":true,\"OriginalFromAmount\":null," + +"\"FromAccountCurrency\":{\"Id\":1,\"Name\":\"UAH\",\"Title\":\"Ukrainian hryvnia\",\"Symbol\":\"\\u20b4\",\"IsDefault\":true}," + +"\"FromAmount\":5000,\"Rate\":0.0,\"RealFromAmount\":-5000,\"SplitAmount\":-5000,\"DateTime\":\"2022-02-15T17:47:19\",\"Id\":0,\"IsSubTransaction\":false}"); + + var subTransactions = JsonConvert.DeserializeObject>( +"[{\"Date\":\"0001-01-01T00:00:00\",\"Time\":\"0001-01-01T00:00:00\",\"FromAccountId\":0,\"PayeeId\":null,\"CategoryId\":37,\"OriginalCurrencyId\":null,\"IsSplitCategory\":false,\"SubTransactions\":[],\"LocationId\":null,\"Note\":null,\"ProjectId\":null,\"IsOriginalFromAmountVisible\":false,\"IsAmountNegative\":true,\"OriginalFromAmount\":null,\"FromAccountCurrency\":null,\"FromAmount\":-3000,\"RealFromAmount\":-3000,\"Id\":0,\"IsSubTransaction\":true}," + +"{\"Date\":\"0001-01-01T00:00:00\",\"Time\":\"0001-01-01T00:00:00\",\"FromAccountId\":0,\"PayeeId\":null,\"CategoryId\":43,\"OriginalCurrencyId\":null,\"IsSplitCategory\":false,\"SubTransactions\":[],\"LocationId\":null,\"Note\":null,\"ProjectId\":null,\"IsOriginalFromAmountVisible\":false,\"IsAmountNegative\":true,\"OriginalFromAmount\":null,\"FromAccountCurrency\":null,\"FromAmount\":-2000,\"RealFromAmount\":-2000,\"Id\":0,\"IsSubTransaction\":true}]"); + + transaction.SubTransactions.Clear(); + foreach (var item in subTransactions) + { + transaction.SubTransactions.Add(item); + } + + return transaction; + } + private TransactionDto CreateSplitTransactionWithTransferTransactionDto() { var transaction = JsonConvert.DeserializeObject( @@ -627,28 +650,6 @@ private List Currencies() "]"); } - private TransactionDto CreateSplitTransactionHomeCurrencyOnlySubTransactionsDto() - { - var transaction = JsonConvert.DeserializeObject( -"{\"Date\":\"2022-02-15T00:00:00+02:00\",\"Time\":\"2022-02-15T17:47:19.515+02:00\"," + -"\"FromAccount\":{\"Id\":1,\"IsActive\":true,\"SortOrder\":1,\"Title\":\"\\u041c\\u0456\\u0439 \\u0413\\u0430\\u043c\\u0430\\u043d\\u0435\\u0446\\u044c\",\"Type\":\"CASH\",\"CurrencyName\":\"UAH\",\"CurrencyId\":1,\"TotalAmount\":0}," + -"\"FromAccountId\":1,\"CategoryId\":-1,\"OriginalCurrencyId\":null,\"IsSplitCategory\":true,\"LocationId\":0,\"Note\":null,\"ProjectId\":0,\"IsOriginalFromAmountVisible\":false,\"IsAmountNegative\":true,\"OriginalFromAmount\":null," + -"\"FromAccountCurrency\":{\"Id\":1,\"Name\":\"UAH\",\"Title\":\"Ukrainian hryvnia\",\"Symbol\":\"\\u20b4\",\"IsDefault\":true}," + -"\"FromAmount\":5000,\"Rate\":0.0,\"RealFromAmount\":-5000,\"SplitAmount\":-5000,\"DateTime\":\"2022-02-15T17:47:19\",\"Id\":0,\"IsSubTransaction\":false}"); - - var subTransactions = JsonConvert.DeserializeObject>( -"[{\"Date\":\"0001-01-01T00:00:00\",\"Time\":\"0001-01-01T00:00:00\",\"FromAccountId\":0,\"PayeeId\":null,\"CategoryId\":37,\"OriginalCurrencyId\":null,\"IsSplitCategory\":false,\"SubTransactions\":[],\"LocationId\":null,\"Note\":null,\"ProjectId\":null,\"IsOriginalFromAmountVisible\":false,\"IsAmountNegative\":true,\"OriginalFromAmount\":null,\"FromAccountCurrency\":null,\"FromAmount\":-3000,\"RealFromAmount\":-3000,\"Id\":0,\"IsSubTransaction\":true}," + -"{\"Date\":\"0001-01-01T00:00:00\",\"Time\":\"0001-01-01T00:00:00\",\"FromAccountId\":0,\"PayeeId\":null,\"CategoryId\":43,\"OriginalCurrencyId\":null,\"IsSplitCategory\":false,\"SubTransactions\":[],\"LocationId\":null,\"Note\":null,\"ProjectId\":null,\"IsOriginalFromAmountVisible\":false,\"IsAmountNegative\":true,\"OriginalFromAmount\":null,\"FromAccountCurrency\":null,\"FromAmount\":-2000,\"RealFromAmount\":-2000,\"Id\":0,\"IsSubTransaction\":true}]"); - - transaction.SubTransactions.Clear(); - foreach (var item in subTransactions) - { - transaction.SubTransactions.Add(item); - } - - return transaction; - } - private TransactionDto EditSplitTransactionDto() { var transaction = JsonConvert.DeserializeObject( diff --git a/src/Tests/Financier.Desktop.Tests/Pages/Dialog/AccountControlVMTest.cs b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/AccountControlVMTest.cs index 6a15fd91..b89ecfdf 100644 --- a/src/Tests/Financier.Desktop.Tests/Pages/Dialog/AccountControlVMTest.cs +++ b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/AccountControlVMTest.cs @@ -9,25 +9,56 @@ namespace Financier.Desktop.Tests.Pages.Dialog public class AccountControlVMTest { - // ── helpers ────────────────────────────────────────────────────────── + [Fact] + public void ClearTitleCommand_Execute_DisablesSaveCommand() + { + var entity = CreateEntity(currencyId: 1, title: "My Account"); + var vm = new AccountControlVM(entity, isNew: true); - private static AccountDto CreateEntity( - string type = "CASH", - int currencyId = 0, - string cardIssuer = null, - string title = null) => - new AccountDto - { - Type = type, - CurrencyId = currencyId, - CardIssuer = cardIssuer, - Title = title, - }; + vm.ClearTitleCommand.Execute(); - private static CurrencyModel MakeCurrency(int id, string name = "USD") => - new CurrencyModel { Id = id, Name = name }; + Assert.False(vm.SaveCommand.CanExecute()); + } - // ── Constructor ────────────────────────────────────────────────────── + [Fact] + public void ClearTitleCommand_Execute_SetsEntityTitleToNull() + { + var entity = CreateEntity(title: "My Account"); + var vm = new AccountControlVM(entity, isNew: true); + + vm.ClearTitleCommand.Execute(); + + Assert.Null(entity.Title); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("NOT_A_TYPE")] + public void Constructor_InvalidType_DefaultsSelectedAccountTypeToCash(string type) + { + var vm = new AccountControlVM(CreateEntity(type: type), isNew: true); + Assert.Equal(AccountType.CASH, vm.SelectedAccountType); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("NOT_A_TYPE")] + public void Constructor_InvalidType_NormalisesEntityTypeToCash(string type) + { + var entity = CreateEntity(type: type); + _ = new AccountControlVM(entity, isNew: true); + Assert.Equal(AccountType.CASH.ToString(), entity.Type); + } + + [Fact] + public void Constructor_SetsCurrencies_FromDbManual() + { + DbManual.SetupTests(new List()); + var vm = new AccountControlVM(CreateEntity(), isNew: true); + Assert.Same(DbManual.Currencies, vm.Currencies); + } [Fact] public void Constructor_SetsEntityProperty() @@ -37,6 +68,7 @@ public void Constructor_SetsEntityProperty() Assert.Same(entity, vm.Entity); } + // ── Constructor ────────────────────────────────────────────────────── [Theory] [InlineData(true)] [InlineData(false)] @@ -46,14 +78,6 @@ public void Constructor_SetsIsNew(bool isNew) Assert.Equal(isNew, vm.IsNew); } - [Fact] - public void Constructor_SetsCurrencies_FromDbManual() - { - DbManual.SetupTests(new List()); - var vm = new AccountControlVM(CreateEntity(), isNew: true); - Assert.Same(DbManual.Currencies, vm.Currencies); - } - [Theory] [InlineData("CASH", AccountType.CASH)] [InlineData("BANK", AccountType.BANK)] @@ -67,27 +91,6 @@ public void Constructor_ValidType_SetsSelectedAccountType(string type, AccountTy Assert.Equal(expected, vm.SelectedAccountType); } - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("NOT_A_TYPE")] - public void Constructor_InvalidType_DefaultsSelectedAccountTypeToCash(string type) - { - var vm = new AccountControlVM(CreateEntity(type: type), isNew: true); - Assert.Equal(AccountType.CASH, vm.SelectedAccountType); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("NOT_A_TYPE")] - public void Constructor_InvalidType_NormalisesEntityTypeToCash(string type) - { - var entity = CreateEntity(type: type); - _ = new AccountControlVM(entity, isNew: true); - Assert.Equal(AccountType.CASH.ToString(), entity.Type); - } - [Fact] public void Constructor_WithCardIssuer_SetsSelectedCardIssuer() { @@ -95,13 +98,6 @@ public void Constructor_WithCardIssuer_SetsSelectedCardIssuer() Assert.Equal(CardIssuer.VISA, vm.SelectedCardIssuer); } - [Fact] - public void Constructor_WithElectronicType_SetsSelectedElectronicType() - { - var vm = new AccountControlVM(CreateEntity(cardIssuer: "PAYPAL"), isNew: true); - Assert.Equal(ElectronicType.PAYPAL, vm.SelectedElectronicType); - } - [Fact] public void Constructor_WithCurrencyId_SetsSelectedCurrency() { @@ -123,6 +119,13 @@ public void Constructor_WithCurrencyIdNotInList_LeavesSelectedCurrencyNull() Assert.Null(vm.SelectedCurrency); } + [Fact] + public void Constructor_WithElectronicType_SetsSelectedElectronicType() + { + var vm = new AccountControlVM(CreateEntity(cardIssuer: "PAYPAL"), isNew: true); + Assert.Equal(ElectronicType.PAYPAL, vm.SelectedElectronicType); + } + [Fact] public void Constructor_WithZeroCurrencyId_LeavesSelectedCurrencyNull() { @@ -133,41 +136,65 @@ public void Constructor_WithZeroCurrencyId_LeavesSelectedCurrencyNull() Assert.Null(vm.SelectedCurrency); } - // ── ClearTitleCommand ──────────────────────────────────────────────── - [Fact] - public void ClearTitleCommand_Execute_SetsEntityTitleToNull() + public void EntityCurrencyIdChanged_RaisesCanExecuteChanged() { - var entity = CreateEntity(title: "My Account"); + var entity = CreateEntity(); var vm = new AccountControlVM(entity, isNew: true); + bool raised = false; + vm.SaveCommand.CanExecuteChanged += (_, _) => raised = true; - vm.ClearTitleCommand.Execute(); + entity.CurrencyId = 5; - Assert.Null(entity.Title); + Assert.True(raised); } [Fact] - public void ClearTitleCommand_Execute_DisablesSaveCommand() + public void EntityTitleChanged_RaisesCanExecuteChanged() { - var entity = CreateEntity(currencyId: 1, title: "My Account"); + var entity = CreateEntity(); var vm = new AccountControlVM(entity, isNew: true); + bool raised = false; + vm.SaveCommand.CanExecuteChanged += (_, _) => raised = true; - vm.ClearTitleCommand.Execute(); + entity.Title = "Updated"; - Assert.False(vm.SaveCommand.CanExecute()); + Assert.True(raised); } - // ── SelectedAccountType setter ──────────────────────────────────────── - [Fact] - public void SelectedAccountType_WhenChanged_SetsEntityType() + public void OnRequestSave_ReturnsEntity() { var entity = CreateEntity(); var vm = new AccountControlVM(entity, isNew: true); + Assert.Same(entity, vm.OnRequestSave()); + } - vm.SelectedAccountType = AccountType.BANK; + [Fact] + public void SaveCommand_WhenCurrencyIdIsZero_CannotExecute() + { + var entity = CreateEntity(currencyId: 0, title: "My Account"); + var vm = new AccountControlVM(entity, isNew: true); + Assert.False(vm.SaveCommand.CanExecute()); + } - Assert.Equal(AccountType.BANK.ToString(), entity.Type); + [Fact] + public void SaveCommand_WhenTitleAndCurrencyIdAreValid_CanExecute() + { + var entity = CreateEntity(currencyId: 1, title: "My Account"); + var vm = new AccountControlVM(entity, isNew: true); + Assert.True(vm.SaveCommand.CanExecute()); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void SaveCommand_WhenTitleIsNullOrWhitespace_CannotExecute(string title) + { + var entity = CreateEntity(currencyId: 1, title: title); + var vm = new AccountControlVM(entity, isNew: true); + Assert.False(vm.SaveCommand.CanExecute()); } [Fact] @@ -187,17 +214,15 @@ public void SelectedAccountType_WhenChanged_RaisesPropertyChangedForAllRelatedPr Assert.Contains(nameof(vm.ShowCreditCardFields), raised); } - // ── SelectedCardIssuer setter ───────────────────────────────────────── - [Fact] - public void SelectedCardIssuer_WhenChanged_SetsEntityCardIssuer() + public void SelectedAccountType_WhenChanged_SetsEntityType() { var entity = CreateEntity(); var vm = new AccountControlVM(entity, isNew: true); - vm.SelectedCardIssuer = CardIssuer.MASTERCARD; + vm.SelectedAccountType = AccountType.BANK; - Assert.Equal(CardIssuer.MASTERCARD.ToString(), entity.CardIssuer); + Assert.Equal(AccountType.BANK.ToString(), entity.Type); } [Fact] @@ -212,42 +237,50 @@ public void SelectedCardIssuer_WhenChanged_RaisesPropertyChanged() Assert.Contains(nameof(vm.SelectedCardIssuer), raised); } - // ── SelectedElectronicType setter ───────────────────────────────────── - [Fact] - public void SelectedElectronicType_WhenChanged_SetsEntityCardIssuer() + public void SelectedCardIssuer_WhenChanged_SetsEntityCardIssuer() { var entity = CreateEntity(); var vm = new AccountControlVM(entity, isNew: true); - vm.SelectedElectronicType = ElectronicType.PAYPAL; + vm.SelectedCardIssuer = CardIssuer.MASTERCARD; - Assert.Equal(ElectronicType.PAYPAL.ToString(), entity.CardIssuer); + Assert.Equal(CardIssuer.MASTERCARD.ToString(), entity.CardIssuer); } [Fact] - public void SelectedElectronicType_WhenChanged_RaisesPropertyChanged() + public void SelectedCurrency_WhenChanged_RaisesCanExecuteChanged() + { + var vm = new AccountControlVM(CreateEntity(), isNew: true); + bool canExecuteChangedRaised = false; + vm.SaveCommand.CanExecuteChanged += (_, _) => canExecuteChangedRaised = true; + + vm.SelectedCurrency = MakeCurrency(id: 1); + + Assert.True(canExecuteChangedRaised); + } + + [Fact] + public void SelectedCurrency_WhenChanged_RaisesPropertyChanged() { var vm = new AccountControlVM(CreateEntity(), isNew: true); var raised = new List(); vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - vm.SelectedElectronicType = ElectronicType.BITCOIN; + vm.SelectedCurrency = MakeCurrency(id: 1); - Assert.Contains(nameof(vm.SelectedElectronicType), raised); + Assert.Contains(nameof(vm.SelectedCurrency), raised); } - // ── SelectedCurrency setter ─────────────────────────────────────────── - [Fact] - public void SelectedCurrency_WithValidId_SetsEntityCurrencyId() + public void SelectedCurrency_WhenCurrencyHasNullId_DoesNotUpdateEntityCurrencyId() { - var entity = CreateEntity(); + var entity = CreateEntity(currencyId: 5); var vm = new AccountControlVM(entity, isNew: true); - vm.SelectedCurrency = MakeCurrency(id: 7); + vm.SelectedCurrency = new CurrencyModel { Id = null }; - Assert.Equal(7, entity.CurrencyId); + Assert.Equal(5, entity.CurrencyId); } [Fact] @@ -262,42 +295,39 @@ public void SelectedCurrency_WhenNullValue_DoesNotUpdateEntityCurrencyId() } [Fact] - public void SelectedCurrency_WhenCurrencyHasNullId_DoesNotUpdateEntityCurrencyId() + public void SelectedCurrency_WithValidId_SetsEntityCurrencyId() { - var entity = CreateEntity(currencyId: 5); + var entity = CreateEntity(); var vm = new AccountControlVM(entity, isNew: true); - vm.SelectedCurrency = new CurrencyModel { Id = null }; + vm.SelectedCurrency = MakeCurrency(id: 7); - Assert.Equal(5, entity.CurrencyId); + Assert.Equal(7, entity.CurrencyId); } [Fact] - public void SelectedCurrency_WhenChanged_RaisesPropertyChanged() + public void SelectedElectronicType_WhenChanged_RaisesPropertyChanged() { var vm = new AccountControlVM(CreateEntity(), isNew: true); var raised = new List(); vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - vm.SelectedCurrency = MakeCurrency(id: 1); + vm.SelectedElectronicType = ElectronicType.BITCOIN; - Assert.Contains(nameof(vm.SelectedCurrency), raised); + Assert.Contains(nameof(vm.SelectedElectronicType), raised); } [Fact] - public void SelectedCurrency_WhenChanged_RaisesCanExecuteChanged() + public void SelectedElectronicType_WhenChanged_SetsEntityCardIssuer() { - var vm = new AccountControlVM(CreateEntity(), isNew: true); - bool canExecuteChangedRaised = false; - vm.SaveCommand.CanExecuteChanged += (_, _) => canExecuteChangedRaised = true; + var entity = CreateEntity(); + var vm = new AccountControlVM(entity, isNew: true); - vm.SelectedCurrency = MakeCurrency(id: 1); + vm.SelectedElectronicType = ElectronicType.PAYPAL; - Assert.True(canExecuteChangedRaised); + Assert.Equal(ElectronicType.PAYPAL.ToString(), entity.CardIssuer); } - // ── Show* computed properties ───────────────────────────────────────── - [Theory] [InlineData(AccountType.DEBIT_CARD, true)] [InlineData(AccountType.CREDIT_CARD, true)] @@ -312,6 +342,19 @@ public void ShowCardIssuer_ReturnsExpectedValue(AccountType accountType, bool ex Assert.Equal(expected, vm.ShowCardIssuer); } + [Theory] + [InlineData(AccountType.CREDIT_CARD, true)] + [InlineData(AccountType.DEBIT_CARD, false)] + [InlineData(AccountType.CASH, false)] + [InlineData(AccountType.ELECTRONIC, false)] + [InlineData(AccountType.BANK, false)] + public void ShowCreditCardFields_ReturnsExpectedValue(AccountType accountType, bool expected) + { + var vm = new AccountControlVM(CreateEntity(), isNew: true); + vm.SelectedAccountType = accountType; + Assert.Equal(expected, vm.ShowCreditCardFields); + } + [Theory] [InlineData(AccountType.ELECTRONIC, true)] [InlineData(AccountType.CASH, false)] @@ -352,84 +395,20 @@ public void ShowNumber_ReturnsExpectedValue(AccountType accountType, bool expect Assert.Equal(expected, vm.ShowNumber); } - [Theory] - [InlineData(AccountType.CREDIT_CARD, true)] - [InlineData(AccountType.DEBIT_CARD, false)] - [InlineData(AccountType.CASH, false)] - [InlineData(AccountType.ELECTRONIC, false)] - [InlineData(AccountType.BANK, false)] - public void ShowCreditCardFields_ReturnsExpectedValue(AccountType accountType, bool expected) - { - var vm = new AccountControlVM(CreateEntity(), isNew: true); - vm.SelectedAccountType = accountType; - Assert.Equal(expected, vm.ShowCreditCardFields); - } - - // ── OnRequestSave ───────────────────────────────────────────────────── - - [Fact] - public void OnRequestSave_ReturnsEntity() - { - var entity = CreateEntity(); - var vm = new AccountControlVM(entity, isNew: true); - Assert.Same(entity, vm.OnRequestSave()); - } - - // ── CanSaveCommandExecute ───────────────────────────────────────────── - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData(" ")] - public void SaveCommand_WhenTitleIsNullOrWhitespace_CannotExecute(string title) - { - var entity = CreateEntity(currencyId: 1, title: title); - var vm = new AccountControlVM(entity, isNew: true); - Assert.False(vm.SaveCommand.CanExecute()); - } - - [Fact] - public void SaveCommand_WhenCurrencyIdIsZero_CannotExecute() - { - var entity = CreateEntity(currencyId: 0, title: "My Account"); - var vm = new AccountControlVM(entity, isNew: true); - Assert.False(vm.SaveCommand.CanExecute()); - } - - [Fact] - public void SaveCommand_WhenTitleAndCurrencyIdAreValid_CanExecute() - { - var entity = CreateEntity(currencyId: 1, title: "My Account"); - var vm = new AccountControlVM(entity, isNew: true); - Assert.True(vm.SaveCommand.CanExecute()); - } - - // ── entity.PropertyChanged subscription ─────────────────────────────── - - [Fact] - public void EntityTitleChanged_RaisesCanExecuteChanged() - { - var entity = CreateEntity(); - var vm = new AccountControlVM(entity, isNew: true); - bool raised = false; - vm.SaveCommand.CanExecuteChanged += (_, _) => raised = true; - - entity.Title = "Updated"; - - Assert.True(raised); - } - - [Fact] - public void EntityCurrencyIdChanged_RaisesCanExecuteChanged() - { - var entity = CreateEntity(); - var vm = new AccountControlVM(entity, isNew: true); - bool raised = false; - vm.SaveCommand.CanExecuteChanged += (_, _) => raised = true; - - entity.CurrencyId = 5; + private static AccountDto CreateEntity( + string type = "CASH", + int currencyId = 0, + string cardIssuer = null, + string title = null) => + new AccountDto + { + Type = type, + CurrencyId = currencyId, + CardIssuer = cardIssuer, + Title = title, + }; - Assert.True(raised); - } + private static CurrencyModel MakeCurrency(int id, string name = "USD") => + new CurrencyModel { Id = id, Name = name }; } } diff --git a/src/Tests/Financier.Desktop.Tests/Pages/Dialog/RuleControlVMTest.cs b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/RuleControlVMTest.cs index adc42e43..92d260f0 100644 --- a/src/Tests/Financier.Desktop.Tests/Pages/Dialog/RuleControlVMTest.cs +++ b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/RuleControlVMTest.cs @@ -11,50 +11,19 @@ namespace Financier.Desktop.Tests.Pages.Dialog public class RuleControlVMTest { - // ── helpers ────────────────────────────────────────────────────────── - - private static RuleDto MccRule( - Mcc mcc, - int? payeeId = 1, - int? locationId = null, - int? categoryId = null, - int? projectId = null) => - new RuleDto - { - Condition = RuleConditionType.MCC, - MCCCategory = mcc, - PayeeId = payeeId, - LocationId = locationId, - CategoryId = categoryId, - ProjectId = projectId, - }; - - private static RuleDto DescriptionRule( - string description, - RuleConditionType condition = RuleConditionType.DescriptionContains, - int? payeeId = 1, - int? locationId = null, - int? categoryId = null, - int? projectId = null) => - new RuleDto - { - Condition = condition, - MCCCategory = Mcc.none, - Description = description, - PayeeId = payeeId, - LocationId = locationId, - CategoryId = categoryId, - ProjectId = projectId, - }; - - // ── Constructor ────────────────────────────────────────────────────── + [Fact] + public void Constructor_MccTitles_IsAlphabeticallyOrdered() + { + var vm = new RuleControlVM(DescriptionRule("Test")); + Assert.Equal(vm.MccTitles.OrderBy(x => x).ToList(), vm.MccTitles); + } [Fact] - public void Constructor_SetsEntityProperty() + public void Constructor_MccTitles_IsPopulatedFromDbManual() { - var entity = DescriptionRule("Test"); - var vm = new RuleControlVM(entity); - Assert.Same(entity, vm.Entity); + var vm = new RuleControlVM(DescriptionRule("Test")); + Assert.NotEmpty(vm.MccTitles); + Assert.Equal(DbManual.MCCTitles.Count, vm.MccTitles.Count); } [Fact] @@ -74,21 +43,25 @@ public void Constructor_SelectedMccTitle_MatchesEntityMCCCategory() } [Fact] - public void Constructor_MccTitles_IsPopulatedFromDbManual() + public void Constructor_SetsEntityProperty() { - var vm = new RuleControlVM(DescriptionRule("Test")); - Assert.NotEmpty(vm.MccTitles); - Assert.Equal(DbManual.MCCTitles.Count, vm.MccTitles.Count); + var entity = DescriptionRule("Test"); + var vm = new RuleControlVM(entity); + Assert.Same(entity, vm.Entity); } [Fact] - public void Constructor_MccTitles_IsAlphabeticallyOrdered() + public void EntityPropertyChanged_TriggersCanExecuteChanged() { - var vm = new RuleControlVM(DescriptionRule("Test")); - Assert.Equal(vm.MccTitles.OrderBy(x => x).ToList(), vm.MccTitles); - } + var entity = DescriptionRule("Test", payeeId: 1); + var vm = new RuleControlVM(entity); + bool canExecuteChangedRaised = false; + vm.SaveCommand.CanExecuteChanged += (_, _) => canExecuteChangedRaised = true; - // ── IsMCCSelected ──────────────────────────────────────────────────── + entity.PayeeId = 99; + + Assert.True(canExecuteChangedRaised); + } [Theory] [InlineData(RuleConditionType.MCC, true)] @@ -101,90 +74,80 @@ public void IsMCCSelected_ReturnsExpectedValue_ForConditionType(RuleConditionTyp Assert.Equal(expected, vm.IsMCCSelected); } - // ── SelectedConditionType setter ───────────────────────────────────── - [Fact] - public void SelectedConditionType_WhenChanged_RaisesPropertyChangedForSelfAndIsMCCSelected() + public void OnRequestSave_MCC_SetsCondition_ClearsDescription_SetsMCCCategory() { - var entity = DescriptionRule("Test"); // starts as DescriptionContains + var entity = MccRule(Mcc.accessories, payeeId: 1); + entity.Description = "some prior description"; var vm = new RuleControlVM(entity); - var raised = new List(); - vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - vm.SelectedConditionType = RuleConditionType.MCC; + vm.OnRequestSave(); - Assert.Contains(nameof(vm.SelectedConditionType), raised); - Assert.Contains(nameof(vm.IsMCCSelected), raised); + Assert.Equal(RuleConditionType.MCC, entity.Condition); + Assert.Null(entity.Description); + Assert.Equal(Mcc.accessories, entity.MCCCategory); } + // ── OnRequestSave ──────────────────────────────────────────────────── [Fact] - public void SelectedConditionType_WhenSetToSameValue_DoesNotRaisePropertyChanged() + public void OnRequestSave_NonMCC_SetsCondition_SetsMCCCategoryToNone() { - var entity = DescriptionRule("Test"); // Condition = DescriptionContains + var entity = DescriptionRule("Google", payeeId: 1); + entity.MCCCategory = Mcc.accessories; // previously had an MCC set var vm = new RuleControlVM(entity); - var raised = new List(); - vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - vm.SelectedConditionType = RuleConditionType.DescriptionContains; // same value + vm.OnRequestSave(); - Assert.Empty(raised); + Assert.Equal(RuleConditionType.DescriptionContains, entity.Condition); + Assert.Equal(Mcc.none, entity.MCCCategory); } - // ── SelectedMccTitle setter ────────────────────────────────────────── - [Fact] - public void SelectedMccTitle_WhenChanged_RaisesPropertyChanged() + public void OnRequestSave_ReturnsEntity() { - var entity = MccRule(Mcc.none); + var entity = MccRule(Mcc.accessories, payeeId: 1); var vm = new RuleControlVM(entity); - var raised = new List(); - vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - vm.SelectedMccTitle = Mcc.accessories.GetEnumLocalizedMccDescription(); + var result = vm.OnRequestSave(); - Assert.Contains(nameof(vm.SelectedMccTitle), raised); + Assert.Same(entity, result); } [Fact] - public void SelectedMccTitle_WhenSetToSameValue_DoesNotRaisePropertyChanged() + public void SaveCommand_CanExecute_Description_EmptyDescription_ReturnsFalse() { - var entity = MccRule(Mcc.accessories); - var vm = new RuleControlVM(entity); - var raised = new List(); - vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - - vm.SelectedMccTitle = Mcc.accessories.GetEnumLocalizedMccDescription(); // same as ctor - - Assert.Empty(raised); + var vm = new RuleControlVM(DescriptionRule(string.Empty, payeeId: 1)); + Assert.False(vm.SaveCommand.CanExecute()); } - // ── CanSaveCommandExecute – MCC condition ──────────────────────────── - [Fact] - public void SaveCommand_CanExecute_MCC_ValidTitle_WithPayeeId_ReturnsTrue() + public void SaveCommand_CanExecute_Description_NullDescription_ReturnsFalse() { - var vm = new RuleControlVM(MccRule(Mcc.accessories, payeeId: 1)); - Assert.True(vm.SaveCommand.CanExecute()); + var vm = new RuleControlVM(DescriptionRule(null, payeeId: 1)); + Assert.False(vm.SaveCommand.CanExecute()); } [Fact] - public void SaveCommand_CanExecute_MCC_ValidTitle_WithLocationId_ReturnsTrue() + public void SaveCommand_CanExecute_Description_WithDescription_NoAccountIds_ReturnsFalse() { - var vm = new RuleControlVM(MccRule(Mcc.accessories, payeeId: null, locationId: 1)); - Assert.True(vm.SaveCommand.CanExecute()); + var vm = new RuleControlVM( + DescriptionRule("Google", payeeId: null, locationId: null, categoryId: null, projectId: null)); + Assert.False(vm.SaveCommand.CanExecute()); } [Fact] - public void SaveCommand_CanExecute_MCC_ValidTitle_WithCategoryId_ReturnsTrue() + public void SaveCommand_CanExecute_DescriptionContains_WithDescription_WithPayeeId_ReturnsTrue() { - var vm = new RuleControlVM(MccRule(Mcc.accessories, payeeId: null, categoryId: 1)); + var vm = new RuleControlVM(DescriptionRule("Google", payeeId: 1)); Assert.True(vm.SaveCommand.CanExecute()); } + // ── CanSaveCommandExecute – non-MCC conditions ─────────────────────── [Fact] - public void SaveCommand_CanExecute_MCC_ValidTitle_WithProjectId_ReturnsTrue() + public void SaveCommand_CanExecute_DescriptionMatches_WithDescription_WithLocationId_ReturnsTrue() { - var vm = new RuleControlVM(MccRule(Mcc.accessories, payeeId: null, projectId: 1)); + var vm = new RuleControlVM( + DescriptionRule("Google", condition: RuleConditionType.DescriptionMatches, payeeId: null, locationId: 1)); Assert.True(vm.SaveCommand.CanExecute()); } @@ -219,98 +182,124 @@ public void SaveCommand_CanExecute_MCC_ValidTitle_NoAccountIds_ReturnsFalse() Assert.False(vm.SaveCommand.CanExecute()); } - // ── CanSaveCommandExecute – non-MCC conditions ─────────────────────── - [Fact] - public void SaveCommand_CanExecute_DescriptionContains_WithDescription_WithPayeeId_ReturnsTrue() + public void SaveCommand_CanExecute_MCC_ValidTitle_WithCategoryId_ReturnsTrue() { - var vm = new RuleControlVM(DescriptionRule("Google", payeeId: 1)); + var vm = new RuleControlVM(MccRule(Mcc.accessories, payeeId: null, categoryId: 1)); Assert.True(vm.SaveCommand.CanExecute()); } [Fact] - public void SaveCommand_CanExecute_DescriptionMatches_WithDescription_WithLocationId_ReturnsTrue() + public void SaveCommand_CanExecute_MCC_ValidTitle_WithLocationId_ReturnsTrue() { - var vm = new RuleControlVM( - DescriptionRule("Google", condition: RuleConditionType.DescriptionMatches, payeeId: null, locationId: 1)); + var vm = new RuleControlVM(MccRule(Mcc.accessories, payeeId: null, locationId: 1)); Assert.True(vm.SaveCommand.CanExecute()); } [Fact] - public void SaveCommand_CanExecute_Description_NullDescription_ReturnsFalse() - { - var vm = new RuleControlVM(DescriptionRule(null, payeeId: 1)); - Assert.False(vm.SaveCommand.CanExecute()); - } - - [Fact] - public void SaveCommand_CanExecute_Description_EmptyDescription_ReturnsFalse() + public void SaveCommand_CanExecute_MCC_ValidTitle_WithPayeeId_ReturnsTrue() { - var vm = new RuleControlVM(DescriptionRule(string.Empty, payeeId: 1)); - Assert.False(vm.SaveCommand.CanExecute()); + var vm = new RuleControlVM(MccRule(Mcc.accessories, payeeId: 1)); + Assert.True(vm.SaveCommand.CanExecute()); } + // ── CanSaveCommandExecute – MCC condition ──────────────────────────── [Fact] - public void SaveCommand_CanExecute_Description_WithDescription_NoAccountIds_ReturnsFalse() + public void SaveCommand_CanExecute_MCC_ValidTitle_WithProjectId_ReturnsTrue() { - var vm = new RuleControlVM( - DescriptionRule("Google", payeeId: null, locationId: null, categoryId: null, projectId: null)); - Assert.False(vm.SaveCommand.CanExecute()); + var vm = new RuleControlVM(MccRule(Mcc.accessories, payeeId: null, projectId: 1)); + Assert.True(vm.SaveCommand.CanExecute()); } - // ── OnRequestSave ──────────────────────────────────────────────────── - [Fact] - public void OnRequestSave_MCC_SetsCondition_ClearsDescription_SetsMCCCategory() + public void SelectedConditionType_WhenChanged_RaisesPropertyChangedForSelfAndIsMCCSelected() { - var entity = MccRule(Mcc.accessories, payeeId: 1); - entity.Description = "some prior description"; + var entity = DescriptionRule("Test"); // starts as DescriptionContains var vm = new RuleControlVM(entity); + var raised = new List(); + vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - vm.OnRequestSave(); + vm.SelectedConditionType = RuleConditionType.MCC; - Assert.Equal(RuleConditionType.MCC, entity.Condition); - Assert.Null(entity.Description); - Assert.Equal(Mcc.accessories, entity.MCCCategory); + Assert.Contains(nameof(vm.SelectedConditionType), raised); + Assert.Contains(nameof(vm.IsMCCSelected), raised); } + // ── Constructor ────────────────────────────────────────────────────── + // ── IsMCCSelected ──────────────────────────────────────────────────── + // ── SelectedConditionType setter ───────────────────────────────────── [Fact] - public void OnRequestSave_NonMCC_SetsCondition_SetsMCCCategoryToNone() + public void SelectedConditionType_WhenSetToSameValue_DoesNotRaisePropertyChanged() { - var entity = DescriptionRule("Google", payeeId: 1); - entity.MCCCategory = Mcc.accessories; // previously had an MCC set + var entity = DescriptionRule("Test"); // Condition = DescriptionContains var vm = new RuleControlVM(entity); + var raised = new List(); + vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - vm.OnRequestSave(); + vm.SelectedConditionType = RuleConditionType.DescriptionContains; // same value - Assert.Equal(RuleConditionType.DescriptionContains, entity.Condition); - Assert.Equal(Mcc.none, entity.MCCCategory); + Assert.Empty(raised); } [Fact] - public void OnRequestSave_ReturnsEntity() + public void SelectedMccTitle_WhenChanged_RaisesPropertyChanged() { - var entity = MccRule(Mcc.accessories, payeeId: 1); + var entity = MccRule(Mcc.none); var vm = new RuleControlVM(entity); + var raised = new List(); + vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - var result = vm.OnRequestSave(); + vm.SelectedMccTitle = Mcc.accessories.GetEnumLocalizedMccDescription(); - Assert.Same(entity, result); + Assert.Contains(nameof(vm.SelectedMccTitle), raised); } - // ── Entity PropertyChanged propagation ─────────────────────────────── - + // ── SelectedMccTitle setter ────────────────────────────────────────── [Fact] - public void EntityPropertyChanged_TriggersCanExecuteChanged() + public void SelectedMccTitle_WhenSetToSameValue_DoesNotRaisePropertyChanged() { - var entity = DescriptionRule("Test", payeeId: 1); + var entity = MccRule(Mcc.accessories); var vm = new RuleControlVM(entity); - bool canExecuteChangedRaised = false; - vm.SaveCommand.CanExecuteChanged += (_, _) => canExecuteChangedRaised = true; + var raised = new List(); + vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - entity.PayeeId = 99; + vm.SelectedMccTitle = Mcc.accessories.GetEnumLocalizedMccDescription(); // same as ctor - Assert.True(canExecuteChangedRaised); + Assert.Empty(raised); } + + private static RuleDto DescriptionRule( + string description, + RuleConditionType condition = RuleConditionType.DescriptionContains, + int? payeeId = 1, + int? locationId = null, + int? categoryId = null, + int? projectId = null) => + new RuleDto + { + Condition = condition, + MCCCategory = Mcc.none, + Description = description, + PayeeId = payeeId, + LocationId = locationId, + CategoryId = categoryId, + ProjectId = projectId, + }; + + private static RuleDto MccRule( + Mcc mcc, + int? payeeId = 1, + int? locationId = null, + int? categoryId = null, + int? projectId = null) => + new RuleDto + { + Condition = RuleConditionType.MCC, + MCCCategory = mcc, + PayeeId = payeeId, + LocationId = locationId, + CategoryId = categoryId, + ProjectId = projectId, + }; } } diff --git a/src/Tests/Financier.Desktop.Tests/Pages/Dialog/SettingsVMTest.cs b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/SettingsVMTest.cs index 7b1013b2..06d665fa 100644 --- a/src/Tests/Financier.Desktop.Tests/Pages/Dialog/SettingsVMTest.cs +++ b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/SettingsVMTest.cs @@ -8,21 +8,24 @@ namespace Financier.Desktop.Tests.Pages.Dialog public class SettingsVMTest { - // ── helpers ────────────────────────────────────────────────────────── - - private static SettingsDto CreateEntity( - ExchangeRatesProviders provider = ExchangeRatesProviders.None, - string appId = "") => - new SettingsDto - { - ExchangeRates = new SettingsExchangeRates - { - Provider = provider, - OpenExchangeRatesProviderAppId = appId - } - }; + [Theory] + [InlineData(null)] + [InlineData("")] + public void Constructor_NullOrEmptyAppId_RemainsUnchanged(string appId) + { + var entity = CreateEntity(appId: appId); + var vm = new SettingsVM(entity); + Assert.Equal(appId, vm.Entity.ExchangeRates.OpenExchangeRatesProviderAppId); + } - // ── Constructor ────────────────────────────────────────────────────── + [Fact] + public void Constructor_PlainTextAppId_IsRetainedAsIs() + { + // TryDecrypt falls back to returning the input when it is not a valid DPAPI blob + var entity = CreateEntity(appId: "plain-text-key"); + var vm = new SettingsVM(entity); + Assert.Equal("plain-text-key", vm.Entity.ExchangeRates.OpenExchangeRatesProviderAppId); + } [Fact] public void Constructor_SetsEntityProperty() @@ -44,34 +47,6 @@ public void Constructor_SetsSelectedProvider_FromEntity(ExchangeRatesProviders p Assert.Equal(provider, vm.SelectedProvider); } - [Fact] - public void Constructor_PlainTextAppId_IsRetainedAsIs() - { - // TryDecrypt falls back to returning the input when it is not a valid DPAPI blob - var entity = CreateEntity(appId: "plain-text-key"); - var vm = new SettingsVM(entity); - Assert.Equal("plain-text-key", vm.Entity.ExchangeRates.OpenExchangeRatesProviderAppId); - } - - [Theory] - [InlineData(null)] - [InlineData("")] - public void Constructor_NullOrEmptyAppId_RemainsUnchanged(string appId) - { - var entity = CreateEntity(appId: appId); - var vm = new SettingsVM(entity); - Assert.Equal(appId, vm.Entity.ExchangeRates.OpenExchangeRatesProviderAppId); - } - - // ── IsOpenExchangeRatesProviderSelected ────────────────────────────── - - [Fact] - public void IsOpenExchangeRatesProviderSelected_WhenOpenExchangeRates_ReturnsTrue() - { - var vm = new SettingsVM(CreateEntity(provider: ExchangeRatesProviders.OpenExchangeRates)); - Assert.True(vm.IsOpenExchangeRatesProviderSelected); - } - [Theory] [InlineData(ExchangeRatesProviders.None)] [InlineData(ExchangeRatesProviders.Monobank)] @@ -82,35 +57,13 @@ public void IsOpenExchangeRatesProviderSelected_WhenNotOpenExchangeRates_Returns Assert.False(vm.IsOpenExchangeRatesProviderSelected); } - // ── SelectedProvider setter ────────────────────────────────────────── - [Fact] - public void SelectedProvider_WhenChanged_RaisesPropertyChangedForSelfAndIsOpenExchangeRatesProviderSelected() - { - var vm = new SettingsVM(CreateEntity(provider: ExchangeRatesProviders.None)); - var raised = new List(); - vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - - vm.SelectedProvider = ExchangeRatesProviders.OpenExchangeRates; - - Assert.Contains(nameof(vm.SelectedProvider), raised); - Assert.Contains(nameof(vm.IsOpenExchangeRatesProviderSelected), raised); - } - - [Fact] - public void SelectedProvider_WhenSetToSameValue_DoesNotRaisePropertyChanged() + public void IsOpenExchangeRatesProviderSelected_WhenOpenExchangeRates_ReturnsTrue() { - var vm = new SettingsVM(CreateEntity(provider: ExchangeRatesProviders.Monobank)); - var raised = new List(); - vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); - - vm.SelectedProvider = ExchangeRatesProviders.Monobank; - - Assert.Empty(raised); + var vm = new SettingsVM(CreateEntity(provider: ExchangeRatesProviders.OpenExchangeRates)); + Assert.True(vm.IsOpenExchangeRatesProviderSelected); } - // ── OnRequestSave ──────────────────────────────────────────────────── - [Fact] public void OnRequestSave_ReturnsEntity() { @@ -156,7 +109,7 @@ public void OnRequestSave_WithNonOpenExchangeRatesProvider_ClearsAppId(ExchangeR [Fact] public void OnRequestSave_WithOpenExchangeRatesProviderAndEmptyAppId_LeavesAppIdEmpty() { - var entity = CreateEntity(provider: ExchangeRatesProviders.OpenExchangeRates, appId: ""); + var entity = CreateEntity(provider: ExchangeRatesProviders.OpenExchangeRates, appId: string.Empty); var vm = new SettingsVM(entity); vm.OnRequestSave(); @@ -176,5 +129,42 @@ public void OnRequestSave_WithOpenExchangeRatesProviderAndNonEmptyAppId_Encrypts Assert.NotEqual(plainText, entity.ExchangeRates.OpenExchangeRatesProviderAppId); Assert.NotEmpty(entity.ExchangeRates.OpenExchangeRatesProviderAppId); } + + [Fact] + public void SelectedProvider_WhenChanged_RaisesPropertyChangedForSelfAndIsOpenExchangeRatesProviderSelected() + { + var vm = new SettingsVM(CreateEntity(provider: ExchangeRatesProviders.None)); + var raised = new List(); + vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); + + vm.SelectedProvider = ExchangeRatesProviders.OpenExchangeRates; + + Assert.Contains(nameof(vm.SelectedProvider), raised); + Assert.Contains(nameof(vm.IsOpenExchangeRatesProviderSelected), raised); + } + + [Fact] + public void SelectedProvider_WhenSetToSameValue_DoesNotRaisePropertyChanged() + { + var vm = new SettingsVM(CreateEntity(provider: ExchangeRatesProviders.Monobank)); + var raised = new List(); + vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName); + + vm.SelectedProvider = ExchangeRatesProviders.Monobank; + + Assert.Empty(raised); + } + + private static SettingsDto CreateEntity( + ExchangeRatesProviders provider = ExchangeRatesProviders.None, + string appId = "") => + new SettingsDto + { + ExchangeRates = new SettingsExchangeRates + { + Provider = provider, + OpenExchangeRatesProviderAppId = appId, + }, + }; } } diff --git a/src/Tests/Financier.Desktop.Tests/Pages/MainWindowVMTest.cs b/src/Tests/Financier.Desktop.Tests/Pages/MainWindowVMTest.cs index 9bc71feb..fc62230b 100644 --- a/src/Tests/Financier.Desktop.Tests/Pages/MainWindowVMTest.cs +++ b/src/Tests/Financier.Desktop.Tests/Pages/MainWindowVMTest.cs @@ -7,11 +7,11 @@ using System.Threading.Tasks; using Financier.Adapter; using Financier.Common.Entities; + using Financier.Common.Localization; using Financier.Common.Model; using Financier.DataAccess.Abstractions; using Financier.DataAccess.Data; using Financier.DataAccess.View; - using Financier.Common.Localization; using Financier.Desktop.Data; using Financier.Desktop.Helpers; using Financier.Desktop.Helpers.BankHelper; @@ -637,12 +637,12 @@ public async Task SaveBackupAsDb_ExecuteCommand_DBQueryExecuted(string backupPat var vm = this.GetFinancierVM(); this.dbMock.Setup(x => x.SaveAsFile(backupPath)).Returns(Task.CompletedTask).Verifiable(); this.dialogMock.Setup(x => x.SaveFileDialog(It.IsAny(), It.IsAny())).Returns(backupPath).Verifiable(); - this.dialogMock.Setup(x => x.ShowMessageBox($"Saved {backupPath}", "Backup done.", false)).Returns(true).Verifiable(); await vm.SaveBackupAsDbCommand.ExecuteAsync(); this.dbMock.VerifyAll(); this.dialogMock.VerifyAll(); + this.toastNotifierMock.Verify(x => x.ShowMessage(It.IsAny()), Times.Once); } [Fact] @@ -667,12 +667,12 @@ public async Task SettingsCommand_DialogReturnsSameLanguage_SettingsUpdated_DbMa { SettingsService.Current.Settings = new SettingsDto { - General = new SettingsGeneralDto { Language = Language.English } + General = new SettingsGeneralDto { Language = Language.English }, }; var updatedSettings = new SettingsDto { - General = new SettingsGeneralDto { Language = Language.English } + General = new SettingsGeneralDto { Language = Language.English }, }; this.dialogMock.Setup(x => x.ShowDialog( @@ -691,12 +691,12 @@ public async Task SettingsCommand_DialogReturnsDifferentLanguage_DbManualRefresh { SettingsService.Current.Settings = new SettingsDto { - General = new SettingsGeneralDto { Language = Language.English } + General = new SettingsGeneralDto { Language = Language.English }, }; var updatedSettings = new SettingsDto { - General = new SettingsGeneralDto { Language = Language.Ukrainian } + General = new SettingsGeneralDto { Language = Language.Ukrainian }, }; this.dialogMock.Setup(x => x.ShowDialog( @@ -724,7 +724,7 @@ public async Task RefreshExchangeRatesCommand_ProviderNone_ShowsWarning() { SettingsService.Current.Settings = new SettingsDto { - ExchangeRates = new SettingsExchangeRates { Provider = ExchangeRatesProviders.None } + ExchangeRates = new SettingsExchangeRates { Provider = ExchangeRatesProviders.None }, }; var vm = this.GetFinancierVM(); diff --git a/src/Tests/Financier.Desktop.Tests/Services/ExchangeRatesServiceTests.cs b/src/Tests/Financier.Desktop.Tests/Services/ExchangeRatesServiceTests.cs index da397344..1b1d808c 100644 --- a/src/Tests/Financier.Desktop.Tests/Services/ExchangeRatesServiceTests.cs +++ b/src/Tests/Financier.Desktop.Tests/Services/ExchangeRatesServiceTests.cs @@ -14,49 +14,29 @@ namespace Financier.Desktop.Tests.Services public class ExchangeRatesServiceTests { - // ── helpers ─────────────────────────────────────────────────────────── - - private static CurrencyModel MakeCurrency(int id, string name) => - new CurrencyModel { Id = id, Name = name, UpdateExchangeRate = true }; - - private static HttpClient CreateHttpClient(string responseBody, HttpStatusCode statusCode = HttpStatusCode.OK) + [Fact] + public async Task LoadFreeCurrencyRates_FailedResponse_ReturnsEmptyList() { - var handler = new Mock(); - handler.Protected() - .Setup>( - "SendAsync", - ItExpr.IsAny(), - ItExpr.IsAny()) - .ReturnsAsync(new HttpResponseMessage - { - StatusCode = statusCode, - Content = new StringContent(responseBody) - }); - return new HttpClient(handler.Object); - } + var currencies = new[] { MakeCurrency(985, "PLN"), MakeCurrency(980, "UAH") }; + var service = new ExchangeRatesService( + CreateHttpClient("error", HttpStatusCode.ServiceUnavailable), () => currencies); - private static string ExtractBodyJson(string html) - { - var start = html.IndexOf("", StringComparison.Ordinal) + "".Length; - var end = html.IndexOf("", start, StringComparison.Ordinal); - return html[start..end]; - } + var result = await service.LoadFreeCurrencyRates(); - // ── ParseExchangeRateJson ───────────────────────────────────────────── + Assert.Empty(result); + } [Fact] - public void ParseExchangeRateJson_ValidJson_ReturnsParsedValues() + public async Task LoadFreeCurrencyRates_NoCurrencies_ReturnsEmptyList() { - var json = ExtractBodyJson(File.ReadAllText(Path.Combine("Assets", "FreeCurrency.htm"))); + var service = new ExchangeRatesService( + CreateHttpClient("{}"), () => Array.Empty()); - var (updatedOn, rate) = ExchangeRatesService.ParseExchangeRateJson(json); + var result = await service.LoadFreeCurrencyRates(); - Assert.Equal(1782999003L, updatedOn); - Assert.Equal(11.879519f, rate); + Assert.Empty(result); } - // ── LoadFreeCurrencyRates ───────────────────────────────────────────── - [Fact] public async Task LoadFreeCurrencyRates_SuccessResponse_ReturnsMappedRates() { @@ -75,29 +55,59 @@ public async Task LoadFreeCurrencyRates_SuccessResponse_ReturnsMappedRates() } [Fact] - public async Task LoadFreeCurrencyRates_FailedResponse_ReturnsEmptyList() + public async Task LoadMonobankRates_FailedResponse_ReturnsEmptyList() { - var currencies = new[] { MakeCurrency(985, "PLN"), MakeCurrency(980, "UAH") }; + var currencies = new[] { MakeCurrency(840, "USD"), MakeCurrency(980, "UAH") }; var service = new ExchangeRatesService( - CreateHttpClient("error", HttpStatusCode.ServiceUnavailable), () => currencies); + CreateHttpClient("error", HttpStatusCode.TooManyRequests), () => currencies); - var result = await service.LoadFreeCurrencyRates(); + var result = await service.LoadMonobankRates(); Assert.Empty(result); } [Fact] - public async Task LoadFreeCurrencyRates_NoCurrencies_ReturnsEmptyList() + public async Task LoadMonobankRates_NoCurrencies_ReturnsEmptyList() { + var json = File.ReadAllText(Path.Combine("Assets", "mono.json")); var service = new ExchangeRatesService( - CreateHttpClient("{}"), () => Array.Empty()); + CreateHttpClient(json), () => Array.Empty()); - var result = await service.LoadFreeCurrencyRates(); + var result = await service.LoadMonobankRates(); Assert.Empty(result); } - // ── LoadOpenExchangeRates ───────────────────────────────────────────── + [Fact] + public async Task LoadMonobankRates_SuccessResponse_ReturnsMappedRate() + { + var json = File.ReadAllText(Path.Combine("Assets", "mono.json")); + + // USD (840) → UAH (980) is in mono.json with rateBuy = 44.61 + // UAH → USD has no entry in the index, so it is skipped + var currencies = new[] { MakeCurrency(840, "USD"), MakeCurrency(980, "UAH") }; + var service = new ExchangeRatesService(CreateHttpClient(json), () => currencies); + + var result = await service.LoadMonobankRates(); + + Assert.Single(result); + Assert.Equal(840, result[0].FromCurrencyId); + Assert.Equal(980, result[0].ToCurrencyId); + Assert.Equal(44.61, (double)result[0].Rate, 2); + Assert.Equal(1782994573L * 1000L, result[0].Date); + } + + [Fact] + public async Task LoadOpenExchangeRates_FailedResponse_ReturnsEmptyList() + { + var currencies = new[] { MakeCurrency(980, "UAH"), MakeCurrency(985, "PLN") }; + var service = new ExchangeRatesService( + CreateHttpClient("error", HttpStatusCode.Unauthorized), () => currencies); + + var result = await service.LoadOpenExchangeRates("bad-key"); + + Assert.Empty(result); + } [Fact] public async Task LoadOpenExchangeRates_SuccessResponse_ReturnsMappedRates() @@ -124,59 +134,40 @@ public async Task LoadOpenExchangeRates_SuccessResponse_ReturnsMappedRates() } [Fact] - public async Task LoadOpenExchangeRates_FailedResponse_ReturnsEmptyList() + public void ParseExchangeRateJson_ValidJson_ReturnsParsedValues() { - var currencies = new[] { MakeCurrency(980, "UAH"), MakeCurrency(985, "PLN") }; - var service = new ExchangeRatesService( - CreateHttpClient("error", HttpStatusCode.Unauthorized), () => currencies); + var json = ExtractBodyJson(File.ReadAllText(Path.Combine("Assets", "FreeCurrency.htm"))); - var result = await service.LoadOpenExchangeRates("bad-key"); + var (updatedOn, rate) = ExchangeRatesService.ParseExchangeRateJson(json); - Assert.Empty(result); + Assert.Equal(1782999003L, updatedOn); + Assert.Equal(11.879519f, rate); } - // ── LoadMonobankRates ───────────────────────────────────────────────── - - [Fact] - public async Task LoadMonobankRates_SuccessResponse_ReturnsMappedRate() + private static HttpClient CreateHttpClient(string responseBody, HttpStatusCode statusCode = HttpStatusCode.OK) { - var json = File.ReadAllText(Path.Combine("Assets", "mono.json")); - // USD (840) → UAH (980) is in mono.json with rateBuy = 44.61 - // UAH → USD has no entry in the index, so it is skipped - var currencies = new[] { MakeCurrency(840, "USD"), MakeCurrency(980, "UAH") }; - var service = new ExchangeRatesService(CreateHttpClient(json), () => currencies); - - var result = await service.LoadMonobankRates(); - - Assert.Single(result); - Assert.Equal(840, result[0].FromCurrencyId); - Assert.Equal(980, result[0].ToCurrencyId); - Assert.Equal(44.61, (double)result[0].Rate, 2); - Assert.Equal(1782994573L * 1000L, result[0].Date); + var handler = new Mock(); + handler.Protected() + .Setup>( + "SendAsync", + ItExpr.IsAny(), + ItExpr.IsAny()) + .ReturnsAsync(new HttpResponseMessage + { + StatusCode = statusCode, + Content = new StringContent(responseBody), + }); + return new HttpClient(handler.Object); } - [Fact] - public async Task LoadMonobankRates_FailedResponse_ReturnsEmptyList() + private static string ExtractBodyJson(string html) { - var currencies = new[] { MakeCurrency(840, "USD"), MakeCurrency(980, "UAH") }; - var service = new ExchangeRatesService( - CreateHttpClient("error", HttpStatusCode.TooManyRequests), () => currencies); - - var result = await service.LoadMonobankRates(); - - Assert.Empty(result); + var start = html.IndexOf("", StringComparison.Ordinal) + "".Length; + var end = html.IndexOf("", start, StringComparison.Ordinal); + return html[start..end]; } - [Fact] - public async Task LoadMonobankRates_NoCurrencies_ReturnsEmptyList() - { - var json = File.ReadAllText(Path.Combine("Assets", "mono.json")); - var service = new ExchangeRatesService( - CreateHttpClient(json), () => Array.Empty()); - - var result = await service.LoadMonobankRates(); - - Assert.Empty(result); - } + private static CurrencyModel MakeCurrency(int id, string name) => + new CurrencyModel { Id = id, Name = name, UpdateExchangeRate = true }; } } diff --git a/src/Tests/Financier.Reports.Tests/ByCategoryReportVMTests.cs b/src/Tests/Financier.Reports.Tests/ByCategoryReportVMTests.cs index d68e1315..cedc055e 100644 --- a/src/Tests/Financier.Reports.Tests/ByCategoryReportVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ByCategoryReportVMTests.cs @@ -32,8 +32,6 @@ public ByCategoryReportVMTests() this.vm = new ByCategoryReportVM(this.dbMock.Object); } - // ── PieChartModel property ─────────────────────────────────────────────── - [Fact] public void GetPlotModel_ExpenseItems_AddedToSecondSeries() { @@ -73,8 +71,8 @@ public void GetPlotModel_PieChart_GroupsByParentId() var items = new List { new TestModel("Food", isExpense: 1, parentId: 1, total: 100.0), - new TestModel("Food", isExpense: 1, parentId: 1, total: 50.0), - new TestModel("Transport",isExpense: 1, parentId: 2, total: 80.0), + new TestModel("Food", isExpense: 1, parentId: 1, total: 50.0), + new TestModel("Transport", isExpense: 1, parentId: 2, total: 80.0), }; testVm.TestGetPlotModel(items); @@ -94,7 +92,6 @@ public void GetPlotModel_PieChart_HasOnePieSeries() Assert.IsType(testVm.PieChartModel.Series[0]); } - // ── Pie chart (PieChartModel) ──────────────────────────────────────────── [Fact] public void GetPlotModel_PieChart_SliceValueIsAbsoluteGroupTotal() { @@ -102,7 +99,7 @@ public void GetPlotModel_PieChart_SliceValueIsAbsoluteGroupTotal() var items = new List { new TestModel("Food", isExpense: 1, parentId: 1, total: -100.0), - new TestModel("Food", isExpense: 1, parentId: 1, total: -50.0), + new TestModel("Food", isExpense: 1, parentId: 1, total: -50.0), }; testVm.TestGetPlotModel(items); @@ -153,7 +150,6 @@ public void GetPlotModel_SetsPieChartModel() Assert.NotNull(testVm.PieChartModel); } - // ── GetPlotModel / bar chart ───────────────────────────────────────────── [Fact] public void GetPlotModel_UsesAbsoluteValueForBarItems() { @@ -202,7 +198,6 @@ public void GetSql_WithFromDate_ContainsFromTimestamp() Assert.Contains("BETWEEN", sql); } - // ── GetSql ─────────────────────────────────────────────────────────────── [Fact] public void GetSql_WithTopCategory_ContainsLeftRightFilter() { @@ -233,8 +228,6 @@ public async Task PieChartModel_RaisesPropertyChanged_AfterRefresh() Assert.True(raised); } - // ── RefreshDataCommand ─────────────────────────────────────────────────── - [Fact] public async Task RefreshDataCommand_EmptyData_EntitiesIsEmpty() { @@ -283,11 +276,10 @@ public async Task RefreshDataCommand_WithData_PopulatesEntities() Assert.Equal(2, this.vm.Entities.Count); } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ByCategoryReportVM { - public TestableVM(IFinancierDatabase db) : base(db) + public TestableVM(IFinancierDatabase db) + : base(db) { } diff --git a/src/Tests/Financier.Reports.Tests/Financier.Reports.Tests.csproj b/src/Tests/Financier.Reports.Tests/Financier.Reports.Tests.csproj index 18dd5cb9..86f62ef9 100644 --- a/src/Tests/Financier.Reports.Tests/Financier.Reports.Tests.csproj +++ b/src/Tests/Financier.Reports.Tests/Financier.Reports.Tests.csproj @@ -20,6 +20,7 @@ + all diff --git a/src/Tests/Financier.Reports.Tests/ReportByPeriodMonthCrcVMTests.cs b/src/Tests/Financier.Reports.Tests/ReportByPeriodMonthCrcVMTests.cs index 2593792c..2bbe2d20 100644 --- a/src/Tests/Financier.Reports.Tests/ReportByPeriodMonthCrcVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportByPeriodMonthCrcVMTests.cs @@ -32,8 +32,6 @@ public ReportByPeriodMonthCrcVMTests() this.vm.EndYearMonths = new YearMonths(); } - // ── GetSql ─────────────────────────────────────────────────────────────── - [Fact] public void GetPlotModel_FirstTwoSeriesAreBarSeries() { @@ -75,7 +73,6 @@ public void GetPlotModel_HasTwoAxes() Assert.Equal(2, model.Axes.Count); } - // ── GetPlotModel ───────────────────────────────────────────────────────── [Fact] public void GetPlotModel_ThirdSeriesIsLineSeries() { @@ -202,8 +199,6 @@ public void GetSql_WithCurrencyFilter_ContainsOneForCurrencyFlag() Assert.Contains("1 =", sql); } - // ── RefreshDataCommand ─────────────────────────────────────────────────── - [Fact] public async Task RefreshDataCommand_EmptyData_EntitiesIsEmpty() { @@ -244,8 +239,6 @@ public async Task RefreshDataCommand_WithData_PopulatesEntities() Assert.Equal(2, this.vm.Entities.Count); } - // ── Helper methods ─────────────────────────────────────────────────────── - private TestableVM CreateTestableVM() { var testVm = new TestableVM(this.dbMock.Object); @@ -254,11 +247,10 @@ private TestableVM CreateTestableVM() return testVm; } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ReportByPeriodMonthCrcVM { - public TestableVM(IFinancierDatabase db) : base(db) + public TestableVM(IFinancierDatabase db) + : base(db) { } diff --git a/src/Tests/Financier.Reports.Tests/ReportDynamicDebitCretitPayeeVMTests.cs b/src/Tests/Financier.Reports.Tests/ReportDynamicDebitCretitPayeeVMTests.cs index 30ff4a7d..41f1eb12 100644 --- a/src/Tests/Financier.Reports.Tests/ReportDynamicDebitCretitPayeeVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportDynamicDebitCretitPayeeVMTests.cs @@ -35,12 +35,11 @@ public ReportDynamicDebitCretitPayeeVMTests() this.vm.DialogService = this.dialogMock.Object; this.vm.StartYearMonths = new YearMonths(); this.vm.EndYearMonths = new YearMonths(); + // Ensure a Category is selected so GetSql() does not reach the dialog path this.vm.Category = new CategoryModel { Id = 1 }; } - // ── GetSql ─────────────────────────────────────────────────────────────── - [Fact] public void GetPlotModel_FirstAxisIsLinearAxis() { @@ -106,7 +105,6 @@ public void GetPlotModel_OrdersPointsByYearThenMonth() Assert.Equal(-300.0, lineSeries.Points[2].Y); } - // ── GetPlotModel ───────────────────────────────────────────────────────── [Fact] public void GetPlotModel_SecondAxisIsDateTimeAxis() { @@ -138,8 +136,8 @@ public void GetPlotModel_WithData_LineSeriesHasExpectedPointCount() public void GetSql_NeitherPayeeNorCategory_ReturnsEmpty() { var testVm = CreateTestableVM(); - // Leave both Payee.Id and Category.Id as null + // Leave both Payee.Id and Category.Id as null var sql = testVm.TestGetSql(); Assert.Empty(sql); @@ -214,8 +212,6 @@ public void GetSql_WithPayeeSelected_ReturnsNonEmptySql() Assert.NotEmpty(sql); } - // ── RefreshDataCommand ─────────────────────────────────────────────────── - [Fact] public async Task RefreshDataCommand_EmptyData_EntitiesIsEmpty() { @@ -256,8 +252,6 @@ public async Task RefreshDataCommand_WithData_PopulatesEntities() Assert.Equal(2, this.vm.Entities.Count); } - // ── Helper methods ─────────────────────────────────────────────────────── - private TestableVM CreateTestableVM() { var testVm = new TestableVM(this.dbMock.Object); @@ -267,11 +261,10 @@ private TestableVM CreateTestableVM() return testVm; } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ReportDynamicDebitCretitPayeeVM { - public TestableVM(IFinancierDatabase db) : base(db) + public TestableVM(IFinancierDatabase db) + : base(db) { } diff --git a/src/Tests/Financier.Reports.Tests/ReportDynamicRestVMTests.cs b/src/Tests/Financier.Reports.Tests/ReportDynamicRestVMTests.cs index 0ff127a5..2952a12f 100644 --- a/src/Tests/Financier.Reports.Tests/ReportDynamicRestVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportDynamicRestVMTests.cs @@ -33,8 +33,6 @@ public ReportDynamicRestVMTests() this.vm.EndYearMonths = new YearMonths(); } - // ── GetSql ─────────────────────────────────────────────────────────────── - [Fact] public void GetPlotModel_FirstAxisIsDateTimeAxis() { @@ -119,7 +117,6 @@ public void GetPlotModel_OrdersPointsByYearThenMonthThenDay() Assert.Equal(300.0, lineSeries.Points[2].Y); } - // ── GetPlotModel ───────────────────────────────────────────────────────── [Fact] public void GetPlotModel_SecondAxisIsLinearAxis() { @@ -138,7 +135,7 @@ public void GetPlotModel_WithData_LineSeriesHasExpectedPointCount() { new TestModel(year: 2024, month: 1, day: 15, total: 1000.0), new TestModel(year: 2024, month: 2, day: 10, total: 1200.0), - new TestModel(year: 2024, month: 3, day: 5, total: 900.0), + new TestModel(year: 2024, month: 3, day: 5, total: 900.0), }; var model = testVm.TestGetPlotModel(items); @@ -177,8 +174,6 @@ public void GetSql_WithNoFilters_ReturnsNonEmptySql() Assert.NotEmpty(sql); } - // ── RefreshDataCommand ─────────────────────────────────────────────────── - [Fact] public async Task RefreshDataCommand_EmptyData_EntitiesIsEmpty() { @@ -219,8 +214,6 @@ public async Task RefreshDataCommand_WithData_PopulatesEntities() Assert.Equal(2, this.vm.Entities.Count); } - // ── Helper methods ─────────────────────────────────────────────────────── - private TestableVM CreateTestableVM() { var testVm = new TestableVM(this.dbMock.Object); @@ -229,11 +222,10 @@ private TestableVM CreateTestableVM() return testVm; } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ReportDynamicRestVM { - public TestableVM(IFinancierDatabase db) : base(db) + public TestableVM(IFinancierDatabase db) + : base(db) { } diff --git a/src/Tests/Financier.Reports.Tests/ReportStructureActivesVMTests.cs b/src/Tests/Financier.Reports.Tests/ReportStructureActivesVMTests.cs index db6a7d18..7c65fac5 100644 --- a/src/Tests/Financier.Reports.Tests/ReportStructureActivesVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportStructureActivesVMTests.cs @@ -33,14 +33,11 @@ public ReportStructureActivesVMTests() this.vm.EndYearMonths = new YearMonths(); } - // ── Constructor ────────────────────────────────────────────────────────── - [Fact] public void Constructor_SetsDateFilter_ToNonNull() { Assert.NotNull(this.vm.DateFilter); } - // ── GetSql ─────────────────────────────────────────────────────────────── [Fact] public void GetPlotModel_EmptyList_ReturnsEmptyPieSeries() @@ -113,7 +110,6 @@ public void GetPlotModel_ReturnsModelWithOnePieSeries() Assert.IsType(model.Series[0]); } - // ── GetPlotModel ───────────────────────────────────────────────────────── [Fact] public void GetPlotModel_SmallSlices_GroupedIntoOthers() { @@ -153,8 +149,6 @@ public void GetSql_WithDateFilter_ReturnsNonEmptySql() Assert.NotEmpty(sql); } - // ── RefreshDataCommand ─────────────────────────────────────────────────── - [Fact] public async Task RefreshDataCommand_EmptyData_EntitiesIsEmpty() { @@ -195,8 +189,6 @@ public async Task RefreshDataCommand_WithData_PopulatesEntities() Assert.Equal(2, this.vm.Entities.Count); } - // ── Helper methods ─────────────────────────────────────────────────────── - private TestableVM CreateTestableVM() { var testVm = new TestableVM(this.dbMock.Object); @@ -205,11 +197,10 @@ private TestableVM CreateTestableVM() return testVm; } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ReportStructureActivesVM { - public TestableVM(IFinancierDatabase db) : base(db) + public TestableVM(IFinancierDatabase db) + : base(db) { } diff --git a/src/Tests/Financier.Reports.Tests/ReportStructureIncomeExpenseVMTests.cs b/src/Tests/Financier.Reports.Tests/ReportStructureIncomeExpenseVMTests.cs index 19452098..e131c125 100644 --- a/src/Tests/Financier.Reports.Tests/ReportStructureIncomeExpenseVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportStructureIncomeExpenseVMTests.cs @@ -34,16 +34,12 @@ public ReportStructureIncomeExpenseVMTests() this.vm.EndYearMonths = new YearMonths(); } - // ── Constructor ────────────────────────────────────────────────────────── - [Fact] public void Constructor_SetsDefaultIsIncome_ToFalse() { Assert.False(this.vm.IsIncome); } - // ── IsIncome property ──────────────────────────────────────────────────── - [Fact] public void GetBarChartModel_HasOneLegend() { @@ -142,7 +138,6 @@ public void GetBarChartModel_ReturnsModelWithTwoAxes() Assert.Equal(2, model.Axes.Count); } - // ── GetBarChartModel ───────────────────────────────────────────────────── [Fact] public void GetBarChartModel_UsesAbsoluteValueForBarItems() { @@ -206,7 +201,6 @@ public void GetPlotModel_ReturnsPieChartWithOneSeries() Assert.IsType(model.Series[0]); } - // ── GetPlotModel / pie chart ───────────────────────────────────────────── [Fact] public void GetPlotModel_SetsBarChartModel() { @@ -256,7 +250,6 @@ public void GetSql_IsIncomeTrue_ContainsGreaterThanSign() Assert.Contains("> 0", sql); } - // ── GetSql ─────────────────────────────────────────────────────────────── [Fact] public void GetSql_WithNoFilters_DoesNotContainAndClause() { @@ -301,8 +294,6 @@ public void IsIncome_SetSameValue_RaisesPropertyChanged() Assert.True(raised); } - // ── RefreshDataCommand ─────────────────────────────────────────────────── - [Fact] public async Task RefreshDataCommand_EmptyData_EntitiesIsEmpty() { @@ -381,8 +372,6 @@ public async Task RefreshDataCommand_WithData_PopulatesEntities() Assert.Equal(2, this.vm.Entities.Count); } - // ── Helper methods ─────────────────────────────────────────────────────── - private TestableVM CreateTestableVM() { var testVm = new TestableVM(this.dbMock.Object); @@ -391,11 +380,10 @@ private TestableVM CreateTestableVM() return testVm; } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ReportStructureIncomeExpenseVM { - public TestableVM(IFinancierDatabase db) : base(db) + public TestableVM(IFinancierDatabase db) + : base(db) { } diff --git a/src/Tests/Financier.Reports.Tests/ReportStructureSaldoVMTests.cs b/src/Tests/Financier.Reports.Tests/ReportStructureSaldoVMTests.cs index fe9f983e..4a4670ea 100644 --- a/src/Tests/Financier.Reports.Tests/ReportStructureSaldoVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportStructureSaldoVMTests.cs @@ -31,8 +31,6 @@ public ReportStructureSaldoVMTests() this.vm = new ReportStructureSaldoVM(this.dbMock.Object); } - // ── Constructor ────────────────────────────────────────────────────────── - [Fact] public void Constructor_SetsDefaultIsUsdCurrencySelected_ToTrue() { @@ -44,7 +42,6 @@ public void Constructor_SetsDefaultRange_ToLast6Months() { Assert.Equal(ReportStructureSaldoRange.Last6Months, this.vm.Range); } - // ── Range property ─────────────────────────────────────────────────────── [Fact] public void GetBarChartModel_IsUsdCurrencySelected_UsesUsdBalance_ForAssets() @@ -136,7 +133,6 @@ public void GetBarChartModel_ReturnsModelWithThreeSeries() Assert.Equal(3, model.Series.Count); } - // ── GetBarChartModel ───────────────────────────────────────────────────── [Fact] public void GetBarChartModel_ReturnsModelWithTwoAxes() { @@ -183,7 +179,6 @@ public void IsUsdCurrencySelected_SetNewValue_RaisesPropertyChanged() Assert.True(raised); } - // ── IsUsdCurrencySelected property ─────────────────────────────────────── [Fact] public void IsUsdCurrencySelected_SetSameValue_DoesNotRaisePropertyChanged() { @@ -235,8 +230,6 @@ public void Range_SetSameValue_DoesNotRaisePropertyChanged() Assert.False(raised); } - // ── Date range query counts ────────────────────────────────────────────── - [Fact] public async Task RefreshDataCommand_AccountExcludedFromTotals_NotIncludedInBalance() { @@ -376,7 +369,6 @@ public async Task RefreshDataCommand_WithAssetRows_SumsAssetsBalances() Assert.Equal(130, this.vm.Entities[0].AssetsUSDBalance); } - // ── RefreshData aggregation ────────────────────────────────────────────── [Fact] public async Task RefreshDataCommand_WithData_EntityCountMatchesDateRange() { @@ -410,7 +402,6 @@ public async Task RefreshDataCommand_WithLiabilityRows_SumsLiabilitiesBalances() Assert.Equal(-800, this.vm.Entities[0].LiabilitiesDefaultCurrencyBalance); Assert.Equal(-300, this.vm.Entities[0].LiabilitiesUSDBalance); } - // ── Helper types ───────────────────────────────────────────────────────── private sealed class TestableVM(IFinancierDatabase db) : ReportStructureSaldoVM(db) {