/// <summary>
        /// Calculates the savings plan for the given <paramref name="tag"/>.
        /// </summary>
        /// <param name="tag">The tag.</param>
        public ISavingsPlan CalculateSavingsPlan(string tag)
        {
            var savingsPlan = new SavingsPlan {
                Tag = tag, Date = DateTime.Now
            };

            var yearQuery = new TransactionYearsQuery()
                            .Register(new TransactionStartDateFilter(DateTime.MinValue))
                            .Register(new TransactionEndDateFilter(_dateCalculationService.GetEndOfToDay()))
                            .Register(new TransactionTagFilter(tag))
                            .Register(new TransactionDividendFilter(true));

            var years = _queryDispatcher.Execute(yearQuery).ToList();

            foreach (var year in years)
            {
                var period = new SavingsPlanPeriod()
                {
                    Year = year.ToString()
                };

                //Time period
                var start       = _dateCalculationService.GetStartAndEndDateOfYear(new DateTime(year, 1, 1), out DateTime end);
                var lastYearEnd = _dateCalculationService.GetEndDateOfYear(new DateTime(years[0] - 1, 1, 1));

                //Only this year
                var actualPeriodResult = CalculateCurrentPeriod(start, end, tag);

                period.PerformanceActualPeriodPercentage = actualPeriodResult.PerformanceActualPeriodPercentage;
                period.SumDividends = actualPeriodResult.SumDividends;

                //Accumulated till this end of year
                var periodResult = CalculateOverallPeriod(lastYearEnd, end, tag);

                period.SumOrderCostsPercentage = periodResult.SumOrderCostsPercentage;
                period.SumOrderCosts           = periodResult.SumOrderCosts;
                period.SumInpayment            = periodResult.SumInpayment;
                period.SumCapital = periodResult.SumCapital;
                period.PerformanceOverallPeriodPercentage = periodResult.PerformanceOverallPeriodPercentage;
                period.SumOverallDividends           = periodResult.SumOverallDividends;
                period.SumOverallDividendsPercentage = decimal.Round((periodResult.SumOverallDividends / periodResult.SumInpayment) * 100, 2);
                period.IsCurrentYear = DateTime.Now.Year == year;
                period.IsForecast    = false;

                savingsPlan.Periods.Add(period);
            }

            //Forecast
            if (savingsPlan.Periods.Any())
            {
                var startYear             = years.Max() + 1;
                var amountOfForecastYears = years.Min() + 35 - startYear;
                foreach (ISavingsPlanPeriod forecast in GetTagPeriodForecast(amountOfForecastYears, startYear, savingsPlan.Periods))
                {
                    savingsPlan.Periods.Add(forecast);
                }
            }

            return(savingsPlan);
        }
Beispiel #2
0
 public async Task <GetBudgetByIdQuery.Result> Budget(Guid id)
 {
     return(await _queryDispatcher.Execute <GetBudgetByIdQuery, GetBudgetByIdQuery.Result>(new GetBudgetByIdQuery
     {
         KeyId = id
     }));
 }
Beispiel #3
0
        public IEnumerable <User> Get()
        {
            var allUser = new AllUserQuery();
            var users   = _queryDispatcher.Execute <AllUserQuery, IEnumerable <User> >(allUser);

            return(users);
        }
        // GET: Feedback
        public IActionResult Index()
        {
            ViewBag.Proportion = Mapper.Map <IEnumerable <FeedbackProportionViewModel> >(
                _queryDispatcher.Execute(new FeedbackProportionAllQuery())).ToDictionary(f => f.Id, f => f);


            return(View(Mapper.Map <IEnumerable <FeedbackViewModel> >(_queryDispatcher.Execute(new FeedbackAllQuery()))));
        }
Beispiel #5
0
        public async Task AddComment(int articleId, string text, string userId)
        {
            var article = await _queryDispatcher.Execute <GetArticleById, Article>(new GetArticleById(articleId));

            var result = await Task.Run(() => _commandDispatcher.Execute(new AddComment(text, userId, article, DateTime.Now)));

            _logger.LogInformation($"User with Id {userId} add comment {result.Success}");
        }
        public ActionResult <AtividadesDto> Get()
        {
            var listarAtividade = new ListarAtividades()
            {
                Concluida = false
            };

            return(_dispatcher.Execute <ListarAtividades, AtividadesDto>(listarAtividade));
        }
        public IActionResult GetHashtagHistory(string hashtag, int pageNumber)
        {
            var query = new GetHashtgHistoryQuery(hashtag, pageNumber);

            var result =
                _queryDispatcher.Execute <GetHashtgHistoryQuery, GetHashtagHistoryQueryResult>(query);

            return(Ok(result.HashtagHistoryModel));
        }
Beispiel #8
0
 public ActionResult CandlestickChartQuoteDataByStockId(Guid id)
 {
     return(Json(_queryDispatcher.Execute(new StockQuotationsByIdQuery(id)).Select(
                     q => new object[]
     {
         _dateCalculationService.ConvertToEpochTimeInMilliseconds(q.Date), q.Open, q.High, q.Low, q.Close
     })
                 .ToArray(), JsonRequestBehavior.AllowGet));
 }
Beispiel #9
0
        // GET: Dashboard
        public IActionResult Index()
        {
            var model = new DashboardViewModel();

            var statistics =
                _queryDispatcher.Execute(new StatisticsByTimeSliceQuery(_timeSliceCreationService.CreateTimeSlices(), TimeSliceType.All));

            model.Cards         = _statisticCardConverterRepository.ConvertStatistic(statistics.FirstOrDefault(s => s.TimeSlice.Type.Equals(TimeSliceType.All)));
            model.OpenPositions = Mapper.Map <OpenPositionsViewModel>(_transactionCalculationService.CalculateOpenPositions());

            return(View(model));
        }
Beispiel #10
0
        // GET: Dashboard
        public ActionResult Index()
        {
            var model = new DashboardViewModel();

            var statistic =
                _queryDispatcher.Execute(new StatisticsByTimeSliceQuery(_timeSliceCreationService.CreateTimeSlices()));

            model.Cards = _statisticCardConverterRepository.ConvertStatistic(statistic);
            //NOTE: Cache disabled because of IQuotation overrides Equals and only date is taken into account
            model.OpenPositions = Mapper.Map <OpenPositionsViewModel>(_transactionCalculationService.CalculateOpenPositions(), o => o.DisableCache = true);

            return(View(model));
        }
        public TransactionsProvider(IQueryDispatcher queryDispatcher)
        {
            //lets cache categories [needed after not loading full categories in transaction query]:
            Mapper.Map <Category[]>(queryDispatcher.Execute <CategoryQuery, Data.DTO.Category[]>(new CategoryQuery()));

            var query = new TransactionQuery();

            DtoTransaction[] dtos = null;
            using (new MeasureTimeWrapper(() => dtos = queryDispatcher.Execute <TransactionQuery, DtoTransaction[]>(query), "query transactions")) { }

            Transaction[] transactions = null;
            using (new MeasureTimeWrapper(() => transactions = Mapper.Map <Transaction[]>(dtos), $"map transactions [{dtos.Length}]")) { }
            using (new MeasureTimeWrapper(() => AllTransactions = new TrulyObservableCollection <Transaction>(transactions), "create tru. ob. coll")) { }
        }
        public IActionResult UpdateQuotationByWkn(string wkn)
        {
            var stock = _queryDispatcher.Execute(new StockByWknQuery(wkn));

            if (stock == null)
            {
                return(Json(new UpdateQuotationStatusViewModel()
                {
                    Message = Resources.NoSuchStock,
                    Successfull = false
                }));
            }

            return(UpdateQuotation(stock.Id));
        }
Beispiel #13
0
        public GetPersonModule(IQueryDispatcher queryDispatcher) : base("/api/v1/")
        {
            Get["/persons/{id}"] = parameters =>
            {
                GetPersonQuery query = null;
                try
                {
                    query = this.Bind <GetPersonQuery>();
                }
                catch (ModelBindingException e)
                {
                    return(Response.AsText(e.Message).WithStatusCode(HttpStatusCode.BadRequest));
                }

                PersonDto person = null;
                try
                {
                    person = queryDispatcher.Execute <GetPersonQuery, PersonDto>(query);
                }
                catch (Exception e)
                {
                    return(Response.AsText(e.Message).WithStatusCode(HttpStatusCode.InternalServerError));
                }


                return(person == null?Response.AsText("").WithStatusCode(HttpStatusCode.NotFound)
                           : Response.AsJson(person).WithStatusCode(HttpStatusCode.OK));
            };
        }
Beispiel #14
0
        /// <summary>
        /// Executes this job.
        /// </summary>
        public void Execute()
        {
            //TODO: Duplicate code, see QuotationController.UpdateQuotation

            Status = ScheduledJobStatus.Running;

            try
            {
                foreach (var stock in _queryDispatcher.Execute(new StockAllQuery()))
                {
                    var latestUpdate = stock.Quotations != null && stock.Quotations.Any() ? stock.Quotations.Max(q => q.Changed) : DateTime.MinValue;

                    var quotations = _quotationServiceClient.Get(stock.Id, latestUpdate.Date).ToList();

                    if (quotations.Any())
                    {
                        var cmd = new StockQuotationsAddOrChangeCommand(
                            stock.Id,
                            stock.OriginalVersion,
                            quotations);

                        _commandDispatcher.Execute(cmd);
                    }
                }
            }
            finally
            {
                Status = ScheduledJobStatus.Stopped;
            }
        }
Beispiel #15
0
        /// <summary>
        /// Creates the time slices which are affected by the given <paramref name="date"/>
        /// </summary>
        /// <param name="date">The date.</param>
        /// <returns></returns>
        public ITimeSlice CreateTimeSlices(DateTime date)
        {
            var minOrderDate = _queryDispatcher.Execute(new TransactionMinimumOrderDateQuery());
            var maxOrderDate = _queryDispatcher.Execute(new TransactionMaximumOrderDateQuery());

            if (minOrderDate == DateTime.MinValue || maxOrderDate == DateTime.MaxValue)
            {
                return(new AllTimeSlice(DateTime.MinValue, DateTime.MaxValue));
            }

            var allSlice = new AllTimeSlice(_dateCalculationService.GetStartDateOfYear(minOrderDate), _dateCalculationService.GetEndDateOfYear(maxOrderDate));

            CreateYears(allSlice, date);

            return(allSlice);
        }
Beispiel #16
0
        public IActionResult Get(string superHero, string villain, int battlegroundId)
        {
            var query  = new GetWinnerQuery(superHero, villain, battlegroundId);
            var winner = queryDispatcher.Execute <GetWinnerQuery, GetWinnerQueryResult>(query);

            return(new OkObjectResult(winner));
        }
        public IActionResult GetUser([FromBody] RetriveUserQuery query)
        {
            try {
                User user = _queryDispatcher.Execute <RetriveUserQuery, User>(query);
                if (user == null)
                {
                    return(BadRequest(UserNotFound));
                }

                return(Ok(user));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Beispiel #18
0
        public async Task <GetUserQuery.Result> Post([FromBody] GetUserQuery userQuery)
        {
            var user = await _queryDispatcher.Execute <GetUserQuery, GetUserQuery.Result>(new GetUserQuery
            {
                UserName = userQuery.UserName,
                Password = userQuery.Password
            });

            return(user);
        }
Beispiel #19
0
        /// <summary>
        /// Returns the quote of the given stock by <paramref name="wkn"/>
        /// </summary>
        /// <param name="wkn">The wkn of the stock</param>
        public decimal GetQuote(string wkn)
        {
            var stock = _queryDispatcher.Execute(new StockByWknQuery(wkn));

            if (stock == null || !stock.Quotations.Any())
            {
                return(default(decimal));
            }

            return(stock.Quotations.Any() ? stock.Quotations.Aggregate((i1, i2) => i1.Date > i2.Date ? i1 : i2).Close : default(decimal));
        }
        public void Update()
        {
            var query    = new SearchStateQuery();
            var searches = Mapper.Map <SearchState[]>(_queryDispatcher.Execute <SearchStateQuery, DtoSearch[]>(query).OrderBy(x => x.InstanceCreationDate));

            foreach (var balance in CustomBalances)
            {
                var input = searches.Select(x => new Selectable(x)).ToArray();
                balance.SearchesPicker.SetInput(input, input.Where(x => balance.Searches.Contains(x.Value)));
            }
        }
        public CustomBalanceManagerViewModel(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher)
        {
            _queryDispatcher   = queryDispatcher;
            _commandDispatcher = commandDispatcher;

            AddCustomBalanceCommand = new RelayCommand(() =>
            {
                var item  = new CustomBalance(string.Empty);
                var query = new SearchStateQuery();
                item.SearchesPicker.SetInput(Mapper.Map <SearchState[]>(_queryDispatcher.Execute <SearchStateQuery, DtoSearch[]>(query)).Select(x => new Selectable(x)));
                CustomBalances.Add(item);
            });
            RemoveCustomBalanceCommand = new RelayCommand <CustomBalance>(ExecuteDeleteCommand);

            var customBalanceQuery = new CustomBalanceQuery();
            var customBalances     = _queryDispatcher.Execute <CustomBalanceQuery, DtoCustomBalance[]>(customBalanceQuery);

            CustomBalances = new TrulyObservableCollection <CustomBalance>(Mapper.Map <CustomBalance[]>(customBalances));
            CustomBalances.CollectionChanged += CustomBalancesOnCollectionChanged;
        }
Beispiel #22
0
        public async Task <IEnumerable <WeatherForecast> > Execute()
        {
            var query    = new ListAllWeatherForecastQuery();
            var entities = await _queryDispatcher.Execute <ListAllWeatherForecastQuery, IEnumerable <WeatherForecastEntity> >(query);

            var result = new List <WeatherForecast>(entities.Count());

            entities.ForEach(entity => result.Add(_mapper.Map <WeatherForecastEntity, WeatherForecast>(entity)));

            return(result);
        }
Beispiel #23
0
        public async Task <WeatherForecast> Execute(Guid id)
        {
            var query  = new GetWeatherForecastByIdQuery(id);
            var entity = await _queryDispatcher.Execute <GetWeatherForecastByIdQuery, WeatherForecastEntity>(query);

            if (entity == null)
            {
                throw new NotFoundException($"No weather forecast found with ID = '{id}'.");
            }

            return(_mapper.Map <WeatherForecastEntity, WeatherForecast>(entity));
        }
        public void Update()
        {
            var stocks = Mapper.Map <Stock[]>(_queryDispatcher.Execute <StockQuery, DtoStock[]>(new StockQuery()))
                         .OrderBy(x => x.InstanceCreationDate)
                         .ToArray();

            Stocks = new TrulyObservableCollection <Stock>(stocks);
            foreach (var stock in Stocks)
            {
                stock.Balance.PropertyChanged += BalanceOnPropertyChanged;
            }
            Stocks.CollectionChanged += StocksOnCollectionChanged;
        }
Beispiel #25
0
        /// <summary>
        /// Calculates the sum of all inpayments for the given transactions.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns>Sum of inpayments</returns>
        public decimal CalculateSumInpayments(IQuery <IEnumerable <ITransaction> > query)
        {
            var transactions = _queryDispatcher.Execute(query);

            var sum = default(decimal);

            foreach (var tr in transactions)
            {
                if (tr is IBuyingTransaction)
                {
                    sum += tr.PositionSize - tr.OrderCosts;
                }
            }

            return(sum);
        }
Beispiel #26
0
        public MassReplacerViewModel(IQueryDispatcher queryDispatcher, ICommandDispatcher commandDispatcher, ViewModelFactory factory, IMessagesService messagesService)
        {
            _queryDispatcher   = queryDispatcher;
            _commandDispatcher = commandDispatcher;
            _messagesService   = messagesService;
            State                 = new ReplacerState();
            SearchViewModel       = factory.Create <SearchViewModel>();
            PerformReplaceCommand = new RelayCommand(ExecutePerformCommand, CanExecutePerformCommand);
            ApplyReverseReplaceSearchStateCommand = new RelayCommand(() =>
                                                                     SearchViewModel.State.ApplyReverseReplaceCriteria(State), () => _transactionSetters.Any(x => x.CanExecute()));

            _transactionSetters = new ISetter <Model.Transaction>[]
            {
                TextSetterCommand.Create(State.TitleSelector, SearchViewModel.State.TitleFilter),
                TextSetterCommand.Create(State.NoteSelector, SearchViewModel.State.NoteFilter),
                TextSetterCommand.Create(State.PositionTitleSelector, SearchViewModel.State.PositionTitleFilter),
                DateSetterCommand.Create(State.BookDateSetter),
                SingleSetterCommand.Create(State.CategoriesSelector),
                SingleSetterCommand.Create(State.UserStocksSelector),
                SingleSetterCommand.Create(State.ExternalStocksSelector),
                SingleSetterCommand.Create(State.TypesSelector),
                MultiSetterCommand.Create(State.TagsSelector)
            };
            _positionSetter = _transactionSetters.OfType <ISetter <Model.Position> >().ToArray();

            MassReplacerSaveCommand = new RelayCommand <string>(name =>
            {
                State.Name        = name;
                State.SearchState = SearchViewModel.State;
                var state         = Mapper.Map <MassReplacerState>(State);
                _commandDispatcher.Execute(new UpsertReplacerStateCommand(state));

                var mapped = Mapper.Map <ReplacerState>(state);
                Patterns.Remove(mapped);
                Patterns.Add(mapped);
            }, name => !string.IsNullOrWhiteSpace(name));
            MassReplacerLoadCommand = new RelayCommand <BaseObservableObject>(selected =>
            {
                var state = selected as ReplacerState;
                ApplyState(state);
            }, selected => selected != null);

            ClearMassReplacerStateCommand = new RelayCommand(() => State.Clear());

            var patterns = _queryDispatcher.Execute <ReplacerStateQuery, MassReplacerState[]>(new ReplacerStateQuery())
                           .OrderBy(x => x.Name);

            Patterns = new ObservableCollection <BaseObservableObject>(Mapper.Map <ReplacerState[]>(patterns));
        }
Beispiel #27
0
        /// <summary>
        /// Returns a list with all items
        /// </summary>
        /// <returns>Items</returns>
        public IEnumerable <SelectListItem> GetItems()
        {
            var items = new List <SelectListItem>();

            var types = _queryDispatcher.Execute(new StockTypeInUseSearchQuery(string.Empty)).Take(10);

            items.Add(new SelectListItem {
                Text = Resources.ViewTextFilterAll, Value = ""
            });
            items.AddRange(types.Select(stock => new SelectListItem {
                Text = stock, Value = stock
            }));

            return(items);
        }
Beispiel #28
0
        public IActionResult GetSurveys()
        {
            string userIdStr = User.FindFirstValue(CustomClaimType.UserId);
            int    userId;

            if (String.IsNullOrEmpty(userIdStr) || !int.TryParse(userIdStr, out userId))
            {
                return(Ok(new ErrorServiceRespose("User id in token is invalid")));
            }

            var query = new SurveyListPageQuery()
            {
                UserId = userId
            };

            QueryResult <SurveyListItem[]> result =
                _queryDispatcher.Execute <SurveyListPageQuery, SurveyListItem[]>(query);

            if (result.IsSuccess)
            {
                return(Ok(new OkServiceResponse <SurveyListItem[]>(result.Value)));
            }
            return(BadRequest(result.Error));
        }
Beispiel #29
0
        public async Task Execute(Guid id, UpdateWeatherForecastRequest input, string username)
        {
            var query  = new GetWeatherForecastByIdQuery(id);
            var entity = await _queryDispatcher.Execute <GetWeatherForecastByIdQuery, WeatherForecastEntity>(query);

            if (entity == null)
            {
                throw new NotFoundException($"No weather forecast found with ID = '{id}'.");
            }

            entity.Temperature = input.TemperatureInCelsius;
            entity.Date        = input.Date;
            entity.Summary     = input.Summary;

            var command = new UpdateWeatherForecastCommand(entity, username);
            await _commandDispatcher.Execute(command);
        }
        public IActionResult GetPrices([FromBody] RetriveMineralPricesQuery query)
        {
            IEnumerable <MineralPriceData> MpdCollection = null;

            try {
                MpdCollection = _queryDispatcher
                                .Execute <RetriveMineralPricesQuery, IEnumerable <MineralPriceData> >(query);
                if (MpdCollection == null)
                {
                    return(BadRequest(NoMpdMessage));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            return(Ok(MpdCollection));
        }