Skip to content

Commit

Permalink
LNK-2738: multi-measure reporting changes (#469)
Browse files Browse the repository at this point in the history
  • Loading branch information
arianamihailescu authored Sep 18, 2024
2 parents 4c1d448 + f13e587 commit d6fd0c1
Show file tree
Hide file tree
Showing 28 changed files with 814 additions and 647 deletions.
3 changes: 2 additions & 1 deletion DotNet/Tenant/Config/TenantConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@ public static class Scheduler

public const string Facility = "Facility";

public const string ReportType = "ReportType";
public const string Frequency = "Frequency";

public const string StartDate = "StartDate";

public const string EndDate = "EndDate";

}

}
Expand Down
33 changes: 17 additions & 16 deletions DotNet/Tenant/Controllers/FacilityController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Diagnostics;
using LantanaGroup.Link.Shared.Application.Enums;
using LantanaGroup.Link.Shared.Application.Models.Responses;
using LantanaGroup.Link.Tenant.Interfaces;

namespace LantanaGroup.Link.Tenant.Controllers
{
Expand All @@ -18,7 +19,7 @@ namespace LantanaGroup.Link.Tenant.Controllers
public class FacilityController : ControllerBase
{

private readonly FacilityConfigurationService _facilityConfigurationService;
private readonly IFacilityConfigurationService _facilityConfigurationService;

private readonly IMapper _mapperModelToDto;

Expand All @@ -30,7 +31,7 @@ public class FacilityController : ControllerBase
public IScheduler _scheduler { get; set; }


public FacilityController(ILogger<FacilityController> logger, FacilityConfigurationService facilityConfigurationService, ISchedulerFactory schedulerFactory)
public FacilityController(ILogger<FacilityController> logger, IFacilityConfigurationService facilityConfigurationService, ISchedulerFactory schedulerFactory)
{

_facilityConfigurationService = facilityConfigurationService;
Expand All @@ -42,18 +43,14 @@ public FacilityController(ILogger<FacilityController> logger, FacilityConfigurat
{
cfg.CreateMap<FacilityConfigModel, FacilityConfigDto>();
cfg.CreateMap<PagedConfigModel<FacilityConfigModel>, PagedFacilityConfigDto>();
cfg.CreateMap<ScheduledTaskModel.ReportTypeSchedule, ScheduledTaskDto.ReportTypeDtoSchedule>();
cfg.CreateMap<ScheduledTaskModel, ScheduledTaskDto>();
cfg.CreateMap<MonthlyReportingPlanModel, MonthlyReportingPlanDto>();
cfg.CreateMap<ScheduledReportModel, ScheduledReportDto>();
});

var configDtoToModel = new MapperConfiguration(cfg =>
{
cfg.CreateMap<FacilityConfigDto, FacilityConfigModel>();
cfg.CreateMap<PagedFacilityConfigDto, PagedConfigModel<FacilityConfigModel>>();
cfg.CreateMap<ScheduledTaskDto.ReportTypeDtoSchedule, ScheduledTaskModel.ReportTypeSchedule>();
cfg.CreateMap<ScheduledTaskDto, ScheduledTaskModel>();
cfg.CreateMap<MonthlyReportingPlanDto, MonthlyReportingPlanModel>();
cfg.CreateMap<ScheduledReportDto, ScheduledReportModel>();
});

_mapperModelToDto = configModelToDto.CreateMapper();
Expand Down Expand Up @@ -199,18 +196,21 @@ public async Task<IActionResult> UpdateFacility(string id, FacilityConfigDto upd

FacilityConfigModel dest = _mapperDtoToModel.Map<FacilityConfigDto, FacilityConfigModel>(updatedFacility);

FacilityConfigModel existingFacility = await _facilityConfigurationService.GetFacilityById(id, cancellationToken);

// validate id and updatedFacility.id match
if (id.ToString() != updatedFacility.Id)
{
_logger.LogError($" {id} in the url and the {updatedFacility.Id} in the payload mismatch");

return BadRequest($" {id} in the url and the {updatedFacility.Id} in the payload mismatch");
}

FacilityConfigModel oldFacility = await _facilityConfigurationService.GetFacilityById(id, cancellationToken);

FacilityConfigModel clonedFacility = oldFacility.ShallowCopy();


try
{

await _facilityConfigurationService.UpdateFacility(id, dest, cancellationToken);
}
catch (ApplicationException ex)
Expand All @@ -226,12 +226,13 @@ public async Task<IActionResult> UpdateFacility(string id, FacilityConfigDto upd
throw;
}

// if existingFacility is not null, then update the jobs, else add new jobs
if (existingFacility != null)
// if clonedFacility is not null, then update the jobs, else add new jobs

if (clonedFacility != null)
{
using (ServiceActivitySource.Instance.StartActivity("Update Jobs for Facility"))
{
await ScheduleService.UpdateJobsForFacility(dest, existingFacility, _scheduler);
await ScheduleService.UpdateJobsForFacility(dest, clonedFacility, _scheduler);
}
}
else
Expand All @@ -242,7 +243,7 @@ public async Task<IActionResult> UpdateFacility(string id, FacilityConfigDto upd
}
}

if (existingFacility == null)
if (oldFacility == null)
{
return CreatedAtAction(nameof(StoreFacility), new { id = dest.Id }, dest);
}
Expand Down Expand Up @@ -279,7 +280,7 @@ public async Task<IActionResult> DeleteFacility(string facilityId, CancellationT

using (ServiceActivitySource.Instance.StartActivity("Delete Jobs for Facility"))
{
await ScheduleService.DeleteJobsForFacility(existingFacility.Id.ToString(), existingFacility.ScheduledTasks, _scheduler);
await ScheduleService.DeleteJobsForFacility(existingFacility.Id.ToString(), _scheduler);
}

return NoContent();
Expand Down
9 changes: 5 additions & 4 deletions DotNet/Tenant/Entities/FacilityConfigModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ public class FacilityConfigModel : BaseEntityExtended
{
public string FacilityId { get; set; } = null!;
public string? FacilityName { get; set; }
public List<ScheduledTaskModel>? ScheduledTasks { get; set; } = new List<ScheduledTaskModel>();
public List<MonthlyReportingPlanModel>? MonthlyReportingPlans { get; set; } = new List<MonthlyReportingPlanModel>();
public DateTime? MRPModifyDate { get; set; }
public DateTime? MRPCreatedDate { get; set; }
public ScheduledReportModel ScheduledReports { get; set; } = null!;

public FacilityConfigModel ShallowCopy()
{
return (FacilityConfigModel)this.MemberwiseClone();
}
}
}
13 changes: 0 additions & 13 deletions DotNet/Tenant/Entities/MonthlyReportingPlanModel.cs

This file was deleted.

11 changes: 11 additions & 0 deletions DotNet/Tenant/Entities/ScheduledReportModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace LantanaGroup.Link.Tenant.Entities
{
public class ScheduledReportModel
{
public string[] Daily { get; set; }

public string[] Weekly { get; set; }

public string[] Monthly { get; set; }
}
}
16 changes: 0 additions & 16 deletions DotNet/Tenant/Entities/ScheduledTaskModel.cs

This file was deleted.

17 changes: 17 additions & 0 deletions DotNet/Tenant/Interfaces/IFacilityConfigurationService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using LantanaGroup.Link.Shared.Application.Enums;
using LantanaGroup.Link.Shared.Application.Models.Responses;
using LantanaGroup.Link.Tenant.Entities;

namespace LantanaGroup.Link.Tenant.Interfaces
{
public interface IFacilityConfigurationService
{
Task CreateFacility(FacilityConfigModel newFacility, CancellationToken cancellationToken);
Task<List<FacilityConfigModel>> GetAllFacilities(CancellationToken cancellationToken = default);
Task<PagedConfigModel<FacilityConfigModel>> GetFacilities(string? facilityId, string? facilityName, string? sortBy, SortOrder? sortOrder, int pageSize = 10, int pageNumber = 1, CancellationToken cancellationToken = default);
Task<FacilityConfigModel> GetFacilityByFacilityId(string facilityId, CancellationToken cancellationToken);
Task<FacilityConfigModel> GetFacilityById(string id, CancellationToken cancellationToken);
Task<string> RemoveFacility(string facilityId, CancellationToken cancellationToken);
Task<string> UpdateFacility(string id, FacilityConfigModel newFacility, CancellationToken cancellationToken = default);
}
}
73 changes: 49 additions & 24 deletions DotNet/Tenant/Jobs/ReportScheduledJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using LantanaGroup.Link.Tenant.Entities;
using LantanaGroup.Link.Tenant.Interfaces;
using LantanaGroup.Link.Tenant.Models.Messages;
using LantanaGroup.Link.Tenant.Services;
using MongoDB.Driver.Linq;
using Quartz;
using System.Text.Json;

Expand All @@ -16,15 +18,14 @@ namespace LantanaGroup.Link.Tenant.Jobs
public class ReportScheduledJob : IJob
{
private readonly ILogger<ReportScheduledJob> _logger;
//private readonly IKafkaProducerFactory<string, object> _kafkaProducerFactory;
private readonly IProducer<string, object> _producer;
private readonly IKafkaProducerFactory<string, object> _kafkaProducerFactory;
private readonly ITenantServiceMetrics _metrics;

public ReportScheduledJob(ILogger<ReportScheduledJob> logger, ITenantServiceMetrics metrics, IProducer<string, object> producer)
public ReportScheduledJob(ILogger<ReportScheduledJob> logger, IKafkaProducerFactory<string, object> kafkaProducerFactory, ITenantServiceMetrics metrics)
{
_logger = logger;
_kafkaProducerFactory = kafkaProducerFactory ?? throw new ArgumentNullException(nameof(kafkaProducerFactory));
_metrics = metrics ?? throw new ArgumentNullException(nameof(metrics));
_producer = producer ?? throw new ArgumentNullException(nameof(producer));
}

public async Task Execute(IJobExecutionContext context)
Expand All @@ -35,30 +36,48 @@ public async Task Execute(IJobExecutionContext context)

JobDataMap triggerMap = context.Trigger.JobDataMap!;

String[] reportTypes = [];

string trigger = (string)triggerMap[TenantConstants.Scheduler.JobTrigger];

FacilityConfigModel facility = (FacilityConfigModel)dataMap[TenantConstants.Scheduler.Facility];

string reportType = (string)dataMap[TenantConstants.Scheduler.ReportType];

List<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>();

/* DateTime startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0);
DateTime endDate1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0);
DateTime endDate = endDate1.AddMinutes(2);
*/
string frequency = (string)dataMap[TenantConstants.Scheduler.Frequency];

DateTime startDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1);

DateTime endDate = startDate.AddMonths(1).AddSeconds(-1);
DateTime currentDateInTimeZone = DateTime.UtcNow;

parameters.Add(new KeyValuePair<string, Object>(TenantConstants.Scheduler.StartDate, startDate));
// initialize startDate, endDate
DateTime startDate = currentDateInTimeZone;
DateTime endDate = currentDateInTimeZone;

parameters.Add(new KeyValuePair<string, Object>(TenantConstants.Scheduler.EndDate, endDate));

_logger.LogInformation($"Produce {KafkaTopic.ReportScheduled} + event for facility {facility.FacilityId} and {reportType} and trigger: {trigger}");
// adjust startDate, endDate based on frequency
switch (frequency)
{
case ScheduleService.MONTHLY:
startDate = new DateTime(currentDateInTimeZone.Year, currentDateInTimeZone.Month, 1);
endDate = startDate.AddMonths(1).AddSeconds(-1);
reportTypes = facility.ScheduledReports.Monthly;
break;
case ScheduleService.WEEKLY:
startDate = new DateTime(currentDateInTimeZone.Year, currentDateInTimeZone.Month, currentDateInTimeZone.Day);
// set to beginning of week in case is not exactly that
DayOfWeek startOfWeek = DayOfWeek.Sunday;
DayOfWeek currentDay = startDate.DayOfWeek;
int difference = currentDay - startOfWeek;
startDate = startDate.AddDays(-difference);
// end date of the week
endDate = startDate.AddDays(7).AddSeconds(-1);
reportTypes = facility.ScheduledReports.Weekly;
break;
case ScheduleService.DAILY:
startDate = new DateTime(currentDateInTimeZone.Year, currentDateInTimeZone.Month, currentDateInTimeZone.Day);
endDate = startDate.AddDays(1).AddSeconds(-1);
reportTypes = facility.ScheduledReports.Daily;
break;
}

_logger.LogInformation($"Produce {KafkaTopic.ReportScheduled} + event for facility {facility.FacilityId} and {frequency} trigger: {trigger}");

var headers = new Headers();
string correlationId = Guid.NewGuid().ToString();
Expand All @@ -68,7 +87,6 @@ public async Task Execute(IJobExecutionContext context)
ReportScheduledKey Key = new ReportScheduledKey()
{
FacilityId = facility.FacilityId,
ReportType = reportType
};

var message = new Message<string, object>
Expand All @@ -77,15 +95,22 @@ public async Task Execute(IJobExecutionContext context)
Headers = headers,
Value = new ReportScheduledMessage()
{
Parameters = parameters
ReportTypes = reportTypes,
Frequency = frequency,
StartDate = startDate,
EndDate = endDate
},
};

await _producer.ProduceAsync(KafkaTopic.ReportScheduled.ToString(), message);
var producerConfig = new ProducerConfig();

var producer = _kafkaProducerFactory.CreateProducer(producerConfig);

await producer.ProduceAsync(KafkaTopic.ReportScheduled.ToString(), message);

_metrics.IncrementReportScheduledCounter([
new KeyValuePair<string, object?>(DiagnosticNames.FacilityId, facility.FacilityId),
new KeyValuePair<string, object?>(DiagnosticNames.ReportType, reportType),
new KeyValuePair<string, object?>(DiagnosticNames.ReportType, reportTypes),
new KeyValuePair<string, object?>(DiagnosticNames.PeriodStart, startDate),
new KeyValuePair<string, object?>(DiagnosticNames.PeriodEnd, endDate)
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public partial class AddFacilitiesTable : Migration
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(name: "Facilities");
migrationBuilder.CreateTable(
name: "Facilities",
columns: table => new
Expand Down
Loading

0 comments on commit d6fd0c1

Please sign in to comment.