065a83442c
Enhanced the application's service layer by adding FormValidationService and EventDefinitionService to the dependency injection container in Program.cs. Updated Create, Edit, and other relevant components to utilize these services for improved form validation and event processing functionality.
83 lines
2.7 KiB
C#
83 lines
2.7 KiB
C#
using Core.Entities;
|
|
using Core.Utility;
|
|
using Data;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace WebApp.Services;
|
|
|
|
/// <summary>
|
|
/// Service for handling EventDefinition-related operations
|
|
/// </summary>
|
|
public class EventDefinitionService
|
|
{
|
|
private readonly AppDbContext _context;
|
|
|
|
public EventDefinitionService(AppDbContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Processes and normalizes related careers for an EventDefinition.
|
|
/// Matches existing careers by normalized name (case-insensitive) or creates new ones.
|
|
/// </summary>
|
|
/// <param name="eventDefinition">The EventDefinition to process careers for</param>
|
|
public async Task ProcessRelatedCareersAsync(EventDefinition eventDefinition)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(eventDefinition.RelatedCareersText))
|
|
{
|
|
eventDefinition.RelatedCareers.Clear();
|
|
return;
|
|
}
|
|
|
|
var normalizedNames = CareerNormalizer.NormalizeCareerNames(eventDefinition.RelatedCareersText).ToList();
|
|
|
|
if (!normalizedNames.Any())
|
|
{
|
|
eventDefinition.RelatedCareers.Clear();
|
|
return;
|
|
}
|
|
|
|
// Get all existing careers from database (case-insensitive lookup)
|
|
var existingCareers = await _context.Careers
|
|
.Where(c => !string.IsNullOrWhiteSpace(c.Name))
|
|
.ToListAsync();
|
|
|
|
// Build lookup dictionary, handling potential duplicates by taking the first occurrence
|
|
var careerLookup = new Dictionary<string, Career>(StringComparer.OrdinalIgnoreCase);
|
|
foreach (var career in existingCareers)
|
|
{
|
|
var normalizedKey = CareerNormalizer.GetNormalizedKey(career.Name);
|
|
if (!careerLookup.ContainsKey(normalizedKey))
|
|
{
|
|
careerLookup[normalizedKey] = career;
|
|
}
|
|
}
|
|
|
|
var careersToAdd = new List<Career>();
|
|
|
|
foreach (var normalizedName in normalizedNames)
|
|
{
|
|
var normalizedKey = CareerNormalizer.GetNormalizedKey(normalizedName);
|
|
|
|
if (careerLookup.TryGetValue(normalizedKey, out var existingCareer))
|
|
{
|
|
// Use existing career (preserve original capitalization)
|
|
careersToAdd.Add(existingCareer);
|
|
}
|
|
else
|
|
{
|
|
// Create new career with the normalized name (preserving capitalization from input)
|
|
var newCareer = new Career { Name = normalizedName };
|
|
_context.Careers.Add(newCareer);
|
|
careersToAdd.Add(newCareer);
|
|
careerLookup[normalizedKey] = newCareer;
|
|
}
|
|
}
|
|
|
|
// Replace the collection
|
|
eventDefinition.RelatedCareers = careersToAdd;
|
|
}
|
|
}
|
|
|