mirror of
https://github.com/Sea-Haven-Industries/proposal-system.git
synced 2026-09-30 19:23:15 +00:00
71 lines
2 KiB
C#
71 lines
2 KiB
C#
|
|
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>();
|
||
|
|
}
|
||
|
|
}
|