Files
chapter-organizer/WebApp/Components/Features/Teams/Create.razor
T
poprhythm 065a83442c Add FormValidationService and EventDefinitionService to dependency injection
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.
2025-12-28 19:56:16 -05:00

224 lines
7.4 KiB
Plaintext

@page "/teams/create"
@attribute [Authorize]
@using Microsoft.EntityFrameworkCore
@using WebApp.Components.Shared.Components
@using MudBlazor
@using WebApp.Services
@inject AppDbContext Context
@inject NavigationManager NavigationManager
@inject ISnackbar Snackbar
@inject FormValidationService ValidationService
@if (_events is null || _editContext is null)
{
<p><em>Loading...</em></p>
return;
}
<PageHeader
Title="Create"
Subtitle="Team"
ShowBackButton="true"
BackButtonUrl="@(ReturnUrl ?? "/teams")" />
<EditForm method="post" EditContext="@_editContext" OnInvalidSubmit="OnInvalidSubmit" FormName="create" Enhance>
<FormChangeTracker @ref="_formChangeTracker" />
<AntiforgeryToken />
<DataAnnotationsValidator />
<ValidationErrorDisplay Errors="_validationErrors" />
<MudGrid>
<MudItem xs="12" sm="7">
<MudPaper Elevation="2" Class="pa-6">
<MudSelect T="EventDefinition" Value="@Team.Event" ValueChanged="OnEventChanged" Label="Event">
@foreach (var evt in _events)
{
<MudSelectItem T="EventDefinition" Value="@(evt)"></MudSelectItem>
}
</MudSelect>
@switch (_existingTeams?.Count)
{
case 1:
<MudAlert Severity="Severity.Info" Class="my-2">
A team for @Team.Event.Name already exists. This will be team 2, and the existing team will become team 1.
</MudAlert>
break;
case >= 2:
<MudAlert Severity="Severity.Error" Class="my-2">
Two teams for @Team.Event.Name already exist. Cannot create a third team.
</MudAlert>
break;
}
<MudDivider Class="my-4" />
<StudentToggleSelector Students="@_students"
@bind-SelectedStudents="_selectedStudents"
Title="Students"
ShowFullName="true" />
<MudStack Class="mt-4">
<TeamCaptainSelector Students="@_selectedStudents"
@bind-SelectedCaptain="Team.Captain"
Title="Captain" />
</MudStack>
</MudPaper>
</MudItem>
</MudGrid>
@if (!string.IsNullOrEmpty(_errorMessage))
{
<MudAlert Severity="Severity.Error" Class="mt-3">@_errorMessage</MudAlert>
}
</EditForm>
<FormActions>
<MudButton OnClick="AddTeam" Variant="Variant.Filled" Color="Color.Primary">Add</MudButton>
<MudButton OnClick="HandleCancel" Variant="Variant.Text">Cancel</MudButton>
</FormActions>
@code {
[SupplyParameterFromQuery]
private string? ReturnUrl { get; set; }
[SupplyParameterFromForm]
private Team Team { get; set; } = new();
private FormChangeTracker? _formChangeTracker;
private EditContext? _editContext;
private List<string> _validationErrors = new();
private List<EventDefinition>? _events;
private List<Student> _students = [];
private IEnumerable<Student> _selectedStudents = [];
private string? _errorMessage;
private List<Team>? _existingTeams;
protected override async Task OnInitializedAsync()
{
_events =
await Context.Events
.OrderBy(e => e.Name)
.ToListAsync();
_students = await Context.Students.ToListAsync();
_editContext = new EditContext(Team);
}
private void OnInvalidSubmit(EditContext editContext)
{
_validationErrors = ValidationService.HandleInvalidSubmit(editContext, Team, errors => _validationErrors = errors);
StateHasChanged();
}
private async Task OnEventChanged(EventDefinition selectedEvent)
{
Team.Event = selectedEvent;
// Clear any previous error messages
_errorMessage = null;
// Get all existing teams for this event
_existingTeams = await Context.Teams
.Include(t => t.Event)
.Where(t => t.Event.Id == selectedEvent.Id)
.ToListAsync();
}
private async Task AddTeam()
{
// Validate before processing
if (_editContext != null)
{
var errors = ValidationService.CollectValidationErrors(_editContext, Team);
if (errors.Any())
{
_validationErrors = ValidationService.HandleInvalidSubmit(_editContext, Team, err => _validationErrors = err);
StateHasChanged();
return;
}
}
_validationErrors.Clear();
// Clear previous error message
_errorMessage = null;
try
{
// Get current count of teams for this event
var existingTeamCount = await Context.Teams
.CountAsync(t => t.Event.Id == Team.Event.Id);
// Prohibit creation of third team
if (existingTeamCount >= 2)
{
_errorMessage = $"Cannot create a third team for {Team.Event.Name}. Maximum of 2 teams allowed.";
Snackbar.Add(_errorMessage, Severity.Error);
return;
}
// Handle automatic numbering based on event format
if (Team.Event.EventFormat == EventFormat.Individual && _selectedStudents.Count() == 1)
{
// For individual events, use student's first name as identifier
var student = _selectedStudents.First();
Team.Identifier = student.FirstName;
Team.Captain = student;
}
else if (existingTeamCount == 1)
{
// This is the second team - assign numbers
var existingTeam = await Context.Teams
.FirstOrDefaultAsync(t => t.Event.Id == Team.Event.Id);
if (existingTeam != null)
{
// Update existing team to number 1
existingTeam.Identifier = "1";
Context.Teams.Update(existingTeam);
}
// Set new team to number 2
Team.Identifier = "2";
}
else
{
// This is the first team - no number
Team.Identifier = null;
}
// Add selected students to the team
foreach (var student in _selectedStudents)
{
Team.Students.Add(student);
}
Context.Teams.Add(Team);
await Context.SaveChangesAsync();
Snackbar.Add($"Team '{Team}' created successfully.", Severity.Success);
_formChangeTracker?.AllowNavigation();
NavigationManager.NavigateTo(ReturnUrl ?? "/teams");
}
catch (DbUpdateException ex)
{
ValidationService.HandleDbUpdateException(
ex,
"An error occurred while creating the team.",
"team",
"creating");
}
catch (Exception ex)
{
ValidationService.HandleException(ex);
}
}
private void HandleCancel()
{
_formChangeTracker?.AllowNavigation();
NavigationManager.NavigateTo(ReturnUrl ?? "/teams");
}
}