using YD_Event.Application.Points.Dtos;
using YD_Event.Core.Entities;
namespace YD_Event.Application.Points;
///
/// 积分规则管理
///
public class PointsRuleService : BaseService, ITransient
{
private readonly ISqlSugarRepository _repository;
private readonly ISqlSugarRepository _detailRepository;
private readonly IIdGenerator _idGenerator;
public PointsRuleService(ISqlSugarRepository repository,
ISqlSugarRepository detailRepository,
IIdGenerator idGenerator) : base(repository)
{
_repository = repository;
_detailRepository = detailRepository;
_idGenerator = idGenerator;
}
///
/// 积分规则分页查询
///
[DisplayName("积分规则分页查询")]
[HttpGet]
public async Task> Page([FromQuery] PointsRuleQueryInput input)
{
return await _repository.AsQueryable()
.WhereIF(!string.IsNullOrWhiteSpace(input.RuleName), x => x.RuleName.Contains(input.RuleName))
.OrderByDescending(x => x.CreatedTime)
.ToPagedListAsync(input);
}
///
/// 添加积分规则
///
[DisplayName("添加积分规则")]
[HttpPost("add")]
[UnitOfWork]
public async Task Add(AddPointsRuleInput input)
{
var entity = input.Adapt();
entity.Id = _idGenerator.NextId();
await _repository.InsertAsync(entity);
if (input.Details != null && input.Details.Any())
{
var details = input.Details.Adapt>();
details.ForEach(x =>
{
x.PointsRuleId = entity.Id;
x.Id = _idGenerator.NextId();
});
await _detailRepository.InsertRangeAsync(details);
}
}
///
/// 更新积分规则
///
[DisplayName("更新积分规则")]
[HttpPut("edit")]
[UnitOfWork]
public async Task Update(UpdatePointsRuleInput input)
{
var entity = await _repository.GetByIdAsync(input.Id);
if (entity == null) throw Oops.Bah("规则不存在");
input.Adapt(entity);
await _repository.UpdateAsync(entity);
// Update details: Delete old, Insert new
await _detailRepository.DeleteAsync(x => x.PointsRuleId == entity.Id);
if (input.Details != null && input.Details.Any())
{
var details = input.Details.Adapt>();
details.ForEach(x =>
{
x.PointsRuleId = entity.Id;
x.Id = _idGenerator.NextId();
});
await _detailRepository.InsertRangeAsync(details);
}
}
///
/// 删除积分规则
///
[DisplayName("删除积分规则")]
[HttpPost("delete")]
[UnitOfWork]
public async Task Delete([FromBody] List ids)
{
await _repository.DeleteAsync(x => ids.Contains(x.Id));
await _detailRepository.DeleteAsync(x => ids.Contains(x.PointsRuleId));
}
///
/// 获取积分规则详情
///
[DisplayName("获取积分规则详情")]
[HttpGet("detail")]
public async Task Detail([FromQuery] long id)
{
var entity = await _repository.GetByIdAsync(id);
if (entity == null) throw Oops.Bah("规则不存在");
entity.Details = await _detailRepository.AsQueryable().Where(x => x.PointsRuleId == id).ToListAsync();
return entity;
}
}