feat(templateDistributor): Изменен метод распределения РР по периоду(DistributeTemplateAsync), EsppScheduleTransformService.GetNextDateAsync теперь проверяет метод распределения РР и возвращает нужную дату

This commit is contained in:
Mikhail Kuznetsov
2024-07-11 11:32:14 +10:00
parent aa555944ae
commit 514110dba0
2 changed files with 259 additions and 151 deletions

View File

@@ -46,11 +46,11 @@ namespace PARR.TemplateDistributor
// сохранить в БД
//applicationInWorkId = Guid.Parse("bdfefd77-bce3-4f62-a484-5042c06f4467");
var appInWork = await applicationsInWorkService.Get()
.Include(aiw => aiw.EsppSchValues)
.ThenInclude(esv => esv.EsppSchTypeValue)
.ThenInclude(etv => etv!.DistributionPeriod)
.FirstOrDefaultAsync(t => t.Id == applicationInWorkId);
//var appInWork = await applicationsInWorkService.Get()
// .Include(aiw => aiw.EsppSchValues)
// .ThenInclude(esv => esv.EsppSchTypeValue)
// .ThenInclude(etv => etv!.DistributionPeriod)
// .FirstOrDefaultAsync(t => t.Id == applicationInWorkId);
var templates = await templateService.Get()
.Include(t => t.Host)
@@ -59,23 +59,15 @@ namespace PARR.TemplateDistributor
.ToListAsync();
//var refDate = appInWork!.ReferenceDate;
//var period = appInWork.EsppSchValues.FirstOrDefault()?.EsppSchTypeValue?.DistributionPeriod;
//DistributionPeriodTypeEnum periodType = (DistributionPeriodTypeEnum)Enum.Parse(typeof(DistributionPeriodTypeEnum), period!.Type);
//var workGroupsWithTemplates = templates.GroupBy(t => new { t.Host!.WorkGroupId, t.NextRun});
var workGroupsWithTemplates = templates.GroupBy(t => t.Host!.WorkGroupId);
//var startPeriod = await esppScheduleTransformService.GetStartPeriodForDateAsync(applicationInWorkId, DateTimeOffset.UtcNow/*.AddDays(45)*/, refDate, periodType, period.Duration);
//var workdays = calendarService.GetWorkDatesForPeriod(startPeriod, periodType, period.Duration, weekendDayService.GetWeekends);
//var templatePerWorkDay = (int)Math.Ceiling((double)templates.Count() / workdays.Count());//
foreach (var item in workGroupsWithTemplates)
foreach (var workGroupWithTemplates in workGroupsWithTemplates)
{
var wgId = item.Key ?? Guid.NewGuid();//TODO сделать правильно
var values = item.ToList();
var wgId = workGroupWithTemplates.Key ?? Guid.NewGuid();//TODO сделать правильно
var values = workGroupWithTemplates.ToList();
if (!values.Any())
continue;
var distrTemplates = await DistributeTemplateAsync(values, applicationInWorkId, wgId);
}
@@ -86,153 +78,132 @@ namespace PARR.TemplateDistributor
}
public async Task<List<Template>> DistributeTemplateAsync(List<Template> templates, Guid applicationInWorkId, Guid workGroupid)
public async Task<List<Template>> DistributeTemplateAsync(List<Template> templates, Guid applicationInWorkId, Guid workGroupId)
{
//TODO: ЗАГУЛШКА переделать!
// распределить?
// не распределить, NextRun = appInWork.ReferenceDate
var appInWork = await applicationsInWorkService.Get()
.Include(aiw => aiw.EsppSchValues)
.ThenInclude(esv => esv.EsppSchTypeValue)
.ThenInclude(etv => etv!.DistributionPeriod)
.FirstOrDefaultAsync(t => t.Id == applicationInWorkId);
//appInWork!.IsAutoDistributionEnabled = true;//!!!!!!!!!!!!!!!!!!!КОСТЫЛЬ пока нет связки с фронтом
var refDate = appInWork!.ReferenceDate;
//Проверяем наличие распределения РР на период
if (appInWork!.IsAutoDistributionEnabled)
{
var existingTemplates = new List<Template>();
var existingTemplates = await templateService.Get()
.Include(t => t.Host)
.Where(t => t.ApplicationInWorkId == applicationInWorkId && t.Host!.WorkGroupId == workGroupId)
.ToListAsync();
//Если распределенная РР получаем начало
//DateOnly startPeriod = await esppScheduleTransformService.GetStartPeriodForDateAsync(applicationInWorkId,DateTimeOffset.UtcNow);
var refDate = appInWork.ReferenceDate;
var period = appInWork.EsppSchValues.FirstOrDefault()?.EsppSchTypeValue?.DistributionPeriod;
//if(period != null) {
DistributionPeriodTypeEnum periodType = (DistributionPeriodTypeEnum)Enum.Parse(typeof(DistributionPeriodTypeEnum), period!.Type);
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//periodType = DistributionPeriodTypeEnum.Day;
//period.Duration = "90";
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
var periodType = ParseDistributionPeriodType(period!.Type);
var startPeriod = await esppScheduleTransformService.GetStartPeriodForDateAsync(applicationInWorkId, DateTimeOffset.UtcNow/*.AddDays(45)*/, appInWork.ReferenceDate, periodType, period.Duration);
var workdays = calendarService.GetWorkDatesForPeriod(startPeriod, periodType, period.Duration, weekendDayService.GetWeekends);
var workDays = await GetWorkDaysAsync(appInWork);
var d = new Dictionary<DateOnly, int>();
foreach (var wd in workdays)
//Готовим план распределения
var distrPlan = GetDistributionPlan(workDays, templates.Count + existingTemplates.Count);
var templateToDistrib = new List<Template>();
if (existingTemplates.Count > 0)
templates = GetTemplatesToDistribute(ref distrPlan, existingTemplates);
templateToDistrib.AddRange(templates);
var distributedTemplates = 0;
foreach (var workDay in distrPlan)
{
var wrokDateTimeOffset = new DateTimeOffset(
wd.Year, wd.Month, wd.Day,
refDate.Hour, refDate.Minute, refDate.Second,
new TimeSpan(0, 0, 0)); ;
var assignedTemplateCount = existingTemplates.Where(t => t.NextRun == wrokDateTimeOffset).Count();
d.Add(wd, assignedTemplateCount);
var templatesCountForCurDay = workDay.Value;
templateToDistrib.Skip(distributedTemplates).Take(templatesCountForCurDay).ToList().ForEach(t =>
{
var nextRun = new DateTimeOffset(
workDay.Key.Year, workDay.Key.Month, workDay.Key.Day,
refDate.Hour, refDate.Minute, refDate.Second,
new TimeSpan(0, 0, 0));
if (nextRun < DateTimeOffset.UtcNow)
nextRun = esppScheduleTransformService.GetNextDateForDistributionRun(nextRun, periodType, period.Duration);
t.NextRun = nextRun;
});
distributedTemplates += templatesCountForCurDay;
}
//templates = templates.Take(5).ToList();
//var templatesPerStep = (int)Math.Ceiling((double)templates.Count() / workdays.Count());//
var templatesPerStep = (double)templates.Count() / workdays.Count();//
//templatesPerStep = (templatesPerStep < 1) ? 1 : templatesPerStep;
var currentDay = new DateTimeOffset(
startPeriod.Year, startPeriod.Month, startPeriod.Day,
refDate.Hour, refDate.Minute, refDate.Second,
new TimeSpan(0, 0, 0)); ;
var balance = templates.Count();
var step = 0;
var stepDays = (int)Math.Floor((double)workdays.Count() / templates.Count());
stepDays = (stepDays < 1) ? 1 : stepDays;
return templateToDistrib;
var currentTemplateStep = (int)Math.Ceiling(templatesPerStep);
var delta = templatesPerStep - currentTemplateStep;
templates.First().NextRun = currentDay;
var templateDistributed = 0;
//Отталкиваясь от количества
while (templateDistributed < templates.Count())
{
var wdCounts = d.Select(wd => wd.Value).OrderBy(count => count).ToArray();
// = existingTemplates.Select(t => t.NextRun).OrderBy(nextRun => nextRun).Distinct().ToArray();//managers.Select(m => m.Orders.Count).OrderBy(count => count).Distinct().ToArray();
var templateCountDelta = d.Max(t => t.Value) - d.Max(t => t.Value);
var addingTemplatesCount = wdCounts.Length > 1 ?
(templateCountDelta == 0) ? (int)Math.Ceiling(templatesPerStep) : templateCountDelta :
(int)Math.Ceiling(templatesPerStep);
var workDaysWithMinTemplates = d.Where(wd => wd.Value == wdCounts[0]).ToArray();
if (workDaysWithMinTemplates.Length * addingTemplatesCount < templates.Count())
{
foreach (var wd in workDaysWithMinTemplates)
{
//Считаем DateTimeOffset, потому что у нас только дата пока
currentDay = new DateTimeOffset(
wd.Key.Year, wd.Key.Month, wd.Key.Day,
refDate.Hour, refDate.Minute, refDate.Second,
new TimeSpan(0, 0, 0));
if (currentDay < DateTimeOffset.UtcNow)
currentDay = esppScheduleTransformService.GetNextDateForDistributionRun(currentDay, periodType, period.Duration);
templates.Skip(templateDistributed).Take(addingTemplatesCount).ToList().ForEach(t => t.NextRun = currentDay);
templateDistributed += addingTemplatesCount;
d[wd.Key] = wd.Value + addingTemplatesCount;
}
}
else
{
while (templateDistributed < templates.Count())
{
//var wdIndex = templateDistributed % workDaysWithMinTemplates.Length;
//var wd = workDaysWithMinTemplates[wdIndex];
var wd = d.Where(wd => wd.Value == d.Min(t => t.Value)).First();
//Считаем DateTimeOffset, потому что у нас только дата пока
currentDay = new DateTimeOffset(
wd.Key.Year, wd.Key.Month, wd.Key.Day,
refDate.Hour, refDate.Minute, refDate.Second,
new TimeSpan(0, 0, 0));
if (currentDay < DateTimeOffset.UtcNow)
currentDay = esppScheduleTransformService.GetNextDateForDistributionRun(currentDay, periodType, period.Duration);
templates.Skip(templateDistributed).Take(addingTemplatesCount).ToList().ForEach(t => t.NextRun = currentDay);
d[wd.Key] = wd.Value + addingTemplatesCount;
templateDistributed += addingTemplatesCount;
}
}
}
////Отталкиваясь от количества рабочих дней
//foreach (var wd in workdays)
//var d = new Dictionary<DateOnly, List<Template>>();
//foreach (var wd in workDays)
//{
// if (currentTemplateStep > 1 && currentTemplateStep >= templatesPerStep)
// {
// var roundedCurTemplStep = (int)Math.Round(currentTemplateStep);
// //Считаем DateTimeOffset, потому что у нас только дата пока
// currentDay = new DateTimeOffset(
// wd.Year, wd.Month, wd.Day,
// refDate.Hour, refDate.Minute, refDate.Second,
// new TimeSpan(0, 0, 0));
// if (currentDay < DateTimeOffset.UtcNow)
// currentDay = esppScheduleTransformService.GetNextDateForDistributionRun(currentDay, periodType, period.Duration);
// var wrokDateTimeOffset = new DateTimeOffset(
// wd.Year, wd.Month, wd.Day,
// refDate.Hour, refDate.Minute, refDate.Second,
// new TimeSpan(0, 0, 0));
// if (wrokDateTimeOffset < DateTimeOffset.UtcNow)
// wrokDateTimeOffset = esppScheduleTransformService.GetNextDateForDistributionRun(wrokDateTimeOffset, periodType, period.Duration);
// templates.Skip(templates.Count - balance).Take(roundedCurTemplStep).ToList().ForEach(t =>
// {
// t.NextRun = currentDay;
// });
// balance -= roundedCurTemplStep;
// delta = currentTemplateStep - roundedCurTemplStep;
// }
// else
// delta = currentTemplateStep;
// currentTemplateStep = delta + templatesPerStep;
// var assignedTemplates = existingTemplates.Where(t => t.NextRun == wrokDateTimeOffset).ToList();
// d.Add(wd, assignedTemplates);
//}
//var templatesPerStep = (double)templates.Count() / workDays.Count();//
//var currentTemplateStep = (int)Math.Ceiling(templatesPerStep);
//var delta = templatesPerStep - currentTemplateStep;
////templates.First().NextRun = currentDay;
//var templateDistributed = 0;
////Отталкиваясь от количества
//while (templateDistributed < templates.Count())
//{
// var wdCounts = d.Select(wd => wd.Value).OrderBy(count => count).ToArray();
// var templateCountDelta = d.Max(t => t.Value.Count()) - d.Min(t => t.Value.Count());
// var addingTemplatesCount = wdCounts.Length > 1 ?
// (templateCountDelta == 0) ? (int)Math.Ceiling(templatesPerStep) : templateCountDelta :
// (int)Math.Ceiling(templatesPerStep);
// var workDaysWithMinTemplates = d.Where(wd => wd.Value == wdCounts[0]).ToArray();
// if (workDaysWithMinTemplates.Length * addingTemplatesCount < templates.Count())
// {
// foreach (var wd in workDaysWithMinTemplates)
// {
// //Считаем DateTimeOffset, потому что у нас только дата пока
// var currentDay = new DateTimeOffset(
// wd.Key.Year, wd.Key.Month, wd.Key.Day,
// refDate.Hour, refDate.Minute, refDate.Second,
// new TimeSpan(0, 0, 0));
// templates.Skip(templateDistributed).Take(addingTemplatesCount).ToList().ForEach(t =>
// {
// t.NextRun = currentDay;
// d[wd.Key].Add(t);
// });
// templateDistributed += addingTemplatesCount;
// }
// }
// else
// {
// while (templateDistributed < templates.Count())
// {
// var wd = d.Where(wd => wd.Value == d.Min(t => t.Value)).First();
// //Считаем DateTimeOffset, потому что у нас только дата пока
// var currentDay = new DateTimeOffset(
// wd.Key.Year, wd.Key.Month, wd.Key.Day,
// refDate.Hour, refDate.Minute, refDate.Second,
// new TimeSpan(0, 0, 0));
// templates.Skip(templateDistributed).Take(addingTemplatesCount).ToList().ForEach(t =>
// {
// t.NextRun = currentDay;
// d[wd.Key].Add(t);
// });
// templateDistributed += addingTemplatesCount;
// }
// }
//}
}
else
templates.ForEach(t => t.NextRun = appInWork!.ReferenceDate);
@@ -240,6 +211,104 @@ namespace PARR.TemplateDistributor
return templates;
}
private async Task<List<DateOnly>> GetWorkDaysAsync(ApplicationsInWork appInWork)
{
var period = appInWork.EsppSchValues.FirstOrDefault()?.EsppSchTypeValue?.DistributionPeriod;
var periodType = ParseDistributionPeriodType(period!.Type);
var startPeriod = await esppScheduleTransformService.GetStartPeriodForDateAsync(appInWork.Id, appInWork.ReferenceDate, appInWork.ReferenceDate, periodType, period.Duration);
var result = calendarService.GetWorkDatesForPeriod(startPeriod, periodType, period.Duration, weekendDayService.GetWeekends);
result.ForEach(wd =>
{
var wrokDateTimeOffset = new DateTimeOffset(
wd.Year, wd.Month, wd.Day,
0, 0, 0,
new TimeSpan(0, 0, 0));
if (wrokDateTimeOffset < DateTimeOffset.UtcNow)
{
wrokDateTimeOffset = esppScheduleTransformService.GetNextDateForDistributionRun(wrokDateTimeOffset, periodType, period.Duration);
wd = DateOnly.FromDateTime(wrokDateTimeOffset.DateTime);
}
});
return result;
}
private List<Template> GetTemplatesToDistribute(ref Dictionary<DateOnly, int> distributionPlan, List<Template> templates)
{
var result = new List<Template>();
foreach (var wd in distributionPlan)
{
var templatesInWd = templates.Where(t => DateOnly.FromDateTime(t.NextRun.DateTime) == wd.Key).ToList();
var templatesToDistribute = templatesInWd.Skip(wd.Value).Take(templatesInWd.Count - wd.Value).ToList();
distributionPlan[wd.Key] -= templatesInWd.Count;
result.AddRange(templatesToDistribute);
}
return result;
}
private DistributionPeriodTypeEnum ParseDistributionPeriodType(string value)
{
var result = (DistributionPeriodTypeEnum)Enum.Parse(typeof(DistributionPeriodTypeEnum), value);
return result;
}
private Dictionary<DateOnly, int> GetDistributionPlan(List<DateOnly> workDays, int templateCount)
{
var d = new Dictionary<DateOnly, int>();
foreach (var wd in workDays)
{
var workDateTimeOffset = new DateOnly(wd.Year, wd.Month, wd.Day);
d.Add(workDateTimeOffset, 0);
}
var templateDistributed = 0;
if (templateCount > workDays.Count)
{
var mainPartTemplateCountToDistribute = templateCount / workDays.Count;
foreach (var item in d)
{
d[item.Key] = mainPartTemplateCountToDistribute;
templateDistributed += mainPartTemplateCountToDistribute;
}
}
var templatesPerWorkDay = (double)workDays.Count / (templateCount % workDays.Count);
var currentStep = (double)Math.Floor(templatesPerWorkDay);//??????? точно double?
var balance = (double)templatesPerWorkDay - Math.Floor(currentStep);
var currentIndex = 0;
while (templateDistributed < templateCount)
{
if (currentStep > 0)
{
d[d.ElementAt(currentIndex).Key] += 1;
templateDistributed++;
currentIndex += (int)Math.Floor(currentStep);
currentStep = templatesPerWorkDay + balance;
balance = currentStep - templatesPerWorkDay;
}
}
return d;
}
}
}