using Microsoft.Data.SqlClient; using PlotLine.Data; using PlotLine.Models; namespace PlotLine.Services; public sealed class GeographicHierarchyService(GeographyRepository repository,GeographicRules rules,IProjectAccessService access, ICurrentUserService currentUser,ILocationRepository locations,IGeocodingProvider provider) { public async Task SubmitAsync(int projectId,int locationId) { if(!await access.CanAccessProjectAsync(projectId))return "Project access is required."; var all=await locations.ListByProjectAsync(projectId); if(!all.Any(l=>l.LocationID==locationId))return "Location is unavailable."; var scope=new HashSet{locationId}; for(var depth=0;depth<100;depth++) { var added=false; foreach(var l in all)if(l.ParentLocationID is int parent && scope.Contains(parent))added|=scope.Add(l.LocationID); if(!added)break; } return await SubmitLocationsAsync(projectId,scope.ToArray(),all); } public async Task SubmitLocationsAsync(int projectId,IReadOnlyCollection ids,IReadOnlyList? projectLocations=null) { if(!await access.CanAccessProjectAsync(projectId))return "Project access is required."; var all=(projectLocations ?? await locations.ListByProjectAsync(projectId)).ToDictionary(l=>l.LocationID); var states=await repository.GetAsync(projectId,currentUser.UserId!.Value); var requests=new List(); foreach(var state in states.Where(s=>ids.Contains(s.LocationID)&&!s.IsExcluded && !s.Confirmed && s.Status!="Resolved" && s.JobState=="Awaiting hierarchy request")) { var chain=new List();var seen=new HashSet();var id=state.LocationID; while(all.TryGetValue(id,out var place)&&seen.Add(id)&&chain.Count<=100) { chain.Add(place); if(place.ParentLocationID is not int parent)break; id=parent; } var query=rules.Query(chain); if(query is not null)requests.Add(new(state.LocationID,state.Generation,GeographicRules.CacheKey(query,provider.Name))); } if(requests.Count==0)return "No new lookups required. Eligible places are already resolved or requested; unsuitable places are excluded."; if(requests.Count>20)return "Choose a smaller branch: at most 20 new eligible places can be requested at a time."; try { var result=await repository.SubmitLocationsAsync(projectId,currentUser.UserId!.Value,requests); return $"{result.Queued} places queued ({result.Cached} cached; {result.Charged} new lookups). The worker processes requests at a maximum of four per minute. Refresh status to see progress."; } catch(SqlException ex) when(ex.Number==51000){return ex.Message;} } }