Files
lux/EgwCoreLib.Lux.Data/Services/Sales/CustomerService.cs
T
2026-05-29 19:21:45 +02:00

120 lines
3.7 KiB
C#

namespace EgwCoreLib.Lux.Data.Services.Sales
{
public class CustomerService : BaseServ, ICustomerService
{
#region Public Constructors
public CustomerService(
IConfiguration config,
IConnectionMultiplexer redis,
ICustomerRepository repo) : base(config, redis)
{
_className = "Customer";
_repo = repo;
}
#endregion Public Constructors
#region Public Methods
/// <inheritdoc />
public async Task<bool> DeleteAsync(CustomerModel rec2del)
{
return await TraceAsync($"{_className}.Delete", async (activity) =>
{
var dbResult = await _repo.GetByIdAsync(rec2del.CustomerID);
if (dbResult == null) return false;
var numChild = await _repo.CountChildrenAsync(rec2del.CustomerID);
if (numChild > 0)
{
activity?.SetTag("delete.status", "rejected_has_children");
return false;
}
bool success = await _repo.DeleteAsync(dbResult);
if (success)
{
await ClearCacheAsync($"{_redisBaseKey}:{_className}:*");
}
return success;
});
}
/// <inheritdoc />
public async Task<List<CustomerModel>> GetAllAsync()
{
// Uso helper TraceAsync che gestisce automaticamente StartActivity, Log e Exception tracking
return await TraceAsync($"{_className}.GetAllAsync", async (activity) =>
{
return await GetOrSetCacheAsync(
$"{_redisBaseKey}:{_className}:ALL",
async () => await _repo.GetAllAsync(),
UltraLongCache
);
});
}
/// <inheritdoc />
public async Task<bool> HasChild(int CustomerID)
{
return await TraceAsync($"{_className}.CountChild", async (activity) =>
{
return await GetOrSetCacheAsync(
$"{_redisBaseKey}:{_className}:HasChild:{CustomerID}",
async () =>
{
var dbResult = await _repo.GetByIdAsync(CustomerID);
if (dbResult == null) return false;
var numChild = await _repo.CountChildrenAsync(CustomerID);
return numChild > 0;
},
FastCache
);
});
}
/// <inheritdoc />
public async Task<bool> UpsertAsync(CustomerModel upsRec)
{
return await TraceAsync($"{_className}.Upsert", async (activity) =>
{
var currRec = await _repo.GetByIdAsync(upsRec.CustomerID);
string operation = "UPDATE";
bool success = false;
if (currRec != null)
{
success = await _repo.UpdateAsync(upsRec);
}
else
{
operation = "INSERT";
success = await _repo.AddAsync(upsRec);
}
activity?.SetTag("db.operation", operation);
if (success)
{
await ClearCacheAsync($"{_redisBaseKey}:{_className}:*");
}
return success;
});
}
#endregion Public Methods
#region Private Fields
private readonly string _className;
private readonly ICustomerRepository _repo;
#endregion Private Fields
}
}