From 80a5227b2cfe4d9ec5e2565e2206fef4efca6ac3 Mon Sep 17 00:00:00 2001 From: vov4uk Date: Fri, 4 Sep 2026 10:29:43 +0200 Subject: [PATCH 01/13] Labels --- Directory.Build.props | 2 +- Directory.Packages.props | 22 +- .../Localization/Resources.Designer.cs | 276 +++++++++++++++--- .../Localization/Resources.pl.resx | 24 +- .../Localization/Resources.resx | 24 +- .../Localization/Resources.uk.resx | 24 +- .../Financier.DataAccess.csproj | 4 - 7 files changed, 259 insertions(+), 117 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 3d4e34fc..6e9f7c3a 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 2026.07.01.1 + 2026.08.21.1 vov4uk Copyright (C) vov4uk diff --git a/Directory.Packages.props b/Directory.Packages.props index 6860619f..f1402e5d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,39 +9,41 @@ + - + - - - + + + + - + - + - - - + + + - + \ No newline at end of file diff --git a/src/Financier.Common/Localization/Resources.Designer.cs b/src/Financier.Common/Localization/Resources.Designer.cs index 15e3269d..e807f5ff 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. /// @@ -420,6 +438,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 +483,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 +537,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 +573,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 +663,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 +825,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 +1104,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 +1212,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 +1267,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 +1293,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 +1401,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 +1446,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 +1491,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 +1626,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 +1635,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 +1690,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 Move down. + /// + public static string position_move_down { + get { + 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 Privat XLSX. + /// Looks up a localized string similar to Move up. /// - public static string privat_xlsx { + public static string position_move_up { get { - return ResourceManager.GetString("privat_xlsx", resourceCulture); + 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 +1770,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 +1968,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 +2175,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 +2337,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 +2355,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..242a66bc 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 diff --git a/src/Financier.Common/Localization/Resources.resx b/src/Financier.Common/Localization/Resources.resx index 9bbad9bd..9d61bdc0 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 diff --git a/src/Financier.Common/Localization/Resources.uk.resx b/src/Financier.Common/Localization/Resources.uk.resx index d44f0874..e4aeab10 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 @@ Примітка + + Назва + Зберегти diff --git a/src/Financier.DataAccess/Financier.DataAccess.csproj b/src/Financier.DataAccess/Financier.DataAccess.csproj index f6951325..2e188795 100644 --- a/src/Financier.DataAccess/Financier.DataAccess.csproj +++ b/src/Financier.DataAccess/Financier.DataAccess.csproj @@ -109,10 +109,6 @@ - - - - From 59afa58c9ed5220fe3d1e619a696d0ae14367181 Mon Sep 17 00:00:00 2001 From: vov4uk Date: Fri, 4 Sep 2026 10:30:44 +0200 Subject: [PATCH 02/13] Warnings --- Directory.Build.props | 2 +- Directory.Packages.props | 8 +- .../Localization/LocalizationService.cs | 2 +- .../Localization/Resources.Designer.cs | 9 - .../Localization/Resources.pl.resx | 3 - .../Localization/Resources.resx | 3 - .../Localization/Resources.uk.resx | 3 - src/Financier.Desktop/Data/RuleDTO.cs | 2 +- src/Financier.Desktop/Data/TransactionDTO.cs | 10 +- src/Financier.Desktop/Data/TransferDTO.cs | 8 +- .../Helpers/BankHelper/AbankExcelHelper.cs | 2 +- .../Helpers/BankHelper/PKOHelper.cs | 20 +- .../Helpers/BankHelper/PireusHelper.cs | 2 +- .../Helpers/BankHelper/PrivatHelper.cs | 2 +- src/Financier.Desktop/Helpers/DialogHelper.cs | 16 +- .../Helpers/IDialogWrapper.cs | 2 +- src/Financier.Desktop/Helpers/MapperHelper.cs | 22 +- src/Financier.Desktop/MainWindow.xaml | 114 +++--- src/Financier.Desktop/MainWindowVM.cs | 24 +- src/Financier.Desktop/Pages/BlotterVM.cs | 12 +- .../Pages/CategoriesView.xaml.cs | 6 +- .../Pages/Controls/CustomDisplayPart.xaml.cs | 2 +- .../Pages/Dialogs/AccountControlVM.cs | 2 +- .../Pages/Dialogs/LocationControlVM.cs | 2 +- .../Pages/Dialogs/SubTransactionControlVM.cs | 4 +- .../Pages/Dialogs/TagControlVM.cs | 2 +- .../Pages/Dialogs/TransactionControlVM.cs | 4 +- .../Pages/Dialogs/TransferControlVM.cs | 4 +- src/Financier.Desktop/Pages/RulesVM.cs | 6 +- .../Services/ExchangeRatesService.cs | 4 +- .../Services/UpdateService.cs | 25 +- .../Wizards/MonoWizard/MonoWizardVM.cs | 6 +- .../Wizards/MonoWizard/Page1VM.cs | 2 +- .../Wizards/MonoWizard/Page2VM.cs | 4 +- .../Wizards/RecipesWizard/Page2VM.cs | 2 +- .../Wizards/RecipesWizard/RecipesVM.cs | 4 +- src/Financier.Desktop/Wizards/WizardBaseVM.cs | 2 +- src/Financier.Reports/BaseReportVM.cs | 16 +- src/Financier.Reports/ReportsControlVM.cs | 8 +- src/Financier.Reports/SafePlotModel.cs | 4 +- .../Pages/Dialog/AccountControlVMTest.cs | 343 +++++++++--------- .../Pages/Dialog/RuleControlVMTest.cs | 273 +++++++------- .../Pages/Dialog/SettingsVMTest.cs | 124 +++---- .../Pages/MainWindowVMTest.cs | 10 +- .../Services/ExchangeRatesServiceTests.cs | 159 ++++---- .../ByCategoryReportVMTests.cs | 11 +- .../ReportByPeriodMonthCrcVMTests.cs | 9 - .../ReportDynamicDebitCretitPayeeVMTests.cs | 12 +- .../ReportDynamicRestVMTests.cs | 9 - .../ReportStructureActivesVMTests.cs | 10 - .../ReportStructureIncomeExpenseVMTests.cs | 13 - .../ReportStructureSaldoVMTests.cs | 9 - 52 files changed, 608 insertions(+), 749 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 6e9f7c3a..cf7f47cf 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 2026.08.21.1 + 2026.09.01.1 vov4uk Copyright (C) vov4uk diff --git a/Directory.Packages.props b/Directory.Packages.props index f1402e5d..8c722106 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,25 +9,19 @@ - - + - - - - - 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 e807f5ff..ca65bdcc 100644 --- a/src/Financier.Common/Localization/Resources.Designer.cs +++ b/src/Financier.Common/Localization/Resources.Designer.cs @@ -384,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. /// diff --git a/src/Financier.Common/Localization/Resources.pl.resx b/src/Financier.Common/Localization/Resources.pl.resx index 242a66bc..05a258d0 100644 --- a/src/Financier.Common/Localization/Resources.pl.resx +++ b/src/Financier.Common/Localization/Resources.pl.resx @@ -552,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 9d61bdc0..80346fc1 100644 --- a/src/Financier.Common/Localization/Resources.resx +++ b/src/Financier.Common/Localization/Resources.resx @@ -552,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 e4aeab10..ba2057a6 100644 --- a/src/Financier.Common/Localization/Resources.uk.resx +++ b/src/Financier.Common/Localization/Resources.uk.resx @@ -552,9 +552,6 @@ Додати нову операцію - - Резервну копію збережено. - Імпортовано {0} операцій. diff --git a/src/Financier.Desktop/Data/RuleDTO.cs b/src/Financier.Desktop/Data/RuleDTO.cs index 0dc3a858..176bdd6c 100644 --- a/src/Financier.Desktop/Data/RuleDTO.cs +++ b/src/Financier.Desktop/Data/RuleDTO.cs @@ -35,7 +35,7 @@ public RuleDto(RuleModel rulesModel) public CategoryModel Category { - get => category ??= DbManual.Category?.Find(x => x.Id == CategoryId)!; + get => category ??= DbManual.Category?.Find(x => x.Id == CategoryId); set { if (SetProperty(ref category, value)) diff --git a/src/Financier.Desktop/Data/TransactionDTO.cs b/src/Financier.Desktop/Data/TransactionDTO.cs index 78e4dfc2..d053b2e6 100644 --- a/src/Financier.Desktop/Data/TransactionDTO.cs +++ b/src/Financier.Desktop/Data/TransactionDTO.cs @@ -42,7 +42,7 @@ public TransactionDto(FinancierTransactionDto x) locationId = x.LocationId; projectId = x.ProjectId; categoryId = x.CategoryId; - category = default!; + category = default; } public TransactionDto(Transaction transaction, IEnumerable subTransactions) @@ -91,7 +91,7 @@ public TransactionDto(Transaction transaction) public CategoryModel Category { - get => category ??= DbManual.Category?.Find(x => x.Id == CategoryId)!; + get => category ??= DbManual.Category?.Find(x => x.Id == CategoryId); set { if (SetProperty(ref category, value)) @@ -120,7 +120,7 @@ public int? CategoryId public AccountFilterModel FromAccount { - get => fromAccount ??= DbManual.Account?.Find(x => x.Id == FromAccountId)!; + get => fromAccount ??= DbManual.Account?.Find(x => x.Id == FromAccountId); set { if (SetProperty(ref fromAccount, value)) @@ -135,7 +135,7 @@ public AccountFilterModel FromAccount public CurrencyModel FromAccountCurrency { - get => DbManual.Currencies?.Find(x => x.Id == (FromAccount != null ? FromAccount.CurrencyId : 0))!; + get => DbManual.Currencies?.Find(x => x.Id == (FromAccount != null ? FromAccount.CurrencyId : 0)); } public int FromAccountId @@ -188,7 +188,7 @@ public int? LocationId public CurrencyModel OriginalCurrency { - get => currency ??= DbManual.Currencies?.Find(x => x.Id == OriginalCurrencyId)!; + get => currency ??= DbManual.Currencies?.Find(x => x.Id == OriginalCurrencyId); set { if (SetProperty(ref currency, value)) diff --git a/src/Financier.Desktop/Data/TransferDTO.cs b/src/Financier.Desktop/Data/TransferDTO.cs index 314aaf6a..88bb9b53 100644 --- a/src/Financier.Desktop/Data/TransferDTO.cs +++ b/src/Financier.Desktop/Data/TransferDTO.cs @@ -28,8 +28,8 @@ public TransferDto(Transaction transaction) toAmount = transaction.ToAmount; date = UnixTimeConverter.Convert(transaction.DateTime).Date; time = UnixTimeConverter.Convert(transaction.DateTime); - fromAccount = DbManual.Account.Find(x => x.Id == fromAccountId)!; - toAccount = DbManual.Account.Find(x => x.Id == toAccountId)!; + fromAccount = DbManual.Account.Find(x => x.Id == fromAccountId); + toAccount = DbManual.Account.Find(x => x.Id == toAccountId); } public AccountFilterModel FromAccount @@ -49,7 +49,7 @@ public AccountFilterModel FromAccount public CurrencyModel FromAccountCurrency { - get => DbManual.Currencies?.Find(x => x.Id == (FromAccount != null ? FromAccount.CurrencyId : 0))!; + get => DbManual.Currencies?.Find(x => x.Id == (FromAccount != null ? FromAccount.CurrencyId : 0)); } public int FromAccountId @@ -111,7 +111,7 @@ public AccountFilterModel ToAccount public CurrencyModel ToAccountCurrency { - get => DbManual.Currencies?.Find(x => x.Id == (ToAccount != null ? ToAccount.CurrencyId : 0))!; + get => DbManual.Currencies?.Find(x => x.Id == (ToAccount != null ? ToAccount.CurrencyId : 0)); } public int ToAccountId diff --git a/src/Financier.Desktop/Helpers/BankHelper/AbankExcelHelper.cs b/src/Financier.Desktop/Helpers/BankHelper/AbankExcelHelper.cs index 4abb0a17..12fe9d6d 100644 --- a/src/Financier.Desktop/Helpers/BankHelper/AbankExcelHelper.cs +++ b/src/Financier.Desktop/Helpers/BankHelper/AbankExcelHelper.cs @@ -30,7 +30,7 @@ public IEnumerable ParseReport(string filePath) { HasHeaderRecord = true, IgnoreBlankLines = true, - ShouldSkipRecord = args => args.Row.Parser.Record!.All(string.IsNullOrWhiteSpace), + ShouldSkipRecord = args => args.Row.Parser.Record.All(string.IsNullOrWhiteSpace), Delimiter = "," })) { diff --git a/src/Financier.Desktop/Helpers/BankHelper/PKOHelper.cs b/src/Financier.Desktop/Helpers/BankHelper/PKOHelper.cs index 962b4158..2a5aa66d 100644 --- a/src/Financier.Desktop/Helpers/BankHelper/PKOHelper.cs +++ b/src/Financier.Desktop/Helpers/BankHelper/PKOHelper.cs @@ -86,7 +86,7 @@ public IEnumerable ParseReport(string filePath) // Pattern to match: date (DD.MM.YYYY) followed by space and ID (4 letters + 11 digits) var operationDatePattern = @"([0-9]{2}\.[0-9]{2}\.[0-9]{4}) ([0-9]{4}[A-Z]{2}[0-9]{11})"; - var rowStart = Regex.Matches(pageText, operationDatePattern); + var rowStart = Regex.Matches(pageText, operationDatePattern, RegexOptions.None, TimeSpan.FromSeconds(5)); for (int i = 0; i < rowStart.Count; i++) { @@ -102,11 +102,11 @@ public IEnumerable ParseReport(string filePath) var transactionBlock = pageText.Substring(blockStart + match.Length, blockEnd - blockStart - match.Length).TrimEnd('|'); // Remove spaces between numbers (e.g., "3 200,00" -> "3200,00") - transactionBlock = Regex.Replace(transactionBlock, @"(?<=[0-9])\s+(?=[0-9])", "").Trim(); + transactionBlock = Regex.Replace(transactionBlock, @"(?<=[0-9])\s+(?=[0-9])", "", RegexOptions.None, TimeSpan.FromSeconds(5)).Trim(); var decimalPattern = @"-?\d+(?:,\d+)"; - var decimalMatches = Regex.Matches(transactionBlock, decimalPattern); + var decimalMatches = Regex.Matches(transactionBlock, decimalPattern, RegexOptions.None, TimeSpan.FromSeconds(5)); if (decimalMatches.Count < 2) { Logger.Warn("PKO row block has fewer than 2 decimal values, skipping. Block: {0}", transactionBlock); @@ -119,13 +119,13 @@ public IEnumerable ParseReport(string filePath) var transactionDescriprion = transactionBlock.Substring(saldo.Index + saldo.Length).Trim('|').Trim(); - var dataWaluty = Regex.Match(transactionDescriprion, @"([0-9]{2}\.[0-9]{2}\.[0-9]{4})"); + var dataWaluty = Regex.Match(transactionDescriprion, @"([0-9]{2}\.[0-9]{2}\.[0-9]{4})", RegexOptions.None, TimeSpan.FromSeconds(5)); if (dataWaluty.Success) { transactionDescriprion = transactionDescriprion.Substring(dataWaluty.Length); } - var dataWalutyGodzina = Regex.Match(transactionDescriprion, @"Godz\.([0-9]{2}:[0-9]{2}:[0-9]{2})"); + var dataWalutyGodzina = Regex.Match(transactionDescriprion, @"Godz\.([0-9]{2}:[0-9]{2}:[0-9]{2})", RegexOptions.None, TimeSpan.FromSeconds(5)); string dataWalutyGodzinaStr = "00:00:00"; if (dataWalutyGodzina.Success) { @@ -137,17 +137,17 @@ public IEnumerable ParseReport(string filePath) DateTime.TryParseExact(dateStr, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var transactionDate); DateTime.TryParseExact($"{dataWaluty.Value} {dataWalutyGodzinaStr}", "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var currencyDate); - var kwotaOryg = Regex.Match(transactionDescriprion, @"(Kwota oryg\.:) (-?\d+(?:,\d+)) ([A-Z]{3})"); + var kwotaOryg = Regex.Match(transactionDescriprion, @"(Kwota oryg\.:) (-?\d+(?:,\d+)) ([A-Z]{3})", RegexOptions.None, TimeSpan.FromSeconds(5)); if (kwotaOryg.Success) { transactionDescriprion = transactionDescriprion.Replace(kwotaOryg.Value, ""); } transactionDescriprion = transactionDescriprion.Replace("|", "").Trim(); - transactionDescriprion = Regex.Replace(transactionDescriprion, @"(Nr ref:|Nrref:)( |)([0-9]{17})", string.Empty).Trim(); - transactionDescriprion = Regex.Replace(transactionDescriprion, @"Tel\.:[0-9]{11}", string.Empty).Trim(); - transactionDescriprion = Regex.Replace(transactionDescriprion, @"Karta:[0-9]{6}\*\*\*\*\*\*[0-9]{4}", string.Empty).Trim(); - transactionDescriprion = Regex.Replace(transactionDescriprion, @"([0-9]{26})", " ").Trim(); + transactionDescriprion = Regex.Replace(transactionDescriprion, @"(Nr ref:|Nrref:)( |)([0-9]{17})", string.Empty, RegexOptions.None, TimeSpan.FromSeconds(5)).Trim(); + transactionDescriprion = Regex.Replace(transactionDescriprion, @"Tel\.:[0-9]{11}", string.Empty, RegexOptions.None, TimeSpan.FromSeconds(5)).Trim(); + transactionDescriprion = Regex.Replace(transactionDescriprion, @"Karta:[0-9]{6}\*\*\*\*\*\*[0-9]{4}", string.Empty, RegexOptions.None, TimeSpan.FromSeconds(5)).Trim(); + transactionDescriprion = Regex.Replace(transactionDescriprion, @"([0-9]{26})", " ", RegexOptions.None, TimeSpan.FromSeconds(5)).Trim(); transactionDescriprion = transactionDescriprion.Replace("Lokalizacja:", string.Empty).Trim(); var transaction = new PkoTransaction diff --git a/src/Financier.Desktop/Helpers/BankHelper/PireusHelper.cs b/src/Financier.Desktop/Helpers/BankHelper/PireusHelper.cs index 33d85257..c306b1a8 100644 --- a/src/Financier.Desktop/Helpers/BankHelper/PireusHelper.cs +++ b/src/Financier.Desktop/Helpers/BankHelper/PireusHelper.cs @@ -48,7 +48,7 @@ protected override IEnumerable ParseTransactionsTable(IEnumerab Balance = GetDouble(item.Balance), Commission = GetDouble(item.Commision), - OperationCurrency = DoubleNotEqual(operationAmount, cardCurrencyAmount) ? operationCurrency! : null!, + OperationCurrency = DoubleNotEqual(operationAmount, cardCurrencyAmount) ? operationCurrency : null, OperationAmount = operationAmount, CardCurrencyAmount = cardCurrencyAmount, Description = item.Details.Replace("(", Space).Replace(")", Space), diff --git a/src/Financier.Desktop/Helpers/BankHelper/PrivatHelper.cs b/src/Financier.Desktop/Helpers/BankHelper/PrivatHelper.cs index 2e888e34..656b8ab1 100644 --- a/src/Financier.Desktop/Helpers/BankHelper/PrivatHelper.cs +++ b/src/Financier.Desktop/Helpers/BankHelper/PrivatHelper.cs @@ -29,7 +29,7 @@ public IEnumerable ParseReport(string filePath) { HasHeaderRecord = true, IgnoreBlankLines = true, - ShouldSkipRecord = args => args.Row.Parser.Record!.All(string.IsNullOrWhiteSpace), + ShouldSkipRecord = args => args.Row.Parser.Record.All(string.IsNullOrWhiteSpace), Delimiter = "," })) { diff --git a/src/Financier.Desktop/Helpers/DialogHelper.cs b/src/Financier.Desktop/Helpers/DialogHelper.cs index 5b872fa3..0cb1d3ed 100644 --- a/src/Financier.Desktop/Helpers/DialogHelper.cs +++ b/src/Financier.Desktop/Helpers/DialogHelper.cs @@ -11,10 +11,10 @@ namespace Financier.Desktop.Helpers public class DialogHelper : IDialogWrapper { private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); - public object ShowDialog(DialogBaseVM context, double height, double width, string title = null!) + public object ShowDialog(DialogBaseVM context, double height, double width, string title = null) where T : System.Windows.Controls.UserControl, new() { - object result = null!; + object result = null; var dialog = new Window { Content = new T() { DataContext = context }, @@ -34,18 +34,18 @@ public object ShowDialog(DialogBaseVM context, double height, double width, s }; context.RequestSave += (sender, _) => { - result = sender!; + result = sender; dialog.Close(); Logger.Info($"{typeof(T).Name} dialog save clicked"); }; dialog.ShowDialog(); - return result!; + return result; } public object ShowWizard(WizardBaseVM context) { bool save = false; - object result = null!; + object result = null; WizardWindow dialog = new WizardWindow() { Language = System.Windows.Markup.XmlLanguage.GetLanguage(LocalizationService.Instance.CurrentCulture.IetfLanguageTag) @@ -55,12 +55,12 @@ public object ShowWizard(WizardBaseVM context) { dialog.Close(); save = args; - result = sender!; + result = sender; }; dialog.DataContext = context; dialog.ShowDialog(); - return save ? result! : null!; + return save ? result : null; } public string OpenFileDialog(string fileExtention) @@ -95,7 +95,7 @@ public bool ShowMessageBox(string text, string caption, bool yesNoButtons = fals { if (yesNoButtons) { - var result = System.Windows.MessageBox.Show(text, caption, MessageBoxButton.YesNo); + var result = MessageBox.Show(text, caption, MessageBoxButton.YesNo); return result == MessageBoxResult.Yes; } diff --git a/src/Financier.Desktop/Helpers/IDialogWrapper.cs b/src/Financier.Desktop/Helpers/IDialogWrapper.cs index 6a52c709..0559c68e 100644 --- a/src/Financier.Desktop/Helpers/IDialogWrapper.cs +++ b/src/Financier.Desktop/Helpers/IDialogWrapper.cs @@ -5,7 +5,7 @@ namespace Financier.Desktop.Helpers { public interface IDialogWrapper { - object ShowDialog(DialogBaseVM context, double height, double width, string title = null!) + object ShowDialog(DialogBaseVM context, double height, double width, string title = null) where T : System.Windows.Controls.UserControl, new(); string OpenFileDialog(string fileExtention); diff --git a/src/Financier.Desktop/Helpers/MapperHelper.cs b/src/Financier.Desktop/Helpers/MapperHelper.cs index 5e6c820b..f6837771 100644 --- a/src/Financier.Desktop/Helpers/MapperHelper.cs +++ b/src/Financier.Desktop/Helpers/MapperHelper.cs @@ -14,9 +14,9 @@ public static class MapperHelper public static void MapTransfer(TransferDto dto, Transaction tr) { tr.FromAccountId = dto.FromAccountId; - tr.FromAccount = null!; + tr.FromAccount = null; tr.ToAccountId = dto.ToAccountId; - tr.ToAccount = null!; + tr.ToAccount = null; tr.Note = dto.Note; tr.FromAmount = Math.Abs(dto.FromAmount) * -1; tr.ToAmount = Math.Abs(dto.IsToAmountVisible ? dto.ToAmount : dto.FromAmount); @@ -35,7 +35,7 @@ public static void MapTransfer(TransferDto dto, Transaction tr) } tr.CategoryId = 0; - tr.Category = default!; + tr.Category = default; } public static void MapTransaction(TransactionDto dto, Transaction tr) @@ -56,12 +56,12 @@ public static void MapTransaction(TransactionDto dto, Transaction tr) } tr.CategoryId = dto.CategoryId ?? 0; - tr.Category = default!; - tr.Location = default!; - tr.Project = default!; - tr.OriginalCurrency = default!; - tr.FromAccount = default!; - tr.ToAccount = default!; + tr.Category = default; + tr.Location = default; + tr.Project = default; + tr.OriginalCurrency = default; + tr.FromAccount = default; + tr.ToAccount = default; tr.PayeeId = dto.PayeeId ?? 0; tr.LocationId = dto.LocationId ?? 0; tr.ProjectId = dto.CategoryId == -1 ? 0 : (dto.ProjectId ?? 0); // parent transaction don't have Project @@ -83,7 +83,7 @@ public static BankTransaction ToBankTransaction(AbankRow item) Cashback = GetDouble(item.Cashback), Commission = GetDouble(item.Commision), ExchangeRate = GetDouble(item.ExchangeRate), - OperationCurrency = DoubleNotEqual(operationAmount, cardCurrencyAmount) ? operationCurrency! : null!, + OperationCurrency = DoubleNotEqual(operationAmount, cardCurrencyAmount) ? operationCurrency : null, OperationAmount = operationAmount, CardCurrencyAmount = cardCurrencyAmount, MCC = item.MCC, @@ -105,7 +105,7 @@ public static BankTransaction ToBankTransaction(PrivatRow item) return new BankTransaction { Balance = GetDouble(item.Balance), - OperationCurrency = DoubleNotEqual(Math.Abs(operationAmount), Math.Abs(cardCurrencyAmount)) ? operationCurrency! : null!, + OperationCurrency = DoubleNotEqual(Math.Abs(operationAmount), Math.Abs(cardCurrencyAmount)) ? operationCurrency : null, OperationAmount = operationAmount, CardCurrencyAmount = cardCurrencyAmount, Description = $"{item.Category} : {item.Details}", diff --git a/src/Financier.Desktop/MainWindow.xaml b/src/Financier.Desktop/MainWindow.xaml index 6d04eb84..59300141 100644 --- a/src/Financier.Desktop/MainWindow.xaml +++ b/src/Financier.Desktop/MainWindow.xaml @@ -1,4 +1,4 @@ - - - - - - - - - - - - - - - - - - - - @@ -283,9 +227,6 @@ - + + + + + + + + + + + + + + + + + + + + + + () { var viewModel = Activator.CreateInstance(typeof(VMType), db, dialogWrapper) as VMType; - _pages.TryAdd(type, viewModel!); + _pages.TryAdd(type, viewModel); } return (VMType)_pages[type]; @@ -395,10 +395,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 +414,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 +478,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 +486,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 +554,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..b0a851c3 100644 --- a/src/Financier.Desktop/Pages/BlotterVM.cs +++ b/src/Financier.Desktop/Pages/BlotterVM.cs @@ -79,7 +79,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 +89,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 +99,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 +109,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 +119,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; @@ -376,7 +376,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; } 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/Dialogs/AccountControlVM.cs b/src/Financier.Desktop/Pages/Dialogs/AccountControlVM.cs index 8e268ae4..5198c925 100644 --- a/src/Financier.Desktop/Pages/Dialogs/AccountControlVM.cs +++ b/src/Financier.Desktop/Pages/Dialogs/AccountControlVM.cs @@ -31,7 +31,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/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..51c0fe75 100644 --- a/src/Financier.Desktop/Services/UpdateService.cs +++ b/src/Financier.Desktop/Services/UpdateService.cs @@ -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,20 @@ public class UpdateService() : IDisposable } #nullable disable - public async Task PrepareUpdateAsync(Version version) + public void Dispose() => _updateManager?.Dispose(); + + 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 +57,15 @@ 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; + await _updateManager.PrepareUpdateAsync(_updateVersion = version); + _isUpdatePrepared = true; } catch (UpdaterAlreadyLaunchedException) { @@ -75,7 +76,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..bb894d43 100644 --- a/src/Financier.Reports/ReportsControlVM.cs +++ b/src/Financier.Reports/ReportsControlVM.cs @@ -123,7 +123,7 @@ 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; @@ -133,14 +133,14 @@ public void OpenReport(string reportType) 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..63ec03f3 100644 --- a/src/Financier.Reports/SafePlotModel.cs +++ b/src/Financier.Reports/SafePlotModel.cs @@ -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.Desktop.Tests/Pages/Dialog/AccountControlVMTest.cs b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/AccountControlVMTest.cs index 6a15fd91..c74a230b 100644 --- a/src/Tests/Financier.Desktop.Tests/Pages/Dialog/AccountControlVMTest.cs +++ b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/AccountControlVMTest.cs @@ -11,60 +11,26 @@ public class AccountControlVMTest { // ── helpers ────────────────────────────────────────────────────────── - 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, - }; - - private static CurrencyModel MakeCurrency(int id, string name = "USD") => - new CurrencyModel { Id = id, Name = name }; - - // ── Constructor ────────────────────────────────────────────────────── - [Fact] - public void Constructor_SetsEntityProperty() + public void ClearTitleCommand_Execute_DisablesSaveCommand() { - var entity = CreateEntity(); + var entity = CreateEntity(currencyId: 1, title: "My Account"); var vm = new AccountControlVM(entity, isNew: true); - Assert.Same(entity, vm.Entity); - } - [Theory] - [InlineData(true)] - [InlineData(false)] - public void Constructor_SetsIsNew(bool isNew) - { - var vm = new AccountControlVM(CreateEntity(), isNew); - Assert.Equal(isNew, vm.IsNew); + vm.ClearTitleCommand.Execute(); + + Assert.False(vm.SaveCommand.CanExecute()); } [Fact] - public void Constructor_SetsCurrencies_FromDbManual() + public void ClearTitleCommand_Execute_SetsEntityTitleToNull() { - DbManual.SetupTests(new List()); - var vm = new AccountControlVM(CreateEntity(), isNew: true); - Assert.Same(DbManual.Currencies, vm.Currencies); - } + var entity = CreateEntity(title: "My Account"); + var vm = new AccountControlVM(entity, isNew: true); - [Theory] - [InlineData("CASH", AccountType.CASH)] - [InlineData("BANK", AccountType.BANK)] - [InlineData("CREDIT_CARD", AccountType.CREDIT_CARD)] - [InlineData("DEBIT_CARD", AccountType.DEBIT_CARD)] - [InlineData("ASSET", AccountType.ASSET)] - [InlineData("ELECTRONIC", AccountType.ELECTRONIC)] - public void Constructor_ValidType_SetsSelectedAccountType(string type, AccountType expected) - { - var vm = new AccountControlVM(CreateEntity(type: type), isNew: true); - Assert.Equal(expected, vm.SelectedAccountType); + vm.ClearTitleCommand.Execute(); + + Assert.Null(entity.Title); } [Theory] @@ -89,17 +55,49 @@ public void Constructor_InvalidType_NormalisesEntityTypeToCash(string type) } [Fact] - public void Constructor_WithCardIssuer_SetsSelectedCardIssuer() + public void Constructor_SetsCurrencies_FromDbManual() { - var vm = new AccountControlVM(CreateEntity(cardIssuer: "VISA"), isNew: true); - Assert.Equal(CardIssuer.VISA, vm.SelectedCardIssuer); + DbManual.SetupTests(new List()); + var vm = new AccountControlVM(CreateEntity(), isNew: true); + Assert.Same(DbManual.Currencies, vm.Currencies); } [Fact] - public void Constructor_WithElectronicType_SetsSelectedElectronicType() + public void Constructor_SetsEntityProperty() { - var vm = new AccountControlVM(CreateEntity(cardIssuer: "PAYPAL"), isNew: true); - Assert.Equal(ElectronicType.PAYPAL, vm.SelectedElectronicType); + var entity = CreateEntity(); + var vm = new AccountControlVM(entity, isNew: true); + Assert.Same(entity, vm.Entity); + } + + // ── Constructor ────────────────────────────────────────────────────── + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Constructor_SetsIsNew(bool isNew) + { + var vm = new AccountControlVM(CreateEntity(), isNew); + Assert.Equal(isNew, vm.IsNew); + } + + [Theory] + [InlineData("CASH", AccountType.CASH)] + [InlineData("BANK", AccountType.BANK)] + [InlineData("CREDIT_CARD", AccountType.CREDIT_CARD)] + [InlineData("DEBIT_CARD", AccountType.DEBIT_CARD)] + [InlineData("ASSET", AccountType.ASSET)] + [InlineData("ELECTRONIC", AccountType.ELECTRONIC)] + public void Constructor_ValidType_SetsSelectedAccountType(string type, AccountType expected) + { + var vm = new AccountControlVM(CreateEntity(type: type), isNew: true); + Assert.Equal(expected, vm.SelectedAccountType); + } + + [Fact] + public void Constructor_WithCardIssuer_SetsSelectedCardIssuer() + { + var vm = new AccountControlVM(CreateEntity(cardIssuer: "VISA"), isNew: true); + Assert.Equal(CardIssuer.VISA, vm.SelectedCardIssuer); } [Fact] @@ -123,6 +121,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 +138,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 +216,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 +239,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 +297,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 +344,25 @@ 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); + } + + // ── ClearTitleCommand ──────────────────────────────────────────────── + // ── SelectedAccountType setter ──────────────────────────────────────── + // ── SelectedCardIssuer setter ───────────────────────────────────────── + // ── SelectedElectronicType setter ───────────────────────────────────── + // ── SelectedCurrency setter ─────────────────────────────────────────── + // ── Show* computed properties ───────────────────────────────────────── [Theory] [InlineData(AccountType.ELECTRONIC, true)] [InlineData(AccountType.CASH, false)] @@ -352,84 +403,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..333fcbc6 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() { @@ -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..4cee21ec 100644 --- a/src/Tests/Financier.Desktop.Tests/Pages/MainWindowVMTest.cs +++ b/src/Tests/Financier.Desktop.Tests/Pages/MainWindowVMTest.cs @@ -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..7935fc4a 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() { @@ -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,8 +276,6 @@ 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) diff --git a/src/Tests/Financier.Reports.Tests/ReportByPeriodMonthCrcVMTests.cs b/src/Tests/Financier.Reports.Tests/ReportByPeriodMonthCrcVMTests.cs index 2593792c..5121dcc2 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,8 +247,6 @@ private TestableVM CreateTestableVM() return testVm; } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ReportByPeriodMonthCrcVM { 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..ffb7d90f 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,8 +261,6 @@ private TestableVM CreateTestableVM() return testVm; } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ReportDynamicDebitCretitPayeeVM { 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..7bbbf99e 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() { @@ -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,8 +222,6 @@ private TestableVM CreateTestableVM() return testVm; } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ReportDynamicRestVM { 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..caeb4c2e 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,8 +197,6 @@ private TestableVM CreateTestableVM() return testVm; } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ReportStructureActivesVM { 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..da15f878 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,8 +380,6 @@ private TestableVM CreateTestableVM() return testVm; } - // ── Helper types ───────────────────────────────────────────────────────── - private sealed class TestableVM : ReportStructureIncomeExpenseVM { 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) { From 6124dc577971322c0e94d6e4f88584332bdb2a0e Mon Sep 17 00:00:00 2001 From: vov4uk Date: Fri, 4 Sep 2026 10:43:16 +0200 Subject: [PATCH 03/13] warnings --- src/Financier.Desktop/Pages/CategoriesVM.cs | 24 +- .../Pages/Dialogs/CategoryControlVM.cs | 14 +- .../Services/UpdateService.cs | 11 +- src/Financier.Reports/ReportsControlVM.cs | 2 +- src/Financier.Reports/SafePlotModel.cs | 4 +- .../BackupReaderTests.cs | 4 +- .../Pages/BlotterVMIntegrationTests.cs | 327 +++++++++--------- .../Pages/Dialog/AccountControlVMTest.cs | 8 - .../Pages/Dialog/SettingsVMTest.cs | 2 +- .../ByCategoryReportVMTests.cs | 7 +- .../ReportByPeriodMonthCrcVMTests.cs | 3 +- .../ReportDynamicDebitCretitPayeeVMTests.cs | 3 +- .../ReportDynamicRestVMTests.cs | 5 +- .../ReportStructureActivesVMTests.cs | 3 +- .../ReportStructureIncomeExpenseVMTests.cs | 3 +- 15 files changed, 223 insertions(+), 197 deletions(-) diff --git a/src/Financier.Desktop/Pages/CategoriesVM.cs b/src/Financier.Desktop/Pages/CategoriesVM.cs index f083de67..a6a2b2af 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( 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/Services/UpdateService.cs b/src/Financier.Desktop/Services/UpdateService.cs index 51c0fe75..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( @@ -32,7 +32,11 @@ public class UpdateService() : IDisposable } #nullable disable - public void Dispose() => _updateManager?.Dispose(); + public void Dispose() + { + _updateManager?.Dispose(); + GC.SuppressFinalize(this); + } public void FinalizeUpdate(bool needRestart) { @@ -64,7 +68,8 @@ public async Task PrepareUpdateAsync(Version version) try { - await _updateManager.PrepareUpdateAsync(_updateVersion = version); + _updateVersion = version; + await _updateManager.PrepareUpdateAsync(_updateVersion); _isUpdatePrepared = true; } catch (UpdaterAlreadyLaunchedException) diff --git a/src/Financier.Reports/ReportsControlVM.cs b/src/Financier.Reports/ReportsControlVM.cs index bb894d43..91c93669 100644 --- a/src/Financier.Reports/ReportsControlVM.cs +++ b/src/Financier.Reports/ReportsControlVM.cs @@ -130,7 +130,7 @@ public void OpenReport(string reportType) } else { - Type type = Type.GetType(reportType, false, true)!; + Type type = Type.GetType(reportType, false, true); if (type != null) { ConstructorInfo constructor = type.GetConstructors().FirstOrDefault(); diff --git a/src/Financier.Reports/SafePlotModel.cs b/src/Financier.Reports/SafePlotModel.cs index 63ec03f3..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) { 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.Desktop.Tests/Pages/BlotterVMIntegrationTests.cs b/src/Tests/Financier.Desktop.Tests/Pages/BlotterVMIntegrationTests.cs index 3cf521fd..94b68e80 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,87 @@ 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 +594,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( @@ -626,29 +648,6 @@ private List Currencies() "{\"_id\":2,\"name\":\"USD\",\"title\":\"United States dollar\",\"symbol\":\"$\",\"is_default\":0,\"decimals\":2,\"decimal_separator\":\"'.'\",\"group_separator\":\"' '\",\"symbol_format\":\"RS\",\"updated_on\":0,\"remote_key\":null,\"sort_order\":0,\"is_active\":1}," + "]"); } - - 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 c74a230b..b89ecfdf 100644 --- a/src/Tests/Financier.Desktop.Tests/Pages/Dialog/AccountControlVMTest.cs +++ b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/AccountControlVMTest.cs @@ -9,8 +9,6 @@ namespace Financier.Desktop.Tests.Pages.Dialog public class AccountControlVMTest { - // ── helpers ────────────────────────────────────────────────────────── - [Fact] public void ClearTitleCommand_Execute_DisablesSaveCommand() { @@ -357,12 +355,6 @@ public void ShowCreditCardFields_ReturnsExpectedValue(AccountType accountType, b Assert.Equal(expected, vm.ShowCreditCardFields); } - // ── ClearTitleCommand ──────────────────────────────────────────────── - // ── SelectedAccountType setter ──────────────────────────────────────── - // ── SelectedCardIssuer setter ───────────────────────────────────────── - // ── SelectedElectronicType setter ───────────────────────────────────── - // ── SelectedCurrency setter ─────────────────────────────────────────── - // ── Show* computed properties ───────────────────────────────────────── [Theory] [InlineData(AccountType.ELECTRONIC, true)] [InlineData(AccountType.CASH, false)] diff --git a/src/Tests/Financier.Desktop.Tests/Pages/Dialog/SettingsVMTest.cs b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/SettingsVMTest.cs index 333fcbc6..06d665fa 100644 --- a/src/Tests/Financier.Desktop.Tests/Pages/Dialog/SettingsVMTest.cs +++ b/src/Tests/Financier.Desktop.Tests/Pages/Dialog/SettingsVMTest.cs @@ -109,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(); diff --git a/src/Tests/Financier.Reports.Tests/ByCategoryReportVMTests.cs b/src/Tests/Financier.Reports.Tests/ByCategoryReportVMTests.cs index 7935fc4a..cedc055e 100644 --- a/src/Tests/Financier.Reports.Tests/ByCategoryReportVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ByCategoryReportVMTests.cs @@ -71,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); @@ -278,7 +278,8 @@ public async Task RefreshDataCommand_WithData_PopulatesEntities() 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/ReportByPeriodMonthCrcVMTests.cs b/src/Tests/Financier.Reports.Tests/ReportByPeriodMonthCrcVMTests.cs index 5121dcc2..2bbe2d20 100644 --- a/src/Tests/Financier.Reports.Tests/ReportByPeriodMonthCrcVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportByPeriodMonthCrcVMTests.cs @@ -249,7 +249,8 @@ private TestableVM CreateTestableVM() 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 ffb7d90f..41f1eb12 100644 --- a/src/Tests/Financier.Reports.Tests/ReportDynamicDebitCretitPayeeVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportDynamicDebitCretitPayeeVMTests.cs @@ -263,7 +263,8 @@ private TestableVM CreateTestableVM() 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 7bbbf99e..2952a12f 100644 --- a/src/Tests/Financier.Reports.Tests/ReportDynamicRestVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportDynamicRestVMTests.cs @@ -135,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); @@ -224,7 +224,8 @@ private TestableVM CreateTestableVM() 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 caeb4c2e..7c65fac5 100644 --- a/src/Tests/Financier.Reports.Tests/ReportStructureActivesVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportStructureActivesVMTests.cs @@ -199,7 +199,8 @@ private TestableVM CreateTestableVM() 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 da15f878..e131c125 100644 --- a/src/Tests/Financier.Reports.Tests/ReportStructureIncomeExpenseVMTests.cs +++ b/src/Tests/Financier.Reports.Tests/ReportStructureIncomeExpenseVMTests.cs @@ -382,7 +382,8 @@ private TestableVM CreateTestableVM() private sealed class TestableVM : ReportStructureIncomeExpenseVM { - public TestableVM(IFinancierDatabase db) : base(db) + public TestableVM(IFinancierDatabase db) + : base(db) { } From f65d0d426193456787650e34e80edd8e3ba8176f Mon Sep 17 00:00:00 2001 From: vov4uk Date: Wed, 9 Sep 2026 18:30:27 +0200 Subject: [PATCH 04/13] CurrencyIds --- Directory.Packages.props | 2 +- src/Financier.Adapter/EntityReader.cs | 14 +++++----- src/Financier.Common/Entities/DbManual.cs | 9 +++++- src/Financier.Desktop/MainWindowVM.cs | 28 ++++++------------- src/Financier.Desktop/Pages/BlotterVM.cs | 26 +++-------------- .../Pages/BlotterVMIntegrationTests.cs | 2 ++ .../Pages/MainWindowVMTest.cs | 4 +-- 7 files changed, 33 insertions(+), 52 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 8c722106..38495f6d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -10,7 +10,7 @@ - + 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.Desktop/MainWindowVM.cs b/src/Financier.Desktop/MainWindowVM.cs index 63ade458..382a1899 100644 --- a/src/Financier.Desktop/MainWindowVM.cs +++ b/src/Financier.Desktop/MainWindowVM.cs @@ -213,6 +213,7 @@ public async Task OpenBackup(string backupPath) ClearPages(); Stopwatch stopwatch = Stopwatch.StartNew(); var (entities, backupVersion, columnsOrder) = await entityReader.ParseBackupFileAsync(backupPath); + entities = entities as IReadOnlyCollection ?? 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) diff --git a/src/Financier.Desktop/Pages/BlotterVM.cs b/src/Financier.Desktop/Pages/BlotterVM.cs index b0a851c3..f63335ee 100644 --- a/src/Financier.Desktop/Pages/BlotterVM.cs +++ b/src/Financier.Desktop/Pages/BlotterVM.cs @@ -438,28 +438,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/Tests/Financier.Desktop.Tests/Pages/BlotterVMIntegrationTests.cs b/src/Tests/Financier.Desktop.Tests/Pages/BlotterVMIntegrationTests.cs index 94b68e80..5c070d2e 100644 --- a/src/Tests/Financier.Desktop.Tests/Pages/BlotterVMIntegrationTests.cs +++ b/src/Tests/Financier.Desktop.Tests/Pages/BlotterVMIntegrationTests.cs @@ -548,6 +548,7 @@ public void PropertySetters_To_RaisesPropertyChanged() Assert.Contains("To", changedProperties); } + private List Accounts() { return JsonDeserializer.Deserialize( @@ -648,6 +649,7 @@ private List Currencies() "{\"_id\":2,\"name\":\"USD\",\"title\":\"United States dollar\",\"symbol\":\"$\",\"is_default\":0,\"decimals\":2,\"decimal_separator\":\"'.'\",\"group_separator\":\"' '\",\"symbol_format\":\"RS\",\"updated_on\":0,\"remote_key\":null,\"sort_order\":0,\"is_active\":1}," + "]"); } + private TransactionDto EditSplitTransactionDto() { var transaction = JsonConvert.DeserializeObject( diff --git a/src/Tests/Financier.Desktop.Tests/Pages/MainWindowVMTest.cs b/src/Tests/Financier.Desktop.Tests/Pages/MainWindowVMTest.cs index 4cee21ec..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] From 233661e8f944df2c8e4ad902c95116ebf949c1ca Mon Sep 17 00:00:00 2001 From: vov4uk Date: Wed, 9 Sep 2026 18:37:45 +0200 Subject: [PATCH 05/13] Update main.yml --- .github/workflows/main.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index a7f03712..f01c47d1 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -56,6 +56,7 @@ jobs: run: > dotnet test -p:EnableWindowsTargeting=true + -p:TestingPlatformDotnetTestSupport=true --configuration Release --no-build --verbosity normal From 21d48a90551a3ba59bb0bd075057383dd9c79127 Mon Sep 17 00:00:00 2001 From: vov4uk Date: Wed, 9 Sep 2026 19:24:50 +0200 Subject: [PATCH 06/13] Update Directory.Build.props --- Directory.Build.props | 1 + 1 file changed, 1 insertion(+) diff --git a/Directory.Build.props b/Directory.Build.props index cf7f47cf..975c37ed 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -3,5 +3,6 @@ 2026.09.01.1 vov4uk Copyright (C) vov4uk + true From 9c4360adcd75e4466ebc7020bdc10f987da10316 Mon Sep 17 00:00:00 2001 From: vov4uk Date: Wed, 9 Sep 2026 20:42:33 +0200 Subject: [PATCH 07/13] Fix build --- .github/workflows/main.yml | 1 - Directory.Packages.props | 1 + global.json | 5 +++++ src/Financier.Desktop/Pages/CategoriesVM.cs | 6 ++++-- .../Financier.Adapter.Tests/Financier.Adapter.Tests.csproj | 1 + .../Financier.Converter.Test/Financier.Common.Test.csproj | 1 + .../Financier.DataAccess.Tests.csproj | 1 + .../Financier.Desktop.Tests/Financier.Desktop.Tests.csproj | 1 + .../Financier.Reports.Tests/Financier.Reports.Tests.csproj | 1 + 9 files changed, 15 insertions(+), 3 deletions(-) create mode 100644 global.json diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f01c47d1..a7f03712 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -56,7 +56,6 @@ jobs: run: > dotnet test -p:EnableWindowsTargeting=true - -p:TestingPlatformDotnetTestSupport=true --configuration Release --no-build --verbosity normal diff --git a/Directory.Packages.props b/Directory.Packages.props index 38495f6d..0cafb92f 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -10,6 +10,7 @@ + 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.Desktop/Pages/CategoriesVM.cs b/src/Financier.Desktop/Pages/CategoriesVM.cs index a6a2b2af..f9f90602 100644 --- a/src/Financier.Desktop/Pages/CategoriesVM.cs +++ b/src/Financier.Desktop/Pages/CategoriesVM.cs @@ -132,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) { @@ -142,6 +143,7 @@ private static (List siblings, int pos) FindSiblingsInSubTree if (result.siblings != null) return result; } } + return (null, -1); } 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.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 From d325ce8f3de0a77f55940f782231b9a886d808ac Mon Sep 17 00:00:00 2001 From: vov4uk Date: Wed, 9 Sep 2026 20:53:13 +0200 Subject: [PATCH 08/13] Update Directory.Packages.props --- Directory.Packages.props | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 0cafb92f..909958ae 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -18,7 +18,7 @@ - + @@ -27,14 +27,14 @@ - + - + From 9f68508fe9a42fd20cbbe0e145badf50089c395e Mon Sep 17 00:00:00 2001 From: vov4uk Date: Thu, 10 Sep 2026 16:33:02 +0200 Subject: [PATCH 09/13] Sync sql scripts with android version --- src/Financier.Common/Model/BlotterModel.cs | 8 + .../Scripts/SQL_alter_files.Designer.cs | 67 +++- .../DataBase/Scripts/SQL_alter_files.resx | 23 +- .../Scripts/SQL_create_files.Designer.cs | 6 +- .../Scripts/SQL_views_files.Designer.cs | 315 ++++++++++-------- .../DataBase/Scripts/SQL_views_files.resx | 14 +- ...628_0122_add_currency_trading_currency.sql | 1 + ...0458_add_transaction_parent_account_id.sql | 1 + ...55_recreate_transactions_parent_id_idx.sql | 3 + ...add_is_include_into_reports_to_account.sql | 1 + ...0260905_0241_add_payee_locations_alias.sql | 18 + .../DataBase/Scripts/create/account.sql | 12 +- .../DataBase/Scripts/create/attributes.sql | 20 +- .../DataBase/Scripts/create/budget.sql | 21 +- .../DataBase/Scripts/create/category.sql | 8 +- .../DataBase/Scripts/create/currency.sql | 11 +- .../DataBase/Scripts/create/locations.sql | 18 +- .../DataBase/Scripts/create/project.sql | 7 +- .../DataBase/Scripts/create/transaction.sql | 30 +- .../Scripts/view/010[v_all_transactions].sql | 102 +++--- ...015[v_blotter_for_account_with_splits].sql | 190 ++++++----- .../view/022[v_blotter_flatsplits].sql | 13 +- .../view/023[v_blotter_with_splits].sql | 4 + .../DataBase/Scripts/view/030[v_category].sql | 25 +- .../Scripts/view/035[v_category_list].sql | 20 +- .../Scripts/view/050[v_attributes].sql | 27 +- .../Scripts/view/060[v_report_category].sql | 16 +- .../view/060[v_report_sub_category].sql | 17 +- .../Scripts/view/061[v_report_period].sql | 9 +- .../Scripts/view/062[v_report_location].sql | 13 +- .../Scripts/view/063[v_report_project].sql | 13 +- .../Scripts/view/064[v_report_payee].sql | 17 +- .../view/080[v_transaction_attributes].sql | 24 +- .../Scripts/view/090[v_exchange_rate].sql | 13 + .../DataBase/Scripts/view/091[v_account].sql | 6 + .../view/092[v_account_with_separator].sql | 17 + .../Financier.DataAccess.csproj | 22 +- src/Financier.Desktop/MainWindowVM.cs | 10 +- src/Financier.Desktop/Pages/BlotterVM.cs | 35 ++ src/Financier.Desktop/Pages/BlotterView.xaml | 41 ++- 40 files changed, 749 insertions(+), 469 deletions(-) create mode 100644 src/Financier.DataAccess/DataBase/Scripts/alter/20260628_0122_add_currency_trading_currency.sql create mode 100644 src/Financier.DataAccess/DataBase/Scripts/alter/20260711_0458_add_transaction_parent_account_id.sql create mode 100644 src/Financier.DataAccess/DataBase/Scripts/alter/20260712_0855_recreate_transactions_parent_id_idx.sql create mode 100644 src/Financier.DataAccess/DataBase/Scripts/alter/20260719_0330_add_is_include_into_reports_to_account.sql create mode 100644 src/Financier.DataAccess/DataBase/Scripts/alter/20260905_0241_add_payee_locations_alias.sql create mode 100644 src/Financier.DataAccess/DataBase/Scripts/view/023[v_blotter_with_splits].sql create mode 100644 src/Financier.DataAccess/DataBase/Scripts/view/090[v_exchange_rate].sql create mode 100644 src/Financier.DataAccess/DataBase/Scripts/view/091[v_account].sql create mode 100644 src/Financier.DataAccess/DataBase/Scripts/view/092[v_account_with_separator].sql 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 @@ - + @@ -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 5198c925..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();