public async Task <IActionResult> PutSubscription(string id, Subscription subscription) { if (id != subscription.Identifier) { return(BadRequest()); } _context.Entry(subscription).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SubscriptionExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task Should_Add_Subscription_To_Database() { var options = new DbContextOptionsBuilder <SubscriptionContext>() .AddInterceptors(new DomainEventDispatcher(Substitute.For <IMediator>())) .UseSqlServer("Server=localhost;Database=Subscriptions;uid=sa;pwd=yourStrong(!)Password;") .Options; var context = new SubscriptionContext(options); await context.Database.EnsureCreatedAsync(); var product = new Product("Flowers", 10, BillingPeriod.Monthly); var customer = new Customer(new Email("*****@*****.**"), new CustomerName("Hossam", "Barakat")); await context.Products.AddAsync(product); await context.Customers.AddAsync(customer); await context.SaveChangesAsync(); var handler = new SubscribeRequestHandler(context, new SubscriptionAmountCalculator()); await handler.Handle(new SubscribeRequest { CustomerId = customer.Id, ProductId = product.Id }, CancellationToken.None); var subscription = await context.Subscriptions .SingleOrDefaultAsync(x => x.Customer.Id == customer.Id && x.Product.Id == product.Id); subscription.ShouldNotBeNull(); }
public async Task <Unit> Handle(SubscribeRequest request, CancellationToken cancellationToken) { var customer = await _subscriptionContext.Customers.FindAsync(request.CustomerId); var product = await _subscriptionContext.Products.FindAsync(request.ProductId); customer.AddSubscription(product, _subscriptionAmountCalculator); await _subscriptionContext.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task <Unit> Handle(SubscribeRequest request, CancellationToken cancellationToken) { var customer = await _subscriptionContext .Customers .Include(x => x.Subscriptions) .FirstAsync(x => x.Id == request.CustomerId, cancellationToken: cancellationToken); var product = await _subscriptionContext.Products.FindAsync(request.ProductId); var subscriptionAmount = product.Amount; if (customer.MoneySpent >= 100) { subscriptionAmount *= 0.8M; } else if (customer.MoneySpent >= 1000) { subscriptionAmount *= 0.5M; } var currentPeriodEndDate = product.BillingPeriod switch { BillingPeriod.Weekly => DateTime.UtcNow.AddDays(7), BillingPeriod.Monthly => DateTime.UtcNow.AddMonths(1), _ => throw new InvalidOperationException() }; var subscription = new Subscription { Id = Guid.NewGuid(), Customer = customer, Product = product, Amount = subscriptionAmount, Status = SubscriptionStatus.Active, CurrentPeriodEndDate = currentPeriodEndDate }; customer.Subscriptions.Add(subscription); customer.MoneySpent += subscription.Amount; await _subscriptionContext.SaveChangesAsync(cancellationToken); await _emailSender.SendEmailAsync("Congratulations! You subscribed to a cool product"); return(Unit.Value); } }
public async Task <Unit> Handle(UnbindConnectionToUserCommand request, CancellationToken cancellationToken) { var userSubscription = _context.UsersSubscription .Include(x => x.Preferences) .Include(x => x.Connections) .Include(x => x.AllowedEvents) .FirstOrDefault(x => x.UserId.Equals(request.UserId)); if (userSubscription is null) { userSubscription = UserSubscription.Factory.Create(request.UserId); } userSubscription.UnBindConnectionWithUserId(request.ConnectionId, request.UserId); await _context.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task Should_Add_Subscription_To_Database() { var options = new DbContextOptionsBuilder <SubscriptionContext>() .UseSqlServer("Server=localhost;Database=Subscriptions;uid=sa;pwd=yourStrong(!)Password;") .Options; var context = new SubscriptionContext(options); await context.Database.EnsureCreatedAsync(); var customer = new Customer { Id = Guid.NewGuid(), Email = "*****@*****.**", FirstName = "Hossam", LastName = "Barakat" }; await context.Customers.AddAsync(customer); var product = new Product { Id = Guid.NewGuid(), Name = "Weekly Bunch", Amount = 10, BillingPeriod = BillingPeriod.Monthly }; await context.Products.AddAsync(product); await context.SaveChangesAsync(); var sut = new SubscribeRequestHandler(context, Substitute.For <IEmailSender>()); var subscribeRequest = new SubscribeRequest { CustomerId = customer.Id, ProductId = product.Id }; await sut.Handle(subscribeRequest, CancellationToken.None); var subscription = await context.Subscriptions .SingleOrDefaultAsync(x => x.Customer.Id == customer.Id && x.Product.Id == product.Id); subscription.ShouldNotBeNull(); }
public async Task <Unit> Handle(SetPreferencesCommand request, CancellationToken cancellationToken) { if (request.Preferences is null) { throw new ArgumentException("Preferences must not be null"); } var userSubscription = _context.UsersSubscription .Include(x => x.Preferences) .Include(x => x.Connections) .Include(x => x.AllowedEvents) .FirstOrDefault(x => x.UserId.Equals(request.UserId)); if (userSubscription is null) { throw new SubscriptionNotFoundException(); } userSubscription.Preferences = request.Preferences; await _context.SaveChangesAsync(cancellationToken); return(Unit.Value); }
public async Task <ActionResult <Subscription> > PostSubscriptions([FromBody] Subscription subscription) { using (var client = new HttpClient()) { // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", this.Request.Headers["Authorization"].ToString()); client.BaseAddress = new Uri("http://localhost:62793/"); try { //Update Availability var response = client.PutAsync($"/Books/{subscription.BookId}", new StringContent(subscription.BookId, Encoding.UTF8, "application/json")).Result; if (response.StatusCode == HttpStatusCode.OK) { _context.SubscriptionList.Add(subscription); await _context.SaveChangesAsync(); string jsonMessage = response.Content.ReadAsStringAsync().Result; // De-serialize var bookDetail = (Books) JsonConvert.DeserializeObject(jsonMessage, typeof(Books)); if (bookDetail?.copiesAvailable <= 0 && subscription.Notify) { // Get the Customer details and email address //client.DefaultRequestHeaders.Clear(); response = client.GetAsync($"/Customer/{subscription.SubscriberName}").Result; if (response.StatusCode == HttpStatusCode.OK) { jsonMessage = response.Content.ReadAsStringAsync().Result; // De-serialize var customer = (Customer) JsonConvert.DeserializeObject(jsonMessage, typeof(Customer)); //Add the alert for the cuscriber as user opted for Notification of availability //client.DefaultRequestHeaders.Clear(); string registerUserJson = RegisterUserJson(subscription.BookId, subscription.Id, customer.Email); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress.ToString()) { Content = new StringContent(registerUserJson, Encoding.UTF8, "application/json") }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response = client.PostAsync($"/AlertSubscription", request.Content).Result; } } //Send alert to all user as books are available if (bookDetail?.copiesAvailable > 0) { //client.DefaultRequestHeaders.Clear(); response = client.GetAsync($"/AlertSubscription/{subscription.BookId}").Result; } } } catch (Exception exception) { throw exception; } } return(CreatedAtAction(nameof(GetSubscriptionLists), new { id = subscription.BookId }, subscription)); }