BudgetAnalyser.Engine.Services.TransactionManagerService.ValidateWithCurrentBudgetsAsync C# (CSharp) Method

ValidateWithCurrentBudgetsAsync() public method

Validates the currently loaded StatementModel against the provided budgets and ensures all buckets used by the transactions exist in the budgets. This is performed asynchronously. This method can be called when a budget is loaded or changed or when a new Budget Analyser Statement is loaded.
public ValidateWithCurrentBudgetsAsync ( BudgetCollection budgets = null ) : Task
budgets BudgetCollection /// The current budgets. This must be provided at least once. It can be omitted when /// calling this method after the statement model has changed if the budget was previously provided. ///
return Task
        public async Task<bool> ValidateWithCurrentBudgetsAsync(BudgetCollection budgets = null)
        {
            // This method must be called at least once with a budget collection.  Second and subsequent times do not require the budget.
            if (this.budgetCollection == null && budgets == null)
            {
                throw new ArgumentNullException(nameof(budgets));
            }

            this.budgetCollection = budgets ?? this.budgetCollection;

            if (StatementModel == null)
            {
                // Can't check yet, statement hasn't been loaded yet. Everything is ok for now.
                return true;
            }

            if (this.budgetCollection.GetHashCode() == this.budgetHash)
            {
                // This budget has already been checked against this statement. No need to repeatedly check the validity below, this is an expensive operation.
                // Everything is ok.
                return true;
            }

            var allBuckets = new List<BudgetBucket>(this.bucketRepository.Buckets.OrderBy(b => b.Code));
            var allTransactionHaveABucket = await Task.Run(
                () =>
                {
                    return StatementModel.AllTransactions
                        .Where(t => t.BudgetBucket != null)
                        .AsParallel()
                        .All(
                            t =>
                            {
                                var bucketExists = allBuckets.Contains(t.BudgetBucket);
                                if (!bucketExists)
                                {
                                    t.BudgetBucket = null;
                                    this.logger.LogWarning(l => l.Format("Transaction {0} has a bucket ({1}) that doesn't exist!", t.Date, t.BudgetBucket));
                                }
                                return bucketExists;
                            });
                });

            this.budgetHash = this.budgetCollection.GetHashCode();
            return allTransactionHaveABucket;
        }