Files
TakeoutSaaS.AdminApi/src/Infrastructure/TakeoutSaaS.Infrastructure/App/Repositories/EfPaymentRepository.cs

101 lines
3.3 KiB
C#

using System.Linq;
using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Payments.Entities;
using TakeoutSaaS.Domain.Payments.Repositories;
using TakeoutSaaS.Infrastructure.App.Persistence;
namespace TakeoutSaaS.Infrastructure.App.Repositories;
/// <summary>
/// 支付记录的 EF Core 仓储实现。
/// </summary>
public sealed class EfPaymentRepository : IPaymentRepository
{
private readonly TakeoutAppDbContext _context;
/// <summary>
/// 初始化仓储。
/// </summary>
public EfPaymentRepository(TakeoutAppDbContext context)
{
_context = context;
}
/// <inheritdoc />
public Task<PaymentRecord?> FindByIdAsync(long paymentId, long tenantId, CancellationToken cancellationToken = default)
{
return _context.PaymentRecords
.AsNoTracking()
.Where(x => x.TenantId == tenantId && x.Id == paymentId)
.FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc />
public Task<PaymentRecord?> FindByOrderIdAsync(long orderId, long tenantId, CancellationToken cancellationToken = default)
{
return _context.PaymentRecords
.AsNoTracking()
.Where(x => x.TenantId == tenantId && x.OrderId == orderId)
.FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<IReadOnlyList<PaymentRefundRecord>> GetRefundsAsync(long paymentId, long tenantId, CancellationToken cancellationToken = default)
{
var refunds = await _context.PaymentRefundRecords
.AsNoTracking()
.Where(x => x.TenantId == tenantId && x.PaymentRecordId == paymentId)
.OrderByDescending(x => x.CreatedAt)
.ToListAsync(cancellationToken);
return refunds;
}
/// <inheritdoc />
public Task AddPaymentAsync(PaymentRecord payment, CancellationToken cancellationToken = default)
{
return _context.PaymentRecords.AddAsync(payment, cancellationToken).AsTask();
}
/// <inheritdoc />
public Task AddRefundAsync(PaymentRefundRecord refund, CancellationToken cancellationToken = default)
{
return _context.PaymentRefundRecords.AddAsync(refund, cancellationToken).AsTask();
}
/// <inheritdoc />
public Task SaveChangesAsync(CancellationToken cancellationToken = default)
{
return _context.SaveChangesAsync(cancellationToken);
}
/// <inheritdoc />
public Task UpdatePaymentAsync(PaymentRecord payment, CancellationToken cancellationToken = default)
{
_context.PaymentRecords.Update(payment);
return Task.CompletedTask;
}
/// <inheritdoc />
public async Task DeletePaymentAsync(long paymentId, long tenantId, CancellationToken cancellationToken = default)
{
var refunds = await _context.PaymentRefundRecords
.Where(x => x.TenantId == tenantId && x.PaymentRecordId == paymentId)
.ToListAsync(cancellationToken);
if (refunds.Count > 0)
{
_context.PaymentRefundRecords.RemoveRange(refunds);
}
var existing = await _context.PaymentRecords
.Where(x => x.TenantId == tenantId && x.Id == paymentId)
.FirstOrDefaultAsync(cancellationToken);
if (existing == null)
{
return;
}
_context.PaymentRecords.Remove(existing);
}
}