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
Original file line number Diff line number Diff line change
@@ -1,29 +1,108 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Customer.API.DTOs;
using Customer.Domain.Interfaces;
using Customer.Domain.Enums;
using Entities = Customer.Domain.Entities;

namespace Customer.API.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class CustomerController : ControllerBase
{
private readonly ICustomerService _customerService;
private readonly ILogger<CustomerController> _logger;

public CustomerController(ILogger<CustomerController> logger)
public CustomerController(ICustomerService customerService, ILogger<CustomerController> logger)
{
_customerService = customerService;
_logger = logger;
}

[HttpGet]
public IActionResult GetAll()
[ProducesResponseType(typeof(IEnumerable<CustomerDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> GetAll()
{
// TODO: Implement — migrate logic from monolith's CustomerController
return Ok(new { service = "Customer", status = "scaffold" });
var customers = await _customerService.GetAllAsync();
return Ok(customers.Select(MapToDto));
}

[HttpGet("{id}")]
public IActionResult GetById(int id)
[ProducesResponseType(typeof(CustomerDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> GetById(int id)
{
// TODO: Implement — migrate logic from monolith
return Ok(new { service = "Customer", id });
var customer = await _customerService.GetByIdAsync(id);
if (customer is null) return NotFound();
return Ok(MapToDto(customer));
}

[HttpPost]
[ProducesResponseType(typeof(CustomerDto), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Create([FromBody] CustomerDto dto)
{
if (string.IsNullOrWhiteSpace(dto.Name) || string.IsNullOrWhiteSpace(dto.Email))
return BadRequest("Name and Email are required.");

var customer = new Entities.Customer
{
Name = dto.Name,
Email = dto.Email,
PhoneNumber = dto.PhoneNumber,
Address = dto.Address,
City = dto.City,
Gender = Enum.TryParse<Gender>(dto.Gender, true, out var g) ? g : Gender.None
};

var created = await _customerService.CreateAsync(customer);
return CreatedAtAction(nameof(GetById), new { id = created.Id }, MapToDto(created));
}

[HttpPut("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Update(int id, [FromBody] CustomerDto dto)
{
var existing = await _customerService.GetByIdAsync(id);
if (existing is null) return NotFound();

existing.Name = dto.Name ?? existing.Name;
existing.Email = dto.Email ?? existing.Email;
existing.PhoneNumber = dto.PhoneNumber;
existing.Address = dto.Address;
existing.City = dto.City;
Comment on lines +78 to +80

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Updating a customer silently erases phone number, address, and city when those fields are omitted

Optional customer fields are overwritten with null (dto.PhoneNumber / dto.Address / dto.City assigned directly at CustomerController.cs:78-80) instead of being preserved like name and email are, so any update request that omits those fields wipes out the stored values.

Impact: A user updating only their name or email loses their phone number, address, and city data.

Inconsistent null-coalescing between required and optional fields in the Update action

In the Update method at src/Services/Customer/Customer.API/Controllers/CustomerController.cs:76-81, Name and Email use the null-coalescing operator (??) so a null DTO value preserves the existing database value:

existing.Name = dto.Name ?? existing.Name;
existing.Email = dto.Email ?? existing.Email;

But the three optional fields are assigned directly without the same guard:

existing.PhoneNumber = dto.PhoneNumber;
existing.Address = dto.Address;
existing.City = dto.City;

When a PUT request omits PhoneNumber, Address, or City (they deserialize as null from the CustomerDto), the existing stored values are overwritten with null. This is an inconsistency: the code intends partial-update semantics (as evidenced by the ?? pattern on the other fields and on Gender at line 81), but three fields use full-replace semantics instead.

Suggested change
existing.PhoneNumber = dto.PhoneNumber;
existing.Address = dto.Address;
existing.City = dto.City;
existing.PhoneNumber = dto.PhoneNumber ?? existing.PhoneNumber;
existing.Address = dto.Address ?? existing.Address;
existing.City = dto.City ?? existing.City;
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — the inconsistency is real. The direct assignment for PhoneNumber/Address/City was implemented per the task spec, but this does create different semantics vs the ??-guarded Name/Email/Gender fields. Escalating to the author to confirm whether partial-update semantics (null-coalescing) should apply to all fields.

existing.Gender = Enum.TryParse<Gender>(dto.Gender, true, out var g) ? g : existing.Gender;

await _customerService.UpdateAsync(existing);
return NoContent();
}

[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Delete(int id)
{
var deleted = await _customerService.DeleteAsync(id);
if (!deleted) return NotFound();
return NoContent();
}

private static CustomerDto MapToDto(Entities.Customer c) => new()
{
Id = c.Id,
Name = c.Name,
Email = c.Email,
PhoneNumber = c.PhoneNumber,
Address = c.Address,
City = c.City,
Gender = c.Gender.ToString()
};
}
1 change: 1 addition & 0 deletions src/Services/Customer/Customer.API/Customer.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<ProjectReference Include="..\..\Shared\Shared.Infrastructure\Shared.Infrastructure.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.*" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.*" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.*" />
</ItemGroup>
Expand Down
12 changes: 12 additions & 0 deletions src/Services/Customer/Customer.API/DTOs/CustomerDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace Customer.API.DTOs;

public class CustomerDto
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Email { get; set; }
public string? PhoneNumber { get; set; }
public string? Address { get; set; }
public string? City { get; set; }
public string? Gender { get; set; }
}
33 changes: 33 additions & 0 deletions src/Services/Customer/Customer.API/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Customer.Infrastructure.Data;
using Customer.Domain.Interfaces;
using Customer.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
Expand All @@ -11,6 +16,31 @@
builder.Services.AddDbContext<CustomerDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddScoped<ICustomerService, CustomerService>();

// JWT Authentication
var jwtSection = builder.Configuration.GetSection("Jwt");
var key = Encoding.UTF8.GetBytes(jwtSection["Secret"]!);
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtSection["Issuer"],
ValidAudience = jwtSection["Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
builder.Services.AddAuthorization();

var app = builder.Build();

using (var scope = app.Services.CreateScope())
Expand All @@ -25,6 +55,9 @@
app.UseSwaggerUI();
}

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapHealthChecks("/healthz");

Expand Down
6 changes: 6 additions & 0 deletions src/Services/Customer/Customer.API/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,11 @@
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=customerdb;Username=postgres;Password=postgres"
},
"Jwt": {
"Secret": "QuickApp_Microservices_SuperSecret_Key_For_Dev_Only_Min_32_Chars!",
"Issuer": "quickapp-identity",
"Audience": "quickapp-api",
"ExpirationMinutes": 60
}
}
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.EntityFrameworkCore;
using Customer.Domain.Interfaces;
using Customer.Infrastructure.Data;
using Entities = Customer.Domain.Entities;

namespace Customer.Infrastructure.Services;

public class CustomerService : ICustomerService
{
private readonly CustomerDbContext _context;

public CustomerService(CustomerDbContext context)
{
_context = context;
}

public async Task<IEnumerable<Entities.Customer>> GetAllAsync()
{
return await _context.Customers.OrderBy(c => c.Name).ToListAsync();
}

public async Task<Entities.Customer?> GetByIdAsync(int id)
{
return await _context.Customers.FindAsync(id);
}

public async Task<Entities.Customer> CreateAsync(Entities.Customer customer)
{
customer.CreatedDate = DateTime.UtcNow;
customer.UpdatedDate = DateTime.UtcNow;
_context.Customers.Add(customer);
await _context.SaveChangesAsync();
return customer;
}

public async Task UpdateAsync(Entities.Customer customer)
{
customer.UpdatedDate = DateTime.UtcNow;
_context.Customers.Update(customer);
await _context.SaveChangesAsync();
}

public async Task<bool> DeleteAsync(int id)
{
var customer = await _context.Customers.FindAsync(id);
if (customer == null) return false;
_context.Customers.Remove(customer);
await _context.SaveChangesAsync();
return true;
}
}