using Microsoft.EntityFrameworkCore; using Microsoft.SelfService.Portal.Core.API.Context; using Microsoft.SelfService.Portal.Core.API.Interfaces; using Microsoft.SelfService.Portal.Core.API.Models; namespace Microsoft.SelfService.Portal.Core.API.Repository { public class DeploymentGroupRepository : IDeploymentGroupInterface { private readonly DataContext _context; public DeploymentGroupRepository(DataContext context) { _context = context; } public ICollection GetDeploymentGroups() { return _context.DeploymentGroups.ToList(); } public DeploymentGroupModel GetDeploymentGroupById(Guid Id) { return _context.DeploymentGroups .Include(t => t.Template) .ThenInclude(tc => tc.TemplateCategory) .ThenInclude(s => s.Service) .Include(d => d.Deployments) .ThenInclude(vm => vm.VirtualMachine) .Where(dg => dg.Id == Id).FirstOrDefault(); } public bool AddDeploymentGroupById(DeploymentGroupModel deploymentgroup, ICollection? virtualMachineIds) { if (deploymentgroup.Id == Guid.Empty) { deploymentgroup.Id = Guid.NewGuid(); } var template = _context.Templates .Include(existing => existing.TemplateCategory) .ThenInclude(existing => existing.Service) .FirstOrDefault(existing => existing.Id == deploymentgroup.TemplateId); if (template == null) { return false; } var isCloudService = template.TemplateCategory.Service.IsCloudService; var selectedVirtualMachineIds = (virtualMachineIds ?? Array.Empty()) .Distinct() .ToList(); if (!isCloudService && selectedVirtualMachineIds.Count == 0) { return false; } if (selectedVirtualMachineIds.Count > 0) { var existingVirtualMachineIds = _context.VirtualMachines .Where(existing => selectedVirtualMachineIds.Contains(existing.Id)) .Select(existing => existing.Id) .ToHashSet(); if (existingVirtualMachineIds.Count != selectedVirtualMachineIds.Count) { return false; } } _context.Add(deploymentgroup); if (!SaveChanges()) { return false; } if (!isCloudService) { foreach (var virtualMachineId in selectedVirtualMachineIds) { _context.Deployments.Add(new DeploymentModel { DeploymentGroupId = deploymentgroup.Id, VirtualMachineId = virtualMachineId, Status = QueueJobStatus.Pending, JSONData = "{}" }); } return SaveChanges(); } return true; } public bool DeleteDeploymentGroupById(DeploymentGroupModel deploymentgroup) { _context.Remove(deploymentgroup); return SaveChanges(); } public bool EditDeploymentGroupById(DeploymentGroupModel deploymentgroup) { _context.Update(deploymentgroup); return SaveChanges(); } public bool CheckDeploymentGroupById(Guid Id) { return _context.DeploymentGroups .Any(d => d.Id == Id); } public bool SaveChanges() { var saved = _context.SaveChanges(); return saved > 0 ? true : false; } } }