104 lines
3.1 KiB
C#
104 lines
3.1 KiB
C#
using Contracts.DTO;
|
|
using Contracts.Repositories;
|
|
using Contracts.SearchModels;
|
|
using Infrastructure.Support.Mappers;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Infrastructure.Repositories;
|
|
|
|
public class SpendingGroupRepo : ISpendingGroupRepo
|
|
{
|
|
public readonly IDbContextFactory<DatabaseContext> _factory;
|
|
|
|
public SpendingGroupRepo(IDbContextFactory<DatabaseContext> factory)
|
|
{
|
|
_factory = factory;
|
|
}
|
|
|
|
public async Task<SpendingGroupDto> Create(SpendingGroupDto spendingGroup)
|
|
{
|
|
using var context = _factory.CreateDbContext();
|
|
|
|
var createdGroup = await context.SpendingGroups.AddAsync(spendingGroup.ToModel());
|
|
await context.SaveChangesAsync();
|
|
return createdGroup.Entity.ToDto();
|
|
}
|
|
|
|
public async Task<SpendingGroupDto?> Delete(SpendingGroupSearch search)
|
|
{
|
|
using var context = _factory.CreateDbContext();
|
|
|
|
var group = await context.SpendingGroups
|
|
.FirstOrDefaultAsync(x => x.Id == search.Id
|
|
|| x.Name == search.Name);
|
|
if (group == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
context.SpendingGroups.Remove(group);
|
|
await context.SaveChangesAsync();
|
|
return group.ToDto();
|
|
}
|
|
|
|
public async Task<SpendingGroupDto?> Get(SpendingGroupSearch search)
|
|
{
|
|
using var context = _factory.CreateDbContext();
|
|
|
|
var group = await context.SpendingGroups
|
|
.Include(x => x.ChangeRecords)
|
|
.Include(x => x.SpendingPlans)
|
|
.FirstOrDefaultAsync(x => x.Id == search.Id
|
|
|| (!string.IsNullOrWhiteSpace(search.Name)
|
|
&& x.Name == search.Name
|
|
&& x.UserId == search.UserId));
|
|
|
|
return group?.ToDto();
|
|
}
|
|
|
|
public async Task<IEnumerable<SpendingGroupDto>> GetList(SpendingGroupSearch? search = null)
|
|
{
|
|
using var context = _factory.CreateDbContext();
|
|
|
|
var query = context.SpendingGroups.AsQueryable();
|
|
|
|
if (search != null)
|
|
{
|
|
if (search.Id != null)
|
|
{
|
|
query = query.Where(x => x.Id == search.Id);
|
|
}
|
|
|
|
if (!string.IsNullOrWhiteSpace(search.Name) && search.UserId.HasValue)
|
|
{
|
|
query = query.Where(x => x.Name.Contains(search.Name, StringComparison.OrdinalIgnoreCase)
|
|
&& x.UserId == search.UserId);
|
|
}
|
|
}
|
|
|
|
return await query
|
|
.Include(x => x.ChangeRecords)
|
|
.Include(x => x.SpendingPlans)
|
|
.Select(x => x.ToDto())
|
|
.ToListAsync();
|
|
}
|
|
|
|
public async Task<SpendingGroupDto?> Update(SpendingGroupDto spendingGroup)
|
|
{
|
|
using var context = _factory.CreateDbContext();
|
|
|
|
var existingGroup = await context.SpendingGroups
|
|
.FirstOrDefaultAsync(x => x.Id == spendingGroup.Id);
|
|
|
|
if (existingGroup == null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
existingGroup.Name = spendingGroup.Name;
|
|
context.SpendingGroups.Update(existingGroup);
|
|
await context.SaveChangesAsync();
|
|
return existingGroup.ToDto();
|
|
}
|
|
}
|