Exemplo n.º 1
0
        public async Task <ActionResult <StudentDto> > GetAsync(Guid?id)
        {
            if (id is null)
            {
                return(BadRequest("Corrupted Id"));
            }

            return((await _studentCrudService.GetByIdAsync(id.Value)).ToDto());
        }
Exemplo n.º 2
0
 public virtual async Task <ActionResult <T2> > GetById(T1 id)
 {
     try
     {
         return(Ok(await _service.GetByIdAsync(id)));
     }
     catch (EntityNotFoundException)
     {
         return(NotFound());
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// 创建,调用范例:POST URL(/api/customers) BODY({name:'a',age:2})
        /// </summary>
        /// <param name="dto">数据传输对象</param>
        /// <returns></returns>
        public virtual async Task <IActionResult> CreateAsync([FromBody] TDto dto)
        {
            if (dto == null)
            {
                return(Fail("请求参数不能为空"));
            }
            CreateBefore(dto);
            await _service.CreateAsync(dto);

            var result = await _service.GetByIdAsync(dto.Id);

            return(Success(result));
        }
        private async Task <IRatingCalculator> GetCalculatorAsync(string storeId)
        {
            var store = await _storeService.GetByIdAsync(storeId, StoreResponseGroup.Full.ToString());

            if (store == null)
            {
                throw new KeyNotFoundException($"Store not found, storeId: {storeId}");
            }

            var calculatorName = store.Settings.GetSettingValue(
                ModuleConstants.Settings.General.CalculationMethod.Name,
                ModuleConstants.Settings.General.CalculationMethod.DefaultValue.ToString());

            if (string.IsNullOrWhiteSpace(calculatorName))
            {
                throw new KeyNotFoundException($"Store settings not found: {ModuleConstants.Settings.General.CalculationMethod.Name}");
            }

            var ratingCalculator = _ratingCalculators.FirstOrDefault(c => c.Name == calculatorName);

            if (ratingCalculator == null)
            {
                throw new KeyNotFoundException($"{calculatorName} not found in DI container");
            }

            return(ratingCalculator);
        }
Exemplo n.º 5
0
        public async Task NotifyAsync(int notificationId, CancellationToken cancellationToken)
        {
            var notification = await _eventNotificationService.GetByIdAsync(notificationId);

            if (notification == null)
            {
                _logger.LogError($"Scheduled notification with Id {notificationId} is not found in database");
                return;
            }

            try
            {
                var chatId = new ChatId(notification.UserTelegramId);
                var msg    = await _botClient.SendTextMessageAsync(chatId, notification.Subject, cancellationToken : cancellationToken);

                _logger.LogDebug($"Sended scheduled notification {notificationId}");

                await _eventNotificationService.DeleteAsync(notificationId);

                _logger.LogDebug($"Deleted scheduled notification {notificationId}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error sending notification {notificationId}");
                throw;
            }
        }
        public static async Task <TModel> UpdateAndGetAsync <TModel>(this ICrudService <TModel> service, TModel data)
            where TModel : class, IBaseModel
        {
            await service.UpdateAsync(data);

            return(await service.GetByIdAsync(data.Id));
        }
Exemplo n.º 7
0
        public async Task <CartAggregate> GetCartByIdAsync(string cartId, string language = null)
        {
            var cart = await _shoppingCartService.GetByIdAsync(cartId);

            if (cart != null)
            {
                return(await InnerGetCartAggregateFromCartAsync(cart, language ?? Language.InvariantLanguage.CultureName));
            }
            return(null);
        }
        public async Task <IActionResult> GetByIdAsync(int id)
        {
            var result = await _service.GetByIdAsync(id);

            if (result == default)
            {
                return(NotFound());
            }
            return(Ok(_mapper.Map <UserModel>(result)));
        }
Exemplo n.º 9
0
 public async Task <IActionResult> GetById(Guid id)
 {
     try
     {
         return(Ok(await _service.GetByIdAsync(id)));
     }
     catch (EntityNotFoundException ex)
     {
         return(NotFound());
     }
 }
Exemplo n.º 10
0
        public async Task <ActionResult> GetById(string id)
        {
            var estudiante = await service.GetByIdAsync(id);

            if (estudiante == null)
            {
                return(NotFound());
            }

            return(Ok(estudiante));
        }
        /// <summary>
        /// Updates the asynchronous.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public virtual async Task <T2> UpdateAsync(T1 id, T2 entity)
        {
            var originalEntity = await _service.GetByIdAsync(id);

            var historicalEvent = new HistoricalEvent
            {
                Action    = HistoricalActions.Update.ToString(),
                Changeset = new HistoricalChangeset()
                {
                    ObjectData  = JsonConvert.SerializeObject(originalEntity),
                    ObjectDelta = originalEntity.DetailedCompare(entity)
                },
                EntityId   = originalEntity.Id.ToString(),
                EntityName = entity.GetType().FullName
            };
            var modifiedEntity = await _service.UpdateAsync(id, entity);

            await _repository.CreateAsync <Guid, HistoricalEvent>(historicalEvent);

            await _repository.SaveChangesAsync();

            return(modifiedEntity);
        }
        protected async Task <PaymentInfo> GetPaymentInfo(PaymentCommandBase command)
        {
            var result = new PaymentInfo();

            if (!string.IsNullOrEmpty(command.OrderId))
            {
                result.CustomerOrder = await _customerOrderService.GetByIdAsync(command.OrderId, CustomerOrderResponseGroup.Full.ToString());

                result.Payment = result.CustomerOrder?.InPayments?.FirstOrDefault(x => x.Id == command.PaymentId);
            }
            else if (!string.IsNullOrEmpty(command.PaymentId))
            {
                result.Payment = await _paymentService.GetByIdAsync(command.PaymentId);

                result.CustomerOrder = await _customerOrderService.GetByIdAsync(result.Payment?.OrderId, CustomerOrderResponseGroup.Full.ToString());

                // take payment from order since Order payment contains instanced PaymentMethod (payment taken from service doesn't)
                result.Payment = result.CustomerOrder?.InPayments?.FirstOrDefault(x => x.Id == command.PaymentId);
            }

            result.Store = await _storeService.GetByIdAsync(result.CustomerOrder?.StoreId, StoreResponseGroup.StoreInfo.ToString());

            return(result);
        }
        public virtual async Task <CustomerOrderAggregate> Handle(CreateOrderFromCartCommand request, CancellationToken cancellationToken)
        {
            var cart = await _cartService.GetByIdAsync(request.CartId);

            await ValidateCart(cart);

            var result = await _customerOrderAggregateRepository.CreateOrderFromCart(cart);

            await _cartService.DeleteAsync(new List <string> {
                request.CartId
            }, softDelete : true);

            // Remark: There is potential bug, because there is no transaction thru two actions above. If a cart deletion fails, the order remains. That causes data inconsistency.
            // Unfortunately, current architecture does not allow us to support such scenarios in a transactional manner.
            return(result);
        }
Exemplo n.º 14
0
        protected virtual async Task SetNotificationParametersAsync(Notification pNotification, CustomerOrder pOrder, Member pCustomer)
        {
            var store = await _storeService.GetByIdAsync(pOrder.StoreId, StoreResponseGroup.StoreInfo.ToString());

            if (pNotification is EmailNotification emailNotification)
            {
                emailNotification.From = store.EmailWithName;
                emailNotification.To   = GetOrderRecipientEmail(pOrder, pCustomer);
            }

            // Allow to filter notification log either by customer order or by subscription
            if (string.IsNullOrEmpty(pOrder.SubscriptionId))
            {
                pNotification.TenantIdentity = new TenantIdentity(pOrder.Id, nameof(CustomerOrder));
            }
            else
            {
                pNotification.TenantIdentity = new TenantIdentity(pOrder.SubscriptionId, "Subscription");
            }
        }
Exemplo n.º 15
0
        public TeamQueries(ICrudService <Team> teamService, ILogger <TeamQueries> logger)
        {
            FieldAsync <ListGraphType <TeamQueryViewModel> >(
                "getAll",
                "Use this to get all the teams",
                new QueryArguments(),
                async context =>
            {
                try
                {
                    return(await teamService.GetAllAsync());
                }
                catch (Exception ex)
                {
                    logger.LogCritical(ex.Message, ex);
                    return(null);
                }
            });

            FieldAsync <TeamQueryViewModel>(
                "getById",
                "Use this to get team info",
                new QueryArguments(new QueryArgument <GuidGraphTypeCustom> {
                Name = "teamId"
            }),
                async context =>
            {
                try
                {
                    var teamId = context.GetArgument <Guid>("teamId");
                    return(await teamService.GetByIdAsync(teamId));
                }
                catch (Exception ex)
                {
                    logger.LogCritical(ex.Message, ex);
                    return(null);
                }
            });
        }
Exemplo n.º 16
0
        public PlanetQueries(ICrudService <Planet> planetService, ILogger <PlanetQueries> logger)
        {
            FieldAsync <ListGraphType <PlanetQueryViewModel> >(
                "getAll",
                "Use this to get all the planets",
                new QueryArguments(),
                async context =>
            {
                try
                {
                    return(await planetService.GetAllAsync());
                }
                catch (Exception ex)
                {
                    logger.LogCritical(ex.Message, ex);
                    return(null);
                }
            });

            FieldAsync <PlanetQueryViewModel>(
                "getById",
                "Use this to get planet info",
                new QueryArguments(new QueryArgument <GuidGraphTypeCustom> {
                Name = "planetId"
            }),
                async context =>
            {
                try
                {
                    var planetId = context.GetArgument <Guid>("planetId");
                    return(await planetService.GetByIdAsync(planetId));
                }
                catch (Exception ex)
                {
                    logger.LogCritical(ex.Message, ex);
                    return(null);
                }
            });
        }
Exemplo n.º 17
0
        public ShuttleQueries(ICrudService <Shuttle> shuttleService, ILogger <ShuttleQueries> logger)
        {
            FieldAsync <ListGraphType <ShuttleQueryViewModel> >(
                "getAll",
                "Use this to get all the shuttles",
                new QueryArguments(),
                async context =>
            {
                try
                {
                    return(await shuttleService.GetAllAsync());
                }
                catch (Exception ex)
                {
                    logger.LogCritical(ex.Message, ex);
                    return(null);
                }
            });

            FieldAsync <ShuttleQueryViewModel>(
                "getById",
                "Use this to get shuttle info",
                new QueryArguments(new QueryArgument <GuidGraphTypeCustom> {
                Name = "shuttleId"
            }),
                async context =>
            {
                try
                {
                    var shuttleId = context.GetArgument <Guid>("shuttleId");
                    return(await shuttleService.GetByIdAsync(shuttleId));
                }
                catch (Exception ex)
                {
                    logger.LogCritical(ex.Message, ex);
                    return(null);
                }
            });
        }
Exemplo n.º 18
0
        public ExplorationQueries(ICrudService <Exploration> explorationService, ILogger <ExplorationQueries> logger)
        {
            FieldAsync <ListGraphType <ExplorationQueryViewModel> >(
                "getAll",
                "Use this to get all the explorations",
                new QueryArguments(),
                async context =>
            {
                try
                {
                    return(await explorationService.GetAllAsync());
                }
                catch (Exception ex)
                {
                    logger.LogCritical(ex.Message, ex);
                    return(null);
                }
            });

            FieldAsync <ExplorationQueryViewModel>(
                "getById",
                "Use this to get exploration info",
                new QueryArguments(new QueryArgument <GuidGraphTypeCustom> {
                Name = "explorationId"
            }),
                async context =>
            {
                try
                {
                    var explorationId = context.GetArgument <Guid>("explorationId");
                    return(await explorationService.GetByIdAsync(explorationId));
                }
                catch (Exception ex)
                {
                    logger.LogCritical(ex.Message, ex);
                    return(null);
                }
            });
        }
Exemplo n.º 19
0
        public async Task <ActionResult <GroupDto> > UpdateAsync(GroupDto dto)
        {
            var entry = await _groupCrudService.GetByIdAsync(dto.Id);

            if (entry is null)
            {
                return(NotFound());
            }

            var validator = new DefaultGroupValidator();

            entry.SelectValidator(validator);
            entry.SetName(dto.Name);

            if (entry.HasErrors)
            {
                return(BadRequest(entry.ErrorsStrings));
            }

            await _groupCrudService.UpdateAsync(entry);

            return(Ok(entry.ToDto()));
        }
Exemplo n.º 20
0
 public async Task <IHttpActionResult> GetAsync([FromUri] Guid id) => await ExecuteAsync(async() => await _crudService.GetByIdAsync(id));
Exemplo n.º 21
0
        //página de detalhes da entidade
        public virtual async Task <IActionResult> Details(long id)
        {
            var entity = await _service.GetByIdAsync(id);

            return(View(_mapper.Map <TViewModel>(entity)));
        }
Exemplo n.º 22
0
 public virtual async Task <TDto> GetByIdAsync(TId id) => _mapper.Map <TDto>(await _service.GetByIdAsync(id));
Exemplo n.º 23
0
 public async Task <T2> GetByIdAsync(T1 id) => await _service.GetByIdAsync(id);
Exemplo n.º 24
0
        public virtual async Task <IActionResult> GetAsync(string id)
        {
            var result = await _service.GetByIdAsync(id);

            return(Success(result));
        }
        public async Task <ActionResult <PaymentMethod> > GetPaymentMethodById(string id)
        {
            var result = await _paymentMethodCrudService.GetByIdAsync(id, null);

            return(Ok(result));
        }
Exemplo n.º 26
0
 public virtual async Task <T> GetByIdAsync(Guid id) => await _service.GetByIdAsync(id);
Exemplo n.º 27
0
        public virtual async Task <SearchProductResponse> Handle(SearchProductQuery request, CancellationToken cancellationToken)
        {
            var allStoreCurrencies = await _storeCurrencyResolver.GetAllStoreCurrenciesAsync(request.StoreId, request.CultureName);

            var currency = await _storeCurrencyResolver.GetStoreCurrencyAsync(request.CurrencyCode, request.StoreId, request.CultureName);

            var store = await _storeService.GetByIdAsync(request.StoreId);

            var responseGroup = EnumUtility.SafeParse(request.GetResponseGroup(), ExpProductResponseGroup.None);

            var builder = new IndexSearchRequestBuilder()
                          .WithCurrency(currency.Code)
                          .WithFuzzy(request.Fuzzy, request.FuzzyLevel)
                          .ParseFilters(_phraseParser, request.Filter)
                          .WithSearchPhrase(request.Query)
                          .WithPaging(request.Skip, request.Take)
                          .AddObjectIds(request.ObjectIds)
                          .AddSorting(request.Sort)
                          .WithIncludeFields(IndexFieldsMapper.MapToIndexIncludes(request.IncludeFields).ToArray());

            if (request.ObjectIds.IsNullOrEmpty())
            {
                AddDefaultTerms(builder, store.Catalog);
            }

            var criteria = new ProductIndexedSearchCriteria
            {
                StoreId      = request.StoreId,
                Currency     = request.CurrencyCode ?? store.DefaultCurrency,
                LanguageCode = store.Languages.Contains(request.CultureName) ? request.CultureName : store.DefaultLanguage,
                CatalogId    = store.Catalog
            };

            //Use predefined  facets for store  if the facet filter expression is not set
            if (responseGroup.HasFlag(ExpProductResponseGroup.LoadFacets))
            {
                var predefinedAggregations = await _aggregationConverter.GetAggregationRequestsAsync(criteria, new FiltersContainer());

                builder.WithCultureName(criteria.LanguageCode);
                builder.ParseFacets(_phraseParser, request.Facet, predefinedAggregations)
                .ApplyMultiSelectFacetSearch();
            }

            var searchRequest = builder.Build();
            var searchResult  = await _searchProvider.SearchAsync(KnownDocumentTypes.Product, searchRequest);

            var resultAggregations = await ConvertResultAggregations(criteria, searchRequest, searchResult);

            searchRequest.SetAppliedAggregations(resultAggregations.ToArray());

            var products = searchResult.Documents?.Select(x => _mapper.Map <ExpProduct>(x)).ToList() ?? new List <ExpProduct>();

            var result = new SearchProductResponse
            {
                Query = request,
                AllStoreCurrencies = allStoreCurrencies,
                Currency           = currency,
                Store   = store,
                Results = products,
                Facets  = resultAggregations?.ApplyLanguageSpecificFacetResult(criteria.LanguageCode)
                          .Select(x => _mapper.Map <FacetResult>(x, options =>
                {
                    options.Items["cultureName"] = criteria.LanguageCode;
                })).ToList(),
                TotalCount = (int)searchResult.TotalCount
            };

            await _pipeline.Execute(result);

            return(result);

            async Task <Aggregation[]> ConvertResultAggregations(ProductIndexedSearchCriteria criteria, SearchRequest searchRequest, SearchResponse searchResult)
            {
                // Preconvert resulting aggregations to be properly understandable by catalog module
                var preconvertedAggregations = new List <AggregationResponse>();
                //Remember term facet ids to distinguish the resulting aggregations are range or term
                var termsInRequest = new List <string>(searchRequest.Aggregations.Where(x => x is TermAggregationRequest).Select(x => x.Id ?? x.FieldName));

                foreach (var aggregation in searchResult.Aggregations)
                {
                    if (!termsInRequest.Contains(aggregation.Id))
                    {
                        // There we'll go converting range facet result
                        var fieldName = new Regex(@"^(?<fieldName>[A-Za-z0-9]+)(-.+)*$", RegexOptions.IgnoreCase).Match(aggregation.Id).Groups["fieldName"].Value;
                        if (!fieldName.IsNullOrEmpty())
                        {
                            preconvertedAggregations.AddRange(aggregation.Values.Select(x =>
                            {
                                var matchId = new Regex(@"^(?<left>[0-9*]+)-(?<right>[0-9*]+)$", RegexOptions.IgnoreCase).Match(x.Id);
                                var left    = matchId.Groups["left"].Value;
                                var right   = matchId.Groups["right"].Value;
                                x.Id        = left == "*" ? $@"under-{right}" : x.Id;
                                x.Id        = right == "*" ? $@"over-{left}" : x.Id;
                                return(new AggregationResponse()
                                {
                                    Id = $@"{fieldName}-{x.Id}", Values = new List <AggregationResponseValue> {
                                        x
                                    }
                                });
                            }
                                                                                        ));
                        }
                    }
                    else
                    {
                        // This is term aggregation, should skip converting and put resulting aggregation as is
                        preconvertedAggregations.Add(aggregation);
                    }
                }

                //Call the catalog aggregation converter service to convert AggregationResponse to proper Aggregation type (term, range, filter)
                return(await _aggregationConverter.ConvertAggregationsAsync(preconvertedAggregations, criteria));
            }
        }
Exemplo n.º 28
0
        public virtual async Task <ActionResult <TDto> > GetAsync(int id, CancellationToken cancellationToken = default)
        {
            var entity = await _crudService.GetByIdAsync(id);

            return(entity == null?NotFound() : Ok(Mapper.Map <TDto>(entity)));
        }
        public async Task <ActionResult <ShippingMethod> > GetShippingMethodById(string id)
        {
            var result = await _shippingMethodsService.GetByIdAsync(id, null);

            return(Ok(result));
        }
Exemplo n.º 30
0
        public async Task <ActionResult <TaxProviderSearchResult> > GetTaxProviderById(string id)
        {
            var result = await _taxProviderService.GetByIdAsync(id, null);

            return(Ok(result));
        }