using DigitalData.Core.Infrastructure; using DigitalData.UserManager.Infrastructure.Repositories; using EnvelopeGenerator.Domain.Entities; using EnvelopeGenerator.Infrastructure.Contracts; using Microsoft.EntityFrameworkCore; using System; namespace EnvelopeGenerator.Infrastructure.Repositories { public class EnvelopeReceiverRepository : CRUDRepository, IEnvelopeReceiverRepository { public EnvelopeReceiverRepository(EGDbContext dbContext) : base(dbContext) { } private IQueryable ReadWhere(string? uuid = null, string? signature = null, bool withEnvelope = false, bool withReceiver = false) { var query = _dbSet.AsQueryable(); if(uuid is not null) query = query.Where(er => er.Envelope != null && er.Envelope.Uuid == uuid); if (signature is not null) query = query.Where(er => er.Receiver != null && er.Receiver.Signature == signature); if (withEnvelope) query = query .Include(er => er.Envelope).ThenInclude(e => e!.Documents!).ThenInclude(d => d.Elements!.Where(e => signature == null || e.Receiver!.Signature == signature)) .Include(er => er.Envelope).ThenInclude(e => e!.History) .Include(er => er.Envelope).ThenInclude(e => e!.User); if (withReceiver) query = query.Include(er => er.Receiver); return query; } public async Task> ReadByUuidAsync(string uuid, bool withEnvelope = true, bool withReceiver = false) => await ReadWhere(uuid: uuid, withEnvelope: withEnvelope, withReceiver: withReceiver).ToListAsync(); public async Task> ReadBySignatureAsync(string signature, bool withEnvelope = false, bool withReceiver = true) => await ReadWhere(signature: signature, withEnvelope: withEnvelope, withReceiver: withReceiver).ToListAsync(); public async Task ReadByUuidSignatureAsync(string uuid, string signature, bool withEnvelope = true, bool withReceiver = true) => await ReadWhere(uuid: uuid, signature: signature, withEnvelope: withEnvelope, withReceiver: withReceiver).FirstOrDefaultAsync(); public async Task ReadAccessCodeAsync(string uuid, string signature) => await ReadWhere(uuid:uuid, signature:signature) .Select(er => er.AccessCode) .FirstOrDefaultAsync(); public async Task CountAsync(string uuid, string signature) => await ReadWhere(uuid: uuid, signature: signature).CountAsync(); } }