PlotDirector/PlotLine/Services/GeographicHierarchyService.cs

51 lines
2.9 KiB
C#

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<string> 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<int>{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<string> SubmitLocationsAsync(int projectId,IReadOnlyCollection<int> ids,IReadOnlyList<LocationItem>? 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<GeographicLookupRequest>();
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<LocationItem>();var seen=new HashSet<int>();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;}
}
}