public async Task <EkApiKiosk> GetKioskAsync(int kioskId) { var kiosk = await _dbContext.Kiosks .Where(x => x.Id == kioskId && x.ApplicationType == KioskApplicationTypeEnum.EK) .Select(x => new EkApiKiosk() { Id = x.Id, Address = new EkApiAddress() { CountryCode = x.Address.Country.Alpha3, RegionCode = x.Address.State.Code, City = x.Address.City, AddressLine1 = x.Address.AddressLine1, AddressLine2 = x.Address.AddressLine2, } }) .FirstOrDefaultAsync(); if (kiosk == null) { throw EntityNotFoundException.Create <EkApiKiosk>(kioskId); } return(kiosk); }
/// <summary> /// Deletes the <see cref="TViewModel"/> with the specified identifier. /// </summary> /// <param name="id">The identifier.</param> /// <returns></returns> public async Task DeleteAsync(string id) { if (!await Repository.DeleteAsync(id, RequestAborted)) { throw EntityNotFoundException.Create <TEntity>(x => x.Id, id); } }
public override async Task <KioskVersionGetResponse> ExecuteAsync(EmptyRequest request) { var kioskId = _currentUser.Id; var kioskData = await _kioskManager.GetActiveKiosksQuery() .Where(x => x.Id == kioskId) .Select(x => new { x.ApplicationType, x.AssignedKioskVersion, }) .FirstOrDefaultAsync(); if (kioskData == null) { throw EntityNotFoundException.Create <Entities.Kiosk>(kioskId); } var response = new KioskVersionGetResponse() { AssignedKioskVersion = kioskData.AssignedKioskVersion, }; if (!string.IsNullOrEmpty(response.AssignedKioskVersion)) { response.AssignedKioskVersionUpdateUrl = await _kioskVersionUpdateManager.GetUpdateUrlAsync( kioskData.ApplicationType, response.AssignedKioskVersion); } return(response); }
/// <summary> /// Updates the breakfast review with the specified identifier. /// </summary> /// <param name="id">The identifier.</param> /// <param name="request">The request.</param> /// <returns></returns> public async Task <BreakfastReviewViewModel> UpdateRatingAsync(string id, UpdateBreakfastReviewRatingRequest request) { var result = await Repository.UpdateRatingAsync(id, request.Rating); if (result == null) { throw EntityNotFoundException.Create <BreakfastReview>(x => x.Id, id); } return(Mapper.Map <BreakfastReviewViewModel>(result)); }
/// <summary> /// Gets the <see cref="TViewModel"/> with the specified identifier. /// </summary> /// <param name="id">The identifier.</param> /// <returns></returns> public async Task <TViewModel> GetAsync(string id) { var item = await Repository.GetAsync(id, RequestAborted); if (item == null) { throw EntityNotFoundException.Create <TEntity>(x => x.Id, id); } return(Mapper.Map <TViewModel>(item)); }
/// <summary> /// Gets the breakfast item with the specified name. Or <c>null</c> if none exist. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public async Task <BreakfastItemViewModel> GetByNameAsync(string name) { var item = await Repository.GetByNameAsync(name, RequestAborted); if (item == null) { throw EntityNotFoundException.Create <BreakfastItem>(x => x.Name, name); } return(Mapper.Map <BreakfastItemViewModel>(item)); }
public async Task <KioskConfiguration> GetKioskConfigurationAsync(int kioskId) { var kiosk = await _dbContext.Kiosks .AsNoTracking() .Include(x => x.Address) .Include(x => x.Customer) .Where(x => x.Id == kioskId) .FirstOrDefaultAsync(); if (kiosk == null) { throw EntityNotFoundException.Create <Kiosk>(kioskId); } var components = new List <ComponentConfiguration>(); ParseAndAddComponentConfigurations(components, kiosk.WorkflowComponentConfigurationsJson, kiosk.Id, nameof(kiosk.WorkflowComponentConfigurationsJson)); var kioskConfiguration = new KioskConfiguration() { KioskId = kiosk.Id, AppComponents = components.ToArray(), SupportPhone = kiosk.Customer.SupportPhone, LanguageCodes = GetConfigurationLanguageCodes(kiosk.CommaSeparatedLanguageCodes), KioskAddress = new KioskAddress() { AddressLine1 = kiosk.Address.AddressLine1, AddressLine2 = kiosk.Address.AddressLine2, City = kiosk.Address.City, }, }; // app-specific settings object specificSettings = null; switch (kiosk.ApplicationType) { case KioskApplicationTypeEnum.EK: specificSettings = new EkSettings() { EuropeCategories = EkCategoryHelper.GetEuropeCategories(), CarModelTree = EkCategoryHelper.GetCarModelTree(), }; break; } if (specificSettings != null) { kioskConfiguration.SpecificSettingsJson = JsonConvert.SerializeObject(specificSettings); } return(kioskConfiguration); }
public override async Task <PortalKioskStateDetailsGetResponse> ExecuteAsync(CommonDetailsGetRequest request) { if (request?.Id == null) { throw new ArgumentNullException(nameof(request.Id)); } var response = await _kioskManager.GetCurrentUserKiosksQuery() .Where(x => x.Id == request.Id.Value) .Select(x => new PortalKioskStateDetailsGetResponse { Form = new PortalKioskStateDetailsForm { Id = x.Id, KioskStateId = x.CurrentStateId, AddressLine1 = x.Address.AddressLine1, AddressLine2 = x.Address.AddressLine2, City = x.Address.City, Country = x.Address.Country.Alpha3, AssignedKioskVersion = x.AssignedKioskVersion, KioskStateVersion = x.CurrentState.KioskVersion, LastPingedOnUtc = x.LastPingedOnUtc, ComponentsStatuses = x.CurrentState.ComponentsStatuses != null ? x.CurrentState.ComponentsStatuses .OrderBy(componentState => componentState.ComponentName) .Select(componentState => new ComponentMonitorableState { Id = componentState.Id, ComponentName = componentState.ComponentName, Status = new ComponentStatus { Code = componentState.StatusCode, Message = componentState.StatusMessage }, SpecificMonitorableStateJson = componentState.SpecificMonitorableStateJson, }) .ToList() : new List <ComponentMonitorableState>() } }) .FirstOrDefaultAsync(); if (response == null) { throw EntityNotFoundException.Create <Entities.Kiosk>(request.Id.Value); } return(response); }
public async Task <Order> GetOrderAsync(int orderId) { var ekTransaction = await _dbContext.EkTransactions .AsNoTracking() .Where(x => x.Id == orderId && x.CompletionStatus == TransactionCompletionStatusEnum.Success) .FirstOrDefaultAsync(); if (ekTransaction == null) { throw EntityNotFoundException.Create <EkTransaction>(orderId); } return(ekTransaction.ToEkOrder()); }
private void ShouldSetNotFoundResultIfEntityNotFoundException() { EntityNotFoundException exception = EntityNotFoundException.Create <TestEntity, int>(); var exceptionContext = new ExceptionContext( new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), new List <IFilterMetadata>()) { Exception = exception }; var filter = new DomainExceptionFilter(); filter.OnException(exceptionContext); exceptionContext.Result.Should().BeEquivalentTo(new NotFoundObjectResult(new ErrorResponse(exception))); }
public override async Task <CommonDetailsPostResponse> ExecuteAsync(PortalCentralBankExchangeRateUpdateDetailsPostRequest request) { CentralBankExchangeRateUpdate entity; if (request.Form.Id == null) { entity = new CentralBankExchangeRateUpdate { CentralBankExchangeRateId = request.Form.CentralBankExchangeRateId }; _dbContext.CentralBankExchangeRateUpdates.Add(entity); } else { var entityId = request.Form.Id.Value; entity = await _dbContext.CentralBankExchangeRateUpdates .Where(x => x.Id == entityId && x.CentralBankExchangeRateId == request.Form.CentralBankExchangeRateId) .FirstOrDefaultAsync(); if (entity == null) { throw EntityNotFoundException.Create <CentralBankExchangeRate>(entityId); } } // check if it's not duplicate by time var updateWithTheSameTimeExists = await _dbContext.CentralBankExchangeRateUpdates .Where(x => x.CentralBankExchangeRateId == entity.CentralBankExchangeRateId && x.Id != request.Form.Id && x.StartTime == request.Form.StartDateTime) .AnyAsync(); if (updateWithTheSameTimeExists) { throw new InvalidOperationException($"A rate update with the same start date & time '{request.Form.StartDateTime.ToDateTimeString()}' already exists."); } UpdateFields(entity, request.Form); await _dbContext.SaveChangesAsync(); return(new CommonDetailsPostResponse { Id = entity.Id, }); }
public override async Task <EmptyResponse> ExecuteAsync(CommonDetailsDeleteRequest request) { var deletingItem = await _dbContext.CentralBankExchangeRateUpdates .Where(x => x.Id == request.Id) .FirstOrDefaultAsync(); if (deletingItem == null) { throw EntityNotFoundException.Create <CentralBankExchangeRate>(request.Id); } // remove _dbContext.CentralBankExchangeRateUpdates.Remove(deletingItem); await _dbContext.SaveChangesAsync(); return(new EmptyResponse()); }
public override async Task <ChangeUserRoleResponse> ChangeUserRole(ChangeUserRoleRequest request, ServerCallContext context) { var user = await dbContext.Users.FindIfNullThrowAsync(request.UserId); var project = await dbContext.Projects.FindIfNullThrowAsync(request.ProjectId); var assignment = await dbContext.UserProjectAssignments .FirstOrDefaultAsync(x => x.User == user && x.Project == project) ?? throw EntityNotFoundException.Create <UserProjectAssignment>($"UserId {request.UserId} and ProjectId {request.ProjectId}"); assignment.Role = (Domain.ValueObjects.UserRole)request.Role; await dbContext.SaveChangesAsync(); return(new ChangeUserRoleResponse { }); }
public override async Task <RemoveUserFromProjectResponse> RemoveUserFromProject(RemoveUserFromProjectRequest request, ServerCallContext context) { var user = await dbContext.Users.FindIfNullThrowAsync(request.UserId); var project = await dbContext.Projects.FindIfNullThrowAsync(request.ProjectId); var assignment = await dbContext.UserProjectAssignments .FirstOrDefaultAsync(x => x.User == user && x.Project == project) ?? throw EntityNotFoundException.Create <UserProjectAssignment>($"projectId {request.ProjectId} userId {request.UserId}"); dbContext.UserProjectAssignments.Remove(assignment); await dbContext.SaveChangesAsync(); return(new RemoveUserFromProjectResponse { }); }
public override async Task <PortalCentralBankExchangeRateUpdateDetailsGetResponse> ExecuteAsync(PortalCentralBankExchangeRateUpdateDetailsGetRequest request) { var entityId = request.Id; PortalCentralBankExchangeRateUpdateDetailsGetResponse response; if (entityId == null) { response = new PortalCentralBankExchangeRateUpdateDetailsGetResponse { Form = new PortalCentralBankExchangeRateUpdateDetailsForm { CentralBankExchangeRateId = request.CentralBankExchangeRateId, // start of tomorrow by default StartDate = TimeZones.GetCustomerNow(_currentUser).Date.AddDays(1), StartTime = "00:00:00", }, }; } else { response = await _dbContext.CentralBankExchangeRateUpdates .Where(x => x.Id == entityId.Value) .Select(x => new PortalCentralBankExchangeRateUpdateDetailsGetResponse { Form = new PortalCentralBankExchangeRateUpdateDetailsForm { Id = x.Id, CentralBankExchangeRateId = x.CentralBankExchangeRateId, StartDate = x.StartTime.Date, StartTime = x.StartTime.ToString("HH:mm:ss"), Rate = x.Rate, } }) .FirstOrDefaultAsync(); if (response == null) { throw EntityNotFoundException.Create <CentralBankExchangeRate>(entityId.Value); } } return(response); }
public override async Task <CommonDetailsPostResponse> ExecuteAsync(PortalCentralBankExchangeRateDetailsPostRequest request) { var isNew = request.Form.Id == null; CentralBankExchangeRate entity; if (isNew) { // check if duplicate currency pair var isDuplicate = await _dbContext.CentralBankExchangeRates .Where(x => x.LocalCurrencyCode == request.Form.LocalCurrencyCode && x.ForeignCurrencyCode == request.Form.ForeignCurrencyCode) .AnyAsync(); if (isDuplicate) { throw new InvalidOperationException("Central bank rate for such currency pair already exists."); } entity = new CentralBankExchangeRate(); _dbContext.CentralBankExchangeRates.Add(entity); } else { var entityId = request.Form.Id.Value; entity = await _dbContext.CentralBankExchangeRates .Where(x => x.Id == entityId) .FirstOrDefaultAsync(); if (entity == null) { throw EntityNotFoundException.Create <CentralBankExchangeRate>(entityId); } } UpdateFields(entity, request.Form, isNew); await _dbContext.SaveChangesAsync(); return(new CommonDetailsPostResponse() { Id = entity.Id, }); }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task <Kiosk> GetKioskAsync(int kioskId) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { if (kioskId % 2 == 0) { throw EntityNotFoundException.Create <Kiosk>(kioskId); } return(new Kiosk() { Id = kioskId, Address = new Address() { CountryCode = "UKR", City = "Киев", AddressLine1 = "ул. Предславинская 30, оф. 25", AddressLine2 = "этаж 5", } }); }
public override async Task <PortalCentralBankExchangeRateDetailsGetResponse> ExecuteAsync(CommonDetailsGetRequest request) { var entityId = request.Id; PortalCentralBankExchangeRateDetailsGetResponse response; if (entityId == null) { response = new PortalCentralBankExchangeRateDetailsGetResponse() { Form = new PortalCentralBankExchangeRateDetailsForm(), }; } else { response = await _dbContext.CentralBankExchangeRates .Where(x => x.Id == entityId.Value) .Select(x => new PortalCentralBankExchangeRateDetailsGetResponse() { Form = new PortalCentralBankExchangeRateDetailsForm() { Id = x.Id, LocalCurrencyCode = x.LocalCurrencyCode, ForeignCurrencyCode = x.ForeignCurrencyCode, DefaultOrder = x.DefaultOrder, } }) .FirstOrDefaultAsync(); if (response == null) { throw EntityNotFoundException.Create <CentralBankExchangeRate>(entityId.Value); } } response.Currencies = CurrencyHelper.GetCurrencyListOptions(); return(response); }
public override async Task <RemoveUserFromDomainResponse> RemoveUserFromDomain(RemoveUserFromDomainRequest request, ServerCallContext context) { var domain = await dbContext.Domains.FindIfNullThrowAsync(request.DomainId); var user = await dbContext.Users.FindIfNullThrowAsync(request.UserId); // remove the domain assignment var domainAssignment = await dbContext.UserDomainAssignments .FirstOrDefaultAsync(x => x.Domain == domain && x.User == user) ?? throw EntityNotFoundException.Create <UserDomainAssignment>($"DomainId {request.DomainId} and UserId {request.UserId}"); dbContext.UserDomainAssignments.Remove(domainAssignment); // remove the project assignment var projectAssignments = dbContext.UserProjectAssignments .Where(x => x.Project.Domain == domain && x.User == user); dbContext.UserProjectAssignments.RemoveRange(projectAssignments); await dbContext.SaveChangesAsync(); return(new RemoveUserFromDomainResponse { }); }
private async Task VerifyKioskAndProcessKioskStateAsync( int kioskId, KioskMonitorableState newKioskState, DateTime utcNow, IList <Notification> notifications) { // check if the kiosk exists and update ping time // DbContext is used to stay in SQL transaction // todo: add/test Dapper/EF common transaction and update LastPingedOnUtc via Dapper var kiosk = await _dbContext.Kiosks .Include(x => x.CurrentState) .ThenInclude(x => x.ComponentsStatuses) .Where(x => x.Id == kioskId) .FirstOrDefaultAsync(); if (kiosk == null) { throw EntityNotFoundException.Create <Entities.Kiosk>(kioskId); } kiosk.LastPingedOnUtc = utcNow; if (newKioskState == null) { return; } // create current kiosk state if it doesn't exist already if (kiosk.CurrentState == null) { kiosk.CurrentState = new KioskState(); } var kioskState = kiosk.CurrentState; // apply new kiosk state kioskState.KioskVersion = newKioskState.KioskVersion; kioskState.LocalTime = newKioskState.LocalTime; kioskState.TimeUtc = utcNow; // kiosk's components' statuses kioskState.ComponentsStatuses = kioskState.ComponentsStatuses ?? new List <KioskStateComponentInfo>(); newKioskState.ComponentMonitorableStates = newKioskState.ComponentMonitorableStates ?? new ComponentMonitorableState[] { }; var existingComponentsStatusesByNames = kioskState.ComponentsStatuses.ToDictionary(x => x.ComponentName); var newComponentsStatusesByNames = newKioskState.ComponentMonitorableStates.ToDictionary(x => x.ComponentName); var deletedComponentsStatusesNames = existingComponentsStatusesByNames.Keys.Except(newComponentsStatusesByNames.Keys).ToHashSet(); var addedComponentsStatusesNames = newComponentsStatusesByNames.Keys.Except(existingComponentsStatusesByNames.Keys).ToHashSet(); // delete DeleteComponentStatuses( _dbContext, kioskState, kioskState.ComponentsStatuses .Where(x => deletedComponentsStatusesNames.Contains(x.ComponentName)) .ToArray()); // update foreach (var componentStatus in kioskState.ComponentsStatuses) { var newComponentStatus = newComponentsStatusesByNames[componentStatus.ComponentName]; // add notification if component switched to non-operational status var newStatus = newComponentStatus.Status?.Code ?? ComponentStatusCodeEnum.Undefined; if (componentStatus.StatusCode.IsOperational() && !newStatus.IsOperational()) { var messageBuilder = new StringBuilder($"Kiosk #{kioskId}: component {componentStatus.ComponentName} switched to non-operational status {newStatus}."); if (!string.IsNullOrWhiteSpace(newComponentStatus.Status?.Message)) { messageBuilder.Append($"\n{newComponentStatus.Status.Message}"); } notifications.Add(new Notification { CustomerId = _currentUser.CustomerId, Type = NotificationTypeEnum.Service, Message = messageBuilder.ToString(), }); } componentStatus.StatusCode = newStatus; componentStatus.StatusMessage = newComponentStatus.Status?.Message; componentStatus.SpecificMonitorableStateJson = newComponentStatus.SpecificMonitorableStateJson; } // add var addedComponentsStatuses = newComponentsStatusesByNames .Where(x => addedComponentsStatusesNames.Contains(x.Key)) .Select(x => x.Value) .Select(KioskStateComponentInfo.FromComponentMonitorableState); kioskState.ComponentsStatuses.AddRange(addedComponentsStatuses); }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task <Order> GetOrderAsync(int orderId) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { if (orderId % 2 == 0) { throw EntityNotFoundException.Create <Order>(orderId); } var now = DateTime.Now; var createdOn = new DateTime(now.Year, now.Month, now.Day, 12, 05, 35); var order = new Order() { Id = orderId, KioskId = 1, CreatedOnLocalTime = createdOn, PreferableLanguageCode = "ru", Products = Enumerable.Range(1, 3) .Select(x => { var source = x % 2 == 0 ? EkProductSourceEnum.OmegaAutoBiz : EkProductSourceEnum.AllegroPl; var product = new EkTransactionProduct() { Key = new EkProductKey(source, x.ToString()).ToKey(), Source = source, Name = new MultiLanguageString() { [Languages.RussianCode] = $"Продукт {x}", }, Description = new MultiLanguageString() { [Languages.RussianCode] = $"Описание продукта {x}", }, BasePrice = 125 * x, BasePriceCurrencyCode = source == EkProductSourceEnum.AllegroPl ? "PLN" : "UAH", Quantity = x, }; if (source == EkProductSourceEnum.AllegroPl) { product.Price = Math.Ceiling(product.BasePrice * 7.93m * 1.5m); product.PriceCurrencyCode = "UAH"; product.PriceCalculationInfo = "BasePrice x 7.93 (exchange rate) x 1.2"; } else { product.Price = Math.Ceiling(product.BasePrice * 1.2m); product.PriceCurrencyCode = product.BasePriceCurrencyCode; product.PriceCalculationInfo = "BasePrice x 1.2"; } return(product); }) .ToArray(), Customer = new EkCustomerInfo() { FullName = "Тимчик Вадим", Phone = "+380977861272", }, Delivery = new EkDeliveryInfo() { Type = EkDeliveryTypeEnum.Courier, Address = new EkTransactionAddress() { City = "Киев", AddressLine1 = "ул. Предславинская 30, оф. 25", }, }, ReceiptNumber = $"XXX-{orderId}", }; order.TotalPrice = order.Products.Sum(x => x.Price * x.Quantity); order.TotalPriceCurrencyCode = "UAH"; return(order); }