public async Task <IEnumerable <TransactionInfo> > GetFilteredAsync(TransactionsFilter filter, int skip, int take)
        {
            using (var context = _contextFactory.CreateDataContext())
            {
                var hasher = Sha3Keccack.Current;

                var items = await context.Transactions
                            .Include(x => x.FunctionCall)
                            .Where(tx =>
                                   (!filter.From.Any() || filter.From.Contains(tx.From)) &&
                                   (!filter.To.Any() || filter.To.Contains(tx.To)) &&
                                   (string.IsNullOrEmpty(filter.FunctionName) ||
                                    tx.FunctionCall.FunctionName == filter.FunctionName) &&
                                   (filter.FunctionSignature == null ||
                                    tx.FunctionCall.FunctionSignature == filter.FunctionSignature) &&
                                   (!filter.AffectedAddresses.Any() || tx.FunctionCall.Parameters
                                    .Where(x => x.ParameterType == Consts.AffectedAddressParameterType)
                                    .Any(p => filter.AffectedAddresses.Select(a => hasher.CalculateHash(a)).Contains(p.ParameterValueHash))))
                            .Skip(skip)
                            .Take(take)
                            .Select(x => x.ToTransactionInfo())
                            .ToListAsync();

                return(items);
            }
        }
Ejemplo n.º 2
0
        public async Task <IReadOnlyList <TransactionDto> > GetTransactions(TransactionsFilter specParams)
        {
            var spec         = new TransactionWithCategoryAndVendorSpecification(specParams);
            var transactions = await _unitOfWork.Repository <TransactionDetail>()
                               .FindAllBySpecAsync <TransactionDto>(spec);

            return(transactions);
        }
Ejemplo n.º 3
0
        public static async Task <List <Settlement> > FetchSettlementsByFilter(TransactionsFilter filter)
        {
            CommerceEntities dbContext = BuildDBContext();
            var query = from rr in dbContext.RedemptionReports
                        join offers in dbContext.Offers on rr.DealId equals offers.GlobalID
                        join rd in dbContext.RedeemedDeals on rr.TransactionId equals rd.Id
                        join m in dbContext.Merchants on rd.MerchantNameId equals m.Id
                        join cardBrands in dbContext.CardBrands on rr.CardBrand equals cardBrands.Name
                        select new Settlement
            {
                PartnerName                = rr.PartnerName,
                CardBrandId                = cardBrands.Id,
                CardBrandName              = rr.CardBrand,
                LastFourDigits             = rr.LastFourDigits,
                PartnerMerchantId          = m.Id,
                MerchantName               = m.Name,
                AuthorizationDateTimeLocal = rr.AuthorizationDateTimeLocal,
                AuthorizationDateTimeUtc   = rr.AuthorizationDateTimeUtc,
                UtcReachedTerminalState    = rr.UtcReachedTerminalState,
                TransactionTypeId          = offers.OfferType,
                TransactionType            = offers.OfferType == EarnTransactionType ? "Earn" : "Burn",
                AuthorizationAmount        = Math.Round((double)rr.AuthorizationAmount / 100, 2),
                SettlementAmount           = Math.Round((double)rr.SettlementAmount / 100, 2),
                DiscountAmount             = Math.Round((double)rr.DiscountAmount / 100, 2),
                CreditStatus               = rr.CreditStatus,
                CurrentState               = rr.CurrentState,
                GlobalUserId               = rr.GlobalUserID
            };

            if (filter.StartDate.HasValue && filter.EndDate.HasValue)
            {
                query = query.Where(x => filter.StartDate <= x.UtcReachedTerminalState && x.UtcReachedTerminalState < filter.EndDate);
            }

            if (filter.TransactionTypes != null && filter.TransactionTypes.Any())
            {
                query = query.Where(x => filter.TransactionTypes.Contains(x.TransactionTypeId));
            }

            if (filter.CardBrandIds != null && filter.CardBrandIds.Any())
            {
                query = query.Where(x => filter.CardBrandIds.Contains(x.CardBrandId));
            }

            if (!string.IsNullOrWhiteSpace(filter.Last4Digits))
            {
                query = query.Where(x => x.LastFourDigits == filter.Last4Digits);
            }

            if (!string.IsNullOrWhiteSpace(filter.MerchantName) && filter.MerchantName != AllMerchants)
            {
                query = query.Where(x => x.MerchantName == filter.MerchantName);
            }

            query = query.OrderByDescending(x => x.UtcReachedTerminalState);

            return(await query.ToListAsync());
        }
        public TransactionWithCategoryAndVendorSpecification(TransactionsFilter filter, bool forCount = false) :
            base(txn =>
                 (!filter.Month.HasValue || txn.TransactionDate.Month == filter.Month) &&
                 (!filter.Year.HasValue || txn.TransactionDate.Year == filter.Year) &&
                 (!filter.PaidBy.HasValue || txn.PaidPartyId == filter.PaidBy) &&
                 (!filter.PaidTo.HasValue || txn.PaidToId == filter.PaidTo) &&
                 (filter.IsAutoGeneratedTxnsNeeded || !txn.IsAutoGenerated) &&
                 (string.IsNullOrEmpty(filter.Search) || txn.Name.ToLower().Contains(filter.Search)) &&
                 (string.IsNullOrEmpty(filter.CategoryName) || txn.Category.Name.ToLower().Contains(filter.CategoryName))
                 )
        {
            if (!forCount)
            {
                AddInclude(t => t.Category);
                AddInclude(t => t.PaidParty);
                AddOrderByDesc(t => t.TransactionDate);
                if (!string.IsNullOrEmpty(filter.Sort))
                {
                    switch (filter.Sort.ToLower())
                    {
                    case "categoryasc":
                        AddOrderBy(x => x.Category.Name);
                        break;

                    case "categorydesc":
                        AddOrderByDesc(x => x.Category.Name);
                        break;

                    case "amountasc":
                        AddOrderBy(x => x.Amount);
                        break;

                    case "amountdesc":
                        AddOrderByDesc(x => x.Amount);
                        break;

                    case "txndateasc":
                        AddOrderBy(x => x.TransactionDate);
                        break;

                    case "namedesc":
                        AddOrderByDesc(x => x.Name);
                        break;

                    case "nameasc":
                        AddOrderBy(x => x.Name);
                        break;

                    default:
                        AddOrderByDesc(x => x.TransactionDate);
                        break;
                    }
                }
                AddPagination((filter.PageIndex - 1) * filter.PageSize, filter.PageSize);
            }
        }
        public Task <IEnumerable <Transaction> > GetAllTransactionsAsync(TransactionsFilter filter)
        {
            var transactions = _transactions
                               .Where(t => t.FromAccountId == filter.AccountId ||
                                      t.ToAccountId == filter.AccountId);

            transactions = FilterTransactions(transactions, filter);

            return(Task.FromResult(transactions.AsEnumerable()));
        }
        public TransactionsFilter GetFilter()
        {
            var filter = new TransactionsFilter
                             {
                                 YearsList = GetTransactionYears(),
                                 MonthsList = GetTransactionMonths(),
                             };

            filter.AddPaymentMethods(ViewModels.PaymentMethod.Method, PaymentMethodService.SelectListPaymentMethods(0));
            filter.AddPaymentMethods(ViewModels.PaymentMethod.Profile, _profileService.SelectListProfiles(0));
            return filter;
        }
Ejemplo n.º 7
0
        public IActionResult GetWalletTransactions([FromBody] TransactionsFilter filter)
        {
            var data = walletService.GetTransactionHistory(CurrentUser.Id, filter ?? new TransactionsFilter());

            if (!data.IsSuccess)
            {
                return(BadRequest(ErrorResult.GetResult(data)));
            }

            return(Ok(new WalletTransactionsViewModel
            {
                Transactions = data.Data.Item1,
                Total = data.Data.Item2
            }));
        }
        public async IAsyncEnumerable <TransactionViewModel> ReadTransactions(TransactionsFilter filter, Guid userId)
        {
            if (filter.Users?.Any() ?? false)
            {
                using var connection = connectionFactory.CreateConnection();

                var builder  = new SqlBuilder();
                var selector = builder.AddTemplate(@"
				SELECT bt.Id as TransactionId, bt.Title as Name, bt.TransactionDate, btt.Name as Type, g.Name as GroupName, g.RuleId as RuleId, bt.Extensions as Extensions, bt.Amount, b.Name as BankName 
				FROM BankTransactions bt
				JOIN BankTransactionTypes btt ON bt.BankTransactionTypeId = btt.Id
				JOIN Banks b ON bt.BankId = b.Id
				LEFT JOIN BankTransactionGroups btg ON bt.Id = btg.BankTransactionId
				LEFT JOIN Groups g ON btg.GroupId = g.Id
				/**where**/
				ORDER BY bt.[Order] desc"                );

                if (filter.OnlyWithoutGroup)
                {
                    builder.Where("btg.BankTransactionId IS NULL");
                }

                if (filter.GroupName != null)
                {
                    builder.Where("g.Name = @GroupName", new { filter.GroupName });
                }

                if (filter.DateFrom != null && filter.DateTo != null)
                {
                    builder.Where("bt.TransactionDate BETWEEN @DateFrom AND @DateTo", new { filter.DateFrom, filter.DateTo });
                }

                builder.Where("bt.UserId IN @usersIds", new { usersIds = filter.Users });

                var transactionGroupsContainers = await connection.QueryAsync <TransactionGroupsContainer>(selector.RawSql, selector.Parameters);

                foreach (var transactionGroups in transactionGroupsContainers.GroupBy(g => g.TransactionId))
                {
                    var transactionGroup = transactionGroups.First();
                    var viewModel        = mapper.Map <TransactionViewModel>(transactionGroup);
                    viewModel.Groups = transactionGroups.Where(t => t.GroupName != null).Select(t =>
                                                                                                new TransactionViewModel.TransactionGroupViewModel(t.GroupName, t.RuleId == null)).ToList();
                    yield return(viewModel);
                }
            }
        }
Ejemplo n.º 9
0
        public ActionResult FilterTransactions(int?transactionType = null, int?currency = null)
        {
            TransactionsService transactionsService = new TransactionsService();
            TransactionsFilter  transactionsFilter  = new TransactionsFilter();

            if (transactionType != null)
            {
                transactionsFilter.Action = ((Variables.ActionValues)transactionType).ToString();
                ViewBag.SelectedAction    = transactionType;
            }
            if (currency != null)
            {
                transactionsFilter.CurrencyCode = ((Variables.CurrencyCodeValues)currency).ToString();
                ViewBag.SelectedCurrency        = currency;
            }

            return(View("Index", transactionsService.GetTransactions(transactionsFilter)));
        }
Ejemplo n.º 10
0
        public async Task <TransactionsResult> GetFilteredAsync(TransactionsFilter filter, int currentPage, int pageSize)
        {
            if (filter == null)
            {
                throw new ArgumentNullException(nameof(filter));
            }

            var(skip, take) = PagingUtils.GetNextPageParameters(currentPage, pageSize);

            var items = await _transactionRepository.GetFilteredAsync(filter, skip, take);

            return(new TransactionsResult
            {
                CurrentPage = currentPage,
                PageSize = pageSize,
                Transactions = items
            });
        }
        public ActionResult FiltredList(FormCollection formCollection)
        {
            var filter = new TransactionsFilter(formCollection);

            var _userHelper = new UserHelper();
            var isAdmin = _userHelper.IsUserInRole(ROLES.admin.ToString());
            ViewData["IsAdmin"] = isAdmin;

            //------------------
            //var list = isAdmin  ? _service.ListTransactions(filter)
                                //: _service.ListTransactions(_userHelper.CurrentUserId);

            //Mapper.CreateMap<Transaction, Transactions>();
            var viewModelList = new TransactionViewModel();
            //viewModelList.Transactions = Mapper.Map<IList<Transaction>, IList<Transactions>>(list);
            viewModelList.Transactions = _service.ListTransactions(filter);
            viewModelList.Filter = _service.GetFilter();

            return View("Index", viewModelList);
        }
Ejemplo n.º 12
0
        public List <Transactions> GetTransactions(TransactionsFilter filter)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Variables.UserNameAuth}:{Variables.PasswordAuth}")));

                    var builder = new UriBuilder(Variables.EndpointAuth);
                    var query   = HttpUtility.ParseQueryString(builder.Query);
                    if (filter.Action != null)
                    {
                        query["action"] = filter.Action;
                    }
                    if (filter.CurrencyCode != null)
                    {
                        query["currencyCode"] = filter.CurrencyCode;
                    }
                    builder.Query = query.ToString();
                    string url = builder.ToString();

                    HttpResponseMessage response = client.GetAsync(url).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        var    responseContent = response.Content;
                        string responseString  = responseContent.ReadAsStringAsync().Result;

                        List <Transactions> transactionsList = JsonConvert.DeserializeObject <List <Transactions> >(responseString);
                        return(transactionsList);
                    }
                }
                return(null);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
        public async Task <ICollection <MovingSumItemDTO> > MovingSum(TransactionsFilter filter = null)
        {
            var transactions = await this.transactionService.GetTransactionsAsync(filter);

            var                 movingSumCollection = new List <MovingSumItemDTO>();
            decimal             sum = 0;
            var                 recalculateCurrencies = false;
            var                 selectedCurrencyCode  = "PLN";
            List <ExchangeRate> exchangeRates         = null;

            if (recalculateCurrencies)
            {
                exchangeRates = (await this.currencyRepository.GetExchangeRatesAsync()).ToList();
            }

            ((transactions.OrderBy(x => x.Date))).ForEach(x =>
            {
                var diff = 0m;
                if (recalculateCurrencies)
                {
                    diff = (x.CurrencyCode == selectedCurrencyCode ? x.Value : this.GetValueInCurrency(exchangeRates, x.CurrencyCode, selectedCurrencyCode, x.Value, x.JustDate));
                }
                else
                {
                    diff = (x.CurrencyCode == selectedCurrencyCode ? x.Value : 0m);
                }
                sum          += diff;
                var movingSum = new MovingSumItemDTO
                {
                    Date     = x.JustDate,
                    Currency = x.CurrencyCode,
                    Value    = sum,
                    Diff     = diff,
                };
                movingSumCollection.Add(movingSum);
            });

            return(movingSumCollection);
        }
Ejemplo n.º 14
0
        public async Task <AccountDetailsDTO> GetAccountDetailsAsync(TransactionsFilter filter)
        {
            Account account;

            if (filter != null && filter.AccountsIds != null && filter.AccountsIds.Any())
            {
                account = await accountRepository.GetAccountAsync(filter.AccountsIds.First());
            }
            else if (filter != null && filter.AccountsExternalIds != null && filter.AccountsExternalIds.Any())
            {
                account = await accountRepository.GetAccountAsync(filter.AccountsExternalIds.First().ToString());
            }
            else
            {
                throw new ArgumentNullException();
            }

            var dto = new AccountDetailsDTO
            {
                Currency          = account.Currency.Code,
                CurrencyId        = account.CurrencyId,
                CurrencySymbol    = account.Currency.Symbol,
                Id                = account.Id,
                ExternalId        = Guid.Parse(account.ExternalId),
                IsIncludedInTotal = account.IsIncludedToTotal,
                Name              = account.Name,
                Comment           = account.Comment,
                AccountGroupId    = account.AccountGroupId,
                Type              = account.Type,
                ParentAccountId   = account.ParentAccountId,
                Order             = account.Order,
                Income            = await accountRepository.GetIncomeAsync(account.Id, filter.FromDate, filter.ToDate),
                Expense           = await accountRepository.GetExpenseAsync(account.Id, filter.FromDate, filter.ToDate),
                Amount            = await accountRepository.GetActualBalanceAsync(account.Id),
            };

            return(dto);
        }
 public List<Transactions> ListTransactions(TransactionsFilter filter)
 {
     return _repository.ListTransaction(filter);
 }
Ejemplo n.º 16
0
        public OperationResult <(List <WalletTransaction>, int)> GetTransactionHistory(Guid userId, TransactionsFilter filter)
        {
            return(InvokeOperations.InvokeOperation(() =>
            {
                var query = context.WalletTransactions
                            .Include(x => x.Wallet)
                            .Include(x => x.InvestmentProgram)
                            .Include(x => x.PaymentTransaction)
                            .ThenInclude(x => x.BlockchainAddress)
                            .Include(x => x.InvestmentRequest)
                            .ThenInclude(x => x.InvestmentProgram)
                            .OrderByDescending(x => x.Date)
                            .Where(x => x.Wallet.UserId == userId);

                var count = query.Count();

                if (filter.Skip.HasValue)
                {
                    query = query.Skip(filter.Skip.Value);
                }
                if (filter.Take.HasValue)
                {
                    query = query.Take(filter.Take.Value);
                }
                if (filter.InvestmentProgramId.HasValue)
                {
                    query = query.Where(x => (x.InvestmentRequest != null &&
                                              x.InvestmentRequest.InvestmentProgramtId == filter.InvestmentProgramId.Value) ||
                                        x.InvestmentProgramtId == filter.InvestmentProgramId.Value);
                }
                if (filter.Type.HasValue)
                {
                    switch (filter.Type.Value)
                    {
                    case WalletTxType.Internal:
                        query = query.Where(x => internalTxType.Contains(x.Type));
                        break;

                    case WalletTxType.External:
                        query = query.Where(x => externalTxType.Contains(x.Type));
                        break;
                    }
                }

                var investments = query.Select(x => x.ToTransaction()).ToList();
                return (investments, count);
            }));
        }
        public async Task <ICollection <TransactionListItemDTO> > GetTransactionsAsync(TransactionsFilter filter = null)
        {
            var transactions = await this.transactionRepository.GetTransactionsAsync(filter);

            var dtos = transactions.Select(t => new TransactionListItemDTO
            {
                AccountId         = t.AccountId,
                Date              = t.Date,
                Id                = t.Id,
                Value             = t.Amount,
                Account           = t.Account.Name,
                ValueWithCurrency = t.Amount + t.Account.Currency.Symbol,
                Type              = t.Type,
                Name              = t.Name,
                CurrencyCode      = t.Account.Currency.Code,
                IsTransfer        = t.IsTransfer,
                ExternalId        = t.ExternalId,
                ModifiedOn        = t.ModifiedOn,
                CreatedOn         = t.CreatedOn,
                CategoryId        = t.CategoryId,
                Category          = t.Category?.Name,
                Tags              = t.TagsToTransaction.Where(x => !x.Tag.IsDeleted).Select(x => new TagDTO {
                    ExternalId = x.Tag.ExternalId, Id = x.Tag.Id, IsDeleted = x.Tag.IsDeleted, Name = x.Tag.Name
                }).ToList()
            }).OrderByDescending(t => t.Date)
                       .ToList();

            return(dtos);
        }
Ejemplo n.º 18
0
        public async Task <List <Settlement> > FetchSettlements([FromUri] TransactionsFilter filter)
        {
            var data = await CustomerService.FetchSettlementsByFilter(filter);

            return(data);
        }
        public async Task <ActionResult <IReadOnlyList <TransactionDto> > > GetTransactions([FromQuery] TransactionsFilter filter)
        {
            var transactions = await _transactionService.GetTransactions(filter);

            int transactionsCount = await _transactionService.GetTransactionsCount(filter);

            Response.AddPaginationHeader(transactionsCount, filter.PageIndex, filter.PageSize);
            return(Ok(transactions));
        }
Ejemplo n.º 20
0
        public static async Task <List <Settlement> > FetchSettlementsByFilter(TransactionsFilter filter)
        {
            var data = await CommerceDal.FetchSettlementsByFilter(filter);

            return(data);
        }
        public IEnumerable <Transaction> FilterTransactions(
            IEnumerable <Transaction> collection,
            TransactionsFilter filter)
        {
            IEnumerable <Transaction> result = collection;

            if (filter.FilterOption == FilterOption.Sorting)
            {
                if (filter.SortField == SortField.Date)
                {
                    if (filter.SortDirection == SortDirection.Ascending)
                    {
                        result = collection.OrderBy(t => t.Timestamp);
                    }
                    else
                    {
                        result = collection.OrderByDescending(t => t.Timestamp);
                    }
                }

                if (filter.SortField == SortField.Price)
                {
                    if (filter.SortDirection == SortDirection.Ascending)
                    {
                        result = collection.OrderBy(t => t.Amount);
                    }
                    else
                    {
                        result = collection.OrderByDescending(t => t.Amount);
                    }
                }
            }

            if (filter.FilterOption == FilterOption.SelectDiapozon)
            {
                if (filter.AmountParams == AmountParams.One)
                {
                    if (filter.SortField == SortField.Price)
                    {
                        if (filter.SortDirection == SortDirection.Ascending)
                        {
                            if (filter.CompareDirection == CompareDirection.LessThen)
                            {
                                result = _transactions
                                         .OrderBy(t => t.Amount).Where(t => t.Amount < filter.Price);
                            }
                            if (filter.CompareDirection == CompareDirection.MoreThen)
                            {
                                result = _transactions
                                         .OrderBy(t => t.Amount).Where(t => t.Amount > filter.Price);
                            }
                            if (filter.CompareDirection == CompareDirection.Equally)
                            {
                                result = _transactions
                                         .OrderBy(t => t.Amount).Where(t => t.Amount == filter.Price);
                            }
                        }

                        if (filter.SortDirection == SortDirection.Descending)
                        {
                            if (filter.CompareDirection == CompareDirection.LessThen)
                            {
                                result = _transactions
                                         .OrderByDescending(t => t.Amount).Where(t => t.Amount < filter.Price);
                            }
                            if (filter.CompareDirection == CompareDirection.MoreThen)
                            {
                                result = _transactions
                                         .OrderByDescending(t => t.Amount).Where(t => t.Amount > filter.Price);
                            }
                            if (filter.CompareDirection == CompareDirection.Equally)
                            {
                                result = _transactions
                                         .OrderByDescending(t => t.Amount).Where(t => t.Amount == filter.Price);
                            }
                        }
                    }

                    if (filter.SortField == SortField.Date)
                    {
                        if (filter.SortDirection == SortDirection.Ascending)
                        {
                            if (filter.CompareDirection == CompareDirection.LessThen)
                            {
                                result = _transactions
                                         .OrderBy(t => t.Timestamp)
                                         .Where(t => t.Timestamp.ConvertFromUnixTimestamp() < filter.Date);
                            }
                            if (filter.CompareDirection == CompareDirection.MoreThen)
                            {
                                result = _transactions
                                         .OrderBy(t => t.Timestamp)
                                         .Where(t => t.Timestamp.ConvertFromUnixTimestamp() > filter.Date);
                            }
                            if (filter.CompareDirection == CompareDirection.Equally)
                            {
                                result = _transactions
                                         .OrderBy(t => t.Timestamp)
                                         .Where(t => t.Timestamp.ConvertFromUnixTimestamp() == filter.Date);
                            }
                        }

                        if (filter.SortDirection == SortDirection.Descending)
                        {
                            if (filter.CompareDirection == CompareDirection.LessThen)
                            {
                                result = _transactions
                                         .OrderBy(t => t.Timestamp)
                                         .Where(t => t.Timestamp.ConvertFromUnixTimestamp() < filter.Date);
                            }
                            if (filter.CompareDirection == CompareDirection.MoreThen)
                            {
                                result = _transactions
                                         .OrderBy(t => t.Timestamp)
                                         .Where(t => t.Timestamp.ConvertFromUnixTimestamp() > filter.Date);
                            }
                            if (filter.CompareDirection == CompareDirection.Equally)
                            {
                                result = _transactions
                                         .OrderBy(t => t.Timestamp)
                                         .Where(t => t.Timestamp.ConvertFromUnixTimestamp() == filter.Date);
                            }
                        }
                    }
                }

                if (filter.AmountParams == AmountParams.Two)
                {
                    if (filter.SortField == SortField.Price)
                    {
                        if (filter.SortDirection == SortDirection.Ascending)
                        {
                            result = collection
                                     .OrderBy(x => x.Timestamp)
                                     .Where(x => x.Amount >= filter.PriceBot &&
                                            x.Amount <= filter.PriceBot);
                        }

                        if (filter.SortDirection == SortDirection.Descending)
                        {
                            result = collection
                                     .OrderByDescending(x => x.Timestamp)
                                     .Where(x => x.Amount >= filter.PriceBot &&
                                            x.Amount <= filter.PriceBot);
                        }

                        else
                        {
                            result = collection
                                     .Where(x => x.Amount >= filter.PriceBot &&
                                            x.Amount <= filter.PriceBot);
                        }
                    }

                    if (filter.SortField == SortField.Date)
                    {
                        if (filter.SortDirection == SortDirection.Ascending)
                        {
                            result = collection
                                     .OrderBy(x => x.Timestamp)
                                     .Where(x => x.Timestamp.ConvertFromUnixTimestamp() >= filter.BotDate &&
                                            x.Timestamp.ConvertFromUnixTimestamp() <= filter.TopDate);
                        }

                        if (filter.SortDirection == SortDirection.Descending)
                        {
                            result = collection
                                     .OrderByDescending(x => x.Timestamp)
                                     .Where(x => x.Timestamp.ConvertFromUnixTimestamp() >= filter.BotDate &&
                                            x.Timestamp.ConvertFromUnixTimestamp() <= filter.TopDate);
                        }

                        else
                        {
                            result = collection
                                     .Where(x => x.Timestamp.ConvertFromUnixTimestamp() >= filter.BotDate &&
                                            x.Timestamp.ConvertFromUnixTimestamp() <= filter.TopDate);
                        }
                    }
                }
            }

            return(result
                   .Skip((filter.PageNumber - 1) * filter.PageSize)
                   .Take(filter.PageSize)
                   .ToList());
        }
Ejemplo n.º 22
0
 public IAsyncEnumerable <TransactionViewModel> Index([FromQuery] TransactionsFilter filter) =>
 transactionReader.ReadTransactions(filter, GetCurrentUserId());
 public TransactionsFilterTests()
 {
     _transactionDateRange     = new TransactionsFilter();
     _queryContainerDescriptor = new QueryContainerDescriptor <QueryableTransaction>();
 }
        public async Task <IActionResult> MovingSum([FromQuery] TransactionsFilter filter)
        {
            var days = await this.reportService.MovingSum(filter);

            return(Ok(days.ToList()));
        }
 public IAsyncEnumerable <TransactionViewModel> GetGroupTransactions([FromQuery] TransactionsFilter transactionsFilter) =>
 transactionReader.ReadTransactions(transactionsFilter, GetCurrentUserId());
Ejemplo n.º 26
0
        public async Task <int> GetTransactionsCount(TransactionsFilter specParams)
        {
            var spec = new TransactionWithCategoryAndVendorSpecification(specParams, true);

            return(await _unitOfWork.Repository <TransactionDetail>().GetCountForSpecAsync(spec));
        }
Ejemplo n.º 27
0
        public async Task <MonthlyBillDto> GenerateMonthlyBillAsync(int month, int year, bool simulated = true)
        {
            if (!simulated)
            {
                var billSpec            = new BillSpecification(month, year);
                var inmateBillsForMonth = await _unitOfWork.Repository <InmateBill>().FindAllBySpecAsync(billSpec);

                _unitOfWork.Repository <InmateBill>().RemoveMany(inmateBillsForMonth);

                var transactionsToDeleteSpec = new TransactionDetailSpecification(month, year, true);
                var transactionsToDelete     = await _unitOfWork.Repository <TransactionDetail>().FindAllBySpecAsync(transactionsToDeleteSpec);

                _unitOfWork.Repository <TransactionDetail>().RemoveMany(transactionsToDelete);

                await _unitOfWork.Complete();
            }

            var filter = new TransactionsFilter(month, year, false)
            {
                IsAutoGeneratedTxnsNeeded = false
            };
            var spec         = new TransactionWithCategoryAndVendorSpecification(filter);
            var transactions = await _unitOfWork.Repository <TransactionDetail>().FindAllBySpecAsync(spec);

            var transactionsGrouped = transactions.GroupBy(t => t.CategoryId);

            var categoricalSum = transactionsGrouped.ToDictionary(billCategory => billCategory.Key, billCategory => billCategory.Sum(b => b.Amount));

            var monthlyBill = new MonthlyBillDto(month, year);

            var categories = await _unitOfWork.Repository <Category>().FindAllAsync();



            var categoryWiseExpensesList = new List <CategoryWiseExpense>();

            decimal monthlyTotal = 0;

            var associatedVendorNamesList = new List <string> {
                VendorNames.Main, VendorNames.Others
            };

            var vendorSpec = new VendorSpecification(associatedVendorNamesList);

            var vendors = await _unitOfWork.Repository <Vendor>().FindAllBySpecAsync(vendorSpec);

            var mainAccount = vendors.FirstOrDefault(v => v.Name == VendorNames.Main);

            var othersAccount = vendors.FirstOrDefault(v => v.Name == VendorNames.Others);


            foreach (var category in categories)
            {
                var categoryWiseExpense = new CategoryWiseExpense
                {
                    CategoryId         = category.Id,
                    CategoryName       = category.Name,
                    TotalAmount        = category.ConsiderDefaultRate && category.DefaultRate != 0 ? category.DefaultRate : (categoricalSum.ContainsKey(category.Id)?categoricalSum[category.Id]:0),
                    TransactionDetails = transactions
                                         .Where(t => t.Category.Name == category.Name)
                                         .Select(t => new TransactionDetailDto()
                    {
                        TransactionDetailName = t.Name,
                        Amount = t.Amount
                    }).ToList()
                };

                if (categoryWiseExpense.TransactionDetails == null || categoryWiseExpense.TransactionDetails.Count == 0)
                {
                    if (!simulated && categoryWiseExpense.TotalAmount > 0)
                    {
                        var transaction = new TransactionDetail
                        {
                            Name            = categoryWiseExpense.CategoryName,
                            CategoryId      = category.Id,
                            PaidPartyId     = mainAccount.Id,
                            PaidToId        = othersAccount.Id,
                            Amount          = categoryWiseExpense.TotalAmount,
                            TransactionDate = new DateTime(year, month, 1),
                            IsExpense       = true,
                            IsAutoGenerated = true
                        };

                        await _transactionService.PostTransaction(transaction);
                    }

                    categoryWiseExpense.TransactionDetails = new List <TransactionDetailDto>
                    {
                        new TransactionDetailDto
                        {
                            TransactionDetailName = categoryWiseExpense.CategoryName,
                            Amount = categoryWiseExpense.TotalAmount
                        }
                    };
                }

                monthlyTotal += categoryWiseExpense.TotalAmount;

                if (category.Name != BillCategory.DEPOSIT.ToString() && category.Name != BillCategory.BILLPAYMENT.ToString())
                {
                    categoryWiseExpensesList.Add(categoryWiseExpense);
                }
            }

            monthlyBill.CategoryWiseExpenses = categoryWiseExpensesList;

            monthlyBill.SubTotal = monthlyTotal;

            return(monthlyBill);
        }
Ejemplo n.º 28
0
        public static async Task <List <Transaction> > FetchTransactionsByFilter(TransactionsFilter filter)
        {
            CommerceEntities dbContext = BuildDBContext();

            var query = from auth in dbContext.Authorizations
                        join tr in dbContext.TransactionLinks on auth.ClaimedDealId equals tr.Id
                        join merchants in dbContext.Merchants on auth.MerchantNameId equals merchants.Id
                        join cards in dbContext.Cards on tr.CardId equals cards.Id
                        join cardBrands in dbContext.CardBrands on cards.CardBrand equals cardBrands.Id
                        join offers in dbContext.Offers on tr.DealId equals offers.Id
                        join users in dbContext.Users on tr.UserId equals users.Id
                        orderby tr.DateAdded descending
                        select new Transaction
            {
                TransactionLinkId = tr.Id,
                DateAdded         = auth.DateAdded,
                MerchantId        = merchants.Id,
                MerchantName      = merchants.Name,
                TransactionTypeId = offers.OfferType,
                TransactionType   = offers.OfferType == EarnTransactionType ? "Earn" : "Burn",
                Percent           = offers.PercentBack,
                TransactionAmount = Math.Round((double)auth.TransactionAmount / 100, 2),
                DiscountAmount    = Math.Round((double)auth.DiscountAmount / 100, 2),
                LastFourDigits    = cards.LastFourDigits,
                CardBrandId       = cards.CardBrand,
                CardBrandName     = cardBrands.Name,
                UserGlobalId      = users.GlobalId
            };

            if (filter.StartDate.HasValue && filter.EndDate.HasValue)
            {
                query = query.Where(x => filter.StartDate <= x.DateAdded && x.DateAdded < filter.EndDate);
            }

            if (filter.TransactionTypes != null && filter.TransactionTypes.Any())
            {
                query = query.Where(x => filter.TransactionTypes.Contains(x.TransactionTypeId));
            }

            if (filter.CardBrandIds != null && filter.CardBrandIds.Any())
            {
                query = query.Where(x => filter.CardBrandIds.Contains(x.CardBrandId));
            }

            if (!string.IsNullOrWhiteSpace(filter.Last4Digits))
            {
                query = query.Where(x => x.LastFourDigits == filter.Last4Digits);
            }

            if (!string.IsNullOrWhiteSpace(filter.MerchantName) && filter.MerchantName != AllMerchants)
            {
                query = query.Where(x => x.MerchantName == filter.MerchantName);
            }

            if (filter.UserId.HasValue)
            {
                query = query.Where(x => x.UserGlobalId == filter.UserId);
            }

            query = query.OrderBy(x => x.DateAdded);

            return(await query.ToListAsync());
        }
        public async Task <ActionResult <IEnumerable <TransactionListItemDTO> > > Get([FromQuery] TransactionsFilter filter)
        {
            var transactions = await this.transactionService.GetTransactionsAsync(filter);

            return(Ok(transactions.ToList()));
        }
Ejemplo n.º 30
0
        public async Task <ICollection <Transaction> > GetTransactionsAsync(TransactionsFilter filter = null)
        {
            var query = this.Context.Transactions
                        .Include(p => p.Category)
                        .Include(p => p.Account)
                        .ThenInclude(p => p.Currency)
                        .Include(p => p.TagsToTransaction)
                        .ThenInclude(p => p.Tag)
                        .Include(p => p.ToTransfers)
                        .Include(p => p.FromTransfers)
                        .Include(p => p.FilesToTransaction)
                        .ThenInclude(p => p.File)
                        .AsQueryable();


            if (filter != null && filter.AccountsIds != null && filter.AccountsIds.Any())
            {
                var accounts = await this.accountRepository.GetSubAccountsAsync(filter.AccountsIds);

                accounts.AddRange(filter.AccountsIds);
                accounts = accounts.Distinct().ToList();

                query = query.Where(q => accounts.Contains(q.AccountId)).AsQueryable();
            }
            else if (filter != null && filter.AccountsExternalIds != null && filter.AccountsExternalIds.Any())
            {
                var accounts = await this.accountRepository.GetSubAccountsAsync(filter.AccountsExternalIds);

                accounts.AddRange(filter.AccountsExternalIds);
                accounts = accounts.Distinct().ToList();

                query = query.Where(q => accounts.Contains(q.Account.ExternalId)).AsQueryable();
            }
            else
            {
                query = query.Where(q => q.Account.OwnerId == userIdentityContext.UserId).AsQueryable();
            }

            if (filter != null && filter.CategoryIds != null && filter.CategoryIds.Any())
            {
                query = query.Where(q => filter.CategoryIds.Contains(q.CategoryId)).AsQueryable();
            }

            if (filter != null && filter.TagIds != null && filter.TagIds.Any())
            {
                query = (from transaction in query
                         join t2t in this.Context.TagsToTransactions on transaction.Id equals t2t.TransactionId
                         where filter.TagIds.Contains(t2t.TagId)
                         select transaction).AsQueryable();
            }


            if (filter != null)
            {
                if (!filter.IncludeDeleted)
                {
                    query = query.Where(q => q.IsDeleted == false).AsQueryable();
                }


                if (filter.FromDate != null)
                {
                    query = query.Where(q => q.Date >= filter.FromDate).AsQueryable();
                }

                if (filter.ToDate != null)
                {
                    query = query.Where(q => q.Date <= filter.ToDate).AsQueryable();
                }

                if (filter.ChangedSince != null)
                {
                    query = query.Where(q => q.CreatedOn >= filter.ChangedSince || q.ModifiedOn >= filter.ChangedSince).AsQueryable();
                }
            }
            else
            {
                query = query.Where(q => q.IsDeleted == false).AsQueryable();
            }

            var temporary = await query.ToListAsync();

            var transactionsWithExtraProperty = (await(from t in query
                                                       orderby t.Date descending
                                                       select new
            {
                t,
                IsTransfer = t.ToTransfers.Any() || t.FromTransfers.Any(),
            })
                                                 .ToListAsync());

            transactionsWithExtraProperty.ForEach(x => x.t.IsTransfer = x.IsTransfer);
            var transactions = transactionsWithExtraProperty.Select(x => x.t).ToList();

            return(transactions);
        }