├── .gitignore ├── ShopPlatform ├── Sellers │ ├── Sellers.Contracts │ │ ├── Role.cs │ │ ├── ShopView.cs │ │ ├── ShopUser.cs │ │ ├── Credentials.cs │ │ ├── Commands │ │ │ ├── GrantRole.cs │ │ │ ├── RevokeRole.cs │ │ │ └── CreateUser.cs │ │ └── Sellers.Contracts.csproj │ ├── Sellers.Api │ │ ├── appsettings.Development.json │ │ ├── QueryExtensions.cs │ │ ├── appsettings.json │ │ ├── Filters │ │ │ └── InvariantViolationFilter.cs │ │ ├── Sellers.Api.csproj │ │ ├── Properties │ │ │ └── launchSettings.json │ │ ├── Program.cs │ │ └── Controllers │ │ │ ├── UsersController.cs │ │ │ └── ShopsControllers.cs │ ├── Sellers.DomainModel │ │ ├── QueryModel │ │ │ ├── IUserReader.cs │ │ │ └── PasswordVerifier.cs │ │ ├── CommandModel │ │ │ ├── IUserRepository.cs │ │ │ ├── InvariantViolationException.cs │ │ │ ├── GrantRoleCommandExecutor.cs │ │ │ ├── UserRepositoryExtensions.cs │ │ │ ├── RevokeRoleCommandExecutor.cs │ │ │ ├── EntityNotFoundException.cs │ │ │ └── CreateUserCommandExecutor.cs │ │ ├── IPasswordHasher.cs │ │ ├── Sellers.DomainModel.csproj │ │ ├── Shop.cs │ │ └── User.cs │ ├── Sellers.Testing │ │ ├── SellersServerCustomization.cs │ │ ├── RoleCustomization.cs │ │ ├── InlineAutoSellersDataAttribute.cs │ │ ├── UserRepositoryCustomization.cs │ │ ├── SellersDbContextCustomization.cs │ │ ├── ShopCustomization.cs │ │ ├── UserCustomization.cs │ │ ├── PasswordHasherCustomization.cs │ │ ├── AutoSellersDataAttribute.cs │ │ ├── Sellers.Testing.csproj │ │ ├── ConnectionStringAttribute.cs │ │ ├── SellersDatabase.cs │ │ ├── SellersServer.cs │ │ └── TestSpecificLanguage.cs │ ├── Sellers.Sql │ │ ├── RoleEntity.cs │ │ ├── UserEntity.cs │ │ ├── Sellers.Sql.csproj │ │ ├── QueryModel │ │ │ ├── BackwardCompatibleUserReader.cs │ │ │ ├── ShopUserReader.cs │ │ │ └── SqlUserReader.cs │ │ ├── Migrations │ │ │ ├── 20220831154330_AddRoles.cs │ │ │ ├── 20220822123735_AddUsers.cs │ │ │ ├── 20220822113310_AddShops.cs │ │ │ ├── 20220822113310_AddShops.Designer.cs │ │ │ ├── 20220822123735_AddUsers.Designer.cs │ │ │ ├── SellersDbContextModelSnapshot.cs │ │ │ └── 20220831154330_AddRoles.Designer.cs │ │ ├── SellersDbContext.cs │ │ └── CommandModel │ │ │ └── SqlUserRepository.cs │ ├── Sellers.UnitTests │ │ ├── CollectionExtensions.cs │ │ ├── Program_specs.cs │ │ ├── api │ │ │ ├── users │ │ │ │ ├── id │ │ │ │ │ ├── grant-role │ │ │ │ │ │ └── Post_specs.cs │ │ │ │ │ ├── revoke-role │ │ │ │ │ │ └── Post_specs.cs │ │ │ │ │ ├── create-user │ │ │ │ │ │ └── Post_specs.cs │ │ │ │ │ └── roles │ │ │ │ │ │ └── Get_specs.cs │ │ │ │ └── verify-password │ │ │ │ │ └── Post_specs.cs │ │ │ └── shops │ │ │ │ ├── id │ │ │ │ └── Get_specs.cs │ │ │ │ └── Get_specs.cs │ │ ├── CommandModel │ │ │ ├── RevokeRoleCommandExecutor_specs.cs │ │ │ ├── GrantRoleCommandExecutor_specs.cs │ │ │ ├── CreateUserCommandExecutor_specs.cs │ │ │ └── SqlUserRepository_specs.cs │ │ ├── Sellers.UnitTests.csproj │ │ ├── AspNetCorePasswordHasher_specs.cs │ │ └── QueryModel │ │ │ ├── PasswordVerifier_specs.cs │ │ │ ├── BackwardCompatibleUserReader_specs.cs │ │ │ ├── ShopUserReader_specs.cs │ │ │ └── SqlUserReader_specs.cs │ └── Sellers.Crypto │ │ ├── Sellers.Crypto.csproj │ │ └── AspNetCorePasswordHasher.cs ├── settings.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── Orders │ ├── Orders.Api │ │ ├── Messaging │ │ │ ├── IBus.cs │ │ │ ├── IAsyncObservable.cs │ │ │ └── StorageQueueBus.cs │ │ ├── Commands │ │ │ ├── StartOrder.cs │ │ │ └── PlaceOrder.cs │ │ ├── Events │ │ │ ├── ItemShipped.cs │ │ │ ├── PaymentApproved.cs │ │ │ ├── BankTransferPaymentCompleted.cs │ │ │ ├── ExternalPaymentApproved.cs │ │ │ └── PaymentApprovedEventHandler.cs │ │ ├── appsettings.Development.json │ │ ├── OrderStatus.cs │ │ ├── QueryExtensions.cs │ │ ├── QueryLanguage.cs │ │ ├── appsettings.json │ │ ├── SellersService.cs │ │ ├── Order.cs │ │ ├── Properties │ │ │ └── launchSettings.json │ │ ├── OrdersDbContext.cs │ │ ├── Orders.Api.csproj │ │ ├── Migrations │ │ │ ├── 20220822090330_AddPaymentTransactionIdToOrder.cs │ │ │ ├── 20220822085914_AddOrders.cs │ │ │ ├── 20220822085914_AddOrders.Designer.cs │ │ │ ├── OrdersDbContextModelSnapshot.cs │ │ │ └── 20220822090330_AddPaymentTransactionIdToOrder.Designer.cs │ │ ├── Program.cs │ │ └── Controllers │ │ │ └── OrdersController.cs │ └── Orders.UnitTests │ │ ├── DefaultPolicy.cs │ │ ├── api │ │ └── orders │ │ │ ├── id │ │ │ ├── Get_specs.cs │ │ │ ├── start-order │ │ │ │ └── Post_specs.cs │ │ │ └── place-order │ │ │ │ └── Post_specs.cs │ │ │ ├── handle │ │ │ ├── bank-transder-payment-completed │ │ │ │ └── Post_specs.cs │ │ │ └── item-shipped │ │ │ │ └── Post_specs.cs │ │ │ ├── accept │ │ │ └── payment-approved │ │ │ │ └── Post_specs.cs │ │ │ └── Get_specs.cs │ │ ├── Orders.UnitTests.csproj │ │ ├── OrdersServer.cs │ │ └── TestSpecificLanguage.cs ├── accounting │ ├── api │ │ ├── src │ │ │ └── main │ │ │ │ ├── java │ │ │ │ └── accounting │ │ │ │ │ ├── Shop.java │ │ │ │ │ ├── query │ │ │ │ │ └── GetOrdersPlacedIn.java │ │ │ │ │ ├── ShopReader.java │ │ │ │ │ ├── OrderReader.java │ │ │ │ │ ├── OrderView.java │ │ │ │ │ ├── OrderRepository.java │ │ │ │ │ ├── App.java │ │ │ │ │ ├── dataaccess │ │ │ │ │ └── QuotedNamingStrategy.java │ │ │ │ │ ├── OrderViewAggregator.java │ │ │ │ │ ├── HttpShopReader.java │ │ │ │ │ ├── controller │ │ │ │ │ └── OrdersController.java │ │ │ │ │ └── Order.java │ │ │ │ └── resources │ │ │ │ └── application.properties │ │ └── build.gradle │ └── unittest │ │ ├── src │ │ └── test │ │ │ └── java │ │ │ └── accounting │ │ │ └── test │ │ │ ├── AccountingCustomizer.java │ │ │ ├── EmptyShopReaderCustomizer.java │ │ │ ├── InMemoryOrderRepository.java │ │ │ ├── OrderViewAggregator_specs.java │ │ │ └── api │ │ │ └── orders │ │ │ └── get_orders_placed_in │ │ │ └── Post_specs.java │ │ └── build.gradle ├── gradlew.bat ├── ShopPlatform.sln └── gradlew ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .vs 2 | bin 3 | obj 4 | .vscode 5 | .idea 6 | .gradle 7 | build 8 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Contracts/Role.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers; 2 | 3 | public sealed record Role(Guid ShopId, string RoleName); 4 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Contracts/ShopView.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers; 2 | 3 | public sealed record ShopView(Guid Id, string Name); 4 | -------------------------------------------------------------------------------- /ShopPlatform/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = "ShopPlatform" 2 | 3 | include("accounting:api") 4 | include("accounting:unittest") 5 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Contracts/ShopUser.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers; 2 | 3 | public sealed record ShopUser(string Id, string Password); 4 | -------------------------------------------------------------------------------- /ShopPlatform/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gyuwon/TDDHandsOn2/HEAD/ShopPlatform/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Contracts/Credentials.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers; 2 | 3 | public sealed record Credentials(string Username, string Password); 4 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Messaging/IBus.cs: -------------------------------------------------------------------------------- 1 | namespace Orders.Messaging; 2 | 3 | public interface IBus 4 | { 5 | Task Send(T message); 6 | } 7 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Commands/StartOrder.cs: -------------------------------------------------------------------------------- 1 | namespace Orders.Commands; 2 | 3 | public sealed record StartOrder(string? PaymentTransactionId = null); 4 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Events/ItemShipped.cs: -------------------------------------------------------------------------------- 1 | namespace Orders.Events; 2 | 3 | public sealed record ItemShipped(Guid OrderId, DateTime EventTimeUtc); 4 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Contracts/Commands/GrantRole.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers.Commands; 2 | 3 | public sealed record GrantRole(Guid ShopId, string RoleName); 4 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Contracts/Commands/RevokeRole.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers.Commands; 2 | 3 | public sealed record RevokeRole(Guid ShopId, string RoleName); 4 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Contracts/Commands/CreateUser.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers.Commands; 2 | 3 | public sealed record CreateUser(string Username, string Password); 4 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/Shop.java: -------------------------------------------------------------------------------- 1 | package accounting; 2 | 3 | import java.util.UUID; 4 | 5 | public record Shop(UUID id, String name) { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Events/PaymentApproved.cs: -------------------------------------------------------------------------------- 1 | namespace Orders.Events; 2 | 3 | public sealed record PaymentApproved( 4 | string TransactionId, 5 | DateTime EventTimeUtc); 6 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Messaging/IAsyncObservable.cs: -------------------------------------------------------------------------------- 1 | namespace Orders.Messaging; 2 | 3 | public interface IAsyncObservable 4 | { 5 | IDisposable Subscribe(Func onNext); 6 | } 7 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Commands/PlaceOrder.cs: -------------------------------------------------------------------------------- 1 | namespace Orders.Commands; 2 | 3 | public sealed record PlaceOrder( 4 | Guid UserId, 5 | Guid ShopId, 6 | Guid ItemId, 7 | decimal Price); 8 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Events/BankTransferPaymentCompleted.cs: -------------------------------------------------------------------------------- 1 | namespace Orders.Events; 2 | 3 | public sealed record BankTransferPaymentCompleted( 4 | Guid OrderId, 5 | DateTime EventTimeUtc); 6 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Api/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/query/GetOrdersPlacedIn.java: -------------------------------------------------------------------------------- 1 | package accounting.query; 2 | 3 | import java.util.UUID; 4 | 5 | public record GetOrdersPlacedIn(UUID shopId, int year, int month) { 6 | } 7 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/QueryModel/IUserReader.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers.QueryModel; 2 | 3 | public interface IUserReader 4 | { 5 | Task FindUser(Guid id); 6 | 7 | Task FindUser(string username); 8 | } 9 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/ShopReader.java: -------------------------------------------------------------------------------- 1 | package accounting; 2 | 3 | import java.util.Optional; 4 | import java.util.UUID; 5 | 6 | public interface ShopReader { 7 | 8 | Optional findShop(UUID id); 9 | } 10 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/CommandModel/IUserRepository.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers.CommandModel; 2 | 3 | public interface IUserRepository 4 | { 5 | Task Add(User user); 6 | 7 | Task TryUpdate(Guid id, Func reviser); 8 | } 9 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/IPasswordHasher.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers; 2 | 3 | public interface IPasswordHasher 4 | { 5 | string HashPassword(string password); 6 | 7 | bool VerifyPassword(string hashedPassword, string providedPassword); 8 | } 9 | -------------------------------------------------------------------------------- /ShopPlatform/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/CommandModel/InvariantViolationException.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers.CommandModel; 2 | 3 | public sealed class InvariantViolationException : InvalidOperationException 4 | { 5 | public InvariantViolationException() 6 | { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/OrderStatus.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace Orders; 4 | 5 | [JsonConverter(typeof(JsonStringEnumConverter))] 6 | public enum OrderStatus 7 | { 8 | Pending, 9 | AwaitingPayment, 10 | AwaitingShipment, 11 | Completed, 12 | } 13 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Events/ExternalPaymentApproved.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | 3 | namespace Orders.Events; 4 | 5 | [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "External API")] 6 | public sealed record ExternalPaymentApproved(string tid, DateTime approved_at); 7 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/SellersServerCustomization.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture; 2 | 3 | namespace Sellers; 4 | 5 | public sealed class SellersServerCustomization : ICustomization 6 | { 7 | public void Customize(IFixture fixture) 8 | => fixture.Register(() => SellersServer.Create()); 9 | } 10 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/QueryExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace Orders; 4 | 5 | public static class QueryExtensions 6 | { 7 | public static Task FindOrder(this DbSet source, Guid id) 8 | => source.SingleOrDefaultAsync(x => x.Id == id); 9 | } 10 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Api/QueryExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace Sellers; 4 | 5 | public static class QueryExtensions 6 | { 7 | public static Task FindShop(this DbSet source, Guid id) 8 | => source.SingleOrDefaultAsync(x => x.Id == id); 9 | } 10 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Contracts/Sellers.Contracts.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Sellers 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/RoleCustomization.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture; 2 | using System.Collections.Immutable; 3 | 4 | namespace Sellers; 5 | 6 | public sealed class RoleCustomization : ICustomization 7 | { 8 | public void Customize(IFixture fixture) 9 | => fixture.Register(() => fixture.CreateMany().ToImmutableArray()); 10 | } 11 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/InlineAutoSellersDataAttribute.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture.Xunit2; 2 | 3 | namespace Sellers; 4 | 5 | public class InlineAutoSellersDataAttribute : InlineAutoDataAttribute 6 | { 7 | public InlineAutoSellersDataAttribute(params object[] values) 8 | : base(new AutoSellersDataAttribute(), values) 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/RoleEntity.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers; 2 | 3 | #nullable disable 4 | 5 | public sealed class RoleEntity 6 | { 7 | public long UserSequence { get; set; } 8 | 9 | public Guid ShopId { get; set; } 10 | 11 | public string RoleName { get; set; } 12 | 13 | public UserEntity User { get; set; } 14 | } 15 | 16 | #nullable enable 17 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/UserRepositoryCustomization.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture; 2 | using Sellers.CommandModel; 3 | 4 | namespace Sellers; 5 | 6 | public sealed class UserRepositoryCustomization : ICustomization 7 | { 8 | public void Customize(IFixture fixture) 9 | => fixture.Register(() => fixture.Create()); 10 | } 11 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Api/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Server=127.0.0.1;Port=5432;Database=Sellers;User Id=postgres;Password=mysecretpassword;" 4 | }, 5 | "Logging": { 6 | "LogLevel": { 7 | "Default": "Information", 8 | "Microsoft.AspNetCore": "Warning" 9 | } 10 | }, 11 | "AllowedHosts": "*" 12 | } 13 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/SellersDbContextCustomization.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture; 2 | 3 | namespace Sellers; 4 | 5 | public sealed class SellersDbContextCustomization : ICustomization 6 | { 7 | public void Customize(IFixture fixture) 8 | { 9 | Func factory = SellersDatabase.CreateContext; 10 | fixture.Register(() => factory); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/OrderReader.java: -------------------------------------------------------------------------------- 1 | package accounting; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.UUID; 5 | 6 | public interface OrderReader { 7 | 8 | Iterable getOrdersPlacedIn( 9 | UUID shopId, 10 | LocalDateTime placedAtUtcStartInclusive, 11 | LocalDateTime placedAtUtcEndExclusive); 12 | } 13 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=1579 2 | 3 | spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/Orders 4 | spring.datasource.username=postgres 5 | spring.datasource.password=mysecretpassword 6 | spring.jpa.show-sql=true 7 | spring.jpa.hibernate.naming.physical-strategy=accounting.dataaccess.QuotedNamingStrategy 8 | 9 | sellers.host=http://localhost:5232 10 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/ShopCustomization.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture; 2 | 3 | namespace Sellers; 4 | 5 | public sealed class ShopCustomization : ICustomization 6 | { 7 | public void Customize(IFixture fixture) 8 | { 9 | ICustomization customization = fixture 10 | .Build() 11 | .Without(x => x.Sequence) 12 | .ToCustomization(); 13 | 14 | fixture.Customize(customization); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/CollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers; 2 | 3 | internal static class CollectionExtensions 4 | { 5 | private static readonly Random random = new(); 6 | 7 | public static T Sample(this IEnumerable source) 8 | { 9 | IOrderedEnumerable query = 10 | from x in source 11 | orderby random.Next() 12 | select x; 13 | 14 | return query.First(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/Sellers.DomainModel.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Sellers 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/OrderView.java: -------------------------------------------------------------------------------- 1 | package accounting; 2 | 3 | import java.math.BigDecimal; 4 | import java.time.LocalDateTime; 5 | import java.util.UUID; 6 | 7 | public record OrderView( 8 | UUID id, 9 | UUID userId, 10 | Shop shop, 11 | UUID itemId, 12 | BigDecimal price, 13 | String status, 14 | String paymentTransactionId, 15 | LocalDateTime placedAtUtc 16 | ) { 17 | 18 | } 19 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/CommandModel/GrantRoleCommandExecutor.cs: -------------------------------------------------------------------------------- 1 | using Sellers.Commands; 2 | 3 | namespace Sellers.CommandModel; 4 | 5 | public sealed class GrantRoleCommandExecutor 6 | { 7 | private readonly IUserRepository repository; 8 | 9 | public GrantRoleCommandExecutor(IUserRepository repository) 10 | => this.repository = repository; 11 | 12 | public Task Execute(Guid id, GrantRole command) 13 | => repository.Update(id, u => u.GrantRole(command)); 14 | } 15 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/CommandModel/UserRepositoryExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers.CommandModel; 2 | 3 | internal static class UserRepositoryExtensions 4 | { 5 | public static async Task Update( 6 | this IUserRepository repository, 7 | Guid id, 8 | Func reviser) 9 | { 10 | if (await repository.TryUpdate(id, reviser) == false) 11 | { 12 | throw new EntityNotFoundException(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/UserEntity.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace Sellers; 4 | 5 | #nullable disable 6 | 7 | public sealed class UserEntity 8 | { 9 | public Guid Id { get; set; } 10 | 11 | public long Sequence { get; set; } 12 | 13 | [Required] 14 | public string Username { get; set; } 15 | 16 | public string PasswordHash { get; set; } 17 | 18 | public List Roles { get; set; } = new(); 19 | } 20 | 21 | #nullable enable 22 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/CommandModel/RevokeRoleCommandExecutor.cs: -------------------------------------------------------------------------------- 1 | using Sellers.Commands; 2 | 3 | namespace Sellers.CommandModel; 4 | 5 | public sealed class RevokeRoleCommandExecutor 6 | { 7 | private readonly IUserRepository repository; 8 | 9 | public RevokeRoleCommandExecutor(IUserRepository repository) 10 | => this.repository = repository; 11 | 12 | public Task Execute(Guid id, RevokeRole command) 13 | => repository.Update(id, u => u.RevokeRole(command)); 14 | } 15 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Api/Filters/InvariantViolationFilter.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Mvc.Filters; 3 | using Sellers.CommandModel; 4 | 5 | namespace Sellers.Filters; 6 | 7 | public sealed class InvariantViolationFilter : IExceptionFilter 8 | { 9 | public void OnException(ExceptionContext context) 10 | { 11 | if (context.Exception is InvariantViolationException) 12 | { 13 | context.Result = new BadRequestResult(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/UserCustomization.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture; 2 | 3 | namespace Sellers; 4 | 5 | public sealed class UserCustomization : ICustomization 6 | { 7 | public void Customize(IFixture fixture) 8 | { 9 | ICustomization customization = fixture 10 | .Build() 11 | .Without(x => x.Sequence) 12 | .With(x => x.Roles, new List()) 13 | .ToCustomization(); 14 | 15 | fixture.Customize(customization); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/Shop.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace Sellers; 5 | 6 | #nullable disable 7 | 8 | public sealed class Shop 9 | { 10 | public Guid Id { get; set; } 11 | 12 | [JsonIgnore] 13 | public int Sequence { get; set; } 14 | 15 | [Required] 16 | public string Name { get; set; } 17 | 18 | public string UserId { get; set; } 19 | 20 | public string PasswordHash { get; set; } 21 | } 22 | 23 | #nullable enable 24 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/unittest/src/test/java/accounting/test/AccountingCustomizer.java: -------------------------------------------------------------------------------- 1 | package accounting.test; 2 | 3 | import accounting.Order; 4 | import org.javaunit.autoparams.customization.CompositeCustomizer; 5 | import org.javaunit.autoparams.customization.InstanceFieldWriter; 6 | 7 | public class AccountingCustomizer extends CompositeCustomizer { 8 | 9 | public AccountingCustomizer() { 10 | super( 11 | new InstanceFieldWriter(Order.class), 12 | new EmptyShopReaderCustomizer()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/PasswordHasherCustomization.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture; 2 | using Microsoft.AspNetCore.Identity; 3 | 4 | namespace Sellers; 5 | 6 | public sealed class PasswordHasherCustomization : ICustomization 7 | { 8 | public void Customize(IFixture fixture) 9 | { 10 | fixture.Register(() => new PasswordHasher()); 11 | fixture.Register(GetPasswordHasher); 12 | } 13 | 14 | private static IPasswordHasher GetPasswordHasher() 15 | => new AspNetCorePasswordHasher(new PasswordHasher()); 16 | } 17 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/Program_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Sellers.QueryModel; 4 | using Xunit; 5 | 6 | namespace Sellers; 7 | 8 | public class Program_specs 9 | { 10 | [Theory, AutoSellersData] 11 | public void Sut_registers_correct_service_of_IUserReader( 12 | SellersServer server) 13 | { 14 | IUserReader actual = server.Services.GetRequiredService(); 15 | actual.Should().BeOfType(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/QueryLanguage.cs: -------------------------------------------------------------------------------- 1 | namespace Orders; 2 | 3 | internal static class QueryLanguage 4 | { 5 | public static IQueryable FilterByUser( 6 | this IQueryable query, 7 | Guid? userId) 8 | { 9 | return userId == null ? query : query.Where(x => x.UserId == userId); 10 | } 11 | 12 | public static IQueryable FilterByShop( 13 | this IQueryable query, 14 | Guid? shopId) 15 | { 16 | return shopId == null ? query : query.Where(x => x.ShopId == shopId); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Crypto/Sellers.Crypto.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Sellers 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DefaultConnection": "Server=127.0.0.1;Port=5432;Database=Orders;User Id=postgres;Password=mysecretpassword;" 4 | }, 5 | "Storage": { 6 | "ConnectionString": "UseDevelopmentStorage=true", 7 | "Queues": { 8 | "PaymentApproved": "payment-approved" 9 | } 10 | }, 11 | "Sellers": { 12 | "Host": "http://localhost:5232" 13 | }, 14 | "Logging": { 15 | "LogLevel": { 16 | "Default": "Information", 17 | "Microsoft.AspNetCore": "Warning" 18 | } 19 | }, 20 | "AllowedHosts": "*" 21 | } 22 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/unittest/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.7.3' 3 | id 'io.spring.dependency-management' version '1.0.13.RELEASE' 4 | id 'java' 5 | } 6 | 7 | sourceCompatibility = '17' 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | testImplementation(project(":accounting:api")) 15 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 16 | testImplementation 'io.github.javaunit:autoparams:0.3.3' 17 | } 18 | 19 | tasks.named('bootJar') { 20 | enabled = false 21 | } 22 | 23 | tasks.named('test') { 24 | useJUnitPlatform() 25 | } 26 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/DefaultPolicy.cs: -------------------------------------------------------------------------------- 1 | using Polly; 2 | 3 | namespace Orders; 4 | 5 | public static class DefaultPolicy 6 | { 7 | private static readonly Random random = new(); 8 | 9 | public static IAsyncPolicy Instance { get; } = Policy 10 | .Handle() 11 | .WaitAndRetryAsync(retryCount: 5, GetDelay); 12 | 13 | private static TimeSpan GetDelay(int retryAttempt) 14 | { 15 | int delay = 100; 16 | for (int i = 1; i < retryAttempt; i++) 17 | { 18 | delay = delay * 2 + random.Next(20); 19 | } 20 | 21 | return TimeSpan.FromMilliseconds(delay); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.7.3' 3 | id 'io.spring.dependency-management' version '1.0.13.RELEASE' 4 | id 'java' 5 | } 6 | 7 | sourceCompatibility = '17' 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | implementation('org.springframework.boot:spring-boot-starter-web') 15 | implementation('org.springdoc:springdoc-openapi-ui:1.6.11') 16 | implementation('org.springframework.boot:spring-boot-starter-data-jpa') 17 | runtimeOnly 'org.postgresql:postgresql' 18 | implementation('com.fasterxml.jackson.core:jackson-databind:2.13.4') 19 | } 20 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/QueryModel/PasswordVerifier.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers.QueryModel; 2 | 3 | public sealed class PasswordVerifier 4 | { 5 | private readonly IUserReader reader; 6 | private readonly IPasswordHasher hasher; 7 | 8 | public PasswordVerifier(IUserReader reader, IPasswordHasher hasher) 9 | { 10 | this.reader = reader; 11 | this.hasher = hasher; 12 | } 13 | 14 | public async Task VerifyPassword(string username, string password) 15 | { 16 | return await reader.FindUser(username) switch 17 | { 18 | User user => hasher.VerifyPassword(user.PasswordHash, password), 19 | _ => false, 20 | }; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/AutoSellersDataAttribute.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture; 2 | using AutoFixture.Xunit2; 3 | 4 | namespace Sellers; 5 | 6 | public class AutoSellersDataAttribute : AutoDataAttribute 7 | { 8 | public AutoSellersDataAttribute() 9 | : base(() => new Fixture().Customize( 10 | new CompositeCustomization( 11 | new UserCustomization(), 12 | new RoleCustomization(), 13 | new ShopCustomization(), 14 | new PasswordHasherCustomization(), 15 | new SellersDbContextCustomization(), 16 | new UserRepositoryCustomization(), 17 | new SellersServerCustomization()))) 18 | { 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/CommandModel/EntityNotFoundException.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | 3 | namespace Sellers.CommandModel; 4 | 5 | public class EntityNotFoundException : InvalidOperationException 6 | { 7 | public EntityNotFoundException() 8 | { 9 | } 10 | 11 | public EntityNotFoundException(string? message) 12 | : base(message) 13 | { 14 | } 15 | 16 | public EntityNotFoundException(string? message, Exception? innerException) 17 | : base(message, innerException) 18 | { 19 | } 20 | 21 | protected EntityNotFoundException( 22 | SerializationInfo info, 23 | StreamingContext context) 24 | : base(info, context) 25 | { 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/Sellers.Sql.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Sellers 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/Sellers.Testing.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Sellers 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/User.cs: -------------------------------------------------------------------------------- 1 | using Sellers.Commands; 2 | using System.Collections.Immutable; 3 | 4 | namespace Sellers; 5 | 6 | public sealed record User( 7 | Guid Id, 8 | string Username, 9 | string PasswordHash, 10 | ImmutableArray Roles) 11 | { 12 | internal User GrantRole(GrantRole command) 13 | { 14 | Role role = new(command.ShopId, command.RoleName); 15 | return Roles.Contains(role) ? this : this with 16 | { 17 | Roles = Roles.Add(role), 18 | }; 19 | } 20 | 21 | internal User RevokeRole(RevokeRole command) 22 | { 23 | Role role = new(command.ShopId, command.RoleName); 24 | return this with { Roles = Roles.Remove(role) }; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/api/users/id/grant-role/Post_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Xunit; 3 | 4 | namespace Sellers.api.users.id.grant_role; 5 | 6 | public class Post_specs 7 | { 8 | [Theory, AutoSellersData] 9 | public async Task Sut_correctly_adds_role_to_user( 10 | SellersServer server, 11 | Guid userId, 12 | string username, 13 | string password, 14 | Guid shopId, 15 | string roleName) 16 | { 17 | await server.CreateUser(userId, username, password); 18 | 19 | await server.GrantRole(userId, shopId, roleName); 20 | 21 | IEnumerable roles = await server.GetRoles(userId); 22 | roles.Should().Contain(new Role(shopId, roleName)); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package accounting; 2 | 3 | import org.springframework.data.jpa.repository.Query; 4 | import org.springframework.data.repository.CrudRepository; 5 | 6 | import java.time.LocalDateTime; 7 | import java.util.UUID; 8 | 9 | public interface OrderRepository extends CrudRepository, OrderReader { 10 | 11 | @Query(""" 12 | SELECT x 13 | FROM Orders x 14 | WHERE 15 | x.shopId = :shopId 16 | AND x.placedAtUtc >= :placedAtUtcStartInclusive 17 | AND x.placedAtUtc < :placedAtUtcEndExclusive 18 | """) 19 | Iterable getOrdersPlacedIn( 20 | UUID shopId, 21 | LocalDateTime placedAtUtcStartInclusive, 22 | LocalDateTime placedAtUtcEndExclusive); 23 | } 24 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/api/users/id/revoke-role/Post_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Xunit; 3 | 4 | namespace Sellers.api.users.id.revoke_role; 5 | 6 | public class Post_specs 7 | { 8 | [Theory, AutoSellersData] 9 | public async Task Sut_correcty_removes_role_from_user( 10 | SellersServer server, 11 | Guid userId, 12 | string username, 13 | string password, 14 | Guid shopId, 15 | string roleName) 16 | { 17 | await server.CreateUser(userId, username, password); 18 | await server.GrantRole(userId, shopId, roleName); 19 | 20 | await server.RevokeRole(userId, shopId, roleName); 21 | 22 | IEnumerable roles = await server.GetRoles(userId); 23 | roles.Should().NotContain(new Role(shopId, roleName)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/unittest/src/test/java/accounting/test/EmptyShopReaderCustomizer.java: -------------------------------------------------------------------------------- 1 | package accounting.test; 2 | 3 | import java.util.Optional; 4 | 5 | import org.javaunit.autoparams.customization.Customizer; 6 | import org.javaunit.autoparams.generator.ObjectContainer; 7 | import org.javaunit.autoparams.generator.ObjectGenerator; 8 | 9 | import accounting.ShopReader; 10 | 11 | public class EmptyShopReaderCustomizer implements Customizer { 12 | 13 | @Override 14 | public ObjectGenerator customize(ObjectGenerator generator) { 15 | return (query, context) -> query.getType().equals(ShopReader.class) 16 | ? new ObjectContainer(create()) 17 | : generator.generate(query, context); 18 | } 19 | 20 | private ShopReader create() { 21 | return id -> Optional.empty(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Crypto/AspNetCorePasswordHasher.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | 3 | namespace Sellers; 4 | 5 | public sealed class AspNetCorePasswordHasher : IPasswordHasher 6 | { 7 | private static readonly object User = "user"; 8 | 9 | private readonly PasswordHasher hasher; 10 | 11 | public AspNetCorePasswordHasher(PasswordHasher hasher) 12 | => this.hasher = hasher; 13 | 14 | public string HashPassword(string password) 15 | => hasher.HashPassword(User, password); 16 | 17 | public bool VerifyPassword(string hashedPassword, string providedPassword) 18 | { 19 | return hasher.VerifyHashedPassword(User, hashedPassword, providedPassword) switch 20 | { 21 | PasswordVerificationResult.Failed => false, 22 | _ => true, 23 | }; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/ConnectionStringAttribute.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture; 2 | using System.Reflection; 3 | 4 | namespace Sellers; 5 | 6 | [AttributeUsage(AttributeTargets.Parameter)] 7 | public class ConnectionStringAttribute : 8 | Attribute, 9 | IParameterCustomizationSource, 10 | ICustomization 11 | { 12 | public ConnectionStringAttribute(string connectionString) 13 | => ConnectionString = connectionString; 14 | 15 | public string ConnectionString { get; } 16 | 17 | public void Customize(IFixture fixture) 18 | => fixture.Register(() => SellersServer.Create(ConnectionString)); 19 | 20 | public ICustomization GetCustomization(ParameterInfo parameter) 21 | { 22 | return parameter.ParameterType == typeof(SellersServer) 23 | ? this 24 | : new CompositeCustomization(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Api/Sellers.Api.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Sellers 8 | 9 | 10 | 11 | 12 | all 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/App.java: -------------------------------------------------------------------------------- 1 | package accounting; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.Bean; 7 | 8 | import java.net.http.HttpClient; 9 | 10 | @SuppressWarnings("unused") 11 | @SpringBootApplication 12 | public class App { 13 | public static void main(String[] args) { 14 | SpringApplication.run(App.class, args); 15 | } 16 | 17 | @Bean 18 | public ShopReader shopReader(@Value("${sellers.host}") String host) { 19 | return new HttpShopReader(HttpClient.newBuilder().build(), host); 20 | } 21 | 22 | @Bean 23 | public OrderViewAggregator aggregator(ShopReader shopReader) { 24 | return new OrderViewAggregator(shopReader); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/SellersService.cs: -------------------------------------------------------------------------------- 1 | using Sellers; 2 | 3 | namespace Orders; 4 | 5 | public sealed class SellersService 6 | { 7 | private readonly HttpClient client; 8 | 9 | public SellersService(HttpClient client) => this.client = client; 10 | 11 | public async Task FindShop(Guid id) 12 | { 13 | HttpResponseMessage response = await client.GetAsync($"api/shops/{id}"); 14 | return response.IsSuccessStatusCode switch 15 | { 16 | true => await response.Content.ReadFromJsonAsync(), 17 | _ => null, 18 | }; 19 | } 20 | 21 | public async Task GetShop(Guid id) 22 | { 23 | HttpResponseMessage response = await client.GetAsync($"api/shops/{id}"); 24 | HttpContent content = response.EnsureSuccessStatusCode().Content; 25 | return (await content.ReadFromJsonAsync())!; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Order.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations.Schema; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace Orders; 5 | 6 | #nullable disable 7 | 8 | public sealed class Order 9 | { 10 | public Guid Id { get; set; } 11 | 12 | [JsonIgnore] 13 | public long Sequence { get; set; } 14 | 15 | public Guid UserId { get; set; } 16 | 17 | public Guid ShopId { get; set; } 18 | 19 | [NotMapped] 20 | public string ShopName { get; set; } 21 | 22 | public Guid ItemId { get; set; } 23 | 24 | public decimal Price { get; set; } 25 | 26 | public OrderStatus Status { get; set; } 27 | 28 | public string PaymentTransactionId { get; set; } 29 | 30 | public DateTime PlacedAtUtc { get; set; } 31 | 32 | public DateTime? StartedAtUtc { get; set; } 33 | 34 | public DateTime? PaidAtUtc { get; set; } 35 | 36 | public DateTime? ShippedAtUtc { get; set; } 37 | } 38 | 39 | #nullable enable -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:21382", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "Orders.Api": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "http://localhost:5094", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Api/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:51068", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "Sellers.Api": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "http://localhost:5232", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/CommandModel/RevokeRoleCommandExecutor_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Sellers.QueryModel; 3 | using Xunit; 4 | 5 | namespace Sellers.CommandModel; 6 | 7 | public class RevokeRoleCommandExecutor_specs 8 | { 9 | [Theory, AutoSellersData] 10 | public async Task Sut_correctly_removes_role( 11 | Func contextFactory, 12 | User user) 13 | { 14 | // Arrange 15 | SqlUserRepository repository = new(contextFactory); 16 | await repository.Add(user); 17 | RevokeRoleCommandExecutor sut = new(repository); 18 | Role role = user.Roles.Sample(); 19 | 20 | // Act 21 | await sut.Execute(user.Id, new(role.ShopId, role.RoleName)); 22 | 23 | // Assert 24 | SqlUserReader reader = new(contextFactory); 25 | User actual = (await reader.FindUser(user.Id))!; 26 | actual.Roles.Should().NotContain(role); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/api/orders/id/Get_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Sellers; 3 | using System.Net.Http.Json; 4 | using Xunit; 5 | 6 | namespace Orders.api.orders.id; 7 | 8 | public class Get_specs 9 | { 10 | [Fact] 11 | public async Task Sut_correctly_sets_shop_name() 12 | { 13 | // Arrange 14 | OrdersServer server = OrdersServer.Create(); 15 | Guid orderId = Guid.NewGuid(); 16 | await server.PlaceOrder(orderId); 17 | 18 | // Act 19 | HttpClient client = server.CreateClient(); 20 | string uri = $"api/orders/{orderId}"; 21 | HttpResponseMessage response = await client.GetAsync(uri); 22 | Order? order = await response.Content.ReadFromJsonAsync(); 23 | string shopName = order!.ShopName; 24 | 25 | // Assert 26 | ShopView shop = await server.GetSellersServer().GetShop(order.ShopId); 27 | shopName.Should().Be(shop.Name); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/SellersDatabase.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace Sellers; 4 | 5 | public static class SellersDatabase 6 | { 7 | public const string DefaultConnectionString = "Server=127.0.0.1;Port=5432;Database=Sellers_UnitTests;User Id=postgres;Password=mysecretpassword;"; 8 | 9 | public static SellersDbContext CreateContext() 10 | => CreateContextUsingSqlServer(); 11 | 12 | private static SellersDbContext CreateContextUsingSqlServer() 13 | { 14 | string connectionString = DefaultConnectionString; 15 | SellersDbContext context = new(GetSqlServerOptions(connectionString)); 16 | context.Database.Migrate(); 17 | return context; 18 | } 19 | 20 | private static DbContextOptions GetSqlServerOptions( 21 | string connectionString) 22 | { 23 | DbContextOptionsBuilder builder = new(); 24 | return builder.UseNpgsql(connectionString).Options; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/OrdersDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | 4 | namespace Orders; 5 | 6 | #nullable disable 7 | 8 | public sealed class OrdersDbContext : DbContext 9 | { 10 | public OrdersDbContext(DbContextOptions options) 11 | : base(options) 12 | { 13 | } 14 | 15 | public DbSet Orders { get; set; } 16 | 17 | protected override void OnModelCreating(ModelBuilder modelBuilder) 18 | { 19 | EntityTypeBuilder order = modelBuilder.Entity(); 20 | order.HasKey(x => x.Sequence); 21 | order.Property(x => x.Sequence).ValueGeneratedOnAdd(); 22 | order.HasIndex(x => x.Id).IsUnique(); 23 | order.HasIndex(x => x.UserId); 24 | order.HasIndex(x => x.ShopId); 25 | order.Property(x => x.Status).HasConversion(); 26 | order.HasIndex(x => x.Status); 27 | order.HasIndex(x => x.PaymentTransactionId); 28 | } 29 | } 30 | 31 | #nullable enable 32 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/unittest/src/test/java/accounting/test/InMemoryOrderRepository.java: -------------------------------------------------------------------------------- 1 | package accounting.test; 2 | 3 | import accounting.Order; 4 | import accounting.OrderReader; 5 | 6 | import java.time.LocalDateTime; 7 | import java.util.ArrayList; 8 | import java.util.UUID; 9 | import java.util.stream.StreamSupport; 10 | 11 | public class InMemoryOrderRepository extends ArrayList implements OrderReader { 12 | 13 | @Override 14 | public Iterable getOrdersPlacedIn(UUID shopId, 15 | LocalDateTime placedAtUtcStartInclusive, 16 | LocalDateTime placedAtUtcEndExclusive) { 17 | return StreamSupport 18 | .stream(spliterator(), false) 19 | .filter(x -> x.getShopId().equals(shopId)) 20 | .filter(x -> x.getPlacedAtUtc().compareTo(placedAtUtcStartInclusive) >= 0) 21 | .filter(x -> x.getPlacedAtUtc().compareTo(placedAtUtcEndExclusive) < 0) 22 | .toList(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/api/shops/id/Get_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using System.Net.Http.Json; 4 | using Xunit; 5 | 6 | namespace Sellers.api.shops.id; 7 | 8 | public class Get_specs 9 | { 10 | [Theory, AutoSellersData] 11 | public async Task Sut_does_not_expose_user_credentials( 12 | SellersServer server, 13 | Shop shop) 14 | { 15 | // Arrange 16 | IServiceScope scope = server.Services.CreateScope(); 17 | SellersDbContext context = scope.ServiceProvider.GetRequiredService(); 18 | context.Shops.Add(shop); 19 | await context.SaveChangesAsync(); 20 | 21 | // Act 22 | HttpClient client = server.CreateClient(); 23 | HttpResponseMessage response = await client.GetAsync($"api/shops/{shop.Id}"); 24 | Shop? actual = await response.Content.ReadFromJsonAsync(); 25 | 26 | // Assert 27 | actual!.UserId.Should().BeNull(); 28 | actual.PasswordHash.Should().BeNull(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Orders.Api.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | Orders 8 | 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Gyuwon Yi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/QueryModel/BackwardCompatibleUserReader.cs: -------------------------------------------------------------------------------- 1 | namespace Sellers.QueryModel; 2 | 3 | public sealed class BackwardCompatibleUserReader : IUserReader 4 | { 5 | private readonly IEnumerable readers; 6 | 7 | private BackwardCompatibleUserReader(params IUserReader[] readers) 8 | => this.readers = readers.ToList().AsReadOnly(); 9 | 10 | public BackwardCompatibleUserReader(Func contextFactory) 11 | : this(new SqlUserReader(contextFactory), 12 | new ShopUserReader(contextFactory)) 13 | { 14 | } 15 | 16 | public Task FindUser(Guid id) 17 | => FindUser(async x => await x.FindUser(id)); 18 | 19 | public Task FindUser(string username) 20 | => FindUser(async x => await x.FindUser(username)); 21 | 22 | private async Task FindUser( 23 | Func> selector) 24 | { 25 | return await readers 26 | .ToAsyncEnumerable() 27 | .SelectAwait(selector) 28 | .Where(x => x != null) 29 | .FirstOrDefaultAsync(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Migrations/20220822090330_AddPaymentTransactionIdToOrder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore.Migrations; 2 | 3 | #nullable disable 4 | 5 | namespace Orders.Migrations 6 | { 7 | public partial class AddPaymentTransactionIdToOrder : Migration 8 | { 9 | protected override void Up(MigrationBuilder migrationBuilder) 10 | { 11 | migrationBuilder.AddColumn( 12 | name: "PaymentTransactionId", 13 | table: "Orders", 14 | type: "text", 15 | nullable: true); 16 | 17 | migrationBuilder.CreateIndex( 18 | name: "IX_Orders_PaymentTransactionId", 19 | table: "Orders", 20 | column: "PaymentTransactionId"); 21 | } 22 | 23 | protected override void Down(MigrationBuilder migrationBuilder) 24 | { 25 | migrationBuilder.DropIndex( 26 | name: "IX_Orders_PaymentTransactionId", 27 | table: "Orders"); 28 | 29 | migrationBuilder.DropColumn( 30 | name: "PaymentTransactionId", 31 | table: "Orders"); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Events/PaymentApprovedEventHandler.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Orders.Messaging; 3 | 4 | namespace Orders.Events; 5 | 6 | internal static class PaymentApprovedEventHandler 7 | { 8 | public static void Listen(IServiceProvider provider) 9 | { 10 | IAsyncObservable stream = 11 | provider.GetRequiredService>(); 12 | 13 | stream.Subscribe(async (PaymentApproved listenedEvent) => 14 | { 15 | using IServiceScope scope = provider.CreateScope(); 16 | var context = scope.ServiceProvider.GetRequiredService(); 17 | 18 | IQueryable query = 19 | from x in context.Orders 20 | where x.PaymentTransactionId == listenedEvent.TransactionId 21 | select x; 22 | 23 | if (await query.SingleOrDefaultAsync() is Order order) 24 | { 25 | order.Status = OrderStatus.AwaitingShipment; 26 | order.PaidAtUtc = listenedEvent.EventTimeUtc; 27 | await context.SaveChangesAsync(); 28 | } 29 | }); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/api/shops/Get_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using System.Net.Http.Json; 5 | using Xunit; 6 | 7 | namespace Sellers.api.shops; 8 | 9 | public class Get_specs 10 | { 11 | private const string ConnectionString = "Server=127.0.0.1;Port=5432;Database=Sellers_80d18902;User Id=postgres;Password=mysecretpassword;"; 12 | 13 | [Theory, AutoSellersData] 14 | public async Task Sut_returns_all_shops( 15 | [ConnectionString(ConnectionString)] SellersServer server, 16 | Shop[] shops) 17 | { 18 | IServiceProvider services = server.Services.CreateScope().ServiceProvider; 19 | SellersDbContext context = services.GetRequiredService(); 20 | context.RemoveRange(await context.Shops.ToListAsync()); 21 | context.AddRange(shops); 22 | await context.SaveChangesAsync(); 23 | 24 | HttpResponseMessage response = await server.CreateClient().GetAsync("api/shops"); 25 | Shop[]? actual = await response.Content.ReadFromJsonAsync(); 26 | 27 | actual.Should().BeEquivalentTo(shops, c => c.Excluding(x => x.Sequence)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/Sellers.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | false 7 | Sellers 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | all 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/QueryModel/ShopUserReader.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using System.Collections.Immutable; 3 | using System.Linq.Expressions; 4 | 5 | namespace Sellers.QueryModel; 6 | 7 | public sealed class ShopUserReader : IUserReader 8 | { 9 | private readonly Func contextFactory; 10 | 11 | public ShopUserReader(Func contextFactory) 12 | => this.contextFactory = contextFactory; 13 | 14 | public Task FindUser(Guid id) 15 | => FindUser(x => x.Id == id); 16 | 17 | public Task FindUser(string username) 18 | => FindUser(x => x.UserId == username); 19 | 20 | private async Task FindUser(Expression> predicate) 21 | { 22 | using SellersDbContext context = contextFactory.Invoke(); 23 | IQueryable query = context.Shops.AsNoTracking().Where(predicate); 24 | return await query.SingleOrDefaultAsync() switch 25 | { 26 | Shop shop => new User( 27 | Id: shop.Id, 28 | Username: shop.UserId, 29 | shop.PasswordHash, 30 | Roles: ImmutableArray.Create(GetRole(shop))), 31 | null => null, 32 | }; 33 | } 34 | 35 | private static Role GetRole(Shop shop) 36 | => new(shop.Id, RoleName: "Administrator"); 37 | } 38 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/dataaccess/QuotedNamingStrategy.java: -------------------------------------------------------------------------------- 1 | package accounting.dataaccess; 2 | 3 | import org.hibernate.boot.model.naming.Identifier; 4 | import org.hibernate.boot.model.naming.PhysicalNamingStrategy; 5 | import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; 6 | 7 | public class QuotedNamingStrategy implements PhysicalNamingStrategy { 8 | @Override 9 | public Identifier toPhysicalCatalogName(Identifier name, JdbcEnvironment jdbcEnvironment) { 10 | return getQuotedIdentifier(name); 11 | } 12 | 13 | @Override 14 | public Identifier toPhysicalSchemaName(Identifier name, JdbcEnvironment jdbcEnvironment) { 15 | return getQuotedIdentifier(name); 16 | } 17 | 18 | @Override 19 | public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) { 20 | return getQuotedIdentifier(name); 21 | } 22 | 23 | @Override 24 | public Identifier toPhysicalSequenceName(Identifier name, JdbcEnvironment jdbcEnvironment) { 25 | return getQuotedIdentifier(name); 26 | } 27 | 28 | @Override 29 | public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment jdbcEnvironment) { 30 | return getQuotedIdentifier(name); 31 | } 32 | 33 | private static Identifier getQuotedIdentifier(Identifier name) { 34 | return name == null ? null : new Identifier(name.getText(), true); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.DomainModel/CommandModel/CreateUserCommandExecutor.cs: -------------------------------------------------------------------------------- 1 | using Sellers.Commands; 2 | using Sellers.QueryModel; 3 | using System.Collections.Immutable; 4 | 5 | namespace Sellers.CommandModel; 6 | 7 | public sealed class CreateUserCommandExecutor 8 | { 9 | private readonly IPasswordHasher hasher; 10 | private readonly IUserReader reader; 11 | private readonly IUserRepository repository; 12 | 13 | public CreateUserCommandExecutor( 14 | IPasswordHasher hasher, 15 | IUserReader reader, 16 | IUserRepository repository) 17 | { 18 | this.hasher = hasher; 19 | this.reader = reader; 20 | this.repository = repository; 21 | } 22 | 23 | public async Task Execute(Guid id, CreateUser command) 24 | { 25 | await AssertThatUsernameIsAvailable(command.Username); 26 | await AddUser(id, command); 27 | } 28 | 29 | private async Task AssertThatUsernameIsAvailable(string username) 30 | { 31 | if (await reader.FindUser(username) is not null) 32 | { 33 | throw new InvariantViolationException(); 34 | } 35 | } 36 | 37 | private Task AddUser(Guid id, CreateUser command) 38 | { 39 | string passwordHash = hasher.HashPassword(command.Password); 40 | ImmutableArray roles = ImmutableArray.Empty; 41 | return repository.Add(new(id, command.Username, passwordHash, roles)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/QueryModel/SqlUserReader.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using System.Collections.Immutable; 3 | using System.Linq.Expressions; 4 | 5 | namespace Sellers.QueryModel; 6 | 7 | public sealed class SqlUserReader : IUserReader 8 | { 9 | private readonly Func contextFactory; 10 | 11 | public SqlUserReader(Func contextFactory) 12 | => this.contextFactory = contextFactory; 13 | 14 | public Task FindUser(Guid id) 15 | => FindUser(x => x.Id == id); 16 | 17 | public Task FindUser(string username) 18 | => FindUser(x => x.Username == username); 19 | 20 | private async Task FindUser( 21 | Expression> predicate) 22 | { 23 | using SellersDbContext context = contextFactory.Invoke(); 24 | 25 | IQueryable query = context.Users 26 | .AsNoTracking() 27 | .Where(predicate); 28 | 29 | return await query.Include(x => x.Roles).SingleOrDefaultAsync() switch 30 | { 31 | UserEntity entity => new User( 32 | entity.Id, 33 | entity.Username, 34 | entity.PasswordHash, 35 | Roles: ImmutableArray.CreateRange( 36 | from x in entity.Roles 37 | select new Role(x.ShopId, x.RoleName))), 38 | null => null, 39 | }; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/api/users/verify-password/Post_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using System.Net; 3 | using System.Net.Http.Json; 4 | using Xunit; 5 | 6 | namespace Sellers.api.users.verify_password; 7 | 8 | public class Post_specs 9 | { 10 | [Theory, AutoSellersData] 11 | public async Task Sut_returns_BadRequest_with_invalid_credentials( 12 | SellersServer server, 13 | Credentials credentials) 14 | { 15 | HttpClient client = server.CreateClient(); 16 | string uri = "api/users/verify-password"; 17 | 18 | HttpResponseMessage response = await client.PostAsJsonAsync(uri, credentials); 19 | 20 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 21 | } 22 | 23 | [Theory, AutoSellersData] 24 | public async Task Sut_returns_OK_with_valid_credentials( 25 | SellersServer server, 26 | string username, 27 | string password) 28 | { 29 | // Arrange 30 | ShopView shop = await server.CreateShop(); 31 | await server.SetShopUser(shop.Id, username, password); 32 | 33 | HttpClient client = server.CreateClient(); 34 | string uri = "api/users/verify-password"; 35 | Credentials credentials = new(username, password); 36 | 37 | // Act 38 | HttpResponseMessage response = await client.PostAsJsonAsync(uri, credentials); 39 | 40 | // Assert 41 | response.StatusCode.Should().Be(HttpStatusCode.OK); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/AspNetCorePasswordHasher_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Xunit; 3 | 4 | namespace Sellers; 5 | 6 | public class AspNetCorePasswordHasher_specs 7 | { 8 | [Fact] 9 | public void Sut_implements_IPasswordHasher() 10 | { 11 | typeof(AspNetCorePasswordHasher).Should().Implement(); 12 | } 13 | 14 | [Theory, AutoSellersData] 15 | public void HashPassword_returns_different_hash_each_time( 16 | AspNetCorePasswordHasher sut, 17 | string password) 18 | { 19 | Enumerable.Range(0, 100) 20 | .Select(_ => sut.HashPassword(password)) 21 | .Should() 22 | .OnlyHaveUniqueItems(); 23 | } 24 | 25 | [Theory, AutoSellersData] 26 | public void VerifyPassword_returns_true_if_passwords_match( 27 | AspNetCorePasswordHasher sut, 28 | string password) 29 | { 30 | string hash = sut.HashPassword(password); 31 | bool actual = sut.VerifyPassword(hash, password); 32 | actual.Should().BeTrue(); 33 | } 34 | 35 | [Theory, AutoSellersData] 36 | public void VerifyPassword_returns_false_if_passwords_not_match( 37 | AspNetCorePasswordHasher sut, 38 | string password, 39 | string wrongPassword) 40 | { 41 | string hash = sut.HashPassword(password); 42 | bool actual = sut.VerifyPassword(hash, wrongPassword); 43 | actual.Should().BeFalse(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/Migrations/20220831154330_AddRoles.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace Sellers.Migrations 7 | { 8 | public partial class AddRoles : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "Roles", 14 | columns: table => new 15 | { 16 | UserSequence = table.Column(type: "bigint", nullable: false), 17 | ShopId = table.Column(type: "uuid", nullable: false), 18 | RoleName = table.Column(type: "text", nullable: false) 19 | }, 20 | constraints: table => 21 | { 22 | table.PrimaryKey("PK_Roles", x => new { x.UserSequence, x.ShopId, x.RoleName }); 23 | table.ForeignKey( 24 | name: "FK_Roles_Users_UserSequence", 25 | column: x => x.UserSequence, 26 | principalTable: "Users", 27 | principalColumn: "Sequence", 28 | onDelete: ReferentialAction.Cascade); 29 | }); 30 | } 31 | 32 | protected override void Down(MigrationBuilder migrationBuilder) 33 | { 34 | migrationBuilder.DropTable( 35 | name: "Roles"); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/Orders.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | false 7 | Orders 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | all 21 | 22 | 23 | runtime; build; native; contentfiles; analyzers; buildtransitive 24 | all 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/SellersDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace Sellers; 4 | 5 | #nullable disable 6 | 7 | public sealed class SellersDbContext : DbContext 8 | { 9 | public SellersDbContext(DbContextOptions options) 10 | : base(options) 11 | { 12 | } 13 | 14 | public DbSet Users { get; set; } 15 | 16 | public DbSet Roles { get; set; } 17 | 18 | public DbSet Shops { get; set; } 19 | 20 | protected override void OnModelCreating(ModelBuilder modelBuilder) 21 | { 22 | modelBuilder.Entity(user => 23 | { 24 | user.HasKey(x => x.Sequence); 25 | user.Property(x => x.Sequence).ValueGeneratedOnAdd(); 26 | user.HasIndex(x => x.Id).IsUnique(); 27 | user.HasIndex(x => x.Username).IsUnique(); 28 | }); 29 | 30 | modelBuilder.Entity(role => 31 | { 32 | role.HasKey(x => new { x.UserSequence, x.ShopId, x.RoleName }); 33 | }); 34 | 35 | modelBuilder.Entity(shop => 36 | { 37 | shop.HasKey(x => x.Sequence); 38 | shop.Property(x => x.Sequence).ValueGeneratedOnAdd(); 39 | shop.HasIndex(x => x.Id).IsUnique(); 40 | shop.HasIndex(x => x.Name).IsUnique(); 41 | shop.HasIndex(x => x.UserId).IsUnique(); 42 | }); 43 | } 44 | 45 | internal Task FindUser(Guid id) 46 | => Users.Include(x => x.Roles).SingleOrDefaultAsync(x => x.Id == id); 47 | } 48 | 49 | #nullable enable 50 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Messaging/StorageQueueBus.cs: -------------------------------------------------------------------------------- 1 | using Azure.Storage.Queues; 2 | using Azure.Storage.Queues.Models; 3 | using Orders.Events; 4 | using System.Reactive.Disposables; 5 | 6 | namespace Orders.Messaging; 7 | 8 | internal sealed class StorageQueueBus : 9 | IBus, 10 | IAsyncObservable 11 | { 12 | private readonly QueueClient client; 13 | 14 | public StorageQueueBus(QueueClient client) => this.client = client; 15 | 16 | public Task Send(PaymentApproved message) 17 | => client.SendMessageAsync(BinaryData.FromObjectAsJson(message)); 18 | 19 | public IDisposable Subscribe(Func onNext) 20 | { 21 | bool listening = true; 22 | Process(); 23 | return Disposable.Create(() => listening = false); 24 | 25 | async void Process() 26 | { 27 | await client.CreateIfNotExistsAsync(); 28 | 29 | while (listening) 30 | { 31 | QueueMessage[] messages = await client.ReceiveMessagesAsync(); 32 | foreach (QueueMessage m in messages) 33 | { 34 | if (listening) 35 | { 36 | await onNext.Invoke(m.Body.ToObjectFromJson()); 37 | await client.DeleteMessageAsync(m.MessageId, m.PopReceipt); 38 | } 39 | } 40 | 41 | if (messages.Any() == false) 42 | { 43 | await Task.Delay(TimeSpan.FromSeconds(3)); 44 | } 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/OrderViewAggregator.java: -------------------------------------------------------------------------------- 1 | package accounting; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.UUID; 6 | import java.util.stream.StreamSupport; 7 | 8 | public class OrderViewAggregator { 9 | 10 | private final ShopReader shopReader; 11 | 12 | public OrderViewAggregator(ShopReader shopReader) { 13 | this.shopReader = shopReader; 14 | } 15 | 16 | public Iterable aggregateViews(Iterable orders) { 17 | Map map = new HashMap<>(); 18 | return StreamSupport 19 | .stream(orders.spliterator(), false) 20 | .map(x -> new OrderView( 21 | x.getId(), 22 | x.getUserId(), 23 | map.computeIfAbsent(x.getShopId(), this::getShop), 24 | x.getItemId(), 25 | x.getPrice(), 26 | localizeStatus(x.getStatus()), 27 | x.getPaymentTransactionId(), 28 | x.getPlacedAtUtc())) 29 | .toList(); 30 | } 31 | 32 | private static String localizeStatus(String status) { 33 | return switch (status) { 34 | case "Pending" -> "보류"; 35 | case "AwaitingPayment" -> "결제대기"; 36 | case "AwaitingShipment" -> "배송대기"; 37 | case "Completed" -> "완료"; 38 | default -> status; 39 | }; 40 | } 41 | 42 | private Shop getShop(UUID shopId) { 43 | return shopReader.findShop(shopId).orElse(new Shop(shopId, shopId.toString())); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/QueryModel/PasswordVerifier_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Xunit; 3 | 4 | namespace Sellers.QueryModel; 5 | 6 | public class PasswordVerifier_specs 7 | { 8 | [Theory] 9 | [InlineAutoSellersData("hello world", "hello world", true)] 10 | [InlineAutoSellersData("hello world", "yellow word", false)] 11 | public async Task Sut_correctly_checks_password( 12 | string password, 13 | string providedPassword, 14 | bool expected, 15 | string username, 16 | Func contextFactory, 17 | IPasswordHasher hasher, 18 | Shop shop) 19 | { 20 | // Arrange 21 | PasswordVerifier sut = new(new ShopUserReader(contextFactory), hasher); 22 | 23 | using SellersDbContext context = contextFactory.Invoke(); 24 | shop.UserId = username; 25 | shop.PasswordHash = hasher.HashPassword(password); 26 | context.Shops.Add(shop); 27 | await context.SaveChangesAsync(); 28 | 29 | // Act 30 | bool actual = await sut.VerifyPassword(username, providedPassword); 31 | 32 | // Assert 33 | actual.Should().Be(expected); 34 | } 35 | 36 | [Theory, AutoSellersData] 37 | public async Task Sut_returns_false_for_unknown_username( 38 | Func contextFactory, 39 | IPasswordHasher hasher, 40 | string username, 41 | string password) 42 | { 43 | PasswordVerifier sut = new(new ShopUserReader(contextFactory), hasher); 44 | bool actual = await sut.VerifyPassword(username, password); 45 | actual.Should().BeFalse(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/api/users/id/create-user/Post_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Sellers.Commands; 3 | using System.Net; 4 | using System.Net.Http.Json; 5 | using Xunit; 6 | 7 | namespace Sellers.api.users.id.create_user; 8 | 9 | public class Post_specs 10 | { 11 | [Theory, AutoSellersData] 12 | public async Task Sut_correctly_executes_command( 13 | SellersServer server, 14 | Guid userId, 15 | CreateUser command) 16 | { 17 | using HttpClient client = server.CreateClient(); 18 | string commandUri = $"api/users/{userId}/create-user"; 19 | await client.PostAsJsonAsync(commandUri, command); 20 | 21 | string queryUri = "api/users/verify-password"; 22 | var credentials = new { command.Username, command.Password }; 23 | HttpResponseMessage response = await client.PostAsJsonAsync(queryUri, credentials); 24 | 25 | response.StatusCode.Should().Be(HttpStatusCode.OK); 26 | } 27 | 28 | [Theory, AutoSellersData] 29 | public async Task Sut_returns_BadRequest_for_duplicate_usernameAsync( 30 | SellersServer server, 31 | Guid userId1, 32 | Guid userId2, 33 | CreateUser command) 34 | { 35 | using HttpClient client = server.CreateClient(); 36 | string commandUri1 = $"api/users/{userId1}/create-user"; 37 | await client.PostAsJsonAsync(commandUri1, command); 38 | 39 | string commandUri2 = $"api/users/{userId2}/create-user"; 40 | HttpResponseMessage response = await client.PostAsJsonAsync(commandUri2, command); 41 | 42 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/unittest/src/test/java/accounting/test/OrderViewAggregator_specs.java: -------------------------------------------------------------------------------- 1 | package accounting.test; 2 | 3 | import accounting.Order; 4 | import accounting.OrderView; 5 | import accounting.OrderViewAggregator; 6 | import org.javaunit.autoparams.CsvAutoSource; 7 | import org.javaunit.autoparams.customization.Customization; 8 | import org.junit.jupiter.params.ParameterizedTest; 9 | 10 | import java.lang.reflect.Field; 11 | import java.util.List; 12 | import static org.junit.jupiter.api.Assertions.assertEquals; 13 | 14 | @SuppressWarnings("NewClassNamingConvention") 15 | public class OrderViewAggregator_specs { 16 | 17 | @ParameterizedTest 18 | @CsvAutoSource({ 19 | "Pending, 보류", 20 | "AwaitingPayment, 결제대기", 21 | "AwaitingShipment, 배송대기", 22 | "Completed, 완료", 23 | }) 24 | @Customization(AccountingCustomizer.class) 25 | void sut_localizes_status( 26 | String statusValue, 27 | String localizedValue, 28 | OrderViewAggregator sut, 29 | Order order 30 | ) { 31 | setStatus(order, statusValue); 32 | 33 | Iterable views = sut.aggregateViews(List.of(order)); 34 | 35 | OrderView actual = views.iterator().next(); 36 | assertEquals(localizedValue, actual.status()); 37 | } 38 | 39 | private static void setStatus(Order order, String statusValue) { 40 | try { 41 | Field status = Order.class.getDeclaredField("status"); 42 | status.setAccessible(true); 43 | status.set(order, statusValue); 44 | } catch (NoSuchFieldException | IllegalAccessException e) { 45 | throw new RuntimeException(e); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/CommandModel/SqlUserRepository.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using System.Collections.Immutable; 3 | 4 | namespace Sellers.CommandModel; 5 | 6 | public sealed class SqlUserRepository : IUserRepository 7 | { 8 | private static readonly IMapper mapper = new MapperConfiguration(c => 9 | { 10 | c.CreateMap(); 11 | c.CreateMap(); 12 | c.CreateMap(); 13 | c.CreateMap(); 14 | c.CreateMap, ImmutableArray>().ConvertUsing(x => ConvertRoles(x)); 15 | }).CreateMapper(); 16 | 17 | private static ImmutableArray ConvertRoles(List roles) 18 | => roles.Select(x => mapper.Map(x)).ToImmutableArray(); 19 | 20 | private readonly Func contextFactory; 21 | 22 | public SqlUserRepository(Func contextFactory) 23 | => this.contextFactory = contextFactory; 24 | 25 | public async Task Add(User user) 26 | { 27 | using SellersDbContext context = contextFactory.Invoke(); 28 | context.Users.Add(mapper.Map(user)); 29 | await context.SaveChangesAsync(); 30 | } 31 | 32 | public async Task TryUpdate(Guid id, Func reviser) 33 | { 34 | using SellersDbContext context = contextFactory.Invoke(); 35 | if (await context.FindUser(id) is UserEntity entity) 36 | { 37 | User revision = reviser.Invoke(mapper.Map(entity)); 38 | mapper.Map(revision, entity, typeof(User), typeof(UserEntity)); 39 | await context.SaveChangesAsync(); 40 | return true; 41 | } 42 | else 43 | { 44 | return false; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/Migrations/20220822123735_AddUsers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 4 | 5 | #nullable disable 6 | 7 | namespace Sellers.Migrations 8 | { 9 | public partial class AddUsers : Migration 10 | { 11 | protected override void Up(MigrationBuilder migrationBuilder) 12 | { 13 | migrationBuilder.CreateTable( 14 | name: "Users", 15 | columns: table => new 16 | { 17 | Sequence = table.Column(type: "bigint", nullable: false) 18 | .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), 19 | Id = table.Column(type: "uuid", nullable: false), 20 | Username = table.Column(type: "text", nullable: false), 21 | PasswordHash = table.Column(type: "text", nullable: true) 22 | }, 23 | constraints: table => 24 | { 25 | table.PrimaryKey("PK_Users", x => x.Sequence); 26 | }); 27 | 28 | migrationBuilder.CreateIndex( 29 | name: "IX_Users_Id", 30 | table: "Users", 31 | column: "Id", 32 | unique: true); 33 | 34 | migrationBuilder.CreateIndex( 35 | name: "IX_Users_Username", 36 | table: "Users", 37 | column: "Username", 38 | unique: true); 39 | } 40 | 41 | protected override void Down(MigrationBuilder migrationBuilder) 42 | { 43 | migrationBuilder.DropTable( 44 | name: "Users"); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/api/orders/handle/bank-transder-payment-completed/Post_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using System.Net; 3 | using Xunit; 4 | 5 | namespace Orders.api.orders.handle.bank_transder_payment_completed; 6 | 7 | public class Post_specs 8 | { 9 | [Fact] 10 | public async Task Sut_fails_if_order_is_pending() 11 | { 12 | OrdersServer server = OrdersServer.Create(); 13 | Guid orderId = Guid.NewGuid(); 14 | await server.PlaceOrder(orderId); 15 | 16 | HttpResponseMessage response = await 17 | server.HandleBankTransferPaymentCompleted(orderId); 18 | 19 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 20 | } 21 | 22 | [Fact] 23 | public async Task Sut_fails_if_payment_already_completed() 24 | { 25 | OrdersServer server = OrdersServer.Create(); 26 | Guid orderId = Guid.NewGuid(); 27 | await server.PlaceOrder(orderId); 28 | await server.StartOrder(orderId); 29 | await server.HandleBankTransferPaymentCompleted(orderId); 30 | 31 | HttpResponseMessage response = await 32 | server.HandleBankTransferPaymentCompleted(orderId); 33 | 34 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 35 | } 36 | 37 | [Fact] 38 | public async Task Sut_fails_if_order_completed() 39 | { 40 | OrdersServer server = OrdersServer.Create(); 41 | Guid orderId = Guid.NewGuid(); 42 | await server.PlaceOrder(orderId); 43 | await server.StartOrder(orderId); 44 | await server.HandleBankTransferPaymentCompleted(orderId); 45 | await server.HandleItemShipped(orderId); 46 | 47 | HttpResponseMessage response = await 48 | server.HandleBankTransferPaymentCompleted(orderId); 49 | 50 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/CommandModel/GrantRoleCommandExecutor_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Sellers.Commands; 3 | using Sellers.QueryModel; 4 | using Xunit; 5 | 6 | namespace Sellers.CommandModel; 7 | 8 | public class GrantRoleCommandExecutor_specs 9 | { 10 | [Theory, AutoSellersData] 11 | public async Task Sut_correctly_adds_role_to_user( 12 | Func contextFactory, 13 | User user, 14 | GrantRole command) 15 | { 16 | SqlUserRepository repository = new(contextFactory); 17 | await repository.Add(user); 18 | GrantRoleCommandExecutor sut = new(repository); 19 | 20 | await sut.Execute(user.Id, command); 21 | 22 | SqlUserReader reader = new(contextFactory); 23 | User actual = (await reader.FindUser(user.Id))!; 24 | Role role = new(command.ShopId, command.RoleName); 25 | actual.Roles.Should().Contain(role); 26 | } 27 | 28 | [Theory, AutoSellersData] 29 | public async Task Sut_fails_if_entity_not_found( 30 | GrantRoleCommandExecutor sut, 31 | Guid userId, 32 | GrantRole command) 33 | { 34 | Func action = () => sut.Execute(userId, command); 35 | await action.Should().ThrowAsync(); 36 | } 37 | 38 | [Theory, AutoSellersData] 39 | public async Task Sut_is_idempotent( 40 | Func contextFactory, 41 | User user, 42 | GrantRole command) 43 | { 44 | SqlUserRepository repository = new(contextFactory); 45 | await repository.Add(user); 46 | GrantRoleCommandExecutor sut = new(repository); 47 | 48 | await sut.Execute(user.Id, command); 49 | await sut.Execute(user.Id, command); 50 | 51 | SqlUserReader reader = new(contextFactory); 52 | User actual = (await reader.FindUser(user.Id))!; 53 | Role role = new(command.ShopId, command.RoleName); 54 | actual.Roles.Should().Contain(role); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/api/users/id/roles/Get_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using System.Net; 4 | using System.Net.Http.Json; 5 | using Xunit; 6 | 7 | namespace Sellers.api.users.id.roles; 8 | 9 | public class Get_specs 10 | { 11 | [Theory, AutoSellersData] 12 | public async Task Sut_returns_NotFound_with_nonexistent_id( 13 | SellersServer server, 14 | Guid id) 15 | { 16 | string uri = $"api/users/{id}/roles"; 17 | HttpResponseMessage actual = await server.CreateClient().GetAsync(uri); 18 | actual.StatusCode.Should().Be(HttpStatusCode.NotFound); 19 | } 20 | 21 | [Theory, AutoSellersData] 22 | public async Task Sut_returns_OK_with_existing_id( 23 | SellersServer server, 24 | Shop shop) 25 | { 26 | using IServiceScope scope = server.Services.CreateScope(); 27 | SellersDbContext context = scope.ServiceProvider.GetRequiredService(); 28 | context.Shops.Add(shop); 29 | await context.SaveChangesAsync(); 30 | 31 | string uri = $"api/users/{shop.Id}/roles"; 32 | HttpResponseMessage actual = await server.CreateClient().GetAsync(uri); 33 | 34 | actual.StatusCode.Should().Be(HttpStatusCode.OK); 35 | } 36 | 37 | [Theory, AutoSellersData] 38 | public async Task Sut_correctly_returns_roles( 39 | SellersServer server, 40 | Shop shop) 41 | { 42 | using IServiceScope scope = server.Services.CreateScope(); 43 | SellersDbContext context = scope.ServiceProvider.GetRequiredService(); 44 | context.Shops.Add(shop); 45 | await context.SaveChangesAsync(); 46 | 47 | string uri = $"api/users/{shop.Id}/roles"; 48 | HttpResponseMessage response = await server.CreateClient().GetAsync(uri); 49 | 50 | Role[]? actual = await response.Content.ReadFromJsonAsync(); 51 | actual.Should().BeEquivalentTo(new[] { new Role(shop.Id, "Administrator") }); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/HttpShopReader.java: -------------------------------------------------------------------------------- 1 | package accounting; 2 | 3 | import com.fasterxml.jackson.databind.DeserializationFeature; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import java.io.IOException; 7 | import java.net.URI; 8 | import java.net.http.HttpClient; 9 | import java.net.http.HttpRequest; 10 | import java.net.http.HttpResponse; 11 | import java.util.Optional; 12 | import java.util.UUID; 13 | 14 | public class HttpShopReader implements ShopReader { 15 | 16 | private final HttpClient client; 17 | private final String host; 18 | private final ObjectMapper mapper = getMapper(); 19 | 20 | private static ObjectMapper getMapper() { 21 | return new ObjectMapper().configure( 22 | DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, 23 | false); 24 | } 25 | 26 | public HttpShopReader(HttpClient client, String host) { 27 | this.client = client; 28 | this.host = host; 29 | } 30 | 31 | @Override 32 | public Optional findShop(UUID id) { 33 | URI uri = URI.create(host + "/api/shops/" + id); 34 | HttpResponse response = getString(uri); 35 | if (response.statusCode() == 200) { 36 | try { 37 | return Optional.of(mapper.readValue(response.body(), Shop.class)); 38 | } catch (IOException e) { 39 | throw new RuntimeException(e); 40 | } 41 | } else { 42 | return Optional.empty(); 43 | } 44 | } 45 | 46 | private HttpResponse getString(URI uri) { 47 | HttpRequest request = HttpRequest 48 | .newBuilder() 49 | .GET() 50 | .uri(uri) 51 | .build(); 52 | try { 53 | return client.send( 54 | request, 55 | HttpResponse.BodyHandlers.ofString()); 56 | } catch (IOException | InterruptedException e) { 57 | throw new RuntimeException(e); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/CommandModel/CreateUserCommandExecutor_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Sellers.Commands; 3 | using Sellers.QueryModel; 4 | using Xunit; 5 | 6 | namespace Sellers.CommandModel; 7 | 8 | public class CreateUserCommandExecutor_specs 9 | { 10 | [Theory, AutoSellersData] 11 | public async Task Sut_creates_user_entity( 12 | IPasswordHasher hasher, 13 | SqlUserReader reader, 14 | SqlUserRepository repository, 15 | Guid userId, 16 | CreateUser command) 17 | { 18 | CreateUserCommandExecutor sut = new(hasher, reader, repository); 19 | 20 | await sut.Execute(userId, command); 21 | 22 | User? actual = await reader.FindUser(command.Username); 23 | actual.Should().NotBeNull(); 24 | actual!.Id.Should().Be(userId); 25 | } 26 | 27 | [Theory, AutoSellersData] 28 | public async Task Sut_correctly_hashes_password( 29 | IPasswordHasher hasher, 30 | SqlUserReader reader, 31 | SqlUserRepository repository, 32 | Guid userId, 33 | CreateUser command) 34 | { 35 | CreateUserCommandExecutor sut = new(hasher, reader, repository); 36 | 37 | await sut.Execute(userId, command); 38 | 39 | User? actual = await reader.FindUser(command.Username); 40 | string passwordHash = actual!.PasswordHash; 41 | hasher.VerifyPassword(passwordHash, command.Password).Should().BeTrue(); 42 | } 43 | 44 | [Theory, AutoSellersData] 45 | public async Task Sut_fails_for_duplicate_username( 46 | IPasswordHasher hasher, 47 | SqlUserReader reader, 48 | SqlUserRepository repository, 49 | Guid userId1, 50 | Guid userId2, 51 | CreateUser command) 52 | { 53 | CreateUserCommandExecutor sut = new(hasher, reader, repository); 54 | await sut.Execute(userId1, command); 55 | 56 | Func action = () => sut.Execute(userId2, command); 57 | 58 | await action.Should().ThrowAsync(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/Migrations/20220822113310_AddShops.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 4 | 5 | #nullable disable 6 | 7 | namespace Sellers.Migrations 8 | { 9 | public partial class AddShops : Migration 10 | { 11 | protected override void Up(MigrationBuilder migrationBuilder) 12 | { 13 | migrationBuilder.CreateTable( 14 | name: "Shops", 15 | columns: table => new 16 | { 17 | Sequence = table.Column(type: "integer", nullable: false) 18 | .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), 19 | Id = table.Column(type: "uuid", nullable: false), 20 | Name = table.Column(type: "text", nullable: false), 21 | UserId = table.Column(type: "text", nullable: true), 22 | PasswordHash = table.Column(type: "text", nullable: true) 23 | }, 24 | constraints: table => 25 | { 26 | table.PrimaryKey("PK_Shops", x => x.Sequence); 27 | }); 28 | 29 | migrationBuilder.CreateIndex( 30 | name: "IX_Shops_Id", 31 | table: "Shops", 32 | column: "Id", 33 | unique: true); 34 | 35 | migrationBuilder.CreateIndex( 36 | name: "IX_Shops_Name", 37 | table: "Shops", 38 | column: "Name", 39 | unique: true); 40 | 41 | migrationBuilder.CreateIndex( 42 | name: "IX_Shops_UserId", 43 | table: "Shops", 44 | column: "UserId", 45 | unique: true); 46 | } 47 | 48 | protected override void Down(MigrationBuilder migrationBuilder) 49 | { 50 | migrationBuilder.DropTable( 51 | name: "Shops"); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/SellersServer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting.Server; 2 | using Microsoft.AspNetCore.Mvc.Testing; 3 | using Microsoft.AspNetCore.TestHost; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Options; 9 | 10 | namespace Sellers; 11 | 12 | public sealed class SellersServer : TestServer 13 | { 14 | public SellersServer( 15 | IServiceProvider services, 16 | IOptions optionsAccessor) 17 | : base(services, optionsAccessor) 18 | { 19 | } 20 | 21 | public static SellersServer Create( 22 | string connectionString = SellersDatabase.DefaultConnectionString) 23 | { 24 | SellersServer server = (SellersServer)new Factory(connectionString).Server; 25 | 26 | lock (typeof(SellersDbContext)) 27 | { 28 | using IServiceScope scope = server.Services.CreateScope(); 29 | SellersDbContext context = scope.ServiceProvider.GetRequiredService(); 30 | context.Database.Migrate(); 31 | } 32 | 33 | return server; 34 | } 35 | 36 | private sealed class Factory : WebApplicationFactory 37 | { 38 | private readonly string connectionString; 39 | 40 | public Factory(string connectionString) 41 | => this.connectionString = connectionString; 42 | 43 | protected override IHost CreateHost(IHostBuilder builder) 44 | { 45 | builder.ConfigureServices(services => 46 | { 47 | services.AddSingleton(); 48 | }); 49 | 50 | builder.ConfigureAppConfiguration((context, config) => 51 | { 52 | config.AddInMemoryCollection(new Dictionary 53 | { 54 | ["ConnectionStrings:DefaultConnection"] = connectionString, 55 | }); 56 | }); 57 | 58 | return base.CreateHost(builder); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/controller/OrdersController.java: -------------------------------------------------------------------------------- 1 | package accounting.controller; 2 | 3 | import accounting.Order; 4 | import accounting.OrderReader; 5 | import accounting.OrderView; 6 | import accounting.OrderViewAggregator; 7 | import accounting.query.GetOrdersPlacedIn; 8 | import io.swagger.v3.oas.annotations.media.ArraySchema; 9 | import io.swagger.v3.oas.annotations.media.Content; 10 | import io.swagger.v3.oas.annotations.media.Schema; 11 | import io.swagger.v3.oas.annotations.responses.ApiResponse; 12 | import org.springframework.web.bind.annotation.PostMapping; 13 | import org.springframework.web.bind.annotation.RequestBody; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | import java.time.LocalDateTime; 18 | 19 | @SuppressWarnings("unused") 20 | @RestController 21 | @RequestMapping("/api/orders") 22 | public class OrdersController { 23 | 24 | private final OrderReader reader; 25 | private final OrderViewAggregator aggregator; 26 | 27 | public OrdersController(OrderReader reader, OrderViewAggregator aggregator) { 28 | this.reader = reader; 29 | this.aggregator = aggregator; 30 | } 31 | 32 | @PostMapping("/get-orders-placed-in") 33 | @ApiResponse(content = { 34 | @Content( 35 | mediaType = "application/json", 36 | array = @ArraySchema(schema = @Schema(implementation = OrderView.class))) 37 | }) 38 | public Iterable getOrdersPlacedIn(@RequestBody GetOrdersPlacedIn query) { 39 | LocalDateTime startInclusive = LocalDateTime.of(query.year(), query.month(), 1, 0, 0); 40 | LocalDateTime endExclusive = startInclusive.plusMonths(1); 41 | Iterable orders = reader.getOrdersPlacedIn( 42 | query.shopId(), 43 | convertKstToUtc(startInclusive), 44 | convertKstToUtc(endExclusive)); 45 | return aggregator.aggregateViews(orders); 46 | } 47 | 48 | private LocalDateTime convertKstToUtc(LocalDateTime kst) { 49 | return kst.minusHours(9); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/api/src/main/java/accounting/Order.java: -------------------------------------------------------------------------------- 1 | package accounting; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.Id; 6 | import java.math.BigDecimal; 7 | import java.time.LocalDateTime; 8 | import java.util.UUID; 9 | 10 | @SuppressWarnings("unused") 11 | @Entity(name = "Orders") 12 | public class Order { 13 | 14 | @Column(name = "Id") 15 | private UUID id; 16 | 17 | @Id 18 | @Column(name = "Sequence") 19 | private Long sequence; 20 | 21 | @Column(name = "UserId") 22 | private UUID userId; 23 | 24 | @Column(name = "ShopId") 25 | private UUID shopId; 26 | 27 | @Column(name = "ItemId") 28 | private UUID itemId; 29 | 30 | @Column(name = "Price") 31 | private BigDecimal price; 32 | 33 | @Column(name = "Status") 34 | private String status; 35 | 36 | @Column(name = "PaymentTransactionId") 37 | private String paymentTransactionId; 38 | 39 | @Column(name = "PlacedAtUtc") 40 | private LocalDateTime placedAtUtc; 41 | 42 | @Column(name = "StartedAtUtc") 43 | private LocalDateTime startedAtUtc; 44 | 45 | @Column(name = "PaidAtUtc") 46 | private LocalDateTime paidAtUtc; 47 | 48 | @Column(name = "ShippedAtUtc") 49 | private LocalDateTime shippedAtUtc; 50 | 51 | public UUID getId() { 52 | return id; 53 | } 54 | 55 | public UUID getUserId() { 56 | return userId; 57 | } 58 | 59 | public UUID getShopId() { 60 | return shopId; 61 | } 62 | 63 | public UUID getItemId() { 64 | return itemId; 65 | } 66 | 67 | public BigDecimal getPrice() { 68 | return price; 69 | } 70 | 71 | public String getStatus() { 72 | return status; 73 | } 74 | 75 | public String getPaymentTransactionId() { 76 | return paymentTransactionId; 77 | } 78 | 79 | public LocalDateTime getPlacedAtUtc() { 80 | return placedAtUtc; 81 | } 82 | 83 | public LocalDateTime getStartedAtUtc() { 84 | return startedAtUtc; 85 | } 86 | 87 | public LocalDateTime getPaidAtUtc() { 88 | return paidAtUtc; 89 | } 90 | 91 | public LocalDateTime getShippedAtUtc() { 92 | return shippedAtUtc; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Api/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using Microsoft.EntityFrameworkCore; 3 | using Sellers.CommandModel; 4 | using Sellers.QueryModel; 5 | 6 | namespace Sellers; 7 | 8 | public class Program 9 | { 10 | public static void Main(string[] args) 11 | { 12 | var builder = WebApplication.CreateBuilder(args); 13 | 14 | IServiceCollection services = builder.Services; 15 | 16 | services.AddDbContext(ConfigureDbContextOptions); 17 | services.AddSingleton(GetDbContextFactory); 18 | 19 | services.AddSingleton, PasswordHasher>(); 20 | services.AddSingleton>(); 21 | services.AddSingleton(); 22 | services.AddSingleton(); 23 | 24 | services.AddSingleton(); 25 | services.AddSingleton(); 26 | services.AddSingleton(); 27 | services.AddSingleton(); 28 | services.AddSingleton(); 29 | 30 | services.AddControllers(); 31 | services.AddEndpointsApiExplorer(); 32 | services.AddSwaggerGen(); 33 | 34 | var app = builder.Build(); 35 | 36 | if (app.Environment.IsDevelopment()) 37 | { 38 | app.UseSwagger(); 39 | app.UseSwaggerUI(); 40 | } 41 | 42 | app.UseAuthorization(); 43 | app.MapControllers(); 44 | app.Run(); 45 | } 46 | 47 | private static void ConfigureDbContextOptions( 48 | IServiceProvider provider, 49 | DbContextOptionsBuilder options) 50 | { 51 | IConfiguration config = provider.GetRequiredService(); 52 | options.UseNpgsql(config.GetConnectionString("DefaultConnection")); 53 | } 54 | 55 | private static Func GetDbContextFactory( 56 | IServiceProvider provider) 57 | { 58 | DbContextOptionsBuilder options = new(); 59 | ConfigureDbContextOptions(provider, options); 60 | return () => new SellersDbContext(options.Options); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/Migrations/20220822113310_AddShops.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 8 | using Sellers; 9 | 10 | #nullable disable 11 | 12 | namespace Sellers.Migrations 13 | { 14 | [DbContext(typeof(SellersDbContext))] 15 | [Migration("20220822113310_AddShops")] 16 | partial class AddShops 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.8") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 63); 24 | 25 | NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); 26 | 27 | modelBuilder.Entity("Sellers.Shop", b => 28 | { 29 | b.Property("Sequence") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("integer"); 32 | 33 | NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Sequence")); 34 | 35 | b.Property("Id") 36 | .HasColumnType("uuid"); 37 | 38 | b.Property("Name") 39 | .IsRequired() 40 | .HasColumnType("text"); 41 | 42 | b.Property("PasswordHash") 43 | .HasColumnType("text"); 44 | 45 | b.Property("UserId") 46 | .HasColumnType("text"); 47 | 48 | b.HasKey("Sequence"); 49 | 50 | b.HasIndex("Id") 51 | .IsUnique(); 52 | 53 | b.HasIndex("Name") 54 | .IsUnique(); 55 | 56 | b.HasIndex("UserId") 57 | .IsUnique(); 58 | 59 | b.ToTable("Shops"); 60 | }); 61 | #pragma warning restore 612, 618 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Api/Controllers/UsersController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Sellers.CommandModel; 3 | using Sellers.Commands; 4 | using Sellers.Filters; 5 | using Sellers.QueryModel; 6 | 7 | namespace Sellers.Controllers; 8 | 9 | [Route("api/users")] 10 | public class UsersController : Controller 11 | { 12 | [HttpPost("verify-password")] 13 | [ProducesResponseType(200)] 14 | [ProducesResponseType(400)] 15 | public async Task VerifyPassword( 16 | [FromBody] Credentials credentials, 17 | [FromServices] PasswordVerifier verifier) 18 | { 19 | (string username, string password) = credentials; 20 | return await verifier.VerifyPassword(username, password) switch 21 | { 22 | true => Ok(), 23 | _ => BadRequest(), 24 | }; 25 | } 26 | 27 | [HttpPost("{id}/create-user")] 28 | [ProducesResponseType(200)] 29 | [ProducesResponseType(400)] 30 | [TypeFilter(typeof(InvariantViolationFilter))] 31 | public Task CreateUser( 32 | Guid id, 33 | [FromBody] CreateUser command, 34 | [FromServices] CreateUserCommandExecutor executor) 35 | { 36 | return executor.Execute(id, command); 37 | } 38 | 39 | [HttpGet("{id}/roles")] 40 | [ProducesResponseType(200, Type = typeof(Role[]))] 41 | [ProducesResponseType(404)] 42 | public async Task GetRoles( 43 | Guid id, 44 | [FromServices] IUserReader reader) 45 | { 46 | return await reader.FindUser(id) switch 47 | { 48 | User user => Ok(user.Roles), 49 | _ => NotFound() 50 | }; 51 | } 52 | 53 | [HttpPost("{id}/grant-role")] 54 | [ProducesResponseType(200)] 55 | public Task GrantRole( 56 | Guid id, 57 | [FromBody] GrantRole command, 58 | [FromServices] GrantRoleCommandExecutor executor) 59 | { 60 | return executor.Execute(id, command); 61 | } 62 | 63 | [HttpPost("{id}/revoke-role")] 64 | [ProducesResponseType(200)] 65 | public Task RevokeRole( 66 | Guid id, 67 | [FromBody] RevokeRole command, 68 | [FromServices] RevokeRoleCommandExecutor executor) 69 | { 70 | return executor.Execute(id, command); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/OrdersServer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting.Server; 2 | using Microsoft.AspNetCore.Mvc.Testing; 3 | using Microsoft.AspNetCore.TestHost; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Options; 9 | using Sellers; 10 | 11 | namespace Orders; 12 | 13 | public sealed class OrdersServer : TestServer 14 | { 15 | private const string ConnectionString = "Server=127.0.0.1;Port=5432;Database=Orders_UnitTests;User Id=postgres;Password=mysecretpassword;"; 16 | 17 | private static readonly Dictionary TestSettings = new() 18 | { 19 | ["ConnectionStrings:DefaultConnection"] = ConnectionString, 20 | ["Storage:Queues:PaymentApproved"] = "payment-approved-unittests", 21 | }; 22 | 23 | public OrdersServer( 24 | IServiceProvider services, 25 | IOptions optionsAccessor) 26 | : base(services, optionsAccessor) 27 | { 28 | } 29 | 30 | public static OrdersServer Create() 31 | { 32 | OrdersServer server = (OrdersServer)new Factory().Server; 33 | 34 | lock (typeof(OrdersDbContext)) 35 | { 36 | using IServiceScope scope = server.Services.CreateScope(); 37 | OrdersDbContext context = scope.ServiceProvider.GetRequiredService(); 38 | context.Database.Migrate(); 39 | } 40 | 41 | return server; 42 | } 43 | 44 | private sealed class Factory : WebApplicationFactory 45 | { 46 | protected override IHost CreateHost(IHostBuilder builder) 47 | { 48 | builder.ConfigureServices(services => 49 | { 50 | services.AddSingleton(); 51 | 52 | SellersServer sellersServer = SellersServer.Create(); 53 | services.AddSingleton(sellersServer); 54 | services.AddSingleton(new SellersService(sellersServer.CreateClient())); 55 | }); 56 | 57 | builder.ConfigureAppConfiguration((context, config) => 58 | { 59 | config.AddInMemoryCollection(TestSettings); 60 | }); 61 | 62 | return base.CreateHost(builder); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/QueryModel/BackwardCompatibleUserReader_specs.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture.Xunit2; 2 | using FluentAssertions; 3 | using System.Reflection; 4 | using Xunit; 5 | 6 | namespace Sellers.QueryModel; 7 | 8 | public class BackwardCompatibleUserReader_specs 9 | { 10 | [Theory, AutoSellersData] 11 | public async Task Sut_returns_correct_entity_with_username_from_user_model( 12 | [Frozen] Func contextFactory, 13 | BackwardCompatibleUserReader sut, 14 | UserEntity user) 15 | { 16 | using SellersDbContext context = contextFactory.Invoke(); 17 | context.Users.Add(user); 18 | await context.SaveChangesAsync(); 19 | 20 | User? actual = await sut.FindUser(user.Username); 21 | 22 | actual.Should().BeEquivalentTo(user, c => c.ExcludingMissingMembers()); 23 | } 24 | 25 | [Theory, AutoSellersData] 26 | public async Task Sut_returns_correct_entity_with_username_from_shop_model( 27 | [Frozen] Func contextFactory, 28 | BackwardCompatibleUserReader sut, 29 | Shop shop) 30 | { 31 | using SellersDbContext context = contextFactory.Invoke(); 32 | context.Shops.Add(shop); 33 | await context.SaveChangesAsync(); 34 | 35 | User? actual = await sut.FindUser(shop.UserId); 36 | 37 | actual.Should().BeEquivalentTo(new 38 | { 39 | shop.Id, 40 | Username = shop.UserId, 41 | shop.PasswordHash, 42 | }); 43 | } 44 | 45 | [Theory, AutoSellersData] 46 | public async Task Sut_returns_null_for_unknown_name( 47 | BackwardCompatibleUserReader sut, 48 | string username) 49 | { 50 | User? actual = await sut.FindUser(username); 51 | actual.Should().BeNull(); 52 | } 53 | 54 | [Theory, AutoSellersData] 55 | public async Task Sut_returns_correct_entity_with_id_from_user_model( 56 | [Frozen] Func contextFactory, 57 | BackwardCompatibleUserReader sut, 58 | UserEntity user) 59 | { 60 | using SellersDbContext context = contextFactory.Invoke(); 61 | context.Users.Add(user); 62 | await context.SaveChangesAsync(); 63 | 64 | User? actual = await sut.FindUser(user.Id); 65 | 66 | actual.Should().BeEquivalentTo(user, c => c.ExcludingMissingMembers()); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Program.cs: -------------------------------------------------------------------------------- 1 | using Azure.Storage.Queues; 2 | using Microsoft.EntityFrameworkCore; 3 | using Orders.Events; 4 | using Orders.Messaging; 5 | 6 | namespace Orders; 7 | 8 | public class Program 9 | { 10 | public static void Main(string[] args) 11 | { 12 | var builder = WebApplication.CreateBuilder(args); 13 | 14 | IServiceCollection services = builder.Services; 15 | 16 | services.AddDbContext(ConfigureDbContextOptions); 17 | services.AddHttpClient(ConfigureSellersClient); 18 | 19 | services.AddSingleton(provider => new StorageQueueBus(GetQueueClient(provider))); 20 | services.AddSingleton>(GetQueueBus); 21 | services.AddSingleton>(GetQueueBus); 22 | 23 | services.AddControllers(); 24 | services.AddEndpointsApiExplorer(); 25 | services.AddSwaggerGen(); 26 | 27 | var app = builder.Build(); 28 | 29 | if (app.Environment.IsDevelopment()) 30 | { 31 | app.UseSwagger(); 32 | app.UseSwaggerUI(); 33 | } 34 | 35 | app.UseAuthorization(); 36 | app.MapControllers(); 37 | 38 | PaymentApprovedEventHandler.Listen(app.Services); 39 | 40 | app.Run(); 41 | } 42 | 43 | private static void ConfigureDbContextOptions( 44 | IServiceProvider provider, 45 | DbContextOptionsBuilder options) 46 | { 47 | IConfiguration config = provider.GetRequiredService(); 48 | options.UseNpgsql(config.GetConnectionString("DefaultConnection")); 49 | } 50 | 51 | private static void ConfigureSellersClient( 52 | IServiceProvider provider, 53 | HttpClient client) 54 | { 55 | IConfiguration config = provider.GetRequiredService(); 56 | client.BaseAddress = new Uri(config["Sellers:Host"]); 57 | } 58 | 59 | private static QueueClient GetQueueClient(IServiceProvider provider) 60 | { 61 | IConfiguration config = provider.GetRequiredService(); 62 | return new( 63 | config["Storage:ConnectionString"], 64 | config["Storage:Queues:PaymentApproved"]); 65 | } 66 | 67 | private static StorageQueueBus GetQueueBus(IServiceProvider provider) 68 | => provider.GetRequiredService(); 69 | } 70 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/api/orders/id/start-order/Post_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using System.Net; 3 | using System.Net.Http.Json; 4 | using Xunit; 5 | 6 | namespace Orders.api.orders.id.start_order; 7 | 8 | public class Post_specs 9 | { 10 | [Fact] 11 | public async Task Sut_fails_if_order_already_started() 12 | { 13 | OrdersServer server = OrdersServer.Create(); 14 | Guid orderId = Guid.NewGuid(); 15 | await server.PlaceOrder(orderId); 16 | await server.StartOrder(orderId); 17 | 18 | HttpResponseMessage response = await server.StartOrder(orderId); 19 | 20 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 21 | } 22 | 23 | [Fact] 24 | public async Task Sut_fails_if_payment_completed() 25 | { 26 | OrdersServer server = OrdersServer.Create(); 27 | Guid orderId = Guid.NewGuid(); 28 | await server.PlaceOrder(orderId); 29 | await server.StartOrder(orderId); 30 | await server.HandleBankTransferPaymentCompleted(orderId); 31 | 32 | HttpResponseMessage response = await server.StartOrder(orderId); 33 | 34 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 35 | } 36 | 37 | [Fact] 38 | public async Task Sut_fails_if_order_completed() 39 | { 40 | OrdersServer server = OrdersServer.Create(); 41 | Guid orderId = Guid.NewGuid(); 42 | await server.PlaceOrder(orderId); 43 | await server.StartOrder(orderId); 44 | await server.HandleBankTransferPaymentCompleted(orderId); 45 | await server.HandleItemShipped(orderId); 46 | 47 | HttpResponseMessage response = await server.StartOrder(orderId); 48 | 49 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 50 | } 51 | 52 | [Fact] 53 | public async Task Sut_correctly_sets_transaction_id() 54 | { 55 | OrdersServer server = OrdersServer.Create(); 56 | Guid orderId = Guid.NewGuid(); 57 | await server.PlaceOrder(orderId); 58 | string paymentTransactionId = $"{Guid.NewGuid()}"; 59 | 60 | await server.StartOrder(orderId, paymentTransactionId); 61 | 62 | HttpClient client = server.CreateClient(); 63 | HttpResponseMessage response = await client.GetAsync($"api/orders/{orderId}"); 64 | Order? order = await response.Content.ReadFromJsonAsync(); 65 | order!.PaymentTransactionId.Should().Be(paymentTransactionId); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/api/orders/id/place-order/Post_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Orders.Commands; 3 | using Sellers; 4 | using System.Net; 5 | using System.Net.Http.Json; 6 | using Xunit; 7 | 8 | namespace Orders.api.orders.id.place_order; 9 | 10 | public class Post_specs 11 | { 12 | [Fact] 13 | public async Task Sut_returns_BadRequest_if_shop_not_exists() 14 | { 15 | OrdersServer server = OrdersServer.Create(); 16 | string uri = $"api/orders/{Guid.NewGuid()}/place-order"; 17 | PlaceOrder body = new( 18 | UserId: Guid.NewGuid(), 19 | ShopId: Guid.NewGuid(), 20 | ItemId: Guid.NewGuid(), 21 | Price: 100000); 22 | 23 | HttpClient client = server.CreateClient(); 24 | HttpResponseMessage response = await client.PostAsJsonAsync(uri, body); 25 | 26 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 27 | } 28 | 29 | [Fact] 30 | public async Task Sut_returns_OK_if_shop_exists() 31 | { 32 | // Arrange 33 | OrdersServer server = OrdersServer.Create(); 34 | 35 | ShopView shop = await server.GetSellersServer().CreateShop(); 36 | 37 | string uri = $"api/orders/{Guid.NewGuid()}/place-order"; 38 | 39 | PlaceOrder body = new( 40 | UserId: Guid.NewGuid(), 41 | ShopId: shop.Id, 42 | ItemId: Guid.NewGuid(), 43 | Price: 100000); 44 | 45 | // Act 46 | HttpClient client = server.CreateClient(); 47 | HttpResponseMessage response = await client.PostAsJsonAsync(uri, body); 48 | 49 | // Assert 50 | response.StatusCode.Should().Be(HttpStatusCode.OK); 51 | } 52 | 53 | [Fact] 54 | public async Task Sut_does_not_create_order_if_shop_not_exists() 55 | { 56 | // Arrange 57 | OrdersServer server = OrdersServer.Create(); 58 | 59 | Guid orderId = Guid.NewGuid(); 60 | 61 | string commandUri = $"api/orders/{orderId}/place-order"; 62 | 63 | PlaceOrder body = new( 64 | UserId: Guid.NewGuid(), 65 | ShopId: Guid.NewGuid(), 66 | ItemId: Guid.NewGuid(), 67 | Price: 100000); 68 | 69 | HttpClient client = server.CreateClient(); 70 | 71 | // Act 72 | await client.PostAsJsonAsync(commandUri, body); 73 | 74 | // Assert 75 | string queryUri = $"api/orders/{orderId}"; 76 | HttpResponseMessage response = await client.GetAsync(queryUri); 77 | response.StatusCode.Should().Be(HttpStatusCode.NotFound); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/api/orders/handle/item-shipped/Post_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Orders.Events; 3 | using System.Net; 4 | using System.Net.Http.Json; 5 | using Xunit; 6 | 7 | namespace Orders.api.orders.handle.item_shipped; 8 | 9 | public class Post_specs 10 | { 11 | [Fact] 12 | public async Task Sut_correctly_sets_event_time() 13 | { 14 | OrdersServer server = OrdersServer.Create(); 15 | Guid orderId = Guid.NewGuid(); 16 | await server.PlaceOrder(orderId); 17 | await server.StartOrder(orderId); 18 | await server.HandleBankTransferPaymentCompleted(orderId); 19 | 20 | DateTime now = DateTime.UtcNow; 21 | ItemShipped body = new(orderId, EventTimeUtc: now); 22 | await server.HandleItemShipped(body); 23 | 24 | HttpClient client = server.CreateClient(); 25 | HttpResponseMessage response = await client.GetAsync($"api/orders/{orderId}"); 26 | Order? order = await response.Content.ReadFromJsonAsync(); 27 | TimeSpan precision = TimeSpan.FromMilliseconds(20); 28 | order!.ShippedAtUtc.Should().BeCloseTo(now, precision); 29 | } 30 | 31 | [Fact] 32 | public async Task Sut_fails_if_order_not_started() 33 | { 34 | OrdersServer server = OrdersServer.Create(); 35 | Guid orderId = Guid.NewGuid(); 36 | await server.PlaceOrder(orderId); 37 | 38 | HttpResponseMessage response = await server.HandleItemShipped(orderId); 39 | 40 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 41 | } 42 | 43 | [Fact] 44 | public async Task Sut_fails_if_payment_not_completed() 45 | { 46 | OrdersServer server = OrdersServer.Create(); 47 | Guid orderId = Guid.NewGuid(); 48 | await server.PlaceOrder(orderId); 49 | await server.StartOrder(orderId); 50 | 51 | HttpResponseMessage response = await server.HandleItemShipped(orderId); 52 | 53 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 54 | } 55 | 56 | [Fact] 57 | public async Task Sut_fails_if_order_already_completed() 58 | { 59 | OrdersServer server = OrdersServer.Create(); 60 | Guid orderId = Guid.NewGuid(); 61 | await server.PlaceOrder(orderId); 62 | await server.StartOrder(orderId); 63 | await server.HandleBankTransferPaymentCompleted(orderId); 64 | await server.HandleItemShipped(orderId); 65 | 66 | HttpResponseMessage response = await server.HandleItemShipped(orderId); 67 | 68 | response.StatusCode.Should().Be(HttpStatusCode.BadRequest); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Testing/TestSpecificLanguage.cs: -------------------------------------------------------------------------------- 1 | using Sellers.Commands; 2 | using System.Net.Http.Json; 3 | 4 | namespace Sellers; 5 | 6 | public static class TestSpecificLanguage 7 | { 8 | public static async Task CreateShop(this SellersServer server) 9 | { 10 | HttpClient client = server.CreateClient(); 11 | string uri = "api/shops"; 12 | var body = new { Name = $"{Guid.NewGuid()}" }; 13 | HttpResponseMessage response = await client.PostAsJsonAsync(uri, body); 14 | return (await response.Content.ReadFromJsonAsync())!; 15 | } 16 | 17 | public static Task SetShopUser( 18 | this SellersServer server, 19 | Guid shopId, 20 | string username, 21 | string password) 22 | { 23 | HttpClient client = server.CreateClient(); 24 | string uri = $"api/shops/{shopId}/user"; 25 | ShopUser body = new(username, password); 26 | return client.PostAsJsonAsync(uri, body); 27 | } 28 | 29 | public static Task CreateUser( 30 | this SellersServer server, 31 | Guid userId, 32 | string username, 33 | string password) 34 | { 35 | HttpClient client = server.CreateClient(); 36 | string uri = $"api/users/{userId}/create-user"; 37 | CreateUser body = new(username, password); 38 | return client.PostAsJsonAsync(uri, body); 39 | } 40 | 41 | public static Task GrantRole( 42 | this SellersServer server, 43 | Guid userId, 44 | Guid shopId, 45 | string roleName) 46 | { 47 | HttpClient client = server.CreateClient(); 48 | string uri = $"api/users/{userId}/grant-role"; 49 | GrantRole body = new(shopId, roleName); 50 | return client.PostAsJsonAsync(uri, body); 51 | } 52 | 53 | public static Task RevokeRole( 54 | this SellersServer server, 55 | Guid userId, 56 | Guid shopId, 57 | string roleName) 58 | { 59 | HttpClient client = server.CreateClient(); 60 | string uri = $"api/users/{userId}/revoke-role"; 61 | RevokeRole body = new(shopId, roleName); 62 | return client.PostAsJsonAsync(uri, body); 63 | } 64 | 65 | public static async Task> GetRoles( 66 | this SellersServer server, 67 | Guid userId) 68 | { 69 | HttpClient client = server.CreateClient(); 70 | string uri = $"api/users/{userId}/roles"; 71 | HttpResponseMessage response = await client.GetAsync(uri); 72 | HttpContent content = response.EnsureSuccessStatusCode().Content; 73 | return (await content.ReadFromJsonAsync>())!; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/TestSpecificLanguage.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Orders.Commands; 3 | using Orders.Events; 4 | using Sellers; 5 | using System.Net.Http.Json; 6 | 7 | namespace Orders; 8 | 9 | internal static class TestSpecificLanguage 10 | { 11 | public static async Task PlaceOrder( 12 | this OrdersServer server, 13 | Guid orderId) 14 | { 15 | string uri = $"api/orders/{orderId}/place-order"; 16 | 17 | ShopView shop = await server.GetSellersServer().CreateShop(); 18 | 19 | PlaceOrder body = new( 20 | UserId: Guid.NewGuid(), 21 | ShopId: shop.Id, 22 | ItemId: Guid.NewGuid(), 23 | Price: 100000); 24 | 25 | return await server.CreateClient().PostAsJsonAsync(uri, body); 26 | } 27 | 28 | public static Task StartOrder( 29 | this OrdersServer server, 30 | Guid orderId, 31 | string? paymentTransactionId = null) 32 | { 33 | string uri = $"api/orders/{orderId}/start-order"; 34 | StartOrder body = new(paymentTransactionId); 35 | return server.CreateClient().PostAsJsonAsync(uri, body); 36 | } 37 | 38 | public static Task HandleBankTransferPaymentCompleted( 39 | this OrdersServer server, 40 | Guid orderId) 41 | { 42 | string uri = "api/orders/handle/bank-transder-payment-completed"; 43 | DateTime now = DateTime.UtcNow; 44 | BankTransferPaymentCompleted body = new(orderId, EventTimeUtc: now); 45 | return server.CreateClient().PostAsJsonAsync(uri, body); 46 | } 47 | 48 | public static Task HandleItemShipped( 49 | this OrdersServer server, 50 | Guid orderId) 51 | { 52 | ItemShipped body = new(orderId, EventTimeUtc: DateTime.UtcNow); 53 | return HandleItemShipped(server, body); 54 | } 55 | 56 | public static Task HandleItemShipped( 57 | this OrdersServer server, 58 | ItemShipped body) 59 | { 60 | string uri = "api/orders/handle/item-shipped"; 61 | return server.CreateClient().PostAsJsonAsync(uri, body); 62 | } 63 | 64 | public static SellersServer GetSellersServer(this OrdersServer server) 65 | => server.Services.GetRequiredService(); 66 | 67 | public static async Task GetShop( 68 | this SellersServer server, 69 | Guid id) 70 | { 71 | string uri = $"api/shops/{id}"; 72 | HttpResponseMessage response = await server.CreateClient().GetAsync(uri); 73 | HttpContent contnet = response.EnsureSuccessStatusCode().Content; 74 | return (await contnet.ReadFromJsonAsync())!; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Migrations/20220822085914_AddOrders.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 4 | 5 | #nullable disable 6 | 7 | namespace Orders.Migrations 8 | { 9 | public partial class AddOrders : Migration 10 | { 11 | protected override void Up(MigrationBuilder migrationBuilder) 12 | { 13 | migrationBuilder.CreateTable( 14 | name: "Orders", 15 | columns: table => new 16 | { 17 | Sequence = table.Column(type: "bigint", nullable: false) 18 | .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), 19 | Id = table.Column(type: "uuid", nullable: false), 20 | UserId = table.Column(type: "uuid", nullable: false), 21 | ShopId = table.Column(type: "uuid", nullable: false), 22 | ItemId = table.Column(type: "uuid", nullable: false), 23 | Price = table.Column(type: "numeric", nullable: false), 24 | Status = table.Column(type: "text", nullable: false), 25 | PlacedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), 26 | StartedAtUtc = table.Column(type: "timestamp with time zone", nullable: true), 27 | PaidAtUtc = table.Column(type: "timestamp with time zone", nullable: true), 28 | ShippedAtUtc = table.Column(type: "timestamp with time zone", nullable: true) 29 | }, 30 | constraints: table => 31 | { 32 | table.PrimaryKey("PK_Orders", x => x.Sequence); 33 | }); 34 | 35 | migrationBuilder.CreateIndex( 36 | name: "IX_Orders_Id", 37 | table: "Orders", 38 | column: "Id", 39 | unique: true); 40 | 41 | migrationBuilder.CreateIndex( 42 | name: "IX_Orders_ShopId", 43 | table: "Orders", 44 | column: "ShopId"); 45 | 46 | migrationBuilder.CreateIndex( 47 | name: "IX_Orders_Status", 48 | table: "Orders", 49 | column: "Status"); 50 | 51 | migrationBuilder.CreateIndex( 52 | name: "IX_Orders_UserId", 53 | table: "Orders", 54 | column: "UserId"); 55 | } 56 | 57 | protected override void Down(MigrationBuilder migrationBuilder) 58 | { 59 | migrationBuilder.DropTable( 60 | name: "Orders"); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/QueryModel/ShopUserReader_specs.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture.Xunit2; 2 | using FluentAssertions; 3 | using System.Collections.Immutable; 4 | using Xunit; 5 | 6 | namespace Sellers.QueryModel; 7 | 8 | public class ShopUserReader_specs 9 | { 10 | [Fact] 11 | public void Sut_implements_IUserReader() 12 | { 13 | typeof(ShopUserReader).Should().Implement(); 14 | } 15 | 16 | [Theory, AutoSellersData] 17 | public async Task Sut_returns_user_with_matching_name( 18 | [Frozen] Func contextFactory, 19 | ShopUserReader sut, 20 | Shop shop, 21 | string password, 22 | IPasswordHasher hasher) 23 | { 24 | // Arrange 25 | using SellersDbContext context = contextFactory.Invoke(); 26 | shop.PasswordHash = hasher.HashPassword(password); 27 | context.Shops.Add(shop); 28 | await context.SaveChangesAsync(); 29 | 30 | // Act 31 | User? actual = await sut.FindUser(username: shop.UserId); 32 | 33 | // Assert 34 | actual.Should().NotBeNull(); 35 | actual!.Id.Should().Be(shop.Id); 36 | actual.Username.Should().Be(shop.UserId); 37 | actual.PasswordHash.Should().Be(shop.PasswordHash); 38 | } 39 | 40 | [Theory, AutoSellersData] 41 | public async Task Sut_returns_null_with_nonexistent_username( 42 | ShopUserReader sut, 43 | string username) 44 | { 45 | User? actual = await sut.FindUser(username); 46 | actual.Should().BeNull(); 47 | } 48 | 49 | [Theory, AutoSellersData] 50 | public async Task Sut_returns_user_with_matching_id( 51 | [Frozen] Func contextFactory, 52 | ShopUserReader sut, 53 | Shop shop) 54 | { 55 | using SellersDbContext context = contextFactory.Invoke(); 56 | context.Shops.Add(shop); 57 | await context.SaveChangesAsync(); 58 | 59 | User? actual = await sut.FindUser(id: shop.Id); 60 | 61 | actual.Should().BeEquivalentTo(new 62 | { 63 | Id = shop.Id, 64 | Username = shop.UserId, 65 | shop.PasswordHash, 66 | }, c => c.ExcludingMissingMembers()); 67 | } 68 | 69 | [Theory, AutoSellersData] 70 | public async Task Sut_correctly_sets_roles( 71 | [Frozen] Func contextFactory, 72 | ShopUserReader sut, 73 | Shop shop) 74 | { 75 | using SellersDbContext context = contextFactory.Invoke(); 76 | context.Shops.Add(shop); 77 | await context.SaveChangesAsync(); 78 | 79 | User? user = await sut.FindUser(id: shop.Id); 80 | ImmutableArray actual = user!.Roles; 81 | 82 | Role role = new(shop.Id, RoleName: "Administrator"); 83 | actual.Should().BeEquivalentTo(new[] { role }); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/QueryModel/SqlUserReader_specs.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture.Xunit2; 2 | using FluentAssertions; 3 | using Xunit; 4 | 5 | namespace Sellers.QueryModel; 6 | 7 | public class SqlUserReader_specs 8 | { 9 | [Theory, AutoSellersData] 10 | public async Task Sut_returns_user_with_matching_name( 11 | [Frozen] Func contextFactory, 12 | SqlUserReader sut, 13 | UserEntity user) 14 | { 15 | using SellersDbContext context = contextFactory.Invoke(); 16 | context.Users.Add(user); 17 | await context.SaveChangesAsync(); 18 | 19 | User? actual = await sut.FindUser(user.Username); 20 | 21 | actual.Should().BeEquivalentTo(user, c => c.ExcludingMissingMembers()); 22 | } 23 | 24 | [Theory, AutoSellersData] 25 | public async Task Sut_returns_null_for_unknown_name( 26 | SqlUserReader sut, 27 | string username) 28 | { 29 | User? actual = await sut.FindUser(username); 30 | actual.Should().BeNull(); 31 | } 32 | 33 | [Theory, AutoSellersData] 34 | public async Task Sut_returns_user_with_matching_id( 35 | [Frozen] Func contextFactory, 36 | SqlUserReader sut, 37 | UserEntity user) 38 | { 39 | using SellersDbContext context = contextFactory.Invoke(); 40 | context.Add(user); 41 | await context.SaveChangesAsync(); 42 | 43 | User? actual = await sut.FindUser(user.Id); 44 | 45 | actual.Should().BeEquivalentTo(user, c => c.ExcludingMissingMembers()); 46 | } 47 | 48 | [Theory, AutoSellersData] 49 | public async Task Sut_returns_null_for_unknown_id( 50 | SqlUserReader sut, 51 | Guid id) 52 | { 53 | User? actual = await sut.FindUser(id); 54 | actual.Should().BeNull(); 55 | } 56 | 57 | [Theory, AutoSellersData] 58 | public async Task Sut_correctly_restores_roles( 59 | [Frozen] Func contextFactory, 60 | SqlUserReader sut, 61 | UserEntity user, 62 | Role[] roles) 63 | { 64 | // Arrange 65 | using SellersDbContext context = contextFactory.Invoke(); 66 | 67 | context.Users.Add(user); 68 | await context.SaveChangesAsync(); 69 | 70 | context.Roles.AddRange(from x in roles 71 | select new RoleEntity 72 | { 73 | UserSequence = user.Sequence, 74 | ShopId = x.ShopId, 75 | RoleName = x.RoleName, 76 | }); 77 | await context.SaveChangesAsync(); 78 | 79 | // Act 80 | User actual = (await sut.FindUser(user.Id))!; 81 | 82 | // Assert 83 | actual.Roles.Should().BeEquivalentTo(roles); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Migrations/20220822085914_AddOrders.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 8 | using Orders; 9 | 10 | #nullable disable 11 | 12 | namespace Orders.Migrations 13 | { 14 | [DbContext(typeof(OrdersDbContext))] 15 | [Migration("20220822085914_AddOrders")] 16 | partial class AddOrders 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.8") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 63); 24 | 25 | NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); 26 | 27 | modelBuilder.Entity("Orders.Order", b => 28 | { 29 | b.Property("Sequence") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("bigint"); 32 | 33 | NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Sequence")); 34 | 35 | b.Property("Id") 36 | .HasColumnType("uuid"); 37 | 38 | b.Property("ItemId") 39 | .HasColumnType("uuid"); 40 | 41 | b.Property("PaidAtUtc") 42 | .HasColumnType("timestamp with time zone"); 43 | 44 | b.Property("PlacedAtUtc") 45 | .HasColumnType("timestamp with time zone"); 46 | 47 | b.Property("Price") 48 | .HasColumnType("numeric"); 49 | 50 | b.Property("ShippedAtUtc") 51 | .HasColumnType("timestamp with time zone"); 52 | 53 | b.Property("ShopId") 54 | .HasColumnType("uuid"); 55 | 56 | b.Property("StartedAtUtc") 57 | .HasColumnType("timestamp with time zone"); 58 | 59 | b.Property("Status") 60 | .IsRequired() 61 | .HasColumnType("text"); 62 | 63 | b.Property("UserId") 64 | .HasColumnType("uuid"); 65 | 66 | b.HasKey("Sequence"); 67 | 68 | b.HasIndex("Id") 69 | .IsUnique(); 70 | 71 | b.HasIndex("ShopId"); 72 | 73 | b.HasIndex("Status"); 74 | 75 | b.HasIndex("UserId"); 76 | 77 | b.ToTable("Orders"); 78 | }); 79 | #pragma warning restore 612, 618 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /ShopPlatform/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Migrations/OrdersDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 7 | using Orders; 8 | 9 | #nullable disable 10 | 11 | namespace Orders.Migrations 12 | { 13 | [DbContext(typeof(OrdersDbContext))] 14 | partial class OrdersDbContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "6.0.8") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 63); 22 | 23 | NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); 24 | 25 | modelBuilder.Entity("Orders.Order", b => 26 | { 27 | b.Property("Sequence") 28 | .ValueGeneratedOnAdd() 29 | .HasColumnType("bigint"); 30 | 31 | NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Sequence")); 32 | 33 | b.Property("Id") 34 | .HasColumnType("uuid"); 35 | 36 | b.Property("ItemId") 37 | .HasColumnType("uuid"); 38 | 39 | b.Property("PaidAtUtc") 40 | .HasColumnType("timestamp with time zone"); 41 | 42 | b.Property("PaymentTransactionId") 43 | .HasColumnType("text"); 44 | 45 | b.Property("PlacedAtUtc") 46 | .HasColumnType("timestamp with time zone"); 47 | 48 | b.Property("Price") 49 | .HasColumnType("numeric"); 50 | 51 | b.Property("ShippedAtUtc") 52 | .HasColumnType("timestamp with time zone"); 53 | 54 | b.Property("ShopId") 55 | .HasColumnType("uuid"); 56 | 57 | b.Property("StartedAtUtc") 58 | .HasColumnType("timestamp with time zone"); 59 | 60 | b.Property("Status") 61 | .IsRequired() 62 | .HasColumnType("text"); 63 | 64 | b.Property("UserId") 65 | .HasColumnType("uuid"); 66 | 67 | b.HasKey("Sequence"); 68 | 69 | b.HasIndex("Id") 70 | .IsUnique(); 71 | 72 | b.HasIndex("PaymentTransactionId"); 73 | 74 | b.HasIndex("ShopId"); 75 | 76 | b.HasIndex("Status"); 77 | 78 | b.HasIndex("UserId"); 79 | 80 | b.ToTable("Orders"); 81 | }); 82 | #pragma warning restore 612, 618 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Migrations/20220822090330_AddPaymentTransactionIdToOrder.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 8 | using Orders; 9 | 10 | #nullable disable 11 | 12 | namespace Orders.Migrations 13 | { 14 | [DbContext(typeof(OrdersDbContext))] 15 | [Migration("20220822090330_AddPaymentTransactionIdToOrder")] 16 | partial class AddPaymentTransactionIdToOrder 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.8") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 63); 24 | 25 | NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); 26 | 27 | modelBuilder.Entity("Orders.Order", b => 28 | { 29 | b.Property("Sequence") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("bigint"); 32 | 33 | NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Sequence")); 34 | 35 | b.Property("Id") 36 | .HasColumnType("uuid"); 37 | 38 | b.Property("ItemId") 39 | .HasColumnType("uuid"); 40 | 41 | b.Property("PaidAtUtc") 42 | .HasColumnType("timestamp with time zone"); 43 | 44 | b.Property("PaymentTransactionId") 45 | .HasColumnType("text"); 46 | 47 | b.Property("PlacedAtUtc") 48 | .HasColumnType("timestamp with time zone"); 49 | 50 | b.Property("Price") 51 | .HasColumnType("numeric"); 52 | 53 | b.Property("ShippedAtUtc") 54 | .HasColumnType("timestamp with time zone"); 55 | 56 | b.Property("ShopId") 57 | .HasColumnType("uuid"); 58 | 59 | b.Property("StartedAtUtc") 60 | .HasColumnType("timestamp with time zone"); 61 | 62 | b.Property("Status") 63 | .IsRequired() 64 | .HasColumnType("text"); 65 | 66 | b.Property("UserId") 67 | .HasColumnType("uuid"); 68 | 69 | b.HasKey("Sequence"); 70 | 71 | b.HasIndex("Id") 72 | .IsUnique(); 73 | 74 | b.HasIndex("PaymentTransactionId"); 75 | 76 | b.HasIndex("ShopId"); 77 | 78 | b.HasIndex("Status"); 79 | 80 | b.HasIndex("UserId"); 81 | 82 | b.ToTable("Orders"); 83 | }); 84 | #pragma warning restore 612, 618 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/Migrations/20220822123735_AddUsers.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 8 | using Sellers; 9 | 10 | #nullable disable 11 | 12 | namespace Sellers.Migrations 13 | { 14 | [DbContext(typeof(SellersDbContext))] 15 | [Migration("20220822123735_AddUsers")] 16 | partial class AddUsers 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.8") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 63); 24 | 25 | NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); 26 | 27 | modelBuilder.Entity("Sellers.Shop", b => 28 | { 29 | b.Property("Sequence") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("integer"); 32 | 33 | NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Sequence")); 34 | 35 | b.Property("Id") 36 | .HasColumnType("uuid"); 37 | 38 | b.Property("Name") 39 | .IsRequired() 40 | .HasColumnType("text"); 41 | 42 | b.Property("PasswordHash") 43 | .HasColumnType("text"); 44 | 45 | b.Property("UserId") 46 | .HasColumnType("text"); 47 | 48 | b.HasKey("Sequence"); 49 | 50 | b.HasIndex("Id") 51 | .IsUnique(); 52 | 53 | b.HasIndex("Name") 54 | .IsUnique(); 55 | 56 | b.HasIndex("UserId") 57 | .IsUnique(); 58 | 59 | b.ToTable("Shops"); 60 | }); 61 | 62 | modelBuilder.Entity("Sellers.UserEntity", b => 63 | { 64 | b.Property("Sequence") 65 | .ValueGeneratedOnAdd() 66 | .HasColumnType("bigint"); 67 | 68 | NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Sequence")); 69 | 70 | b.Property("Id") 71 | .HasColumnType("uuid"); 72 | 73 | b.Property("PasswordHash") 74 | .HasColumnType("text"); 75 | 76 | b.Property("Username") 77 | .IsRequired() 78 | .HasColumnType("text"); 79 | 80 | b.HasKey("Sequence"); 81 | 82 | b.HasIndex("Id") 83 | .IsUnique(); 84 | 85 | b.HasIndex("Username") 86 | .IsUnique(); 87 | 88 | b.ToTable("Users"); 89 | }); 90 | #pragma warning restore 612, 618 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Api/Controllers/ShopsControllers.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Identity; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace Sellers.Controllers; 6 | 7 | [Route("api/shops")] 8 | public sealed class ShopsControllers : Controller 9 | { 10 | [HttpPost] 11 | [Produces("application/json", Type = typeof(Shop))] 12 | public async Task CreateShop( 13 | [FromBody] Shop shop, 14 | [FromServices] SellersDbContext context) 15 | { 16 | shop.Id = Guid.NewGuid(); 17 | context.Shops.Add(shop); 18 | await context.SaveChangesAsync(); 19 | return Ok(shop); 20 | } 21 | 22 | [HttpGet] 23 | [Produces("application/json", Type = typeof(Shop[]))] 24 | public async Task> GetShops( 25 | [FromServices] SellersDbContext context) 26 | { 27 | return await context.Shops.AsNoTracking().ToListAsync(); 28 | } 29 | 30 | [HttpGet("{id}")] 31 | [Produces("application/json", Type = typeof(Shop))] 32 | [ProducesResponseType(404)] 33 | public async Task FindShop( 34 | Guid id, 35 | [FromServices] SellersDbContext context) 36 | { 37 | return await context.Shops.FindShop(id) switch 38 | { 39 | Shop shop => Ok(new ShopView(shop.Id, shop.Name)), 40 | null => NotFound(), 41 | }; 42 | } 43 | 44 | [HttpPost("{id}/user")] 45 | [ProducesResponseType(200)] 46 | [ProducesResponseType(404)] 47 | public async Task PostUser( 48 | Guid id, 49 | [FromBody] ShopUser user, 50 | [FromServices] SellersDbContext context, 51 | [FromServices] IPasswordHasher hasher) 52 | { 53 | Shop? shop = await context.Shops.FindShop(id); 54 | if (shop == null) 55 | { 56 | return NotFound(); 57 | } 58 | 59 | shop.UserId = user.Id; 60 | shop.PasswordHash = hasher.HashPassword(user, user.Password); 61 | 62 | await context.SaveChangesAsync(); 63 | 64 | return Ok(); 65 | } 66 | 67 | [HttpPost("verify-password")] 68 | [ProducesResponseType(200)] 69 | [ProducesResponseType(400)] 70 | public async Task VerifyPassword( 71 | [FromBody] ShopUser user, 72 | [FromServices] SellersDbContext dbContext, 73 | [FromServices] IPasswordHasher hasher) 74 | { 75 | IQueryable query = 76 | from s in dbContext.Shops 77 | where s.UserId == user.Id 78 | select s; 79 | 80 | Shop? shop = await query.SingleOrDefaultAsync(); 81 | 82 | if (shop == null) 83 | { 84 | return BadRequest(); 85 | } 86 | else 87 | { 88 | if (shop.PasswordHash == null) 89 | { 90 | return BadRequest(); 91 | } 92 | else 93 | { 94 | PasswordVerificationResult result = hasher.VerifyHashedPassword( 95 | user, 96 | shop.PasswordHash, 97 | user.Password); 98 | 99 | return result == PasswordVerificationResult.Failed 100 | ? BadRequest() 101 | : Ok(); 102 | } 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/api/orders/accept/payment-approved/Post_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Orders.Events; 3 | using System.Net; 4 | using System.Net.Http.Json; 5 | using Xunit; 6 | 7 | namespace Orders.api.orders.accept.payment_approved; 8 | 9 | public class Post_specs 10 | { 11 | [Fact] 12 | public async Task Sut_correctly_changes_order_status() 13 | { 14 | // Arrange 15 | OrdersServer server = OrdersServer.Create(); 16 | 17 | Guid orderId = Guid.NewGuid(); 18 | string paymentTransactionId = $"{Guid.NewGuid()}"; 19 | 20 | await server.PlaceOrder(orderId); 21 | await server.StartOrder(orderId, paymentTransactionId); 22 | 23 | HttpClient client = server.CreateClient(); 24 | 25 | string uri = "api/orders/accept/payment-approved"; 26 | 27 | ExternalPaymentApproved body = new( 28 | tid: paymentTransactionId, 29 | approved_at: DateTime.UtcNow); 30 | 31 | // Act 32 | await client.PostAsJsonAsync(uri, body); 33 | 34 | // Assert 35 | await DefaultPolicy.Instance.ExecuteAsync(async () => { 36 | HttpResponseMessage response = await client.GetAsync($"api/orders/{orderId}"); 37 | Order? order = await response.Content.ReadFromJsonAsync(); 38 | order!.Status.Should().Be(OrderStatus.AwaitingShipment); 39 | }); 40 | } 41 | 42 | [Fact] 43 | public async Task Sut_returns_Accepted() 44 | { 45 | // Arrange 46 | OrdersServer server = OrdersServer.Create(); 47 | 48 | Guid orderId = Guid.NewGuid(); 49 | string paymentTransactionId = $"{Guid.NewGuid()}"; 50 | 51 | await server.PlaceOrder(orderId); 52 | await server.StartOrder(orderId, paymentTransactionId); 53 | 54 | 55 | string uri = "api/orders/accept/payment-approved"; 56 | 57 | ExternalPaymentApproved body = new( 58 | tid: paymentTransactionId, 59 | approved_at: DateTime.UtcNow); 60 | 61 | // Act 62 | HttpResponseMessage response = await server.CreateClient().PostAsJsonAsync(uri, body); 63 | 64 | // Assert 65 | response.StatusCode.Should().Be(HttpStatusCode.Accepted); 66 | } 67 | 68 | [Fact] 69 | public async Task Sut_correctly_sets_event_time() 70 | { 71 | // Arrange 72 | OrdersServer server = OrdersServer.Create(); 73 | 74 | Guid orderId = Guid.NewGuid(); 75 | string paymentTransactionId = $"{Guid.NewGuid()}"; 76 | 77 | await server.PlaceOrder(orderId); 78 | await server.StartOrder(orderId, paymentTransactionId); 79 | 80 | HttpClient client = server.CreateClient(); 81 | 82 | string uri = "api/orders/accept/payment-approved"; 83 | 84 | ExternalPaymentApproved body = new( 85 | tid: paymentTransactionId, 86 | approved_at: DateTime.UtcNow); 87 | 88 | // Act 89 | await client.PostAsJsonAsync(uri, body); 90 | 91 | // Assert 92 | await DefaultPolicy.Instance.ExecuteAsync(async () => { 93 | HttpResponseMessage response = await client.GetAsync($"api/orders/{orderId}"); 94 | Order? order = await response.Content.ReadFromJsonAsync(); 95 | TimeSpan precision = TimeSpan.FromMilliseconds(20); 96 | order!.PaidAtUtc.Should().BeCloseTo(body.approved_at, precision); 97 | }); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /ShopPlatform/accounting/unittest/src/test/java/accounting/test/api/orders/get_orders_placed_in/Post_specs.java: -------------------------------------------------------------------------------- 1 | package accounting.test.api.orders.get_orders_placed_in; 2 | 3 | import accounting.Order; 4 | import accounting.OrderReader; 5 | import accounting.OrderView; 6 | import accounting.ShopReader; 7 | import accounting.query.GetOrdersPlacedIn; 8 | import accounting.test.AccountingCustomizer; 9 | import accounting.test.InMemoryOrderRepository; 10 | import org.javaunit.autoparams.CsvAutoSource; 11 | import org.javaunit.autoparams.customization.Customization; 12 | import org.junit.jupiter.params.ParameterizedTest; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.boot.test.context.SpringBootTest; 15 | import org.springframework.boot.test.context.TestConfiguration; 16 | import org.springframework.boot.test.web.client.TestRestTemplate; 17 | import org.springframework.boot.test.web.server.LocalServerPort; 18 | import org.springframework.context.annotation.Bean; 19 | import org.springframework.context.annotation.Import; 20 | import org.springframework.context.annotation.Primary; 21 | 22 | import java.lang.reflect.Field; 23 | import java.time.LocalDateTime; 24 | import java.util.Arrays; 25 | import java.util.Optional; 26 | 27 | import static org.junit.jupiter.api.Assertions.assertEquals; 28 | 29 | @SuppressWarnings("NewClassNamingConvention") 30 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 31 | @Import(Post_specs.TestDoubles.class) 32 | public class Post_specs { 33 | 34 | @LocalServerPort 35 | private int port; 36 | 37 | @Autowired 38 | private TestRestTemplate client; 39 | 40 | @Autowired 41 | private InMemoryOrderRepository orderRepository; 42 | 43 | @SuppressWarnings("unused") 44 | @TestConfiguration 45 | public static class TestDoubles { 46 | 47 | @Bean 48 | public InMemoryOrderRepository inMemoryOrderRepository() { 49 | return new InMemoryOrderRepository(); 50 | } 51 | 52 | @Bean 53 | @Primary 54 | public OrderReader orderReaderDouble(InMemoryOrderRepository repository) { 55 | return repository; 56 | } 57 | 58 | @Bean 59 | @Primary 60 | public ShopReader shopReaderDouble() { 61 | return id -> Optional.empty(); 62 | } 63 | } 64 | 65 | @ParameterizedTest 66 | @CsvAutoSource({ 67 | "2022-08-31T23:59:59, 2022, 9, true", 68 | "2022-09-01T00:00:00, 2022, 9, true", 69 | "2022-08-31T14:59:59, 2022, 9, false", 70 | "2022-10-31T14:59:59, 2022, 10, true", 71 | }) 72 | @Customization(AccountingCustomizer.class) 73 | public void sut_correctly_globalizes_time_window( 74 | String placedAtUtcSource, 75 | int year, 76 | int month, 77 | boolean selected, 78 | Order order 79 | ) { 80 | setPlacedAtUtc(order, LocalDateTime.parse(placedAtUtcSource)); 81 | orderRepository.add(order); 82 | 83 | String uri = "http://localhost:" + port + "/api/orders/get-orders-placed-in"; 84 | var query = new GetOrdersPlacedIn(order.getShopId(), year, month); 85 | OrderView[] views = client.postForObject(uri, query, OrderView[].class); 86 | 87 | assertEquals(selected, Arrays.stream(views).anyMatch(x -> x.id().equals(order.getId()))); 88 | } 89 | 90 | private static void setPlacedAtUtc(Order order, LocalDateTime value) { 91 | try { 92 | Field status = Order.class.getDeclaredField("placedAtUtc"); 93 | status.setAccessible(true); 94 | status.set(order, value); 95 | } catch (NoSuchFieldException | IllegalAccessException e) { 96 | throw new RuntimeException(e); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.UnitTests/CommandModel/SqlUserRepository_specs.cs: -------------------------------------------------------------------------------- 1 | using AutoFixture.Xunit2; 2 | using FluentAssertions; 3 | using Microsoft.EntityFrameworkCore; 4 | using Sellers.QueryModel; 5 | using System.Collections.Immutable; 6 | using Xunit; 7 | 8 | namespace Sellers.CommandModel; 9 | 10 | public class SqlUserRepository_specs 11 | { 12 | [Theory, AutoSellersData] 13 | public async Task Sut_correctly_creates_new_entity( 14 | [Frozen] Func contextFactory, 15 | SqlUserRepository sut, 16 | User source) 17 | { 18 | User user = source with { Roles = ImmutableArray.Empty }; 19 | 20 | await sut.Add(user); 21 | 22 | using SellersDbContext context = contextFactory.Invoke(); 23 | UserEntity? actual = await context.Users.SingleOrDefaultAsync(x => x.Id == user.Id); 24 | actual.Should().BeEquivalentTo(user, c => c.ExcludingMissingMembers()); 25 | } 26 | 27 | [Theory, AutoSellersData] 28 | public async Task Sut_correctly_saves_roles( 29 | [Frozen] Func contextFactory, 30 | SqlUserRepository sut, 31 | User user) 32 | { 33 | await sut.Add(user); 34 | 35 | SqlUserReader reader = new(contextFactory); 36 | User actual = (await reader.FindUser(user.Id))!; 37 | actual.Roles.Should().BeEquivalentTo(user.Roles); 38 | } 39 | 40 | [Theory, AutoSellersData] 41 | public async Task TryUpdate_returns_true_if_entity_exists( 42 | SqlUserRepository sut, 43 | User user) 44 | { 45 | await sut.Add(user); 46 | bool actual = await sut.TryUpdate(user.Id, x => x); 47 | actual.Should().BeTrue(); 48 | } 49 | 50 | [Theory, AutoSellersData] 51 | public async Task TryUpdate_correctly_restores_user( 52 | SqlUserRepository sut, 53 | User user) 54 | { 55 | await sut.Add(user); 56 | User? actual = null; 57 | 58 | await sut.TryUpdate(user.Id, x => actual = x); 59 | 60 | actual.Should().BeEquivalentTo(user); 61 | } 62 | 63 | [Theory, AutoSellersData] 64 | public async Task TryUpdate_correctly_changes_username( 65 | [Frozen] Func contextFactory, 66 | SqlUserRepository sut, 67 | User user, 68 | string newValue) 69 | { 70 | await sut.Add(user); 71 | 72 | await sut.TryUpdate(user.Id, x => x with { Username = newValue }); 73 | 74 | SqlUserReader reader = new(contextFactory); 75 | User actual = (await reader.FindUser(user.Id))!; 76 | actual.Username.Should().Be(newValue); 77 | } 78 | 79 | [Theory, AutoSellersData] 80 | public async Task TryUpdate_correctly_changes_password_hash( 81 | [Frozen] Func contextFactory, 82 | SqlUserRepository sut, 83 | User user, 84 | string newValue) 85 | { 86 | await sut.Add(user); 87 | 88 | await sut.TryUpdate(user.Id, x => x with { PasswordHash = newValue }); 89 | 90 | SqlUserReader reader = new(contextFactory); 91 | User actual = (await reader.FindUser(user.Id))!; 92 | actual.PasswordHash.Should().Be(newValue); 93 | } 94 | 95 | [Theory, AutoSellersData] 96 | public async Task TryUpdate_correctly_changes_roles( 97 | [Frozen] Func contextFactory, 98 | SqlUserRepository sut, 99 | User user, 100 | Role newRole) 101 | { 102 | await sut.Add(user); 103 | 104 | await sut.TryUpdate(user.Id, x => x with 105 | { 106 | Roles = x.Roles.Add(newRole), 107 | }); 108 | 109 | SqlUserReader reader = new(contextFactory); 110 | User actual = (await reader.FindUser(user.Id))!; 111 | actual.Roles.Should().Contain(user.Roles).And.Contain(newRole); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 현실 세상의 TDD 실전편 실습 코드 2 | 3 | Fast campus 강의 ['현실 세상의 TDD 실전편'](https://fastcampus.co.kr/dev_red_ygw2) 실습에 사용된 예제 코드를 제공합니다. 4 | 5 | > 예제 코드는 강의 촬영 전에 미리 준비되었고 강의 촬영 시 라이브 코딩이 진행되었기 때문에 세부 코드는 강의 영상에서 보는 것과 다를 수 있습니다. 6 | 7 | ## 질문 및 토론 8 | 9 | TDD 또는 강의와 관련된 질문과 토론을 위해 Discord 서버를 만들었습니다. 여기 [**초대 링크**](https://discord.gg/NjC9r6kvUz)를 통해 들어오실 수 있습니다. 이 저장소에 이슈를 등록해주셔도 됩니다. 두 소통 채널은 각자 장단점이 있으니 주제에 따라 편하게 적합한 수단을 선택해 주세요. 10 | 11 | ## 세션 별 코드 12 | 13 | 태그를 통해 실습이 포함된 각 세션 별 실습 진행에 기반이되는 코드를 볼 수 있습니다. 14 | 15 | [홈으로](../../) 16 | 17 | ### 챕터 2. 주문 및 정산 기능 개선 18 | 19 | | 세션 | 기반 코드 | 20 | | - | :-: | 21 | | 1. 작은 변경들 | [`2-1`](../../tree/2-1) | 22 | | 2. 리팩터링 | [`2-2`](../../tree/2-2) | 23 | | 3. 읽기 쉬운 테스트 코드 | [`2-3`](../../tree/2-3) | 24 | | 4. 비동기 프로세스 | [`2-4`](../../tree/2-4) | 25 | | 5. 매개변수화 테스트 | [`2-5`](../../tree/2-5) | 26 | | 6. (Bonus) Mac에서 예제 구동 | [`2-6`](../../tree/2-6) | 27 | 28 | ### 챕터 3. B2B 계정관리 기능 개선 29 | 30 | | 세션 | 기반 코드| 31 | | - | :-: | 32 | | 1. 코드 분리 | [`3-1`](../../tree/3-1) | 33 | | 2. 테스트 환경 격리 | [`3-2`](../../tree/3-2) | 34 | | 3. 모델 정제 | [`3-3`](../../tree/3-3) | 35 | | 4. 모델 통합 | [`3-4`](../../tree/3-4) | 36 | | 5. 모델 확장 | [`3-5`](../../tree/3-5) | 37 | 38 | ## 개발 환경 39 | 40 | 예제 코드를 실행하고 실습하기 위해 다음 도구들이 설치되어 있어야 합니다. 41 | 42 | ### Docker 43 | 44 | https://docs.docker.com/get-docker/ 45 | 46 | ### 데이터베이스 47 | 48 | PostgreSQL을 데이터베이스로 사용합니다. 49 | 50 | https://hub.docker.com/_/postgres 51 | 52 | ```text 53 | docker run --name postgres -p 5432:5432 -e POSTGRES_PASSWORD=mysecretpassword -d postgres 54 | ``` 55 | 56 | ### Azure Storage Queue 57 | 58 | 메시지 중개자로 Azure Storage Queue를 사용합니다. 59 | 60 | https://hub.docker.com/_/microsoft-azure-storage-azurite 61 | 62 | ```text 63 | docker run --name azurite -p 10000:10000 -p 10001:10001 -p 10002:10002 mcr.microsoft.com/azure-storage/azurite 64 | ``` 65 | 66 | ### Java 17 및 빌드 도구 67 | 68 | - https://www.oracle.com/java/technologies/downloads/#java17 69 | - https://gradle.org/install/ 70 | 71 | ### .NET 6 72 | 73 | https://dotnet.microsoft.com/en-us/download/dotnet/6.0 74 | 75 | ### IDE 또는 편집기 76 | 77 | #### Windows 78 | 79 | - [Visual Studio Community](https://visualstudio.microsoft.com/vs/community/) 80 | - [IntelliJ IDEA Community](https://www.jetbrains.com/idea/download/) 81 | 82 | #### Mac 83 | 84 | - [Visual Studio Code](https://code.visualstudio.com/download) 85 | 86 | ##### Visual Studio Code 확장 87 | 88 | - [C# for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp) 89 | - [Extension Pack for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack) 90 | 91 | ### 데이터베이스 클라이언트 92 | 93 | - [pgAdmin 4](https://www.pgadmin.org/download/) 94 | 95 | ## 응용프로그램 실행 96 | 97 | Mac과 Windows에서 예제 응용프로그램을 실행하는 방법을 설명합니다. 98 | 99 | > 먼저 '개발 환경' 섹션을 참고해 PostgreSQL 서버와 Azurite가 구동시키고, JDK 17, Gradle, .NET 6.0을 설치해주세요. 100 | 101 | > 설명된 모든 CLI 명령 실행은 코드 저장소 루트 디렉터리가 기준입니다. 다른 디렉터리에서 명령을 실행하려면 명령 인자를 수정해야 합니다. 102 | 103 | ### 데이터베이스 마이그레이션 104 | 105 | Entity Framework 도구를 설치합니다. 106 | 107 | ```text 108 | dotnet tool install dotnet-ef --global 109 | ``` 110 | 111 | Orders 서비스 데이터베이스를 마이그레이션 합니다. 112 | 113 | ```text 114 | dotnet ef database update --project ./ShopPlatform/Orders/Orders.Api/ 115 | ``` 116 | 117 | Sellers 서비스 데이터베이스를 마이그레이션 합니다. 118 | 119 | ```text 120 | dotnet ef database update --project ./ShopPlatform/Sellers/Sellers.Sql/ --startup-project ./ShopPlatform/Sellers/Sellers.Api/ 121 | ``` 122 | 123 | ### Orders 서비스 실행 124 | 125 | Orders API 응용프로그램을 구동합니다. 126 | 127 | ```text 128 | dotnet run --project ./ShopPlatform/Orders/Orders.Api/ 129 | ``` 130 | 131 | Orders API Swagger 문서에 접속합니다. 132 | 133 | http://localhost:5094/swagger/index.html 134 | 135 | ### Sellers 서비스 실행 136 | 137 | Sellers API 응용프로그램을 구동합니다. 138 | 139 | ```text 140 | dotnet run --project ./ShopPlatform/Sellers/Sellers.Api/ 141 | ``` 142 | 143 | Sellers API Swagger 문서에 접속합니다. 144 | 145 | http://localhost:5232/swagger/index.html 146 | 147 | ### Accounting 서비스 실행 148 | 149 | ```text 150 | ./ShopPlatform/gradlew bootRun -p ./ShopPlatform/ 151 | ``` 152 | 153 | Accounting API Swagger 문서에 접속합니다. 154 | 155 | http://localhost:1579/swagger-ui/index.html 156 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/Migrations/SellersDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 6 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 7 | using Sellers; 8 | 9 | #nullable disable 10 | 11 | namespace Sellers.Migrations 12 | { 13 | [DbContext(typeof(SellersDbContext))] 14 | partial class SellersDbContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "6.0.8") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 63); 22 | 23 | NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); 24 | 25 | modelBuilder.Entity("Sellers.RoleEntity", b => 26 | { 27 | b.Property("UserSequence") 28 | .HasColumnType("bigint"); 29 | 30 | b.Property("ShopId") 31 | .HasColumnType("uuid"); 32 | 33 | b.Property("RoleName") 34 | .HasColumnType("text"); 35 | 36 | b.HasKey("UserSequence", "ShopId", "RoleName"); 37 | 38 | b.ToTable("Roles"); 39 | }); 40 | 41 | modelBuilder.Entity("Sellers.Shop", b => 42 | { 43 | b.Property("Sequence") 44 | .ValueGeneratedOnAdd() 45 | .HasColumnType("integer"); 46 | 47 | NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Sequence")); 48 | 49 | b.Property("Id") 50 | .HasColumnType("uuid"); 51 | 52 | b.Property("Name") 53 | .IsRequired() 54 | .HasColumnType("text"); 55 | 56 | b.Property("PasswordHash") 57 | .HasColumnType("text"); 58 | 59 | b.Property("UserId") 60 | .HasColumnType("text"); 61 | 62 | b.HasKey("Sequence"); 63 | 64 | b.HasIndex("Id") 65 | .IsUnique(); 66 | 67 | b.HasIndex("Name") 68 | .IsUnique(); 69 | 70 | b.HasIndex("UserId") 71 | .IsUnique(); 72 | 73 | b.ToTable("Shops"); 74 | }); 75 | 76 | modelBuilder.Entity("Sellers.UserEntity", b => 77 | { 78 | b.Property("Sequence") 79 | .ValueGeneratedOnAdd() 80 | .HasColumnType("bigint"); 81 | 82 | NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Sequence")); 83 | 84 | b.Property("Id") 85 | .HasColumnType("uuid"); 86 | 87 | b.Property("PasswordHash") 88 | .HasColumnType("text"); 89 | 90 | b.Property("Username") 91 | .IsRequired() 92 | .HasColumnType("text"); 93 | 94 | b.HasKey("Sequence"); 95 | 96 | b.HasIndex("Id") 97 | .IsUnique(); 98 | 99 | b.HasIndex("Username") 100 | .IsUnique(); 101 | 102 | b.ToTable("Users"); 103 | }); 104 | 105 | modelBuilder.Entity("Sellers.RoleEntity", b => 106 | { 107 | b.HasOne("Sellers.UserEntity", "User") 108 | .WithMany() 109 | .HasForeignKey("UserSequence") 110 | .OnDelete(DeleteBehavior.Cascade) 111 | .IsRequired(); 112 | 113 | b.Navigation("User"); 114 | }); 115 | #pragma warning restore 612, 618 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /ShopPlatform/Sellers/Sellers.Sql/Migrations/20220831154330_AddRoles.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Migrations; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; 8 | using Sellers; 9 | 10 | #nullable disable 11 | 12 | namespace Sellers.Migrations 13 | { 14 | [DbContext(typeof(SellersDbContext))] 15 | [Migration("20220831154330_AddRoles")] 16 | partial class AddRoles 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.8") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 63); 24 | 25 | NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); 26 | 27 | modelBuilder.Entity("Sellers.RoleEntity", b => 28 | { 29 | b.Property("UserSequence") 30 | .HasColumnType("bigint"); 31 | 32 | b.Property("ShopId") 33 | .HasColumnType("uuid"); 34 | 35 | b.Property("RoleName") 36 | .HasColumnType("text"); 37 | 38 | b.HasKey("UserSequence", "ShopId", "RoleName"); 39 | 40 | b.ToTable("Roles"); 41 | }); 42 | 43 | modelBuilder.Entity("Sellers.Shop", b => 44 | { 45 | b.Property("Sequence") 46 | .ValueGeneratedOnAdd() 47 | .HasColumnType("integer"); 48 | 49 | NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Sequence")); 50 | 51 | b.Property("Id") 52 | .HasColumnType("uuid"); 53 | 54 | b.Property("Name") 55 | .IsRequired() 56 | .HasColumnType("text"); 57 | 58 | b.Property("PasswordHash") 59 | .HasColumnType("text"); 60 | 61 | b.Property("UserId") 62 | .HasColumnType("text"); 63 | 64 | b.HasKey("Sequence"); 65 | 66 | b.HasIndex("Id") 67 | .IsUnique(); 68 | 69 | b.HasIndex("Name") 70 | .IsUnique(); 71 | 72 | b.HasIndex("UserId") 73 | .IsUnique(); 74 | 75 | b.ToTable("Shops"); 76 | }); 77 | 78 | modelBuilder.Entity("Sellers.UserEntity", b => 79 | { 80 | b.Property("Sequence") 81 | .ValueGeneratedOnAdd() 82 | .HasColumnType("bigint"); 83 | 84 | NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Sequence")); 85 | 86 | b.Property("Id") 87 | .HasColumnType("uuid"); 88 | 89 | b.Property("PasswordHash") 90 | .HasColumnType("text"); 91 | 92 | b.Property("Username") 93 | .IsRequired() 94 | .HasColumnType("text"); 95 | 96 | b.HasKey("Sequence"); 97 | 98 | b.HasIndex("Id") 99 | .IsUnique(); 100 | 101 | b.HasIndex("Username") 102 | .IsUnique(); 103 | 104 | b.ToTable("Users"); 105 | }); 106 | 107 | modelBuilder.Entity("Sellers.RoleEntity", b => 108 | { 109 | b.HasOne("Sellers.UserEntity", "User") 110 | .WithMany() 111 | .HasForeignKey("UserSequence") 112 | .OnDelete(DeleteBehavior.Cascade) 113 | .IsRequired(); 114 | 115 | b.Navigation("User"); 116 | }); 117 | #pragma warning restore 612, 618 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.UnitTests/api/orders/Get_specs.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Orders.Commands; 3 | using Sellers; 4 | using System.Net.Http.Json; 5 | using Xunit; 6 | 7 | namespace Orders.api.orders; 8 | 9 | public class Get_specs 10 | { 11 | [Fact] 12 | public async Task Sut_correctly_filters_orders_by_user_id() 13 | { 14 | // Arrange 15 | OrdersServer server = OrdersServer.Create(); 16 | 17 | ShopView shop = await server.GetSellersServer().CreateShop(); 18 | Guid itemId = Guid.NewGuid(); 19 | decimal price = 100000; 20 | 21 | List commands = new() 22 | { 23 | new PlaceOrder(UserId: Guid.NewGuid(), shop.Id, itemId, price), 24 | new PlaceOrder(UserId: Guid.NewGuid(), shop.Id, itemId, price), 25 | new PlaceOrder(UserId: Guid.NewGuid(), shop.Id, itemId, price), 26 | }; 27 | 28 | HttpClient client = server.CreateClient(); 29 | 30 | await Task.WhenAll(from command in commands 31 | let orderId = Guid.NewGuid() 32 | let uri = $"api/orders/{orderId}/place-order" 33 | orderby orderId 34 | select client.PostAsJsonAsync(uri, command)); 35 | 36 | Guid userId = commands[0].UserId; 37 | 38 | // Act 39 | string queryUri = $"api/orders?user-id={userId}"; 40 | HttpResponseMessage response = await client.GetAsync(queryUri); 41 | 42 | // Assert 43 | Order[]? orders = await response.Content.ReadFromJsonAsync(); 44 | orders.Should().OnlyContain(x => x.UserId == userId); 45 | } 46 | 47 | [Fact] 48 | public async Task Sut_correctly_filters_orders_by_shop_id() 49 | { 50 | // Arrange 51 | OrdersServer server = OrdersServer.Create(); 52 | 53 | ShopView shop1 = await server.GetSellersServer().CreateShop(); 54 | ShopView shop2 = await server.GetSellersServer().CreateShop(); 55 | ShopView shop3 = await server.GetSellersServer().CreateShop(); 56 | 57 | Guid userId = Guid.NewGuid(); 58 | Guid itemId = Guid.NewGuid(); 59 | decimal price = 100000; 60 | 61 | List commands = new() 62 | { 63 | new PlaceOrder(userId, shop1.Id, itemId, price), 64 | new PlaceOrder(userId, shop2.Id, itemId, price), 65 | new PlaceOrder(userId, shop3.Id, itemId, price), 66 | }; 67 | 68 | HttpClient client = server.CreateClient(); 69 | 70 | await Task.WhenAll(from command in commands 71 | let orderId = Guid.NewGuid() 72 | let uri = $"api/orders/{orderId}/place-order" 73 | orderby orderId 74 | select client.PostAsJsonAsync(uri, command)); 75 | 76 | // Act 77 | string queryUri = $"api/orders?shop-id={shop1.Id}"; 78 | HttpResponseMessage response = await client.GetAsync(queryUri); 79 | 80 | // Assert 81 | Order[]? orders = await response.Content.ReadFromJsonAsync(); 82 | orders.Should().OnlyContain(x => x.ShopId == shop1.Id); 83 | } 84 | 85 | [Fact] 86 | public async Task Sut_correctly_filters_orders_by_user_id_and_shop_id() 87 | { 88 | // Arrange 89 | OrdersServer server = OrdersServer.Create(); 90 | 91 | ShopView shop1 = await server.GetSellersServer().CreateShop(); 92 | ShopView shop2 = await server.GetSellersServer().CreateShop(); 93 | 94 | Guid userId = Guid.NewGuid(); 95 | Guid itemId = Guid.NewGuid(); 96 | decimal price = 100000; 97 | 98 | HttpClient client = server.CreateClient(); 99 | 100 | List commands = new() 101 | { 102 | new PlaceOrder(userId, shop2.Id, itemId, price), 103 | new PlaceOrder(userId, shop1.Id, itemId, price), 104 | new PlaceOrder(UserId: Guid.NewGuid(), shop1.Id, itemId, price), 105 | }; 106 | 107 | await Task.WhenAll(from command in commands 108 | let orderId = Guid.NewGuid() 109 | let uri = $"api/orders/{orderId}/place-order" 110 | orderby orderId 111 | select client.PostAsJsonAsync(uri, command)); 112 | 113 | // Act 114 | string queryUri = $"api/orders?user-id={userId}&shop-id={shop1.Id}"; 115 | HttpResponseMessage response = await client.GetAsync(queryUri); 116 | 117 | // Assert 118 | Order[]? orders = await response.Content.ReadFromJsonAsync(); 119 | orders.Should().OnlyContain(x => x.UserId == userId && x.ShopId == shop1.Id); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /ShopPlatform/Orders/Orders.Api/Controllers/OrdersController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.EntityFrameworkCore; 3 | using Orders.Commands; 4 | using Orders.Events; 5 | using Orders.Messaging; 6 | using Sellers; 7 | 8 | namespace Orders.Controllers; 9 | 10 | [Route("api/orders")] 11 | public sealed class OrdersController : Controller 12 | { 13 | [HttpGet] 14 | [Produces("application/json", Type = typeof(Order[]))] 15 | public async Task> GetOrders( 16 | [FromQuery(Name = "user-id")] Guid? userId, 17 | [FromQuery(Name = "shop-id")] Guid? shopId, 18 | [FromServices] OrdersDbContext context) 19 | { 20 | return await context.Orders 21 | .AsNoTracking() 22 | .FilterByUser(userId) 23 | .FilterByShop(shopId) 24 | .ToListAsync(); 25 | } 26 | 27 | [HttpGet("{id}")] 28 | [Produces("application/json", Type = typeof(Order))] 29 | [ProducesResponseType(404)] 30 | public async Task FindOrder( 31 | Guid id, 32 | [FromServices] OrdersDbContext context, 33 | [FromServices] SellersService service) 34 | { 35 | if (await context.Orders.FindOrder(id) is Order order) 36 | { 37 | ShopView shop = await service.GetShop(order.ShopId); 38 | order.ShopName = shop.Name; 39 | return Ok(order); 40 | } 41 | else 42 | { 43 | return NotFound(); 44 | } 45 | } 46 | 47 | [HttpPost("{id}/place-order")] 48 | public async Task PlaceOrder( 49 | Guid id, 50 | [FromBody] PlaceOrder command, 51 | [FromServices] OrdersDbContext context, 52 | [FromServices] SellersService sellers) 53 | { 54 | if (await sellers.FindShop(command.ShopId) is not null) 55 | { 56 | context.Add(new Order 57 | { 58 | Id = id, 59 | UserId = command.UserId, 60 | ShopId = command.ShopId, 61 | ItemId = command.ItemId, 62 | Price = command.Price, 63 | Status = OrderStatus.Pending, 64 | PlacedAtUtc = DateTime.UtcNow, 65 | }); 66 | await context.SaveChangesAsync(); 67 | return Ok(); 68 | } 69 | else 70 | { 71 | return BadRequest(); 72 | } 73 | } 74 | 75 | [HttpPost("{id}/start-order")] 76 | [ProducesResponseType(200)] 77 | [ProducesResponseType(404)] 78 | public async Task StartOrder( 79 | Guid id, 80 | [FromBody] StartOrder command, 81 | [FromServices] OrdersDbContext context) 82 | { 83 | Order? order = await context.Orders.FindOrder(id); 84 | 85 | if (order == null) 86 | { 87 | return NotFound(); 88 | } 89 | 90 | if (order.Status != OrderStatus.Pending) 91 | { 92 | return BadRequest(); 93 | } 94 | 95 | order.Status = OrderStatus.AwaitingPayment; 96 | order.PaymentTransactionId = command.PaymentTransactionId; 97 | order.StartedAtUtc = DateTime.UtcNow; 98 | await context.SaveChangesAsync(); 99 | return Ok(); 100 | } 101 | 102 | [HttpPost("handle/bank-transder-payment-completed")] 103 | [ProducesResponseType(200)] 104 | [ProducesResponseType(404)] 105 | public async Task HandleBankTransferPaymentCompleted( 106 | [FromBody] BankTransferPaymentCompleted listenedEvent, 107 | [FromServices] OrdersDbContext context) 108 | { 109 | Order? order = await context.Orders.FindOrder(listenedEvent.OrderId); 110 | 111 | if (order == null) 112 | { 113 | return NotFound(); 114 | } 115 | 116 | if (order.Status != OrderStatus.AwaitingPayment) 117 | { 118 | return BadRequest(); 119 | } 120 | 121 | order.Status = OrderStatus.AwaitingShipment; 122 | order.PaidAtUtc = listenedEvent.EventTimeUtc; 123 | await context.SaveChangesAsync(); 124 | return Ok(); 125 | } 126 | 127 | [HttpPost("handle/item-shipped")] 128 | [ProducesResponseType(200)] 129 | [ProducesResponseType(404)] 130 | public async Task HandleItemShipped( 131 | [FromBody] ItemShipped listenedEvent, 132 | [FromServices] OrdersDbContext context) 133 | { 134 | Order? order = await context.Orders.FindOrder(listenedEvent.OrderId); 135 | 136 | if (order == null) 137 | { 138 | return NotFound(); 139 | } 140 | 141 | if (order.Status != OrderStatus.AwaitingShipment) 142 | { 143 | return BadRequest(); 144 | } 145 | 146 | order.Status = OrderStatus.Completed; 147 | order.ShippedAtUtc = listenedEvent.EventTimeUtc; 148 | await context.SaveChangesAsync(); 149 | return Ok(); 150 | } 151 | 152 | [HttpPost("accept/payment-approved")] 153 | public async Task AcceptPaymentApproved( 154 | [FromBody] ExternalPaymentApproved externalEvent, 155 | [FromServices] IBus bus) 156 | { 157 | await bus.Send(new(externalEvent.tid, externalEvent.approved_at)); 158 | return Accepted(); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /ShopPlatform/ShopPlatform.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.1.32414.318 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Orders", "Orders", "{1A971FD7-BD9E-41E4-8B20-D0E0F65144D5}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Orders.Api", "Orders\Orders.Api\Orders.Api.csproj", "{5D856F14-5B33-4115-AD77-4EDE1AF7496B}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Sellers", "Sellers", "{C5D2AED1-52B4-40FB-A4AF-83AD40DECEBB}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sellers.Api", "Sellers\Sellers.Api\Sellers.Api.csproj", "{FC098083-45A4-4E6A-ACE6-819091BE2842}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Orders.UnitTests", "Orders\Orders.UnitTests\Orders.UnitTests.csproj", "{DEA5BB9E-654F-491B-A4A6-FB2E5D336B8D}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sellers.UnitTests", "Sellers\Sellers.UnitTests\Sellers.UnitTests.csproj", "{2FB2AEDE-419C-4CF9-B6EF-B373DA36DA25}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sellers.Testing", "Sellers\Sellers.Testing\Sellers.Testing.csproj", "{A9BF1CBD-8068-4199-AAD9-05C45445116E}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sellers.Contracts", "Sellers\Sellers.Contracts\Sellers.Contracts.csproj", "{DD0F3E18-B774-40B8-8D54-E35AE48842F6}" 21 | EndProject 22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sellers.DomainModel", "Sellers\Sellers.DomainModel\Sellers.DomainModel.csproj", "{B268ACFB-BFA2-481A-8FB5-B66E9A7180FC}" 23 | EndProject 24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sellers.Sql", "Sellers\Sellers.Sql\Sellers.Sql.csproj", "{31185376-4989-4870-8822-09728B4C7905}" 25 | EndProject 26 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sellers.Crypto", "Sellers\Sellers.Crypto\Sellers.Crypto.csproj", "{91BD80B0-50B1-4F38-8050-A8E807427B9C}" 27 | EndProject 28 | Global 29 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 30 | Debug|Any CPU = Debug|Any CPU 31 | Release|Any CPU = Release|Any CPU 32 | EndGlobalSection 33 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 34 | {5D856F14-5B33-4115-AD77-4EDE1AF7496B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {5D856F14-5B33-4115-AD77-4EDE1AF7496B}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {5D856F14-5B33-4115-AD77-4EDE1AF7496B}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {5D856F14-5B33-4115-AD77-4EDE1AF7496B}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {FC098083-45A4-4E6A-ACE6-819091BE2842}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {FC098083-45A4-4E6A-ACE6-819091BE2842}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {FC098083-45A4-4E6A-ACE6-819091BE2842}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {FC098083-45A4-4E6A-ACE6-819091BE2842}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {DEA5BB9E-654F-491B-A4A6-FB2E5D336B8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {DEA5BB9E-654F-491B-A4A6-FB2E5D336B8D}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {DEA5BB9E-654F-491B-A4A6-FB2E5D336B8D}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {DEA5BB9E-654F-491B-A4A6-FB2E5D336B8D}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {2FB2AEDE-419C-4CF9-B6EF-B373DA36DA25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {2FB2AEDE-419C-4CF9-B6EF-B373DA36DA25}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {2FB2AEDE-419C-4CF9-B6EF-B373DA36DA25}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {2FB2AEDE-419C-4CF9-B6EF-B373DA36DA25}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {A9BF1CBD-8068-4199-AAD9-05C45445116E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {A9BF1CBD-8068-4199-AAD9-05C45445116E}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {A9BF1CBD-8068-4199-AAD9-05C45445116E}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {A9BF1CBD-8068-4199-AAD9-05C45445116E}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {DD0F3E18-B774-40B8-8D54-E35AE48842F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {DD0F3E18-B774-40B8-8D54-E35AE48842F6}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {DD0F3E18-B774-40B8-8D54-E35AE48842F6}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {DD0F3E18-B774-40B8-8D54-E35AE48842F6}.Release|Any CPU.Build.0 = Release|Any CPU 58 | {B268ACFB-BFA2-481A-8FB5-B66E9A7180FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 59 | {B268ACFB-BFA2-481A-8FB5-B66E9A7180FC}.Debug|Any CPU.Build.0 = Debug|Any CPU 60 | {B268ACFB-BFA2-481A-8FB5-B66E9A7180FC}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {B268ACFB-BFA2-481A-8FB5-B66E9A7180FC}.Release|Any CPU.Build.0 = Release|Any CPU 62 | {31185376-4989-4870-8822-09728B4C7905}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 63 | {31185376-4989-4870-8822-09728B4C7905}.Debug|Any CPU.Build.0 = Debug|Any CPU 64 | {31185376-4989-4870-8822-09728B4C7905}.Release|Any CPU.ActiveCfg = Release|Any CPU 65 | {31185376-4989-4870-8822-09728B4C7905}.Release|Any CPU.Build.0 = Release|Any CPU 66 | {91BD80B0-50B1-4F38-8050-A8E807427B9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 67 | {91BD80B0-50B1-4F38-8050-A8E807427B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU 68 | {91BD80B0-50B1-4F38-8050-A8E807427B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU 69 | {91BD80B0-50B1-4F38-8050-A8E807427B9C}.Release|Any CPU.Build.0 = Release|Any CPU 70 | EndGlobalSection 71 | GlobalSection(SolutionProperties) = preSolution 72 | HideSolutionNode = FALSE 73 | EndGlobalSection 74 | GlobalSection(NestedProjects) = preSolution 75 | {5D856F14-5B33-4115-AD77-4EDE1AF7496B} = {1A971FD7-BD9E-41E4-8B20-D0E0F65144D5} 76 | {FC098083-45A4-4E6A-ACE6-819091BE2842} = {C5D2AED1-52B4-40FB-A4AF-83AD40DECEBB} 77 | {DEA5BB9E-654F-491B-A4A6-FB2E5D336B8D} = {1A971FD7-BD9E-41E4-8B20-D0E0F65144D5} 78 | {2FB2AEDE-419C-4CF9-B6EF-B373DA36DA25} = {C5D2AED1-52B4-40FB-A4AF-83AD40DECEBB} 79 | {A9BF1CBD-8068-4199-AAD9-05C45445116E} = {C5D2AED1-52B4-40FB-A4AF-83AD40DECEBB} 80 | {DD0F3E18-B774-40B8-8D54-E35AE48842F6} = {C5D2AED1-52B4-40FB-A4AF-83AD40DECEBB} 81 | {B268ACFB-BFA2-481A-8FB5-B66E9A7180FC} = {C5D2AED1-52B4-40FB-A4AF-83AD40DECEBB} 82 | {31185376-4989-4870-8822-09728B4C7905} = {C5D2AED1-52B4-40FB-A4AF-83AD40DECEBB} 83 | {91BD80B0-50B1-4F38-8050-A8E807427B9C} = {C5D2AED1-52B4-40FB-A4AF-83AD40DECEBB} 84 | EndGlobalSection 85 | GlobalSection(ExtensibilityGlobals) = postSolution 86 | SolutionGuid = {7CC5FAC9-580D-44E4-9E09-EC36B4311EB9} 87 | EndGlobalSection 88 | EndGlobal 89 | -------------------------------------------------------------------------------- /ShopPlatform/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | --------------------------------------------------------------------------------