Feat: Cambios Varios
This commit is contained in:
71
src/SIGCM.Infrastructure/Repositories/ClientRepository.cs
Normal file
71
src/SIGCM.Infrastructure/Repositories/ClientRepository.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using Dapper;
|
||||
using SIGCM.Domain.Entities;
|
||||
using SIGCM.Infrastructure.Data;
|
||||
|
||||
namespace SIGCM.Infrastructure.Repositories;
|
||||
|
||||
public class ClientRepository
|
||||
{
|
||||
private readonly IDbConnectionFactory _db;
|
||||
|
||||
public ClientRepository(IDbConnectionFactory db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
// Búsqueda inteligente por Nombre O DNI
|
||||
public async Task<IEnumerable<Client>> SearchAsync(string query)
|
||||
{
|
||||
using var conn = _db.CreateConnection();
|
||||
var sql = @"
|
||||
SELECT TOP 10 * FROM Clients
|
||||
WHERE Name LIKE @Query OR DniOrCuit LIKE @Query
|
||||
ORDER BY Name";
|
||||
return await conn.QueryAsync<Client>(sql, new { Query = $"%{query}%" });
|
||||
}
|
||||
|
||||
// Buscar o Crear (Upsert) al guardar el aviso
|
||||
public async Task<int> EnsureClientExistsAsync(string name, string dni)
|
||||
{
|
||||
using var conn = _db.CreateConnection();
|
||||
|
||||
// 1. Buscamos por DNI/CUIT (es el identificador único más fiable)
|
||||
var existingId = await conn.ExecuteScalarAsync<int?>(
|
||||
"SELECT Id FROM Clients WHERE DniOrCuit = @Dni", new { Dni = dni });
|
||||
|
||||
if (existingId.HasValue)
|
||||
{
|
||||
// Opcional: Actualizar nombre si cambió
|
||||
await conn.ExecuteAsync("UPDATE Clients SET Name = @Name WHERE Id = @Id", new { Name = name, Id = existingId });
|
||||
return existingId.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Crear nuevo
|
||||
var sql = @"
|
||||
INSERT INTO Clients (Name, DniOrCuit) VALUES (@Name, @Dni);
|
||||
SELECT CAST(SCOPE_IDENTITY() as int);";
|
||||
return await conn.QuerySingleAsync<int>(sql, new { Name = name, Dni = dni });
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<dynamic>> GetAllWithStatsAsync()
|
||||
{
|
||||
using var conn = _db.CreateConnection();
|
||||
var sql = @"
|
||||
SELECT c.*,
|
||||
(SELECT COUNT(1) FROM Listings l WHERE l.ClientId = c.Id) as TotalAds,
|
||||
(SELECT SUM(AdFee) FROM Listings l WHERE l.ClientId = c.Id) as TotalSpent
|
||||
FROM Clients c
|
||||
ORDER BY c.Name";
|
||||
return await conn.QueryAsync(sql);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Listing>> GetClientHistoryAsync(int clientId)
|
||||
{
|
||||
using var conn = _db.CreateConnection();
|
||||
return await conn.QueryAsync<Listing>(
|
||||
"SELECT * FROM Listings WHERE ClientId = @Id ORDER BY CreatedAt DESC",
|
||||
new { Id = clientId });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user