proposal-system/api/src/ProposalSystem.Infrastructure/Services/CustomerService.cs

71 lines
2 KiB
C#
Raw Normal View History

using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using ProposalSystem.Application.DTOs;
using ProposalSystem.Application.Interfaces;
using ProposalSystem.Domain.Entities;
using ProposalSystem.Infrastructure.Data;
namespace ProposalSystem.Infrastructure.Services;
public class CustomerService : ICustomerService
{
private readonly ProposalDbContext _db;
public CustomerService(ProposalDbContext db)
{
_db = db;
}
public async Task<IReadOnlyList<CustomerResponse>> SearchAsync(string? query, CancellationToken ct = default)
{
var q = _db.Customers.AsQueryable();
if (!string.IsNullOrWhiteSpace(query))
{
var search = query.ToLower();
q = q.Where(c => c.Name.ToLower().Contains(search));
}
var customers = await q
.OrderBy(c => c.Name)
.Take(50)
.ToListAsync(ct);
return customers.Select(c => new CustomerResponse(
c.Id,
c.Name,
DeserializeAddresses(c.Addresses),
c.CreatedAt
)).ToList();
}
public async Task<CustomerResponse> CreateAsync(CreateCustomerRequest request, CancellationToken ct = default)
{
var now = DateTime.UtcNow;
var customer = new Customer
{
Id = Guid.NewGuid(),
Name = request.Name,
Addresses = request.Addresses != null ? JsonSerializer.Serialize(request.Addresses) : null,
CreatedAt = now,
UpdatedAt = now,
};
_db.Customers.Add(customer);
await _db.SaveChangesAsync(ct);
return new CustomerResponse(
customer.Id,
customer.Name,
request.Addresses ?? new List<string>(),
customer.CreatedAt
);
}
private static List<string> DeserializeAddresses(string? json)
{
if (string.IsNullOrEmpty(json)) return new List<string>();
return JsonSerializer.Deserialize<List<string>>(json) ?? new List<string>();
}
}