using AsbCloudApp.Data; using AsbCloudApp.Data.User; using AsbCloudApp.Exceptions; using AsbCloudApp.Services; using AsbCloudDb.Model; using Mapster; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace AsbCloudInfrastructure.Services { public class WellContactService : IWellContactService { private readonly IAsbCloudDbContext db; public WellContactService(IAsbCloudDbContext db) { this.db = db; } public async Task> GetAllAsync(int wellId, int contactTypeId, CancellationToken token) { var query = db.Contacts .Where(c => c.IdCompanyType == contactTypeId) .Where(c => c.IdWell == wellId) .Select(c => c.Adapt()); var entities = await query.AsNoTracking() .ToArrayAsync(token); return entities; } public async Task GetAsync(int idWell, int id, CancellationToken token) { var dbContact = await GetContact(idWell, id, token); var result = dbContact?.Adapt(); return result; } public async Task> GetTypesAsync(CancellationToken token) { var query = db.CompaniesTypes .Where(t => t.IsContact) .OrderBy(t => t.Order); var entities = await query.AsNoTracking() .ToArrayAsync(token); var dtos = entities.Adapt>(); return dtos; } public async Task InsertAsync(ContactDto contactDto, CancellationToken token) { var entity = contactDto.Adapt(); db.Contacts.Add(entity); await db.SaveChangesAsync(token).ConfigureAwait(false); return entity.Id; } public async Task UpdateAsync(ContactDto contactDto, CancellationToken token) { var dbContact = await GetContact(contactDto.IdWell, contactDto.Id, token); if (dbContact is null) throw new ForbidException("Contact doesn't exist"); var entity = contactDto.Adapt(); db.Contacts.Update(entity); return await db.SaveChangesAsync(token); } public async Task DeleteAsync(int idWell, int id, CancellationToken token) { var dbContact = await GetContact(idWell, id, token); if (dbContact is null) throw new ForbidException("Contact doesn't exist"); db.Contacts.Remove(dbContact); return await db.SaveChangesAsync(token); } private async Task GetContact(int idWell, int idContact, CancellationToken token) { var contact = await db.Contacts .Where(c => c.IdWell == idWell) .Where(c => c.Id == idContact) .AsNoTracking() .FirstOrDefaultAsync(token); return contact; } } }