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; /// /// 支付记录的 EF Core 仓储实现。 /// public sealed class EfPaymentRepository : IPaymentRepository { private readonly TakeoutAppDbContext _context; /// /// 初始化仓储。 /// public EfPaymentRepository(TakeoutAppDbContext context) { _context = context; } /// public Task FindByIdAsync(long paymentId, long tenantId, CancellationToken cancellationToken = default) { return _context.PaymentRecords .AsNoTracking() .Where(x => x.TenantId == tenantId && x.Id == paymentId) .FirstOrDefaultAsync(cancellationToken); } /// public Task FindByOrderIdAsync(long orderId, long tenantId, CancellationToken cancellationToken = default) { return _context.PaymentRecords .AsNoTracking() .Where(x => x.TenantId == tenantId && x.OrderId == orderId) .FirstOrDefaultAsync(cancellationToken); } /// public async Task> 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; } /// public Task AddPaymentAsync(PaymentRecord payment, CancellationToken cancellationToken = default) { return _context.PaymentRecords.AddAsync(payment, cancellationToken).AsTask(); } /// public Task AddRefundAsync(PaymentRefundRecord refund, CancellationToken cancellationToken = default) { return _context.PaymentRefundRecords.AddAsync(refund, cancellationToken).AsTask(); } /// public Task SaveChangesAsync(CancellationToken cancellationToken = default) { return _context.SaveChangesAsync(cancellationToken); } /// public Task UpdatePaymentAsync(PaymentRecord payment, CancellationToken cancellationToken = default) { _context.PaymentRecords.Update(payment); return Task.CompletedTask; } /// 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); } }