Browse Source

Merge branch 'marketingcampaign' into dev

pull/223/head
Christian Arenas 7 years ago
parent
commit
1d46ba3a15
54 changed files with 867 additions and 88 deletions
  1. +13
    -1
      docker-compose-windows.override.yml
  2. +13
    -1
      docker-compose-windows.prod.yml
  3. +13
    -1
      docker-compose-windows.yml
  4. +3
    -0
      docker-compose.override.yml
  5. +3
    -0
      docker-compose.prod.yml
  6. +3
    -0
      docker-compose.yml
  7. +1
    -1
      eShopOnContainers-ServicesAndWebApps.sln
  8. +2
    -1
      src/Services/Location/Locations.API/Controllers/LocationsController.cs
  9. +8
    -4
      src/Services/Location/Locations.API/Infrastructure/LocationsContextSeed.cs
  10. +1
    -1
      src/Services/Location/Locations.API/Infrastructure/Repositories/ILocationsRepository.cs
  11. +2
    -2
      src/Services/Location/Locations.API/Infrastructure/Repositories/LocationsRepository.cs
  12. +1
    -1
      src/Services/Location/Locations.API/Infrastructure/Services/ILocationsService.cs
  13. +39
    -19
      src/Services/Location/Locations.API/Infrastructure/Services/LocationsService.cs
  14. +18
    -0
      src/Services/Location/Locations.API/IntegrationEvents/Events/UserLocationUpdatedIntegrationEvent.cs
  15. +5
    -0
      src/Services/Location/Locations.API/Locations.API.csproj
  16. +2
    -0
      src/Services/Location/Locations.API/Model/Locations.cs
  17. +2
    -3
      src/Services/Location/Locations.API/Model/UserLocation.cs
  18. +14
    -0
      src/Services/Location/Locations.API/Model/UserLocationDetails.cs
  19. +40
    -10
      src/Services/Location/Locations.API/Startup.cs
  20. +38
    -1
      src/Services/Marketing/Marketing.API/Controllers/CampaignsController.cs
  21. +2
    -2
      src/Services/Marketing/Marketing.API/Controllers/LocationsController.cs
  22. +12
    -0
      src/Services/Marketing/Marketing.API/Dto/UserLocationDTO.cs
  23. +3
    -3
      src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs
  24. +1
    -1
      src/Services/Marketing/Marketing.API/Infrastructure/MarketingContextSeed.cs
  25. +26
    -0
      src/Services/Marketing/Marketing.API/Infrastructure/MarketingReadDataContext.cs
  26. +11
    -0
      src/Services/Marketing/Marketing.API/Infrastructure/Repositories/IMarketingDataRepository.cs
  27. +41
    -0
      src/Services/Marketing/Marketing.API/Infrastructure/Repositories/MarketingDataRepository.cs
  28. +18
    -0
      src/Services/Marketing/Marketing.API/IntegrationEvents/Events/UserLocationUpdatedIntegrationEvent.cs
  29. +46
    -0
      src/Services/Marketing/Marketing.API/IntegrationEvents/Handlers/UserLocationUpdatedIntegrationEventHandler.cs
  30. +8
    -2
      src/Services/Marketing/Marketing.API/Marketing.API.csproj
  31. +2
    -0
      src/Services/Marketing/Marketing.API/MarketingSettings.cs
  32. +16
    -0
      src/Services/Marketing/Marketing.API/Model/Location.cs
  33. +19
    -0
      src/Services/Marketing/Marketing.API/Model/MarketingData.cs
  34. +51
    -0
      src/Services/Marketing/Marketing.API/Model/RuleType.cs
  35. +0
    -20
      src/Services/Marketing/Marketing.API/Model/RuleTypeEnum.cs
  36. +9
    -0
      src/Services/Marketing/Marketing.API/Model/UserLocationDetails.cs
  37. +53
    -2
      src/Services/Marketing/Marketing.API/Startup.cs
  38. +2
    -0
      src/Services/Marketing/Marketing.API/appsettings.json
  39. +35
    -0
      test/Services/FunctionalTests/FunctionalTests.csproj
  40. +1
    -1
      test/Services/FunctionalTests/Middleware/AutoAuthorizeMiddleware.cs
  41. +39
    -0
      test/Services/FunctionalTests/Services/Location/LocationsScenariosBase.cs
  42. +45
    -0
      test/Services/FunctionalTests/Services/Location/LocationsTestsStartup.cs
  43. +8
    -0
      test/Services/FunctionalTests/Services/Location/appsettings.json
  44. +35
    -0
      test/Services/FunctionalTests/Services/Marketing/CampaignScenariosBase.cs
  45. +58
    -0
      test/Services/FunctionalTests/Services/Marketing/MarketingScenarios.cs
  46. +20
    -0
      test/Services/FunctionalTests/Services/Marketing/MarketingScenariosBase.cs
  47. +26
    -0
      test/Services/FunctionalTests/Services/Marketing/MarketingTestsStartup.cs
  48. +40
    -0
      test/Services/FunctionalTests/Services/Marketing/UserLocationRoleScenariosBase.cs
  49. +8
    -0
      test/Services/FunctionalTests/Services/Marketing/appsettings.json
  50. +1
    -1
      test/Services/FunctionalTests/Services/Ordering/OrderingScenarios.cs
  51. +1
    -1
      test/Services/IntegrationTests/IntegrationTests.csproj
  52. +2
    -5
      test/Services/IntegrationTests/Services/Locations/LocationsScenarioBase.cs
  53. +3
    -3
      test/Services/IntegrationTests/Services/Locations/LocationsScenarios.cs
  54. +4
    -1
      test/Services/IntegrationTests/Services/Marketing/appsettings.json

+ 13
- 1
docker-compose-windows.override.yml View File

@ -95,4 +95,16 @@ services:
- identityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5105. at range 5100-5105.
- EventBusConnection=rabbitmq
ports:
- "5109:80"
- "5109:80"
marketing.api:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://0.0.0.0:80
- ConnectionString=Server=sql.data;Database=Microsoft.eShopOnContainers.Services.MarketingDb;User Id=sa;Password=Pass@word
- EventBusConnection=rabbitmq
- MongoConnectionString=mongodb://nosql.data
- MongoDatabase=MarketingDb
- identityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5105. at range 5100-5105.
ports:
- "5110:80"

+ 13
- 1
docker-compose-windows.prod.yml View File

@ -75,7 +75,19 @@ services:
- BasketUrl=http://basket.api
ports:
- "5100:80"
marketing.api:
environment:
- ASPNETCORE_ENVIRONMENT=Production
- ASPNETCORE_URLS=http://0.0.0.0:80
- ConnectionString=Server=sql.data;Database=Microsoft.eShopOnContainers.Services.MarketingDb;User Id=sa;Password=Pass@word
- EventBusConnection=rabbitmq
- MongoConnectionString=mongodb://nosql.data
- MongoDatabase=MarketingDb
- identityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5105. at range 5100-5105.
ports:
- "5110:80"
sql.data:
environment:
- SA_PASSWORD=Pass@word


+ 13
- 1
docker-compose-windows.yml View File

@ -61,7 +61,19 @@ services:
dockerfile: Dockerfile
depends_on:
- nosql.data
- rabbitmq
marketing.api:
image: eshop/marketing.api
build:
context: ./src/Services/Marketing/Marketing.API
dockerfile: Dockerfile
depends_on:
- sql.data
- nosql.data
- identity.api
- rabbitmq
sql.data:
image: microsoft/mssql-server-windows


+ 3
- 0
docker-compose.override.yml View File

@ -58,6 +58,9 @@ services:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://0.0.0.0:80
- ConnectionString=Server=sql.data;Database=Microsoft.eShopOnContainers.Services.MarketingDb;User Id=sa;Password=Pass@word
- MongoConnectionString=mongodb://nosql.data
- MongoDatabase=MarketingDb
- EventBusConnection=rabbitmq
- identityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5105. at range 5100-5105.
ports:
- "5110:80"


+ 3
- 0
docker-compose.prod.yml View File

@ -59,6 +59,9 @@ services:
- ASPNETCORE_ENVIRONMENT=Production
- ASPNETCORE_URLS=http://0.0.0.0:80
- ConnectionString=Server=sql.data;Database=Microsoft.eShopOnContainers.Services.MarketingDb;User Id=sa;Password=Pass@word
- MongoConnectionString=mongodb://nosql.data
- MongoDatabase=MarketingDb
- EventBusConnection=rabbitmq
- identityUrl=http://identity.api #Local: You need to open your local dev-machine firewall at range 5100-5105. at range 5100-5105.
ports:
- "5110:80"


+ 3
- 0
docker-compose.yml View File

@ -53,7 +53,9 @@ services:
dockerfile: Dockerfile
depends_on:
- sql.data
- nosql.data
- identity.api
- rabbitmq
webspa:
image: eshop/webspa
@ -112,3 +114,4 @@ services:
dockerfile: Dockerfile
depends_on:
- nosql.data
- rabbitmq

+ 1
- 1
eShopOnContainers-ServicesAndWebApps.sln View File

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26430.6
VisualStudioVersion = 15.0.26430.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{932D8224-11F6-4D07-B109-DA28AD288A63}"
EndProject


+ 2
- 1
src/Services/Location/Locations.API/Controllers/LocationsController.cs View File

@ -41,7 +41,7 @@ namespace Locations.API.Controllers
//GET api/v1/[controller]/1
[Route("{locationId}")]
[HttpGet]
public async Task<IActionResult> GetLocation(string locationId)
public async Task<IActionResult> GetLocation(int locationId)
{
var location = await _locationsService.GetLocation(locationId);
return Ok(location);
@ -54,6 +54,7 @@ namespace Locations.API.Controllers
{
var userId = _identityService.GetUserIdentity();
var result = await _locationsService.AddOrUpdateUserLocation(userId, newLocReq);
return result ?
(IActionResult)Ok() :
(IActionResult)BadRequest();


+ 8
- 4
src/Services/Location/Locations.API/Infrastructure/LocationsContextSeed.cs View File

@ -32,7 +32,8 @@
var us = new Locations()
{
Code = "US",
Description = "United States"
Description = "United States",
LocationId = 1
};
us.SetLocation(-101.357386, 41.650455);
us.SetArea(GetUSPoligon());
@ -46,7 +47,8 @@
{
Parent_Id = parentId,
Code = "WHT",
Description = "Washington"
Description = "Washington",
LocationId = 2
};
wht.SetLocation(-119.542781, 47.223652);
wht.SetArea(GetWashingtonPoligon());
@ -61,7 +63,8 @@
{
Parent_Id = parentId,
Code = "SEAT",
Description = "Seattle"
Description = "Seattle",
LocationId = 3
};
stl.SetArea(GetSeattlePoligon());
stl.SetLocation(-122.330747, 47.603111);
@ -74,7 +77,8 @@
{
Parent_Id = parentId,
Code = "REDM",
Description = "Redmond"
Description = "Redmond",
LocationId = 4
};
rdm.SetLocation(-122.122887, 47.674961);
rdm.SetArea(GetRedmondPoligon());


+ 1
- 1
src/Services/Location/Locations.API/Infrastructure/Repositories/ILocationsRepository.cs View File

@ -7,7 +7,7 @@
public interface ILocationsRepository
{
Task<Locations> GetAsync(string locationId);
Task<Locations> GetAsync(int locationId);
Task<List<Locations>> GetLocationListAsync();


+ 2
- 2
src/Services/Location/Locations.API/Infrastructure/Repositories/LocationsRepository.cs View File

@ -20,9 +20,9 @@
_context = new LocationsContext(settings);
}
public async Task<Locations> GetAsync(string locationId)
public async Task<Locations> GetAsync(int locationId)
{
var filter = Builders<Locations>.Filter.Eq("Id", ObjectId.Parse(locationId));
var filter = Builders<Locations>.Filter.Eq("LocationId", locationId);
return await _context.Locations
.Find(filter)
.FirstOrDefaultAsync();


+ 1
- 1
src/Services/Location/Locations.API/Infrastructure/Services/ILocationsService.cs View File

@ -7,7 +7,7 @@
public interface ILocationsService
{
Task<Locations> GetLocation(string locationId);
Task<Locations> GetLocation(int locationId);
Task<UserLocation> GetUserLocation(string id);


+ 39
- 19
src/Services/Location/Locations.API/Infrastructure/Services/LocationsService.cs View File

@ -8,29 +8,28 @@
using System.Linq;
using Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.Exceptions;
using System.Collections.Generic;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.Services.Locations.API.IntegrationEvents.Events;
public class LocationsService : ILocationsService
{
private ILocationsRepository _locationsRepository;
private readonly ILocationsRepository _locationsRepository;
private readonly IEventBus _eventBus;
public LocationsService(ILocationsRepository locationsRepository)
public LocationsService(ILocationsRepository locationsRepository, IEventBus eventBus)
{
_locationsRepository = locationsRepository ?? throw new ArgumentNullException(nameof(locationsRepository));
_eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
}
public async Task<Locations> GetLocation(string locationId)
public async Task<Locations> GetLocation(int locationId)
{
return await _locationsRepository.GetAsync(locationId);
}
public async Task<UserLocation> GetUserLocation(string id)
public async Task<UserLocation> GetUserLocation(string userId)
{
if (!Guid.TryParse(id, out Guid userId))
{
throw new ArgumentException("Not valid userId");
}
return await _locationsRepository.GetUserLocationAsync(userId.ToString());
return await _locationsRepository.GetUserLocationAsync(userId);
}
public async Task<List<Locations>> GetAllLocation()
@ -38,13 +37,8 @@
return await _locationsRepository.GetLocationListAsync();
}
public async Task<bool> AddOrUpdateUserLocation(string id, LocationRequest currentPosition)
{
if (!Guid.TryParse(id, out Guid userId))
{
throw new ArgumentException("Not valid userId");
}
public async Task<bool> AddOrUpdateUserLocation(string userId, LocationRequest currentPosition)
{
// Get the list of ordered regions the user currently is within
var currentUserAreaLocationList = await _locationsRepository.GetCurrentUserRegionsListAsync(currentPosition);
@ -55,14 +49,40 @@
// If current area found, then update user location
var locationAncestors = new List<string>();
var userLocation = await _locationsRepository.GetUserLocationAsync(userId.ToString());
var userLocation = await _locationsRepository.GetUserLocationAsync(userId);
userLocation = userLocation ?? new UserLocation();
userLocation.UserId = userId;
userLocation.LocationId = currentUserAreaLocationList[0].Id;
userLocation.LocationId = currentUserAreaLocationList[0].LocationId;
userLocation.UpdateDate = DateTime.UtcNow;
await _locationsRepository.UpdateUserLocationAsync(userLocation);
// Publish integration event to update marketing read data model
// with the new locations updated
PublishNewUserLocationPositionIntegrationEvent(userId, currentUserAreaLocationList);
return true;
}
private void PublishNewUserLocationPositionIntegrationEvent(string userId, List<Locations> newLocations)
{
var newUserLocations = MapUserLocationDetails(newLocations);
var @event = new UserLocationUpdatedIntegrationEvent(userId, newUserLocations);
_eventBus.Publish(@event);
}
private List<UserLocationDetails> MapUserLocationDetails(List<Locations> newLocations)
{
var result = new List<UserLocationDetails>();
newLocations.ForEach(location => {
result.Add(new UserLocationDetails()
{
LocationId = location.LocationId,
Code = location.Code,
Description = location.Description
});
});
return result;
}
}
}

+ 18
- 0
src/Services/Location/Locations.API/IntegrationEvents/Events/UserLocationUpdatedIntegrationEvent.cs View File

@ -0,0 +1,18 @@
namespace Microsoft.eShopOnContainers.Services.Locations.API.IntegrationEvents.Events
{
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.eShopOnContainers.Services.Locations.API.Model;
using System.Collections.Generic;
public class UserLocationUpdatedIntegrationEvent : IntegrationEvent
{
public string UserId { get; private set; }
public List<UserLocationDetails> LocationList { get; private set; }
public UserLocationUpdatedIntegrationEvent(string userId, List<UserLocationDetails> locationList)
{
UserId = userId;
LocationList = locationList;
}
}
}

+ 5
- 0
src/Services/Location/Locations.API/Locations.API.csproj View File

@ -10,6 +10,7 @@
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.1.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="1.2.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
@ -37,5 +38,9 @@
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj" />
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBus\EventBus.csproj" />
</ItemGroup>
</Project>

+ 2
- 0
src/Services/Location/Locations.API/Model/Locations.cs View File

@ -7,8 +7,10 @@
public class Locations
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public int LocationId { get; set; }
public string Code { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
public string Parent_Id { get; set; }


+ 2
- 3
src/Services/Location/Locations.API/Model/UserLocation.cs View File

@ -9,9 +9,8 @@
[BsonIgnoreIfDefault]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public Guid UserId { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
public string LocationId { get; set; }
public string UserId { get; set; }
public int LocationId { get; set; }
public DateTime UpdateDate { get; set; }
}
}

+ 14
- 0
src/Services/Location/Locations.API/Model/UserLocationDetails.cs View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.Services.Locations.API.Model
{
public class UserLocationDetails
{
public int LocationId { get; set; }
public string Code { get; set; }
public string Description { get; set; }
}
}

+ 40
- 10
src/Services/Location/Locations.API/Startup.cs View File

@ -1,17 +1,21 @@
using Microsoft.AspNetCore.Builder;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ;
using Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure;
using Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.Filters;
using Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.Repositories;
using Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using System.Reflection;
using System;
using Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.Services;
using Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.eShopOnContainers.Services.Locations.API.Infrastructure.Filters;
namespace Microsoft.eShopOnContainers.Services.Locations.API
{
@ -37,7 +41,7 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(options =>
@ -46,7 +50,21 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API
}).AddControllersAsServices();
services.Configure<LocationSettings>(Configuration);
services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
{
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
var factory = new ConnectionFactory()
{
HostName = Configuration["EventBusConnection"]
};
return new DefaultRabbitMQPersistentConnection(factory, logger);
});
RegisterServiceBus(services);
// Add framework services.
services.AddSwaggerGen(options =>
{
@ -72,7 +90,13 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IIdentityService, IdentityService>();
services.AddTransient<ILocationsService, LocationsService>();
services.AddTransient<ILocationsRepository, LocationsRepository>();
services.AddTransient<ILocationsRepository, LocationsRepository>();
//configure autofac
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@ -109,5 +133,11 @@ namespace Microsoft.eShopOnContainers.Services.Locations.API
RequireHttpsMetadata = false
});
}
private void RegisterServiceBus(IServiceCollection services)
{
services.AddSingleton<IEventBus, EventBusRabbitMQ>();
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
}
}
}

+ 38
- 1
src/Services/Marketing/Marketing.API/Controllers/CampaignsController.cs View File

@ -1,5 +1,6 @@
namespace Microsoft.eShopOnContainers.Services.Marketing.API.Controllers
{
using Infrastructure.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure;
using System.Threading.Tasks;
@ -8,16 +9,21 @@
using Microsoft.eShopOnContainers.Services.Marketing.API.Dto;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Linq;
[Route("api/v1/[controller]")]
[Authorize]
public class CampaignsController : Controller
{
private readonly MarketingContext _context;
private readonly IMarketingDataRepository _marketingDataRepository;
public CampaignsController(MarketingContext context)
public CampaignsController(MarketingContext context,
IMarketingDataRepository marketingDataRepository)
{
_context = context;
_marketingDataRepository = marketingDataRepository;
}
[HttpGet]
@ -112,6 +118,37 @@
return NoContent();
}
[HttpGet("user/{userId:guid}")]
public async Task<IActionResult> GetCampaignsByUserId(Guid userId)
{
var marketingData = await _marketingDataRepository.GetAsync(userId.ToString());
if (marketingData is null)
{
return NotFound();
}
var campaignDtoList = new List<CampaignDTO>();
//Get User Location Campaign
foreach(var userLocation in marketingData.Locations)
{
var userCampaignList = await _context.Rules
.OfType<UserLocationRule>()
.Include(c => c.Campaign)
.Where(c => c.LocationId == userLocation.LocationId)
.Select(c => c.Campaign)
.ToListAsync();
if (userCampaignList != null && userCampaignList.Any())
{
var userCampaignDtoList = MapCampaignModelListToDtoList(userCampaignList);
campaignDtoList.AddRange(userCampaignDtoList);
}
}
return Ok(campaignDtoList);
}
private List<CampaignDTO> MapCampaignModelListToDtoList(List<Campaign> campaignList)


+ 2
- 2
src/Services/Marketing/Marketing.API/Controllers/LocationsController.cs View File

@ -83,8 +83,8 @@ namespace Microsoft.eShopOnContainers.Services.Marketing.API.Controllers
await _context.Rules.AddAsync(locationRule);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetLocationByCampaignAndLocationRuleId),
new { campaignId = campaignId, locationRuleId = locationRule.Id }, null);
return CreatedAtAction(nameof(GetLocationByCampaignAndLocationRuleId),
new { campaignId = campaignId, userLocationRuleId = locationRule.Id }, null);
}
[HttpDelete]


+ 12
- 0
src/Services/Marketing/Marketing.API/Dto/UserLocationDTO.cs View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
namespace Microsoft.eShopOnContainers.Services.Marketing.API.Dto
{
public class UserLocationDTO
{
public string Id { get; set; }
public Guid UserId { get; set; }
public int LocationId { get; set; }
public DateTime UpdateDate { get; set; }
}
}

+ 3
- 3
src/Services/Marketing/Marketing.API/Infrastructure/MarketingContext.cs View File

@ -64,9 +64,9 @@
.IsRequired();
builder.HasDiscriminator<int>("RuleTypeId")
.HasValue<UserProfileRule>((int)RuleTypeEnum.UserProfileRule)
.HasValue<PurchaseHistoryRule>((int)RuleTypeEnum.PurchaseHistoryRule)
.HasValue<UserLocationRule>((int)RuleTypeEnum.UserLocationRule);
.HasValue<UserProfileRule>(RuleType.UserProfileRule.Id)
.HasValue<PurchaseHistoryRule>(RuleType.PurchaseHistoryRule.Id)
.HasValue<UserLocationRule>(RuleType.UserLocationRule.Id);
builder.Property(r => r.Description)
.HasColumnName("Description")


+ 1
- 1
src/Services/Marketing/Marketing.API/Infrastructure/MarketingContextSeed.cs View File

@ -57,7 +57,7 @@
new UserLocationRule
{
Description = "UserLocationRule2",
LocationId = 3
LocationId = 6
}
}
}


+ 26
- 0
src/Services/Marketing/Marketing.API/Infrastructure/MarketingReadDataContext.cs View File

@ -0,0 +1,26 @@
namespace Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure
{
using Microsoft.eShopOnContainers.Services.Marketing.API.Model;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
public class MarketingReadDataContext
{
private readonly IMongoDatabase _database = null;
public MarketingReadDataContext(IOptions<MarketingSettings> settings)
{
var client = new MongoClient(settings.Value.MongoConnectionString);
if (client != null)
_database = client.GetDatabase(settings.Value.MongoDatabase);
}
public IMongoCollection<MarketingData> MarketingData
{
get
{
return _database.GetCollection<MarketingData>("MarketingReadDataModel");
}
}
}
}

+ 11
- 0
src/Services/Marketing/Marketing.API/Infrastructure/Repositories/IMarketingDataRepository.cs View File

@ -0,0 +1,11 @@
namespace Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Repositories
{
using Model;
using System.Threading.Tasks;
public interface IMarketingDataRepository
{
Task<MarketingData> GetAsync(string userId);
Task UpdateLocationAsync(MarketingData marketingData);
}
}

+ 41
- 0
src/Services/Marketing/Marketing.API/Infrastructure/Repositories/MarketingDataRepository.cs View File

@ -0,0 +1,41 @@
using Microsoft.eShopOnContainers.Services.Marketing.API.Model;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Repositories
{
public class MarketingDataRepository
: IMarketingDataRepository
{
private readonly MarketingReadDataContext _context;
public MarketingDataRepository(IOptions<MarketingSettings> settings)
{
_context = new MarketingReadDataContext(settings);
}
public async Task<MarketingData> GetAsync(string userId)
{
var filter = Builders<MarketingData>.Filter.Eq("UserId", userId);
return await _context.MarketingData
.Find(filter)
.FirstOrDefaultAsync();
}
public async Task UpdateLocationAsync(MarketingData marketingData)
{
var filter = Builders<MarketingData>.Filter.Eq("UserId", marketingData.UserId);
var update = Builders<MarketingData>.Update
.Set("Locations", marketingData.Locations)
.CurrentDate("UpdateDate");
await _context.MarketingData
.UpdateOneAsync(filter, update, new UpdateOptions { IsUpsert = true });
}
}
}

+ 18
- 0
src/Services/Marketing/Marketing.API/IntegrationEvents/Events/UserLocationUpdatedIntegrationEvent.cs View File

@ -0,0 +1,18 @@
namespace Microsoft.eShopOnContainers.Services.Marketing.API.IntegrationEvents.Events
{
using Model;
using System.Collections.Generic;
using BuildingBlocks.EventBus.Events;
public class UserLocationUpdatedIntegrationEvent : IntegrationEvent
{
public string UserId { get; private set; }
public List<UserLocationDetails> LocationList { get; private set; }
public UserLocationUpdatedIntegrationEvent(string userId, List<UserLocationDetails> locationList)
{
UserId = userId;
LocationList = locationList;
}
}
}

+ 46
- 0
src/Services/Marketing/Marketing.API/IntegrationEvents/Handlers/UserLocationUpdatedIntegrationEventHandler.cs View File

@ -0,0 +1,46 @@
namespace Microsoft.eShopOnContainers.Services.Marketing.API.IntegrationEvents.Handlers
{
using BuildingBlocks.EventBus.Abstractions;
using System.Threading.Tasks;
using Events;
using System;
using Infrastructure.Repositories;
using Model;
using System.Collections.Generic;
public class UserLocationUpdatedIntegrationEventHandler
: IIntegrationEventHandler<UserLocationUpdatedIntegrationEvent>
{
private readonly IMarketingDataRepository _marketingDataRepository;
public UserLocationUpdatedIntegrationEventHandler(IMarketingDataRepository repository)
{
_marketingDataRepository = repository ?? throw new ArgumentNullException(nameof(repository));
}
public async Task Handle(UserLocationUpdatedIntegrationEvent @event)
{
var userMarketingData = await _marketingDataRepository.GetAsync(@event.UserId);
userMarketingData = userMarketingData ??
new MarketingData() { UserId = @event.UserId };
userMarketingData.Locations = MapUpdatedUserLocations(@event.LocationList);
await _marketingDataRepository.UpdateLocationAsync(userMarketingData);
}
private List<Location> MapUpdatedUserLocations(List<UserLocationDetails> newUserLocations)
{
var result = new List<Location>();
newUserLocations.ForEach(location => {
result.Add(new Location()
{
LocationId = location.LocationId,
Code = location.Code,
Description = location.Description
});
});
return result;
}
}
}

+ 8
- 2
src/Services/Marketing/Marketing.API/Marketing.API.csproj View File

@ -12,10 +12,9 @@
<ItemGroup>
<Folder Include="Infrastructure\MarketingMigrations\" />
<Folder Include="IntegrationEvents\EventHandling\" />
<Folder Include="IntegrationEvents\Events\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.1.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="1.2.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
@ -39,6 +38,10 @@
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.1" />
<PackageReference Include="mongocsharpdriver" Version="2.4.3" />
<PackageReference Include="MongoDB.Bson" Version="2.4.3" />
<PackageReference Include="MongoDB.Driver" Version="2.4.3" />
<PackageReference Include="MongoDB.Driver.Core" Version="2.4.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
@ -47,4 +50,7 @@
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj" />
</ItemGroup>
</Project>

+ 2
- 0
src/Services/Marketing/Marketing.API/MarketingSettings.cs View File

@ -3,5 +3,7 @@
public class MarketingSettings
{
public string ConnectionString { get; set; }
public string MongoConnectionString { get; set; }
public string MongoDatabase { get; set; }
}
}

+ 16
- 0
src/Services/Marketing/Marketing.API/Model/Location.cs View File

@ -0,0 +1,16 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.Services.Marketing.API.Model
{
public class Location
{
public int LocationId { get; set; }
public string Code { get; set; }
public string Description { get; set; }
}
}

+ 19
- 0
src/Services/Marketing/Marketing.API/Model/MarketingData.cs View File

@ -0,0 +1,19 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.Services.Marketing.API.Model
{
public class MarketingData
{
[BsonIgnoreIfDefault]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string UserId { get; set; }
public List<Location> Locations { get; set; }
public DateTime UpdateDate { get; set; }
}
}

+ 51
- 0
src/Services/Marketing/Marketing.API/Model/RuleType.cs View File

@ -0,0 +1,51 @@
namespace Microsoft.eShopOnContainers.Services.Marketing.API.Model
{
using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
public sealed class RuleType
{
public static readonly RuleType UserProfileRule = new RuleType(1, nameof(UserProfileRule));
public static readonly RuleType PurchaseHistoryRule = new RuleType(2, nameof(UserProfileRule));
public static readonly RuleType UserLocationRule = new RuleType(3, nameof(UserProfileRule));
public readonly int Id;
public readonly string Name;
private RuleType(int id, string name)
{
Id = id;
Name = name;
}
public static IEnumerable<RuleType> List() =>
new[] { UserProfileRule, PurchaseHistoryRule, UserLocationRule };
public static RuleType FromName(string name)
{
var state = List()
.SingleOrDefault(s => String.Equals(s.Name, name, StringComparison.CurrentCultureIgnoreCase));
if (state == null)
{
throw new MarketingDomainException($"Possible values for RuleType: {String.Join(",", List().Select(s => s.Name))}");
}
return state;
}
public static RuleType From(int id)
{
var state = List().SingleOrDefault(s => s.Id == id);
if (state == null)
{
throw new MarketingDomainException($"Possible values for RuleType: {String.Join(",", List().Select(s => s.Name))}");
}
return state;
}
}
}

+ 0
- 20
src/Services/Marketing/Marketing.API/Model/RuleTypeEnum.cs View File

@ -1,20 +0,0 @@
namespace Microsoft.eShopOnContainers.Services.Marketing.API.Model
{
using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Exceptions;
using System;
public enum RuleTypeEnum { UserProfileRule = 1, PurchaseHistoryRule = 2, UserLocationRule = 3 }
public static class RuleType
{
public static RuleTypeEnum From(int id)
{
if (!Enum.IsDefined(typeof(RuleTypeEnum), id))
{
throw new MarketingDomainException($"Invalid value for RuleType, RuleTypeId: {id}");
}
return (RuleTypeEnum)id;
}
}
}

+ 9
- 0
src/Services/Marketing/Marketing.API/Model/UserLocationDetails.cs View File

@ -0,0 +1,9 @@
namespace Microsoft.eShopOnContainers.Services.Marketing.API.Model
{
public class UserLocationDetails
{
public int LocationId { get; set; }
public string Code { get; set; }
public string Description { get; set; }
}
}

+ 53
- 2
src/Services/Marketing/Marketing.API/Startup.cs View File

@ -11,6 +11,15 @@
using System.Reflection;
using System;
using Microsoft.eShopOnContainers.Services.Marketing.API.Infrastructure.Filters;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ;
using RabbitMQ.Client;
using BuildingBlocks.EventBus.Abstractions;
using BuildingBlocks.EventBus;
using IntegrationEvents.Events;
using IntegrationEvents.Handlers;
using Infrastructure.Repositories;
using Autofac;
using Autofac.Extensions.DependencyInjection;
public class Startup
{
@ -35,7 +44,7 @@
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(options =>
@ -43,6 +52,8 @@
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
}).AddControllersAsServices(); //Injecting Controllers themselves thru DIFor further info see: http://docs.autofac.org/en/latest/integration/aspnetcore.html#controllers-as-services
services.Configure<MarketingSettings>(Configuration);
services.AddDbContext<MarketingContext>(options =>
{
options.UseSqlServer(Configuration["ConnectionString"],
@ -59,6 +70,20 @@
//Check Client vs. Server evaluation: https://docs.microsoft.com/en-us/ef/core/querying/client-eval
});
services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
{
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
var factory = new ConnectionFactory()
{
HostName = Configuration["EventBusConnection"]
};
return new DefaultRabbitMQPersistentConnection(factory, logger);
});
RegisterServiceBus(services);
// Add framework services.
services.AddSwaggerGen(options =>
{
@ -80,6 +105,14 @@
.AllowAnyHeader()
.AllowCredentials());
});
services.AddTransient<IMarketingDataRepository, MarketingDataRepository>();
//configure autofac
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@ -100,11 +133,12 @@
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
ConfigureEventBus(app);
MarketingContextSeed.SeedAsync(app, loggerFactory)
.Wait();
}
protected virtual void ConfigureAuth(IApplicationBuilder app)
{
var identityUrl = Configuration.GetValue<string>("IdentityUrl");
@ -115,5 +149,22 @@
RequireHttpsMetadata = false
});
}
private void RegisterServiceBus(IServiceCollection services)
{
services.AddSingleton<IEventBus, EventBusRabbitMQ>();
services.AddSingleton<IEventBusSubscriptionsManager,
InMemoryEventBusSubscriptionsManager>();
services.AddTransient<IIntegrationEventHandler<UserLocationUpdatedIntegrationEvent>,
UserLocationUpdatedIntegrationEventHandler>();
}
private void ConfigureEventBus(IApplicationBuilder app)
{
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<UserLocationUpdatedIntegrationEvent,
IIntegrationEventHandler<UserLocationUpdatedIntegrationEvent>>();
}
}
}

+ 2
- 0
src/Services/Marketing/Marketing.API/appsettings.json View File

@ -6,5 +6,7 @@
}
},
"ConnectionString": "127.0.0.1",
"MongoConnectionString": "mongodb://nosql.data",
"MongoDatabase": "MarketingDb",
"IdentityUrl": "http://localhost:5105"
}

+ 35
- 0
test/Services/FunctionalTests/FunctionalTests.csproj View File

@ -2,16 +2,46 @@
<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<PackageTargetFallback>$(PackageTargetFallback);netstandard1.6.1;dnxcore50;portable-net451+win8</PackageTargetFallback>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Services\Location\**" />
<Compile Remove="Services\Marketing\**" />
<EmbeddedResource Remove="Services\Location\**" />
<EmbeddedResource Remove="Services\Marketing\**" />
<None Remove="Services\Location\**" />
<None Remove="Services\Marketing\**" />
</ItemGroup>
<ItemGroup>
<None Remove="Services\Catalog\settings.json" />
</ItemGroup>
<ItemGroup>
<Compile Include="Services\Location\LocationsScenariosBase.cs" />
<Compile Include="Services\Location\LocationsTestsStartup.cs" />
<Compile Include="Services\Marketing\CampaignScenariosBase.cs" />
<Compile Include="Services\Marketing\UserLocationRoleScenariosBase.cs" />
<Compile Include="Services\Marketing\MarketingScenarios.cs" />
<Compile Include="Services\Marketing\MarketingScenariosBase.cs" />
<Compile Include="Services\Marketing\MarketingTestsStartup.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Services\Catalog\settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Services\Location\appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Services\Marketing\appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
@ -25,6 +55,8 @@
<ItemGroup>
<ProjectReference Include="..\..\..\src\Services\Basket\Basket.API\Basket.API.csproj" />
<ProjectReference Include="..\..\..\src\Services\Catalog\Catalog.API\Catalog.API.csproj" />
<ProjectReference Include="..\..\..\src\Services\Location\Locations.API\Locations.API.csproj" />
<ProjectReference Include="..\..\..\src\Services\Marketing\Marketing.API\Marketing.API.csproj" />
<ProjectReference Include="..\..\..\src\Services\Ordering\Ordering.API\Ordering.API.csproj" />
<ProjectReference Include="..\..\..\src\Web\WebMVC\WebMVC.csproj" />
</ItemGroup>
@ -33,6 +65,9 @@
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Services\Locations\appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="Services\Ordering\settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>


+ 1
- 1
test/Services/FunctionalTests/Middleware/AutoAuthorizeMiddleware.cs View File

@ -18,7 +18,7 @@ namespace FunctionalTests.Middleware
public async Task Invoke(HttpContext httpContext)
{
var identity = new ClaimsIdentity("cookies");
identity.AddClaim(new Claim("sub", "1234"));
identity.AddClaim(new Claim("sub", "9e3163b9-1ae6-4652-9dc6-7898ab7b7a00"));
httpContext.User.AddIdentity(identity);
await _next.Invoke(httpContext);
}


+ 39
- 0
test/Services/FunctionalTests/Services/Location/LocationsScenariosBase.cs View File

@ -0,0 +1,39 @@
namespace FunctionalTests.Services.Locations
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System;
using System.IO;
public class LocationsScenariosBase
{
public TestServer CreateServer()
{
var webHostBuilder = new WebHostBuilder();
webHostBuilder.UseContentRoot(Directory.GetCurrentDirectory() + "\\Services\\Location");
webHostBuilder.UseStartup<LocationsTestsStartup>();
return new TestServer(webHostBuilder);
}
public static class Get
{
public static string Locations = "api/v1/locations";
public static string LocationBy(string id)
{
return $"api/v1/locations/{id}";
}
public static string UserLocationBy(Guid id)
{
return $"api/v1/locations/user/{id}";
}
}
public static class Post
{
public static string AddNewLocation = "api/v1/locations/";
}
}
}

+ 45
- 0
test/Services/FunctionalTests/Services/Location/LocationsTestsStartup.cs View File

@ -0,0 +1,45 @@
namespace FunctionalTests.Services.Locations
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.eShopOnContainers.Services.Locations.API;
using System.Security.Claims;
using System.Threading.Tasks;
public class LocationsTestsStartup : Startup
{
public LocationsTestsStartup(IHostingEnvironment env) : base(env)
{
}
protected override void ConfigureAuth(IApplicationBuilder app)
{
if (Configuration["isTest"] == bool.TrueString.ToLowerInvariant())
{
app.UseMiddleware<LocationAuthorizeMiddleware>();
}
else
{
base.ConfigureAuth(app);
}
}
class LocationAuthorizeMiddleware
{
private readonly RequestDelegate _next;
public LocationAuthorizeMiddleware(RequestDelegate rd)
{
_next = rd;
}
public async Task Invoke(HttpContext httpContext)
{
var identity = new ClaimsIdentity("cookies");
identity.AddClaim(new Claim("sub", "4611ce3f-380d-4db5-8d76-87a8689058ed"));
httpContext.User.AddIdentity(identity);
await _next.Invoke(httpContext);
}
}
}
}

+ 8
- 0
test/Services/FunctionalTests/Services/Location/appsettings.json View File

@ -0,0 +1,8 @@
{
"ConnectionString": "mongodb://localhost:27017",
"Database": "LocationsDb",
"ExternalCatalogBaseUrl": "http://localhost:5101",
"IdentityUrl": "http://localhost:5105",
"isTest": "true",
"EventBusConnection": "localhost"
}

+ 35
- 0
test/Services/FunctionalTests/Services/Marketing/CampaignScenariosBase.cs View File

@ -0,0 +1,35 @@
namespace FunctionalTests.Services.Marketing
{
using System;
public class CampaignScenariosBase : MarketingScenariosBase
{
public static class Get
{
public static string Campaigns = CampaignsUrlBase;
public static string CampaignBy(int id)
=> $"{CampaignsUrlBase}/{id}";
public static string UserCampaignsByUserId(Guid userId)
=> $"{CampaignsUrlBase}/user/{userId}";
}
public static class Post
{
public static string AddNewCampaign = CampaignsUrlBase;
}
public static class Put
{
public static string CampaignBy(int id)
=> $"{CampaignsUrlBase}/{id}";
}
public static class Delete
{
public static string CampaignBy(int id)
=> $"{CampaignsUrlBase}/{id}";
}
}
}

+ 58
- 0
test/Services/FunctionalTests/Services/Marketing/MarketingScenarios.cs View File

@ -0,0 +1,58 @@
namespace FunctionalTests.Services.Marketing
{
using UserLocation = Microsoft.eShopOnContainers.Services.Locations.API.Model.UserLocation;
using LocationRequest = Microsoft.eShopOnContainers.Services.Locations.API.ViewModel.LocationRequest;
using FunctionalTests.Services.Locations;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using System.Collections.Generic;
using Microsoft.eShopOnContainers.Services.Marketing.API.Dto;
public class MarketingScenarios : MarketingScenariosBase
{
[Fact]
public async Task Set_new_user_location_and_get_location_campaign_by_user_id()
{
using (var locationsServer = new LocationsScenariosBase().CreateServer())
using (var marketingServer = new MarketingScenariosBase().CreateServer())
{
var location = new LocationRequest
{
Longitude = -122.315752,
Latitude = 47.604610
};
var content = new StringContent(JsonConvert.SerializeObject(location),
Encoding.UTF8, "application/json");
var userId = new Guid("4611ce3f-380d-4db5-8d76-87a8689058ed");
// GIVEN a new location of user is created
var response = await locationsServer.CreateClient()
.PostAsync(LocationsScenariosBase.Post.AddNewLocation, content);
//Get location user from Location.API
var userLocationResponse = await locationsServer.CreateClient()
.GetAsync(LocationsScenariosBase.Get.UserLocationBy(userId));
var responseBody = await userLocationResponse.Content.ReadAsStringAsync();
var userLocation = JsonConvert.DeserializeObject<UserLocation>(responseBody);
await Task.Delay(300);
//Get campaing from Marketing.API given a userId
var UserLocationCampaignResponse = await marketingServer.CreateClient()
.GetAsync(CampaignScenariosBase.Get.UserCampaignsByUserId(userId));
responseBody = await UserLocationCampaignResponse.Content.ReadAsStringAsync();
var userLocationCampaigns = JsonConvert.DeserializeObject<List<CampaignDTO>>(responseBody);
Assert.True(userLocationCampaigns.Count > 0);
}
}
}
}

+ 20
- 0
test/Services/FunctionalTests/Services/Marketing/MarketingScenariosBase.cs View File

@ -0,0 +1,20 @@
namespace FunctionalTests.Services.Marketing
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System.IO;
public class MarketingScenariosBase
{
public static string CampaignsUrlBase => "api/v1/campaigns";
public TestServer CreateServer()
{
var webHostBuilder = new WebHostBuilder();
webHostBuilder.UseContentRoot(Directory.GetCurrentDirectory() + "\\Services\\Marketing");
webHostBuilder.UseStartup<MarketingTestsStartup>();
return new TestServer(webHostBuilder);
}
}
}

+ 26
- 0
test/Services/FunctionalTests/Services/Marketing/MarketingTestsStartup.cs View File

@ -0,0 +1,26 @@
namespace FunctionalTests.Services.Marketing
{
using Microsoft.eShopOnContainers.Services.Marketing.API;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using FunctionalTests.Middleware;
public class MarketingTestsStartup : Startup
{
public MarketingTestsStartup(IHostingEnvironment env) : base(env)
{
}
protected override void ConfigureAuth(IApplicationBuilder app)
{
if (Configuration["isTest"] == bool.TrueString.ToLowerInvariant())
{
app.UseMiddleware<AutoAuthorizeMiddleware>();
}
else
{
base.ConfigureAuth(app);
}
}
}
}

+ 40
- 0
test/Services/FunctionalTests/Services/Marketing/UserLocationRoleScenariosBase.cs View File

@ -0,0 +1,40 @@
namespace FunctionalTests.Services.Marketing
{
public class UserLocationRoleScenariosBase : MarketingScenariosBase
{
private const string EndpointLocationName = "locations";
public static class Get
{
public static string UserLocationRulesByCampaignId(int campaignId)
=> GetUserLocationRolesUrlBase(campaignId);
public static string UserLocationRuleByCampaignAndUserLocationRuleId(int campaignId,
int userLocationRuleId)
=> $"{GetUserLocationRolesUrlBase(campaignId)}/{userLocationRuleId}";
}
public static class Post
{
public static string AddNewuserLocationRule(int campaignId)
=> GetUserLocationRolesUrlBase(campaignId);
}
public static class Put
{
public static string UserLocationRoleBy(int campaignId,
int userLocationRuleId)
=> $"{GetUserLocationRolesUrlBase(campaignId)}/{userLocationRuleId}";
}
public static class Delete
{
public static string UserLocationRoleBy(int campaignId,
int userLocationRuleId)
=> $"{GetUserLocationRolesUrlBase(campaignId)}/{userLocationRuleId}";
}
private static string GetUserLocationRolesUrlBase(int campaignId)
=> $"{CampaignsUrlBase}/{campaignId}/{EndpointLocationName}";
}
}

+ 8
- 0
test/Services/FunctionalTests/Services/Marketing/appsettings.json View File

@ -0,0 +1,8 @@
{
"ConnectionString": "Server=tcp:127.0.0.1,5433;Initial Catalog=Microsoft.eShopOnContainers.Services.MarketingDb;User Id=sa;Password=Pass@word",
"MongoConnectionString": "mongodb://localhost:27017",
"MongoDatabase": "MarketingDb",
"IdentityUrl": "http://localhost:5105",
"isTest": "true",
"EventBusConnection": "localhost"
}

+ 1
- 1
test/Services/FunctionalTests/Services/Ordering/OrderingScenarios.cs View File

@ -88,7 +88,7 @@ namespace FunctionalTests.Services.Ordering
string BuildBasket()
{
var order = new CustomerBasket("1234");
var order = new CustomerBasket("9e3163b9-1ae6-4652-9dc6-7898ab7b7a00");
order.Items = new List<Microsoft.eShopOnContainers.Services.Basket.API.Model.BasketItem>()
{
new Microsoft.eShopOnContainers.Services.Basket.API.Model.BasketItem()


+ 1
- 1
test/Services/IntegrationTests/IntegrationTests.csproj View File

@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
<AssemblyName>IntegrationTests</AssemblyName>
<AssemblyName>FunctionalTests</AssemblyName>
<PackageId>FunctionalTests</PackageId>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<PackageTargetFallback>$(PackageTargetFallback);netstandard1.6.1;dnxcore50;portable-net451+win8</PackageTargetFallback>


+ 2
- 5
test/Services/IntegrationTests/Services/Locations/LocationsScenarioBase.cs View File

@ -1,9 +1,6 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace IntegrationTests.Services.Locations
{
@ -22,12 +19,12 @@ namespace IntegrationTests.Services.Locations
{
public static string Locations = "api/v1/locations";
public static string LocationBy(string id)
public static string LocationBy(int id)
{
return $"api/v1/locations/{id}";
}
public static string UserLocationBy(Guid id)
public static string UserLocationBy(string id)
{
return $"api/v1/locations/user/{id}";
}


+ 3
- 3
test/Services/IntegrationTests/Services/Locations/LocationsScenarios.cs View File

@ -19,7 +19,7 @@ namespace IntegrationTests.Services.Locations
{
using (var server = CreateServer())
{
var userId = new Guid("4611ce3f-380d-4db5-8d76-87a8689058ed");
var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed";
var content = new StringContent(BuildLocationsRequest(-122.315752, 47.604610), UTF8Encoding.UTF8, "application/json");
// Expected result
@ -51,7 +51,7 @@ namespace IntegrationTests.Services.Locations
{
using (var server = CreateServer())
{
var userId = new Guid("4611ce3f-380d-4db5-8d76-87a8689058ed");
var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed";
var content = new StringContent(BuildLocationsRequest(-122.119998, 47.690876), UTF8Encoding.UTF8, "application/json");
// Expected result
@ -83,7 +83,7 @@ namespace IntegrationTests.Services.Locations
{
using (var server = CreateServer())
{
var userId = new Guid("4611ce3f-380d-4db5-8d76-87a8689058ed");
var userId = "4611ce3f-380d-4db5-8d76-87a8689058ed";
var content = new StringContent(BuildLocationsRequest(-121.040360, 48.091631), UTF8Encoding.UTF8, "application/json");
// Expected result


+ 4
- 1
test/Services/IntegrationTests/Services/Marketing/appsettings.json View File

@ -1,5 +1,8 @@
{
"ConnectionString": "Server=tcp:127.0.0.1,5433;Initial Catalog=Microsoft.eShopOnContainers.Services.MarketingDb;User Id=sa;Password=Pass@word",
"MongoConnectionString": "mongodb://localhost:27017",
"MongoDatabase": "MarketingDb",
"IdentityUrl": "http://localhost:5105",
"isTest": "true"
"isTest": "true",
"EventBusConnection": "localhost"
}

Loading…
Cancel
Save