Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
264 changes: 250 additions & 14 deletions src/Microservices.sln

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/Services/Customer/Customer.API/Customer.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
<ItemGroup>
<ProjectReference Include="..\Customer.Domain\Customer.Domain.csproj" />
<ProjectReference Include="..\Customer.Infrastructure\Customer.Infrastructure.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj" />
<ProjectReference Include="..\..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\..\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.*" />
Expand Down
4 changes: 2 additions & 2 deletions src/Services/Identity/Identity.API/Identity.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
<ItemGroup>
<ProjectReference Include="..\Identity.Domain\Identity.Domain.csproj" />
<ProjectReference Include="..\Identity.Infrastructure\Identity.Infrastructure.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj" />
<ProjectReference Include="..\..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\..\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.*" />
Expand Down
1 change: 1 addition & 0 deletions src/Services/Notification/Notification.API/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ FROM build AS publish
RUN dotnet publish -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=publish /app/publish .
ENV ASPNETCORE_URLS=http://+:5005
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
<ItemGroup>
<ProjectReference Include="..\Notification.Domain\Notification.Domain.csproj" />
<ProjectReference Include="..\Notification.Infrastructure\Notification.Infrastructure.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj" />
<ProjectReference Include="..\..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\..\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.*" />
Expand Down
147 changes: 139 additions & 8 deletions src/Services/Order/Order.API/Controllers/OrderController.cs
Original file line number Diff line number Diff line change
@@ -1,29 +1,160 @@
using Microsoft.AspNetCore.Mvc;
using Order.Domain.Entities;
using Order.Domain.Interfaces;
using Shared.Contracts.Events;

namespace Order.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class OrderController : ControllerBase
{
private readonly IOrderRepository _repository;
private readonly HttpClient _productClient;
private readonly HttpClient _notificationClient;
private readonly ILogger<OrderController> _logger;

public OrderController(ILogger<OrderController> logger)
public OrderController(
IOrderRepository repository,
IHttpClientFactory httpClientFactory,
ILogger<OrderController> logger)
{
_repository = repository;
_productClient = httpClientFactory.CreateClient("ProductService");
_notificationClient = httpClientFactory.CreateClient("NotificationService");
_logger = logger;
}

[HttpGet]
public IActionResult GetAll()
public async Task<IActionResult> GetAll()
{
// TODO: Implement — migrate logic from monolith's OrderController
return Ok(new { service = "Order", status = "scaffold" });
var orders = await _repository.GetAllAsync();
return Ok(orders.Select(o => new
{
o.Id,
o.CustomerId,
o.ProductId,
o.ProductName,
o.Quantity,
o.UnitPrice,
o.TotalAmount,
o.Status,
o.CreatedAt
}));
}

[HttpGet("{id}")]
public IActionResult GetById(int id)
[HttpGet("{id:guid}")]
public async Task<IActionResult> GetById(Guid id)
{
// TODO: Implement — migrate logic from monolith
return Ok(new { service = "Order", id });
var order = await _repository.GetByIdAsync(id);
if (order is null)
return NotFound();

return Ok(new
{
order.Id,
order.CustomerId,
order.ProductId,
order.ProductName,
order.Quantity,
order.UnitPrice,
order.TotalAmount,
order.Status,
order.CreatedAt
});
}

[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateOrderRequest request)
{
if (request.CustomerId == Guid.Empty)
return BadRequest(new { error = "A valid customer ID is required." });

if (request.ProductId == Guid.Empty)
return BadRequest(new { error = "A valid product ID is required." });

if (request.Quantity <= 0)
return BadRequest(new { error = "Quantity must be greater than zero." });

// Validate product exists by calling Product service
ProductDto? product;
try
{
var response = await _productClient.GetAsync($"/api/product/{request.ProductId}");
if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("Product {ProductId} not found", request.ProductId);
return BadRequest(new { error = $"Product {request.ProductId} does not exist." });
}
product = await response.Content.ReadFromJsonAsync<ProductDto>();
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "Failed to reach Product service");
return StatusCode(503, new { error = "Product service is unavailable." });
}

if (product is null)
return BadRequest(new { error = $"Product {request.ProductId} does not exist." });

var totalAmount = product.Price * request.Quantity;

var order = new OrderEntity
{
Id = Guid.NewGuid(),
CustomerId = request.CustomerId,
ProductId = request.ProductId,
ProductName = product.Name,
Quantity = request.Quantity,
UnitPrice = product.Price,
TotalAmount = totalAmount,
Status = OrderStatus.Confirmed,
CreatedAt = DateTime.UtcNow
};

await _repository.AddAsync(order);
_logger.LogInformation("Order {OrderId} created for customer {CustomerId}", order.Id, order.CustomerId);

// Publish OrderPlacedEvent to Notification service
try
{
var orderEvent = new OrderPlacedEvent(
order.Id,
order.CustomerId,
order.TotalAmount,
order.CreatedAt);

await _notificationClient.PostAsJsonAsync("/api/notification/events/order-placed", orderEvent);
_logger.LogInformation("OrderPlacedEvent published for order {OrderId}", order.Id);
}
catch (HttpRequestException ex)
{
_logger.LogWarning(ex, "Failed to publish OrderPlacedEvent for order {OrderId}", order.Id);
}

return CreatedAtAction(nameof(GetById), new { id = order.Id }, new
{
order.Id,
order.CustomerId,
order.ProductId,
order.ProductName,
order.Quantity,
order.UnitPrice,
order.TotalAmount,
order.Status,
order.CreatedAt
});
}
}

public record CreateOrderRequest(
Guid CustomerId,
Guid ProductId,
int Quantity);

public record ProductDto(
Guid Id,
string Name,
string? Description,
decimal Price,
int StockQuantity);
1 change: 1 addition & 0 deletions src/Services/Order/Order.API/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ FROM build AS publish
RUN dotnet publish -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=publish /app/publish .
ENV ASPNETCORE_URLS=http://+:5003
Expand Down
4 changes: 2 additions & 2 deletions src/Services/Order/Order.API/Order.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
<ItemGroup>
<ProjectReference Include="..\Order.Domain\Order.Domain.csproj" />
<ProjectReference Include="..\Order.Infrastructure\Order.Infrastructure.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj" />
<ProjectReference Include="..\..\..\Shared\Shared.Contracts\Shared.Contracts.csproj" />
<ProjectReference Include="..\..\..\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.*" />
Expand Down
22 changes: 22 additions & 0 deletions src/Services/Order/Order.API/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Order.Domain.Interfaces;
using Order.Infrastructure.Data;
using Order.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
Expand All @@ -11,8 +13,28 @@
builder.Services.AddDbContext<OrderDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddScoped<IOrderRepository, OrderRepository>();

builder.Services.AddHttpClient("ProductService", client =>
{
var baseUrl = builder.Configuration["ServiceUrls:ProductService"] ?? "http://product-service:5004";
client.BaseAddress = new Uri(baseUrl);
});

builder.Services.AddHttpClient("NotificationService", client =>
{
var baseUrl = builder.Configuration["ServiceUrls:NotificationService"] ?? "http://notification-service:5005";
client.BaseAddress = new Uri(baseUrl);
});

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<OrderDbContext>();
db.Database.EnsureCreated();
}

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
Expand Down
Empty file.
23 changes: 23 additions & 0 deletions src/Services/Order/Order.Domain/Entities/OrderEntity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace Order.Domain.Entities;

public class OrderEntity
{
public Guid Id { get; set; }
public Guid CustomerId { get; set; }
public Guid ProductId { get; set; }
public string ProductName { get; set; } = string.Empty;
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal TotalAmount { get; set; }
public OrderStatus Status { get; set; }
public DateTime CreatedAt { get; set; }
}

public enum OrderStatus
{
Pending,
Confirmed,
Shipped,
Delivered,
Cancelled
}
Empty file.
10 changes: 10 additions & 0 deletions src/Services/Order/Order.Domain/Interfaces/IOrderRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Order.Domain.Entities;

namespace Order.Domain.Interfaces;

public interface IOrderRepository
{
Task<OrderEntity?> GetByIdAsync(Guid id);
Task<IReadOnlyList<OrderEntity>> GetAllAsync();
Task<OrderEntity> AddAsync(OrderEntity order);
}
14 changes: 13 additions & 1 deletion src/Services/Order/Order.Infrastructure/Data/OrderDbContext.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Order.Domain.Entities;

namespace Order.Infrastructure.Data;

Expand All @@ -8,9 +9,20 @@ public OrderDbContext(DbContextOptions<OrderDbContext> options) : base(options)
{
}

public DbSet<OrderEntity> Orders => Set<OrderEntity>();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// TODO: Configure entity mappings migrated from monolith

modelBuilder.Entity<OrderEntity>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.ProductName).HasMaxLength(256);
entity.Property(e => e.UnitPrice).HasColumnType("decimal(18,2)");
entity.Property(e => e.TotalAmount).HasColumnType("decimal(18,2)");
entity.HasIndex(e => e.CustomerId);
entity.HasIndex(e => e.ProductId);
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Microsoft.EntityFrameworkCore;
using Order.Domain.Entities;
using Order.Domain.Interfaces;
using Order.Infrastructure.Data;

namespace Order.Infrastructure.Repositories;

public class OrderRepository : IOrderRepository
{
private readonly OrderDbContext _context;

public OrderRepository(OrderDbContext context)
{
_context = context;
}

public async Task<OrderEntity?> GetByIdAsync(Guid id)
{
return await _context.Orders.FindAsync(id);
}

public async Task<IReadOnlyList<OrderEntity>> GetAllAsync()
{
return await _context.Orders
.OrderByDescending(o => o.CreatedAt)
.ToListAsync();
}

public async Task<OrderEntity> AddAsync(OrderEntity order)
{
_context.Orders.Add(order);
await _context.SaveChangesAsync();
return order;
}
}
Loading