Events-MVC (example with htmx)

This commit is contained in:
Boris Milašinović
2026-04-25 22:21:35 +02:00
parent eb04483417
commit 0ee1b22f61
114 changed files with 7966 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
<Solution>
<Project Path="Events.EF/Events.EF.csproj" />
<Project Path="Events.MVC/Events.MVC.csproj" />
<Project Path="Tests/Events.Tests.IntegrationTests/Events.Tests.IntegrationTests.csproj" />
<Project Path="Tests/Events.Tests.UITests/Events.Tests.UITests.csproj" />
<Project Path="Tests/Events.Tests.UnitTests/Events.Tests.UnitTests.csproj" />
</Solution>

View File

@@ -0,0 +1,143 @@
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable enable
using System;
using System.Collections.Generic;
using Events.EF.Models;
using Microsoft.EntityFrameworkCore;
namespace Events.EF.Data.MSSQL;
public partial class EventsContext : DbContext
{
public EventsContext(DbContextOptions<EventsContext> options)
: base(options)
{
}
public virtual DbSet<Country> Countries { get; set; }
public virtual DbSet<Event> Events { get; set; }
public virtual DbSet<Person> People { get; set; }
public virtual DbSet<Registration> Registrations { get; set; }
public virtual DbSet<Sport> Sports { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Country>(entity =>
{
entity.HasKey(e => e.Code);
entity.ToTable("Country");
entity.HasIndex(e => e.Name, "UQ_Country_Name").IsUnique();
entity.Property(e => e.Code)
.HasMaxLength(3)
.IsUnicode(false);
entity.Property(e => e.Alpha3)
.HasMaxLength(3)
.IsUnicode(false)
.IsFixedLength();
entity.Property(e => e.Name)
.HasMaxLength(100)
.IsUnicode(false);
});
modelBuilder.Entity<Event>(entity =>
{
entity.ToTable("Event");
entity.Property(e => e.Name)
.HasMaxLength(150)
.IsUnicode(false);
});
modelBuilder.Entity<Person>(entity =>
{
entity.ToTable("Person");
entity.HasIndex(e => new { e.DocumentNumber, e.CountryCode }, "UQ_Person_DocumentNumber_CountryCode").IsUnique();
entity.Property(e => e.AddressCountry)
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.AddressLine)
.HasMaxLength(200)
.IsUnicode(false);
entity.Property(e => e.City)
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.ContactPhone)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.CountryCode)
.HasMaxLength(3)
.IsUnicode(false);
entity.Property(e => e.DocumentNumber)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Email)
.HasMaxLength(255)
.IsUnicode(false);
entity.Property(e => e.FirstName)
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.FirstNameTranscription)
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.LastName)
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.LastNameTranscription)
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.PostalCode)
.HasMaxLength(20)
.IsUnicode(false);
entity.HasOne(d => d.CountryCodeNavigation).WithMany(p => p.People)
.HasForeignKey(d => d.CountryCode)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Person_Country");
});
modelBuilder.Entity<Registration>(entity =>
{
entity.ToTable("Registration");
entity.HasIndex(e => new { e.PersonId, e.SportId, e.EventId }, "UQ_Registration_PersonId_SportId_EventId").IsUnique();
entity.Property(e => e.RegisteredAt).HasDefaultValueSql("(sysutcdatetime())", "DF_Registration_RegisteredAt");
entity.HasOne(d => d.Event).WithMany(p => p.Registrations)
.HasForeignKey(d => d.EventId)
.HasConstraintName("FK_Registration_Event");
entity.HasOne(d => d.Person).WithMany(p => p.Registrations)
.HasForeignKey(d => d.PersonId)
.HasConstraintName("FK_Registration_Person");
entity.HasOne(d => d.Sport).WithMany(p => p.Registrations)
.HasForeignKey(d => d.SportId)
.HasConstraintName("FK_Registration_Sport");
});
modelBuilder.Entity<Sport>(entity =>
{
entity.ToTable("Sport");
entity.HasIndex(e => e.Name, "UQ_Sport_Name").IsUnique();
entity.Property(e => e.Name)
.HasMaxLength(100)
.IsUnicode(false);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

View File

@@ -0,0 +1,165 @@
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable enable
using System;
using System.Collections.Generic;
using Events.EF.Models;
using Microsoft.EntityFrameworkCore;
namespace Events.EF.Data.Postgres;
public partial class EventsContext : DbContext
{
public EventsContext(DbContextOptions<EventsContext> options)
: base(options)
{
}
public virtual DbSet<Country> Countries { get; set; }
public virtual DbSet<Event> Events { get; set; }
public virtual DbSet<Person> People { get; set; }
public virtual DbSet<Registration> Registrations { get; set; }
public virtual DbSet<Sport> Sports { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Country>(entity =>
{
entity.HasKey(e => e.Code).HasName("country_pkey");
entity.ToTable("country");
entity.HasIndex(e => e.Name, "country_name_key").IsUnique();
entity.Property(e => e.Code)
.HasMaxLength(3)
.HasColumnName("code");
entity.Property(e => e.Alpha3)
.HasMaxLength(3)
.IsFixedLength()
.HasColumnName("alpha3");
entity.Property(e => e.Name)
.HasMaxLength(100)
.HasColumnName("name");
entity.Property(e => e.Translations)
.HasColumnType("jsonb")
.HasColumnName("translations");
});
modelBuilder.Entity<Event>(entity =>
{
entity.HasKey(e => e.Id).HasName("event_pkey");
entity.ToTable("event");
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.EventDate).HasColumnName("event_date");
entity.Property(e => e.Name)
.HasMaxLength(150)
.HasColumnName("name");
});
modelBuilder.Entity<Person>(entity =>
{
entity.HasKey(e => e.Id).HasName("person_pkey");
entity.ToTable("person");
entity.HasIndex(e => new { e.DocumentNumber, e.CountryCode }, "person_document_number_country_code_key").IsUnique();
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.AddressCountry)
.HasMaxLength(100)
.HasColumnName("address_country");
entity.Property(e => e.AddressLine)
.HasMaxLength(200)
.HasColumnName("address_line");
entity.Property(e => e.BirthDate).HasColumnName("birth_date");
entity.Property(e => e.City)
.HasMaxLength(100)
.HasColumnName("city");
entity.Property(e => e.ContactPhone)
.HasMaxLength(50)
.HasColumnName("contact_phone");
entity.Property(e => e.CountryCode)
.HasMaxLength(3)
.HasColumnName("country_code");
entity.Property(e => e.DocumentNumber)
.HasMaxLength(50)
.HasColumnName("document_number");
entity.Property(e => e.Email)
.HasMaxLength(255)
.HasColumnName("email");
entity.Property(e => e.FirstName)
.HasMaxLength(100)
.HasColumnName("first_name");
entity.Property(e => e.FirstNameTranscription)
.HasMaxLength(100)
.HasColumnName("first_name_transcription");
entity.Property(e => e.LastName)
.HasMaxLength(100)
.HasColumnName("last_name");
entity.Property(e => e.LastNameTranscription)
.HasMaxLength(100)
.HasColumnName("last_name_transcription");
entity.Property(e => e.PostalCode)
.HasMaxLength(20)
.HasColumnName("postal_code");
entity.HasOne(d => d.CountryCodeNavigation).WithMany(p => p.People)
.HasForeignKey(d => d.CountryCode)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("person_country_code_fkey");
});
modelBuilder.Entity<Registration>(entity =>
{
entity.HasKey(e => e.Id).HasName("registration_pkey");
entity.ToTable("registration");
entity.HasIndex(e => new { e.PersonId, e.SportId, e.EventId }, "registration_person_id_sport_id_event_id_key").IsUnique();
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.EventId).HasColumnName("event_id");
entity.Property(e => e.PersonId).HasColumnName("person_id");
entity.Property(e => e.RegisteredAt)
.HasDefaultValueSql("CURRENT_TIMESTAMP")
.HasColumnName("registered_at");
entity.Property(e => e.SportId).HasColumnName("sport_id");
entity.HasOne(d => d.Event).WithMany(p => p.Registrations)
.HasForeignKey(d => d.EventId)
.HasConstraintName("registration_event_id_fkey");
entity.HasOne(d => d.Person).WithMany(p => p.Registrations)
.HasForeignKey(d => d.PersonId)
.HasConstraintName("registration_person_id_fkey");
entity.HasOne(d => d.Sport).WithMany(p => p.Registrations)
.HasForeignKey(d => d.SportId)
.HasConstraintName("registration_sport_id_fkey");
});
modelBuilder.Entity<Sport>(entity =>
{
entity.HasKey(e => e.Id).HasName("sport_pkey");
entity.ToTable("sport");
entity.HasIndex(e => e.Name, "sport_name_key").IsUnique();
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.Name)
.HasMaxLength(100)
.HasColumnName("name");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.7" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,19 @@
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable enable
using System;
using System.Collections.Generic;
namespace Events.EF.Models;
public partial class Country
{
public string Code { get; set; } = null!;
public string Alpha3 { get; set; } = null!;
public string Name { get; set; } = null!;
public string? Translations { get; set; }
public virtual ICollection<Person> People { get; set; } = new List<Person>();
}

View File

@@ -0,0 +1,17 @@
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable enable
using System;
using System.Collections.Generic;
namespace Events.EF.Models;
public partial class Event
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public DateOnly EventDate { get; set; }
public virtual ICollection<Registration> Registrations { get; set; } = new List<Registration>();
}

View File

@@ -0,0 +1,41 @@
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable enable
using System;
using System.Collections.Generic;
namespace Events.EF.Models;
public partial class Person
{
public int Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string FirstNameTranscription { get; set; } = null!;
public string LastNameTranscription { get; set; } = null!;
public string? AddressLine { get; set; }
public string? PostalCode { get; set; }
public string? City { get; set; }
public string? AddressCountry { get; set; }
public string? Email { get; set; }
public string? ContactPhone { get; set; }
public DateOnly BirthDate { get; set; }
public string DocumentNumber { get; set; } = null!;
public string CountryCode { get; set; } = null!;
public virtual Country CountryCodeNavigation { get; set; } = null!;
public virtual ICollection<Registration> Registrations { get; set; } = new List<Registration>();
}

View File

@@ -0,0 +1,25 @@
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable enable
using System;
using System.Collections.Generic;
namespace Events.EF.Models;
public partial class Registration
{
public int Id { get; set; }
public int PersonId { get; set; }
public int SportId { get; set; }
public int EventId { get; set; }
public DateTime RegisteredAt { get; set; }
public virtual Event Event { get; set; } = null!;
public virtual Person Person { get; set; } = null!;
public virtual Sport Sport { get; set; } = null!;
}

View File

@@ -0,0 +1,15 @@
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable enable
using System;
using System.Collections.Generic;
namespace Events.EF.Models;
public partial class Sport
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public virtual ICollection<Registration> Registrations { get; set; } = new List<Registration>();
}

View File

@@ -0,0 +1,70 @@
{
"CodeGenerationMode": 6,
"ContextClassName": "EventsContext",
"ContextNamespace": null,
"FilterSchemas": false,
"IncludeConnectionString": false,
"IrregularWords": null,
"MinimumProductVersion": "2.6.1465",
"ModelNamespace": null,
"OutputContextPath": "Data\/MSSQL",
"OutputPath": "Models",
"PluralRules": null,
"PreserveCasingWithRegex": true,
"ProjectRootNamespace": "Events.EF",
"Schemas": null,
"SelectedHandlebarsLanguage": 2,
"SelectedToBeGenerated": 0,
"SingularRules": null,
"T4TemplatePath": null,
"Tables": [
{
"Name": "[dbo].[Country]",
"ObjectType": 0
},
{
"Name": "[dbo].[Event]",
"ObjectType": 0
},
{
"Name": "[dbo].[Person]",
"ObjectType": 0
},
{
"Name": "[dbo].[Registration]",
"ObjectType": 0
},
{
"Name": "[dbo].[Sport]",
"ObjectType": 0
}
],
"UiHint": null,
"UncountableWords": null,
"UseAsyncStoredProcedureCalls": true,
"UseBoolPropertiesWithoutDefaultSql": false,
"UseDatabaseNames": false,
"UseDatabaseNamesForRoutines": true,
"UseDateOnlyTimeOnly": true,
"UseDbContextSplitting": false,
"UseDecimalDataAnnotationForSprocResult": true,
"UseFluentApiOnly": true,
"UseHandleBars": false,
"UseHierarchyId": false,
"UseInflector": true,
"UseInternalAccessModifiersForSprocsAndFunctions": false,
"UseLegacyPluralizer": false,
"UseManyToManyEntity": false,
"UseNoDefaultConstructor": true,
"UseNoNavigations": false,
"UseNoObjectFilter": false,
"UseNodaTime": false,
"UseNullableReferences": true,
"UsePrefixNavigationNaming": false,
"UseSchemaFolders": false,
"UseSchemaNamespaces": false,
"UseSpatial": false,
"UseT4": false,
"UseT4Split": false,
"UseTypedTvpParameters": true
}

View File

@@ -0,0 +1,70 @@
{
"CodeGenerationMode": 6,
"ContextClassName": "EventsContext",
"ContextNamespace": null,
"FilterSchemas": false,
"IncludeConnectionString": false,
"IrregularWords": null,
"MinimumProductVersion": "2.6.1465",
"ModelNamespace": null,
"OutputContextPath": "Data\/Postgres",
"OutputPath": "Models",
"PluralRules": null,
"PreserveCasingWithRegex": true,
"ProjectRootNamespace": "Events.EF",
"Schemas": null,
"SelectedHandlebarsLanguage": 2,
"SelectedToBeGenerated": 0,
"SingularRules": null,
"T4TemplatePath": null,
"Tables": [
{
"Name": "public.country",
"ObjectType": 0
},
{
"Name": "public.event",
"ObjectType": 0
},
{
"Name": "public.person",
"ObjectType": 0
},
{
"Name": "public.registration",
"ObjectType": 0
},
{
"Name": "public.sport",
"ObjectType": 0
}
],
"UiHint": null,
"UncountableWords": null,
"UseAsyncStoredProcedureCalls": true,
"UseBoolPropertiesWithoutDefaultSql": false,
"UseDatabaseNames": false,
"UseDatabaseNamesForRoutines": true,
"UseDateOnlyTimeOnly": true,
"UseDbContextSplitting": false,
"UseDecimalDataAnnotationForSprocResult": true,
"UseFluentApiOnly": true,
"UseHandleBars": false,
"UseHierarchyId": false,
"UseInflector": true,
"UseInternalAccessModifiersForSprocsAndFunctions": false,
"UseLegacyPluralizer": false,
"UseManyToManyEntity": false,
"UseNoDefaultConstructor": true,
"UseNoNavigations": false,
"UseNoObjectFilter": false,
"UseNodaTime": false,
"UseNullableReferences": true,
"UsePrefixNavigationNaming": false,
"UseSchemaFolders": false,
"UseSchemaNamespaces": false,
"UseSpatial": false,
"UseT4": false,
"UseT4Split": false,
"UseTypedTvpParameters": true
}

View File

@@ -0,0 +1,67 @@
namespace Events.MVC;
public static class Constants
{
public static class TempDataKeys
{
public const string ToastMessage = "ToastMessage";
public const string ToastVariant = "ToastVariant";
public const string ToastTitle = "ToastTitle";
}
public static class ToastVariants
{
public const string Success = "success";
public const string Error = "error";
}
public static class ToastTitles
{
public const string Success = "Success";
public const string Error = "Error";
public const string Notification = "Notification";
}
public static class ViewDataKeys
{
public const string Title = "Title";
public const string HeaderActionLabel = "HeaderActionLabel";
public const string HeaderActionTarget = "HeaderActionTarget";
public const string CreatePersonModel = "CreatePersonModel";
public const string Prefix = "Prefix";
public const string CanRemoveRows = "CanRemoveRows";
}
public static class HtmxHeaders
{
public const string Request = "HX-Request";
public const string Retarget = "HX-Retarget";
public const string Reswap = "HX-Reswap";
public const string Trigger = "HX-Trigger";
}
public static class HtmxEvents
{
public const string ShowToast = "show-toast";
public const string CountryCreated = "country-created";
public const string EventCreated = "event-created";
public const string PersonCreated = "person-created";
public const string RegistrationCreated = "registration-created";
public const string SportCreated = "sport-created";
}
public static class HtmxSwap
{
public const string OuterHtml = "outerHTML";
}
public static class Messages
{
public const string EmailOrContactPhoneRequired = "Email or contact phone is required.";
public const string CountriesRequiredForPeople = "At least one country must be created before adding people.";
public const string EventsRequiredForRegistrations = "At least one event must be created before adding registrations.";
public const string SportsRequiredForRegistrations = "At least one sport must be created before adding registrations.";
public const string PeopleRequiredForRegistrations = "At least one person must be created before adding registrations.";
public const string RegistrationDependenciesRequired = "At least one event, one person, and one sport are required before adding registrations.";
}
}

View File

@@ -0,0 +1,347 @@
using System.Text.Json;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Models.Countries;
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
namespace Events.MVC.Controllers;
public class CountriesController : Controller
{
private readonly EventsContext ctx;
private readonly ISieveProcessor sieveProcessor;
private readonly PagingSettings pagingSettings;
public CountriesController(EventsContext ctx, ISieveProcessor sieveProcessor, IOptions<PagingSettings> pagingSettings)
{
this.ctx = ctx;
this.sieveProcessor = sieveProcessor;
this.pagingSettings = pagingSettings.Value;
}
public async Task<IActionResult> Index(SieveModel sieveModel)
{
var viewModel = await BuildCountriesListAsync(sieveModel);
if (Request.Headers.ContainsKey(Constants.HtmxHeaders.Request))
{
return PartialView("_CountriesList", viewModel);
}
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Row(string id)
{
var country = await ctx.Countries
.AsNoTracking()
.Select(c => new CountryViewModel
{
Code = c.Code,
Alpha3 = c.Alpha3,
Name = c.Name
})
.FirstOrDefaultAsync(c => c.Code == id);
if (country is null)
{
return NotFound();
}
return PartialView("_CountryRow", country);
}
[HttpGet]
public async Task<IActionResult> EditRow(string id)
{
var country = await ctx.Countries
.AsNoTracking()
.FirstOrDefaultAsync(c => c.Code == id);
if (country is null)
{
return NotFound();
}
return PartialView("_CountryEditRow", MapCountryToViewModel(country, includeTranslations: true));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(CountryViewModel model, SieveModel sieveModel)
{
NormalizeTranslations(model);
ValidateTranslations(model);
if (!ModelState.IsValid)
{
Response.Headers[Constants.HtmxHeaders.Retarget] = "#create-country-form";
Response.Headers[Constants.HtmxHeaders.Reswap] = Constants.HtmxSwap.OuterHtml;
return PartialView("_CreateCountryForm", model);
}
var country = new Country
{
Code = model.Code.Trim().ToUpperInvariant(),
Alpha3 = model.Alpha3.Trim().ToUpperInvariant(),
Name = model.Name.Trim(),
Translations = SerializeTranslations(model.Translations)
};
ctx.Countries.Add(country);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.CountryCreated] = true,
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Country '{country.Name}' was added successfully."
}
});
var viewModel = await BuildCountriesListAsync(sieveModel);
return PartialView("_CountriesList", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, CountryViewModel model)
{
if (!string.Equals(id, model.Code, StringComparison.OrdinalIgnoreCase))
{
return BadRequest();
}
NormalizeTranslations(model);
ValidateTranslations(model);
if (!ModelState.IsValid)
{
return PartialView("_CountryEditRow", model);
}
var country = await ctx.Countries.FirstOrDefaultAsync(c => c.Code == id);
if (country is null)
{
return NotFound();
}
country.Alpha3 = model.Alpha3.Trim().ToUpperInvariant();
country.Name = model.Name.Trim();
country.Translations = SerializeTranslations(model.Translations);
await ctx.SaveChangesAsync();
return PartialView("_CountryRow", new CountryViewModel
{
Code = country.Code,
Alpha3 = country.Alpha3,
Name = country.Name
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(string id, SieveModel sieveModel)
{
var country = await ctx.Countries
.Include(c => c.People)
.FirstOrDefaultAsync(c => c.Code == id);
if (country is null)
{
return NotFound();
}
if (country.People.Count > 0)
{
Response.StatusCode = StatusCodes.Status409Conflict;
return Content("The country cannot be deleted because related people exist.");
}
ctx.Countries.Remove(country);
var deletedName = country.Name;
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Country '{deletedName}' was deleted successfully."
}
});
var viewModel = await BuildCountriesListAsync(sieveModel);
return PartialView("_CountriesList", viewModel);
}
private async Task<PagedList<CountryViewModel>> BuildCountriesListAsync(SieveModel sieveModel)
{
sieveModel.SetDefaultPagingAndSorting(pagingSettings.PageSize, "Name");
var normalizedFilters = sieveModel.Filters?.Trim() ?? string.Empty;
var nameFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "Name");
var baseQuery = ctx.Countries
.AsNoTracking()
.Select(c => new CountryViewModel
{
Code = c.Code,
Alpha3 = c.Alpha3,
Name = c.Name
});
var totalCount = await baseQuery.CountAsync();
var filteredCount = string.IsNullOrWhiteSpace(normalizedFilters)
? totalCount
: await sieveProcessor
.Apply(
sieveModel,
baseQuery,
applyFiltering: true,
applySorting: false,
applyPagination: false)
.CountAsync();
var pagingInfo = new PagingInfo
{
FilteredItemsCount = filteredCount,
TotalItemsCount = totalCount,
ItemsPerPage = sieveModel.PageSize!.Value,
CurrentPage = sieveModel.Page!.Value,
Sorts = sieveModel.Sorts ?? "Name",
Filters = normalizedFilters,
NameFilter = nameFilter
};
if (pagingInfo.CurrentPage > pagingInfo.TotalPages)
{
pagingInfo.CurrentPage = pagingInfo.TotalPages;
sieveModel.Page = pagingInfo.CurrentPage;
}
var countries = await sieveProcessor
.Apply(sieveModel, baseQuery)
.ToListAsync();
return new PagedList<CountryViewModel>(countries, pagingInfo);
}
private void ValidateTranslations(CountryViewModel model)
{
var languages = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var hasErrors = false;
for (var i = 0; i < model.Translations.Count; i++)
{
var translation = model.Translations[i] ?? new CountryTranslationViewModel();
var language = translation.LanguageCode?.Trim() ?? string.Empty;
var name = translation.Name?.Trim() ?? string.Empty;
if (string.IsNullOrEmpty(language) && string.IsNullOrEmpty(name))
{
continue;
}
if (string.IsNullOrEmpty(language))
{
ModelState.AddModelError($"Translations[{i}].LanguageCode", "Enter a language code.");
hasErrors = true;
}
if (string.IsNullOrEmpty(name))
{
ModelState.AddModelError($"Translations[{i}].Name", "Enter a translation.");
hasErrors = true;
}
if (!string.IsNullOrEmpty(language) && !languages.Add(language))
{
ModelState.AddModelError($"Translations[{i}].LanguageCode", "The language code has already been entered.");
hasErrors = true;
}
}
if (hasErrors)
{
ModelState.AddModelError(string.Empty, "Check the translations. Every row must have both a language code and a translation, and language codes must be unique.");
}
}
private static void NormalizeTranslations(CountryViewModel model)
{
model.Translations ??= [];
model.Translations = model.Translations
.Where(t => t is not null)
.Select(t => new CountryTranslationViewModel
{
LanguageCode = t!.LanguageCode?.Trim().ToLowerInvariant() ?? string.Empty,
Name = t.Name?.Trim() ?? string.Empty
})
.ToList();
}
private static CountryViewModel MapCountryToViewModel(Country country, bool includeTranslations)
{
return new CountryViewModel
{
Code = country.Code,
Alpha3 = country.Alpha3,
Name = country.Name,
Translations = includeTranslations ? ParseTranslations(country.Translations) : []
};
}
private static List<CountryTranslationViewModel> ParseTranslations(string? translationsJson)
{
if (string.IsNullOrWhiteSpace(translationsJson))
{
return [];
}
try
{
var translations = JsonSerializer.Deserialize<Dictionary<string, string>>(translationsJson);
if (translations is null)
{
return [];
}
return translations
.OrderBy(t => t.Key, StringComparer.OrdinalIgnoreCase)
.Select(t => new CountryTranslationViewModel
{
LanguageCode = t.Key,
Name = t.Value
})
.ToList();
}
catch (JsonException)
{
return [];
}
}
private static string? SerializeTranslations(IEnumerable<CountryTranslationViewModel> translations)
{
var dictionary = translations
.Where(t => t is not null && !string.IsNullOrWhiteSpace(t.LanguageCode) && !string.IsNullOrWhiteSpace(t.Name))
.ToDictionary(t => t.LanguageCode.Trim().ToLowerInvariant(), t => t.Name.Trim(), StringComparer.OrdinalIgnoreCase);
return dictionary.Count == 0 ? null : JsonSerializer.Serialize(dictionary);
}
}

View File

@@ -0,0 +1,241 @@
using System.Text.Json;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Models.Events;
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
namespace Events.MVC.Controllers;
public class EventsController : Controller
{
private readonly EventsContext ctx;
private readonly ISieveProcessor sieveProcessor;
private readonly PagingSettings pagingSettings;
public EventsController(EventsContext ctx, ISieveProcessor sieveProcessor, IOptions<PagingSettings> pagingSettings)
{
this.ctx = ctx;
this.sieveProcessor = sieveProcessor;
this.pagingSettings = pagingSettings.Value;
}
public async Task<IActionResult> Index(SieveModel sieveModel)
{
var viewModel = await BuildEventsListAsync(sieveModel);
if (Request.Headers.ContainsKey(Constants.HtmxHeaders.Request))
{
return PartialView("_EventsList", viewModel);
}
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Row(int id)
{
var eventModel = await ctx.Events
.AsNoTracking()
.Select(e => new EventViewModel
{
Id = e.Id,
Name = e.Name,
EventDate = e.EventDate,
ParticipantsCount = e.Registrations.Count
})
.FirstOrDefaultAsync(e => e.Id == id);
if (eventModel is null)
{
return NotFound();
}
return PartialView("_EventRow", eventModel);
}
[HttpGet]
public async Task<IActionResult> EditRow(int id)
{
var eventModel = await ctx.Events
.AsNoTracking()
.Select(e => new EventViewModel
{
Id = e.Id,
Name = e.Name,
EventDate = e.EventDate
})
.FirstOrDefaultAsync(e => e.Id == id);
if (eventModel is null)
{
return NotFound();
}
return PartialView("_EventEditRow", eventModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(EventViewModel model, SieveModel sieveModel)
{
if (!ModelState.IsValid)
{
Response.Headers[Constants.HtmxHeaders.Retarget] = "#create-event-form";
Response.Headers[Constants.HtmxHeaders.Reswap] = Constants.HtmxSwap.OuterHtml;
return PartialView("_CreateEventForm", model);
}
var eventEntity = new Event
{
Name = model.Name,
EventDate = model.EventDate
};
ctx.Events.Add(eventEntity);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.EventCreated] = true,
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Event '{model.Name}' was added successfully."
}
});
var viewModel = await BuildEventsListAsync(sieveModel);
return PartialView("_EventsList", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, EventViewModel model)
{
if (id != model.Id)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
return PartialView("_EventEditRow", model);
}
var existingEvent = await ctx.Events.FirstOrDefaultAsync(e => e.Id == id);
if (existingEvent is null)
{
return NotFound();
}
existingEvent.Name = model.Name;
existingEvent.EventDate = model.EventDate;
await ctx.SaveChangesAsync();
return PartialView("_EventRow", new EventViewModel
{
Id = existingEvent.Id,
Name = existingEvent.Name,
EventDate = existingEvent.EventDate,
ParticipantsCount = await ctx.Registrations.CountAsync(r => r.EventId == existingEvent.Id)
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, SieveModel sieveModel)
{
var eventEntity = await ctx.Events
.Include(e => e.Registrations)
.FirstOrDefaultAsync(e => e.Id == id);
if (eventEntity is null)
{
return NotFound();
}
if (eventEntity.Registrations.Count > 0)
{
Response.StatusCode = StatusCodes.Status409Conflict;
return Content("The event cannot be deleted because registrations exist.");
}
ctx.Events.Remove(eventEntity);
var deletedName = eventEntity.Name;
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Event '{deletedName}' was deleted successfully."
}
});
var viewModel = await BuildEventsListAsync(sieveModel);
return PartialView("_EventsList", viewModel);
}
private async Task<PagedList<EventViewModel>> BuildEventsListAsync(SieveModel sieveModel)
{
sieveModel.SetDefaultPagingAndSorting(pagingSettings.PageSize, "EventDate");
var normalizedFilters = sieveModel.Filters?.Trim() ?? string.Empty;
var nameFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "Name");
var baseQuery = ctx.Events
.AsNoTracking()
.Select(e => new EventViewModel
{
Id = e.Id,
Name = e.Name,
EventDate = e.EventDate,
ParticipantsCount = e.Registrations.Count
});
var totalCount = await baseQuery.CountAsync();
var filteredCount = string.IsNullOrWhiteSpace(normalizedFilters)
? totalCount
: await sieveProcessor
.Apply(
sieveModel,
baseQuery,
applyFiltering: true,
applySorting: false,
applyPagination: false)
.CountAsync();
var pagingInfo = new PagingInfo
{
FilteredItemsCount = filteredCount,
TotalItemsCount = totalCount,
ItemsPerPage = sieveModel.PageSize!.Value,
CurrentPage = sieveModel.Page!.Value,
Sorts = sieveModel.Sorts ?? "EventDate",
Filters = normalizedFilters,
NameFilter = nameFilter
};
if (pagingInfo.CurrentPage > pagingInfo.TotalPages)
{
pagingInfo.CurrentPage = pagingInfo.TotalPages;
sieveModel.Page = pagingInfo.CurrentPage;
}
var events = await sieveProcessor
.Apply(sieveModel, baseQuery)
.ToListAsync();
return new PagedList<EventViewModel>(events, pagingInfo);
}
}

View File

@@ -0,0 +1,21 @@
using System.Diagnostics;
using Events.MVC.Models;
using Microsoft.AspNetCore.Mvc;
namespace Events.MVC.Controllers;
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
}
}

View File

@@ -0,0 +1,337 @@
using System.Text.Json;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Models.People;
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
namespace Events.MVC.Controllers;
public class PeopleController : Controller
{
private readonly EventsContext ctx;
private readonly ISieveProcessor sieveProcessor;
private readonly PagingSettings pagingSettings;
public PeopleController(EventsContext ctx, ISieveProcessor sieveProcessor, IOptions<PagingSettings> pagingSettings)
{
this.ctx = ctx;
this.sieveProcessor = sieveProcessor;
this.pagingSettings = pagingSettings.Value;
}
public async Task<IActionResult> Index(SieveModel sieveModel)
{
if (!await ctx.Countries.AsNoTracking().AnyAsync())
{
TempData[Constants.TempDataKeys.ToastVariant] = Constants.ToastVariants.Error;
TempData[Constants.TempDataKeys.ToastTitle] = Constants.ToastTitles.Error;
TempData[Constants.TempDataKeys.ToastMessage] = Constants.Messages.CountriesRequiredForPeople;
return RedirectToAction("Index", "Countries");
}
var viewModel = await BuildPeopleListAsync(sieveModel);
if (Request.Headers.ContainsKey(Constants.HtmxHeaders.Request))
{
return PartialView("_PeopleList", viewModel);
}
ViewData[Constants.ViewDataKeys.CreatePersonModel] = new PersonViewModel
{
CountryOptions = await GetCountryOptionsAsync()
};
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Row(int id)
{
var person = await ctx.People
.AsNoTracking()
.Select(p => new PersonViewModel
{
Id = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
FirstNameTranscription = p.FirstNameTranscription,
LastNameTranscription = p.LastNameTranscription,
FullName = p.FirstName + " " + p.LastName,
FullNameTranscription = p.FirstNameTranscription + " " + p.LastNameTranscription,
BirthDate = p.BirthDate,
CountryName = p.CountryCodeNavigation.Name,
RegistrationsCount = p.Registrations.Count
})
.FirstOrDefaultAsync(p => p.Id == id);
if (person is null)
{
return NotFound();
}
return PartialView("_PersonRow", person);
}
[HttpGet]
public async Task<IActionResult> EditRow(int id)
{
var person = await ctx.People
.AsNoTracking()
.Select(p => new PersonViewModel
{
Id = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
FirstNameTranscription = p.FirstNameTranscription,
LastNameTranscription = p.LastNameTranscription,
AddressLine = p.AddressLine,
PostalCode = p.PostalCode,
City = p.City,
AddressCountry = p.AddressCountry,
Email = p.Email,
ContactPhone = p.ContactPhone,
BirthDate = p.BirthDate,
DocumentNumber = p.DocumentNumber,
CountryCode = p.CountryCode
})
.FirstOrDefaultAsync(p => p.Id == id);
if (person is null)
{
return NotFound();
}
person.CountryOptions = await GetCountryOptionsAsync(person.CountryCode);
return PartialView("_PersonEditRow", person);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(PersonViewModel model, SieveModel sieveModel)
{
if (!ModelState.IsValid)
{
model.CountryOptions = await GetCountryOptionsAsync(model.CountryCode);
Response.Headers[Constants.HtmxHeaders.Retarget] = "#create-person-form";
Response.Headers[Constants.HtmxHeaders.Reswap] = Constants.HtmxSwap.OuterHtml;
return PartialView("_CreatePersonForm", model);
}
var person = new Person
{
FirstName = model.FirstName.TrimToNull(),
LastName = model.LastName.TrimToNull(),
FirstNameTranscription = model.FirstNameTranscription.Trim(),
LastNameTranscription = model.LastNameTranscription.Trim(),
AddressLine = model.AddressLine.TrimToNull(),
PostalCode = model.PostalCode.TrimToNull(),
City = model.City.TrimToNull(),
AddressCountry = model.AddressCountry.TrimToNull(),
Email = model.Email.TrimToNull(),
ContactPhone = model.ContactPhone.TrimToNull(),
BirthDate = model.BirthDate!.Value,
DocumentNumber = model.DocumentNumber.Trim(),
CountryCode = model.CountryCode.Trim().ToUpperInvariant()
};
ctx.People.Add(person);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.PersonCreated] = true,
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Person '{person.FirstName} {person.LastName}' was added successfully."
}
});
var viewModel = await BuildPeopleListAsync(sieveModel);
return PartialView("_PeopleList", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, PersonViewModel model)
{
if (id != model.Id)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
model.CountryOptions = await GetCountryOptionsAsync(model.CountryCode);
return PartialView("_PersonEditRow", model);
}
var person = await ctx.People.FirstOrDefaultAsync(p => p.Id == id);
if (person is null)
{
return NotFound();
}
person.FirstName = model.FirstName.TrimToNull();
person.LastName = model.LastName.TrimToNull();
person.FirstNameTranscription = model.FirstNameTranscription.Trim();
person.LastNameTranscription = model.LastNameTranscription.Trim();
person.AddressLine = model.AddressLine.TrimToNull();
person.PostalCode = model.PostalCode.TrimToNull();
person.City = model.City.TrimToNull();
person.AddressCountry = model.AddressCountry.TrimToNull();
person.Email = model.Email.TrimToNull();
person.ContactPhone = model.ContactPhone.TrimToNull();
person.BirthDate = model.BirthDate!.Value;
person.DocumentNumber = model.DocumentNumber.Trim();
person.CountryCode = model.CountryCode.Trim().ToUpperInvariant();
await ctx.SaveChangesAsync();
var rowModel = await ctx.People
.AsNoTracking()
.Where(p => p.Id == id)
.Select(p => new PersonViewModel
{
Id = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
FirstNameTranscription = p.FirstNameTranscription,
LastNameTranscription = p.LastNameTranscription,
FullName = p.FirstName + " " + p.LastName,
FullNameTranscription = p.FirstNameTranscription + " " + p.LastNameTranscription,
BirthDate = p.BirthDate,
CountryName = p.CountryCodeNavigation.Name,
RegistrationsCount = p.Registrations.Count
})
.FirstAsync();
return PartialView("_PersonRow", rowModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, SieveModel sieveModel)
{
var person = await ctx.People
.Include(p => p.Registrations)
.FirstOrDefaultAsync(p => p.Id == id);
if (person is null)
{
return NotFound();
}
if (person.Registrations.Count > 0)
{
Response.StatusCode = StatusCodes.Status409Conflict;
return Content("The person cannot be deleted because registrations exist.");
}
ctx.People.Remove(person);
var deletedName = $"{person.FirstName} {person.LastName}";
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Person '{deletedName}' was deleted successfully."
}
});
var viewModel = await BuildPeopleListAsync(sieveModel);
return PartialView("_PeopleList", viewModel);
}
private async Task<PeoplePageViewModel> BuildPeopleListAsync(SieveModel sieveModel)
{
sieveModel.SetDefaultPagingAndSorting(pagingSettings.PageSize, "LastNameTranscription");
var normalizedFilters = sieveModel.Filters?.Trim() ?? string.Empty;
var nameFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "FullNameTranscription");
var countryFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "CountryCode", "==");
var baseQuery = ctx.People
.AsNoTracking()
.Select(p => new PersonViewModel
{
Id = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
FirstNameTranscription = p.FirstNameTranscription,
LastNameTranscription = p.LastNameTranscription,
FullName = p.FirstName + " " + p.LastName,
FullNameTranscription = p.FirstNameTranscription + " " + p.LastNameTranscription,
CountryCode = p.CountryCode,
BirthDate = p.BirthDate,
CountryName = p.CountryCodeNavigation.Name,
RegistrationsCount = p.Registrations.Count
});
var totalCount = await baseQuery.CountAsync();
var filteredCount = string.IsNullOrWhiteSpace(normalizedFilters)
? totalCount
: await sieveProcessor
.Apply(
sieveModel,
baseQuery,
applyFiltering: true,
applySorting: false,
applyPagination: false)
.CountAsync();
var pagingInfo = new PagingInfo
{
FilteredItemsCount = filteredCount,
TotalItemsCount = totalCount,
ItemsPerPage = sieveModel.PageSize!.Value,
CurrentPage = sieveModel.Page!.Value,
Sorts = sieveModel.Sorts ?? "LastNameTranscription",
Filters = normalizedFilters,
NameFilter = nameFilter
};
if (pagingInfo.CurrentPage > pagingInfo.TotalPages)
{
pagingInfo.CurrentPage = pagingInfo.TotalPages;
sieveModel.Page = pagingInfo.CurrentPage;
}
var people = await sieveProcessor
.Apply(sieveModel, baseQuery)
.ToListAsync();
return new PeoplePageViewModel
{
People = new PagedList<PersonViewModel>(people, pagingInfo),
CountryOptions = await GetCountryOptionsAsync(countryFilter),
CountryFilter = countryFilter
};
}
private async Task<List<SelectListItem>> GetCountryOptionsAsync(string? selectedCode = null)
{
return await ctx.Countries
.AsNoTracking()
.OrderBy(c => c.Name)
.Select(c => new SelectListItem
{
Value = c.Code,
Text = c.Name,
Selected = c.Code == selectedCode
})
.ToListAsync();
}
}

View File

@@ -0,0 +1,430 @@
using System.Text.Json;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Models.Registrations;
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
namespace Events.MVC.Controllers;
public class RegistrationsController : Controller
{
private readonly EventsContext ctx;
private readonly ISieveProcessor sieveProcessor;
private readonly PagingSettings pagingSettings;
public RegistrationsController(EventsContext ctx, ISieveProcessor sieveProcessor, IOptions<PagingSettings> pagingSettings)
{
this.ctx = ctx;
this.sieveProcessor = sieveProcessor;
this.pagingSettings = pagingSettings.Value;
}
public async Task<IActionResult> Index(int? eventId, SieveModel sieveModel)
{
var events = await GetEventOptionsAsync(eventId);
if (events.Count == 0)
{
TempData[Constants.TempDataKeys.ToastVariant] = Constants.ToastVariants.Error;
TempData[Constants.TempDataKeys.ToastTitle] = Constants.ToastTitles.Error;
TempData[Constants.TempDataKeys.ToastMessage] = Constants.Messages.EventsRequiredForRegistrations;
return RedirectToAction("Index", "Events");
}
if (!await ctx.Sports.AsNoTracking().AnyAsync())
{
TempData[Constants.TempDataKeys.ToastVariant] = Constants.ToastVariants.Error;
TempData[Constants.TempDataKeys.ToastTitle] = Constants.ToastTitles.Error;
TempData[Constants.TempDataKeys.ToastMessage] = Constants.Messages.SportsRequiredForRegistrations;
return RedirectToAction("Index", "Sports");
}
if (!await ctx.People.AsNoTracking().AnyAsync())
{
TempData[Constants.TempDataKeys.ToastVariant] = Constants.ToastVariants.Error;
TempData[Constants.TempDataKeys.ToastTitle] = Constants.ToastTitles.Error;
TempData[Constants.TempDataKeys.ToastMessage] = Constants.Messages.PeopleRequiredForRegistrations;
return RedirectToAction("Index", "People");
}
var selectedEventId = eventId ?? int.Parse(events[0].Value);
MarkSelectedEvent(events, selectedEventId);
var viewModel = await BuildPageViewModelAsync(selectedEventId, sieveModel, events);
if (Request.Headers.ContainsKey(Constants.HtmxHeaders.Request))
{
return PartialView("_RegistrationsPanel", viewModel);
}
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Row(int id, int eventId)
{
var registration = await ctx.Registrations
.AsNoTracking()
.Where(r => r.Id == id && r.EventId == eventId)
.Select(r => new RegistrationViewModel
{
Id = r.Id,
EventId = r.EventId,
PersonId = r.PersonId,
SportId = r.SportId,
PersonName = r.Person.FirstName + " " + r.Person.LastName,
PersonTranscription = r.Person.FirstNameTranscription + " " + r.Person.LastNameTranscription,
CountryCode = r.Person.CountryCode,
CountryName = r.Person.CountryCodeNavigation.Name,
SportName = r.Sport.Name,
RegisteredAt = r.RegisteredAt
})
.FirstOrDefaultAsync();
if (registration is null)
{
return NotFound();
}
return PartialView("_RegistrationRow", registration);
}
[HttpGet]
public async Task<IActionResult> EditRow(int id, int eventId)
{
var registration = await ctx.Registrations
.AsNoTracking()
.Where(r => r.Id == id && r.EventId == eventId)
.Select(r => new RegistrationViewModel
{
Id = r.Id,
EventId = r.EventId,
PersonId = r.PersonId,
SportId = r.SportId,
RegisteredAt = r.RegisteredAt
})
.FirstOrDefaultAsync();
if (registration is null)
{
return NotFound();
}
await PopulateRegistrationOptionsAsync(registration);
return PartialView("_RegistrationEditRow", registration);
}
[HttpGet]
public async Task<IActionResult> PersonSuggestions(string? personLookup, string? countryFilter)
{
if (string.IsNullOrWhiteSpace(personLookup))
{
return PartialView("_PersonSuggestions", Array.Empty<SelectListItem>());
}
var searchTerm = personLookup.Trim().ToLowerInvariant();
var query = ctx.People
.AsNoTracking()
.Where(p =>
p.FirstNameTranscription.ToLower().Contains(searchTerm) ||
p.LastNameTranscription.ToLower().Contains(searchTerm) ||
(p.FirstNameTranscription + " " + p.LastNameTranscription).ToLower().Contains(searchTerm))
.AsQueryable();
if (!string.IsNullOrWhiteSpace(countryFilter))
{
query = query.Where(p => p.CountryCode == countryFilter);
}
var suggestions = await query
.OrderBy(p => p.LastName)
.ThenBy(p => p.FirstName)
.Take(10)
.Select(p => new SelectListItem
{
Value = p.Id.ToString(),
Text = p.FirstName + " " + p.LastName + "|" + p.FirstNameTranscription + " " + p.LastNameTranscription
})
.ToListAsync();
return PartialView("_PersonSuggestions", suggestions);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(RegistrationViewModel model, SieveModel sieveModel)
{
if (!await CanCreateRegistrationsAsync())
{
Response.StatusCode = StatusCodes.Status409Conflict;
return Content(Constants.Messages.RegistrationDependenciesRequired);
}
if (!ModelState.IsValid)
{
await PopulateRegistrationOptionsAsync(model);
Response.Headers[Constants.HtmxHeaders.Retarget] = "#create-registration-form";
Response.Headers[Constants.HtmxHeaders.Reswap] = Constants.HtmxSwap.OuterHtml;
return PartialView("_CreateRegistrationForm", model);
}
var registration = new Registration
{
EventId = model.EventId,
PersonId = model.PersonId,
SportId = model.SportId
};
ctx.Registrations.Add(registration);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.RegistrationCreated] = true,
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = "Registration was added successfully."
}
});
var viewModel = await BuildPageViewModelAsync(model.EventId, sieveModel);
return PartialView("_RegistrationsPanel", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, RegistrationViewModel model)
{
if (id != model.Id)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
await PopulateRegistrationOptionsAsync(model);
return PartialView("_RegistrationEditRow", model);
}
var registration = await ctx.Registrations.FirstOrDefaultAsync(r => r.Id == id && r.EventId == model.EventId);
if (registration is null)
{
return NotFound();
}
registration.PersonId = model.PersonId;
registration.SportId = model.SportId;
await ctx.SaveChangesAsync();
var rowModel = await ctx.Registrations
.AsNoTracking()
.Where(r => r.Id == id)
.Select(r => new RegistrationViewModel
{
Id = r.Id,
EventId = r.EventId,
PersonId = r.PersonId,
SportId = r.SportId,
PersonName = r.Person.FirstName + " " + r.Person.LastName,
PersonTranscription = r.Person.FirstNameTranscription + " " + r.Person.LastNameTranscription,
CountryCode = r.Person.CountryCode,
CountryName = r.Person.CountryCodeNavigation.Name,
SportName = r.Sport.Name,
RegisteredAt = r.RegisteredAt
})
.FirstAsync();
return PartialView("_RegistrationRow", rowModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, int eventId, SieveModel sieveModel)
{
var registration = await ctx.Registrations.FirstOrDefaultAsync(r => r.Id == id && r.EventId == eventId);
if (registration is null)
{
return NotFound();
}
ctx.Registrations.Remove(registration);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = "Registration was deleted successfully."
}
});
var viewModel = await BuildPageViewModelAsync(eventId, sieveModel);
return PartialView("_RegistrationsPanel", viewModel);
}
private async Task<RegistrationsPageViewModel> BuildPageViewModelAsync(int selectedEventId, SieveModel sieveModel, List<SelectListItem>? eventOptions = null)
{
sieveModel.SetDefaultPagingAndSorting(pagingSettings.PageSize, "RegisteredAt");
var normalizedFilters = sieveModel.Filters?.Trim() ?? string.Empty;
var nameFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "PersonTranscription");
var countryFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "CountryCode", "==");
var baseQuery = ctx.Registrations
.AsNoTracking()
.Where(r => r.EventId == selectedEventId)
.Select(r => new RegistrationViewModel
{
Id = r.Id,
EventId = r.EventId,
PersonId = r.PersonId,
SportId = r.SportId,
PersonName = r.Person.FirstName + " " + r.Person.LastName,
PersonTranscription = r.Person.FirstNameTranscription + " " + r.Person.LastNameTranscription,
CountryCode = r.Person.CountryCode,
CountryName = r.Person.CountryCodeNavigation.Name,
SportName = r.Sport.Name,
RegisteredAt = r.RegisteredAt
});
var totalCount = await baseQuery.CountAsync();
var filteredCount = string.IsNullOrWhiteSpace(normalizedFilters)
? totalCount
: await sieveProcessor
.Apply(sieveModel, baseQuery, applyFiltering: true, applySorting: false, applyPagination: false)
.CountAsync();
var pagingInfo = new PagingInfo
{
FilteredItemsCount = filteredCount,
TotalItemsCount = totalCount,
ItemsPerPage = sieveModel.PageSize!.Value,
CurrentPage = sieveModel.Page!.Value,
Sorts = sieveModel.Sorts ?? "RegisteredAt",
Filters = normalizedFilters,
NameFilter = nameFilter
};
if (pagingInfo.CurrentPage > pagingInfo.TotalPages)
{
pagingInfo.CurrentPage = pagingInfo.TotalPages;
sieveModel.Page = pagingInfo.CurrentPage;
}
var registrationsData = await sieveProcessor
.Apply(sieveModel, baseQuery)
.ToListAsync();
var registrations = new PagedList<RegistrationViewModel>(registrationsData, pagingInfo);
eventOptions ??= await GetEventOptionsAsync(selectedEventId);
MarkSelectedEvent(eventOptions, selectedEventId);
var selectedEventName = eventOptions.FirstOrDefault(e => e.Selected)?.Text ?? string.Empty;
var canCreate = await CanCreateRegistrationsAsync();
var countryOptions = await GetCountryOptionsAsync(countryFilter);
var createModel = new RegistrationViewModel
{
EventId = selectedEventId
};
await PopulateRegistrationOptionsAsync(createModel);
return new RegistrationsPageViewModel
{
SelectedEventId = selectedEventId,
SelectedEventName = selectedEventName,
EventOptions = eventOptions,
CountryOptions = countryOptions,
CountryFilter = countryFilter,
Registrations = registrations,
CreateModel = createModel,
CanCreate = canCreate,
CreateDisabledMessage = canCreate ? null : Constants.Messages.RegistrationDependenciesRequired
};
}
private async Task PopulateRegistrationOptionsAsync(RegistrationViewModel model)
{
if (model.PersonId > 0)
{
model.PersonLookup = await ctx.People
.AsNoTracking()
.Where(p => p.Id == model.PersonId)
.Select(p => p.FirstName + " " + p.LastName + " (" + p.FirstNameTranscription + " " + p.LastNameTranscription + ")")
.FirstOrDefaultAsync() ?? string.Empty;
}
else
{
model.PersonLookup = string.Empty;
}
model.SportOptions = await ctx.Sports
.AsNoTracking()
.OrderBy(s => s.Name)
.Select(s => new SelectListItem
{
Value = s.Id.ToString(),
Text = s.Name,
Selected = s.Id == model.SportId
})
.ToListAsync();
}
private async Task<List<SelectListItem>> GetEventOptionsAsync(int? selectedEventId)
{
var events = await ctx.Events
.AsNoTracking()
.OrderBy(e => e.EventDate)
.ThenBy(e => e.Name)
.ToListAsync();
return events
.Select(e => new SelectListItem
{
Value = e.Id.ToString(),
Text = $"{e.Name} ({e.EventDate:dd.MM.yyyy.})",
Selected = e.Id == selectedEventId
})
.ToList();
}
private async Task<bool> CanCreateRegistrationsAsync()
{
return await ctx.Events.AsNoTracking().AnyAsync()
&& await ctx.People.AsNoTracking().AnyAsync()
&& await ctx.Sports.AsNoTracking().AnyAsync();
}
private async Task<List<SelectListItem>> GetCountryOptionsAsync(string? selectedCountryCode)
{
return await ctx.Countries
.AsNoTracking()
.OrderBy(c => c.Name)
.Select(c => new SelectListItem
{
Value = c.Code,
Text = c.Name,
Selected = c.Code == selectedCountryCode
})
.ToListAsync();
}
private static void MarkSelectedEvent(IEnumerable<SelectListItem> events, int selectedEventId)
{
foreach (var eventOption in events)
{
eventOption.Selected = string.Equals(eventOption.Value, selectedEventId.ToString(), StringComparison.Ordinal);
}
}
}

View File

@@ -0,0 +1,228 @@
using System.Text.Json;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Models.Sports;
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Sieve.Models;
using Sieve.Services;
namespace Events.MVC.Controllers;
public class SportsController : Controller
{
private readonly EventsContext ctx;
private readonly ISieveProcessor sieveProcessor;
private readonly PagingSettings pagingSettings;
public SportsController(EventsContext ctx, ISieveProcessor sieveProcessor, IOptions<PagingSettings> pagingSettings)
{
this.ctx = ctx;
this.sieveProcessor = sieveProcessor;
this.pagingSettings = pagingSettings.Value;
}
public async Task<IActionResult> Index(SieveModel sieveModel)
{
var viewModel = await BuildSportsListAsync(sieveModel);
if (Request.Headers.ContainsKey(Constants.HtmxHeaders.Request))
{
return PartialView("_SportsList", viewModel);
}
return View(viewModel);
}
[HttpGet]
public async Task<IActionResult> Row(int id)
{
var sport = await ctx.Sports
.AsNoTracking()
.FirstOrDefaultAsync(s => s.Id == id);
if (sport is null)
{
return NotFound();
}
return PartialView("_SportRow", new SportViewModel
{
Id = sport.Id,
Name = sport.Name
});
}
[HttpGet]
public async Task<IActionResult> EditRow(int id)
{
var sport = await ctx.Sports
.AsNoTracking()
.FirstOrDefaultAsync(s => s.Id == id);
if (sport is null)
{
return NotFound();
}
return PartialView("_SportEditRow", new SportViewModel
{
Id = sport.Id,
Name = sport.Name
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(SportViewModel model, SieveModel sieveModel)
{
if (!ModelState.IsValid)
{
Response.Headers[Constants.HtmxHeaders.Retarget] = "#create-sport-form";
Response.Headers[Constants.HtmxHeaders.Reswap] = Constants.HtmxSwap.OuterHtml;
return PartialView("_CreateSportForm", model);
}
var sport = new Sport
{
Name = model.Name
};
ctx.Sports.Add(sport);
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.SportCreated] = true,
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Sport '{model.Name}' was added successfully."
}
});
var viewModel = await BuildSportsListAsync(sieveModel);
return PartialView("_SportsList", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, SportViewModel model)
{
if (id != model.Id)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
return PartialView("_SportEditRow", model);
}
var existingSport = await ctx.Sports.FirstOrDefaultAsync(s => s.Id == id);
if (existingSport is null)
{
return NotFound();
}
existingSport.Name = model.Name;
await ctx.SaveChangesAsync();
return PartialView("_SportRow", new SportViewModel
{
Id = existingSport.Id,
Name = existingSport.Name
});
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, SieveModel sieveModel)
{
var sport = await ctx.Sports
.Include(s => s.Registrations)
.FirstOrDefaultAsync(s => s.Id == id);
if (sport is null)
{
return NotFound();
}
if (sport.Registrations.Count > 0)
{
Response.StatusCode = StatusCodes.Status409Conflict;
return Content("The sport cannot be deleted because registrations exist.");
}
ctx.Sports.Remove(sport);
var deletedName = sport.Name;
await ctx.SaveChangesAsync();
Response.Headers[Constants.HtmxHeaders.Trigger] = JsonSerializer.Serialize(new Dictionary<string, object?>
{
[Constants.HtmxEvents.ShowToast] = new
{
variant = Constants.ToastVariants.Success,
title = Constants.ToastTitles.Success,
message = $"Sport '{deletedName}' was deleted successfully."
}
});
var viewModel = await BuildSportsListAsync(sieveModel);
return PartialView("_SportsList", viewModel);
}
private async Task<PagedList<SportViewModel>> BuildSportsListAsync(SieveModel sieveModel)
{
sieveModel.SetDefaultPagingAndSorting(pagingSettings.PageSize, "Name");
var normalizedFilters = sieveModel.Filters?.Trim() ?? string.Empty;
var nameFilter = SieveModelExtensions.ExtractFilterValue(normalizedFilters, "Name");
var baseQuery = ctx.Sports
.AsNoTracking()
.Select(s => new SportViewModel
{
Id = s.Id,
Name = s.Name
});
var totalCount = await baseQuery.CountAsync();
var filteredCount = string.IsNullOrWhiteSpace(normalizedFilters)
? totalCount
: await sieveProcessor
.Apply(
sieveModel,
baseQuery,
applyFiltering: true,
applySorting: false,
applyPagination: false)
.CountAsync();
var pagingInfo = new PagingInfo
{
FilteredItemsCount = filteredCount,
TotalItemsCount = totalCount,
ItemsPerPage = sieveModel.PageSize!.Value,
CurrentPage = sieveModel.Page!.Value,
Sorts = sieveModel.Sorts ?? "Name",
Filters = normalizedFilters,
NameFilter = nameFilter
};
if (pagingInfo.CurrentPage > pagingInfo.TotalPages)
{
pagingInfo.CurrentPage = pagingInfo.TotalPages;
sieveModel.Page = pagingInfo.CurrentPage;
}
var sports = await sieveProcessor
.Apply(sieveModel, baseQuery)
.ToListAsync();
return new PagedList<SportViewModel>(sports, pagingInfo);
}
}

View File

@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<UserSecretsId>PI</UserSecretsId>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>$(DefineConstants);MSSQL</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Web.LibraryManager.Build" Version="3.0.71" />
<PackageReference Include="Sieve" Version="2.5.5" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Events.EF\Events.EF.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,14 @@
using System.ComponentModel.DataAnnotations;
namespace Events.MVC.Models.Countries;
public class CountryTranslationViewModel
{
[Display(Name = "Language")]
[StringLength(10)]
public string LanguageCode { get; set; } = string.Empty;
[Display(Name = "Translation")]
[StringLength(200)]
public string Name { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,27 @@
using System.ComponentModel.DataAnnotations;
using Sieve.Attributes;
namespace Events.MVC.Models.Countries;
public class CountryViewModel
{
[Display(Name = "Code")]
[Required]
[StringLength(3, MinimumLength = 2)]
[Sieve(CanSort = true, CanFilter = true)]
public string Code { get; set; } = string.Empty;
[Display(Name = "Alpha-3")]
[Required]
[StringLength(3, MinimumLength = 3)]
[Sieve(CanSort = true, CanFilter = true)]
public string Alpha3 { get; set; } = string.Empty;
[Display(Name = "Name")]
[Required]
[StringLength(100)]
[Sieve(CanSort = true, CanFilter = true)]
public string Name { get; set; } = string.Empty;
public List<CountryTranslationViewModel> Translations { get; set; } = [];
}

View File

@@ -0,0 +1,8 @@
namespace Events.MVC.Models;
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}

View File

@@ -0,0 +1,26 @@
using System.ComponentModel.DataAnnotations;
using Sieve.Attributes;
namespace Events.MVC.Models.Events;
public class EventViewModel
{
[Display(Name = "ID")]
[Sieve(CanSort = true)]
public int Id { get; set; }
[Display(Name = "Name")]
[Required]
[StringLength(150)]
[Sieve(CanSort = true, CanFilter = true)]
public string Name { get; set; } = string.Empty;
[Display(Name = "Date")]
[DataType(DataType.Date)]
[Sieve(CanSort = true)]
public DateOnly EventDate { get; set; }
[Display(Name = "Participants")]
[Sieve(CanSort = true)]
public int ParticipantsCount { get; set; }
}

View File

@@ -0,0 +1,3 @@
namespace Events.MVC.Models;
public record PagedList<T>(List<T> Data, PagingInfo PagingInfo);

View File

@@ -0,0 +1,39 @@
namespace Events.MVC.Models;
public class PagingInfo
{
public int TotalItemsCount { get; set; }
public int FilteredItemsCount { get; set; }
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
public string Sorts { get; set; } = "Name";
public string Filters { get; set; } = string.Empty;
public string NameFilter { get; set; } = string.Empty;
public int TotalPages => Math.Max(1, (int)Math.Ceiling((decimal)FilteredItemsCount / ItemsPerPage));
public bool IsFiltered => !string.IsNullOrWhiteSpace(Filters);
public string ToggleSort(string propertyName)
{
return string.Equals(Sorts, propertyName, StringComparison.OrdinalIgnoreCase)
? $"-{propertyName}"
: propertyName;
}
public bool IsSortedBy(string propertyName)
{
return string.Equals(Sorts.TrimStart('-'), propertyName, StringComparison.OrdinalIgnoreCase);
}
public bool IsDescending()
{
return Sorts.StartsWith("-", StringComparison.Ordinal);
}
}

View File

@@ -0,0 +1,10 @@
namespace Events.MVC.Models;
public class PagingSettings
{
public const string SectionName = "Paging";
public int PageSize { get; set; } = 2;
public int PageOffset { get; set; } = 5;
}

View File

@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Events.MVC.Models.People;
public class PeoplePageViewModel
{
public PagedList<PersonViewModel> People { get; set; } = new([], new PagingInfo());
public List<SelectListItem> CountryOptions { get; set; } = [];
public string CountryFilter { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,100 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
using Sieve.Attributes;
namespace Events.MVC.Models.People;
public class PersonViewModel : IValidatableObject
{
[Sieve(CanSort = true)]
public int Id { get; set; }
[Display(Name = "First name")]
[StringLength(100)]
public string? FirstName { get; set; }
[Display(Name = "Last name")]
[StringLength(100)]
public string? LastName { get; set; }
[Display(Name = "First name (transcription)")]
[Required]
[StringLength(100)]
[Sieve(CanSort = true)]
public string FirstNameTranscription { get; set; } = string.Empty;
[Display(Name = "Last name (transcription)")]
[Required]
[StringLength(100)]
[Sieve(CanSort = true)]
public string LastNameTranscription { get; set; } = string.Empty;
[Display(Name = "Address")]
[StringLength(200)]
public string? AddressLine { get; set; }
[Display(Name = "Postal code")]
[StringLength(20)]
public string? PostalCode { get; set; }
[Display(Name = "City")]
[StringLength(100)]
public string? City { get; set; }
[Display(Name = "Address country")]
[StringLength(100)]
public string? AddressCountry { get; set; }
[Display(Name = "E-mail")]
[EmailAddress]
[StringLength(255)]
[Sieve(CanSort = true)]
public string? Email { get; set; }
[Display(Name = "Phone")]
[StringLength(50)]
public string? ContactPhone { get; set; }
[Display(Name = "Birth date")]
[Required]
[Sieve(CanSort = true)]
public DateOnly? BirthDate { get; set; }
[Display(Name = "Document number")]
[Required]
[StringLength(50)]
public string DocumentNumber { get; set; } = string.Empty;
[Display(Name = "Country")]
[Required]
[StringLength(3)]
[Sieve(CanFilter = true)]
public string CountryCode { get; set; } = string.Empty;
[Display(Name = "Full name")]
public string FullName { get; set; } = string.Empty;
[Display(Name = "Full name (transcription)")]
[Sieve(CanFilter = true)]
public string FullNameTranscription { get; set; } = string.Empty;
[Display(Name = "Country")]
[Sieve(CanSort = true)]
public string CountryName { get; set; } = string.Empty;
[Display(Name = "Registrations")]
[Sieve(CanSort = true)]
public int RegistrationsCount { get; set; }
public List<SelectListItem> CountryOptions { get; set; } = [];
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(Email) && string.IsNullOrWhiteSpace(ContactPhone))
{
yield return new ValidationResult(
Constants.Messages.EmailOrContactPhoneRequired,
new[] { nameof(Email), nameof(ContactPhone) });
}
}
}

View File

@@ -0,0 +1,52 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
using Sieve.Attributes;
namespace Events.MVC.Models.Registrations;
public class RegistrationViewModel
{
[Sieve(CanSort = true)]
public int Id { get; set; }
[Required]
[Range(1, int.MaxValue)]
public int EventId { get; set; }
[Display(Name = "Person")]
[Required]
[Range(1, int.MaxValue)]
public int PersonId { get; set; }
[Display(Name = "Sport")]
[Required]
[Range(1, int.MaxValue)]
public int SportId { get; set; }
[Display(Name = "Person")]
public string PersonLookup { get; set; } = string.Empty;
[Display(Name = "Person")]
[Sieve(CanSort = true, CanFilter = true)]
public string PersonName { get; set; } = string.Empty;
[Display(Name = "Transcription")]
[Sieve(CanFilter = true)]
public string PersonTranscription { get; set; } = string.Empty;
[Display(Name = "Country")]
[Sieve(CanFilter = true)]
public string CountryCode { get; set; } = string.Empty;
public string CountryName { get; set; } = string.Empty;
[Display(Name = "Sport")]
[Sieve(CanSort = true)]
public string SportName { get; set; } = string.Empty;
[Display(Name = "Registered at")]
[Sieve(CanSort = true)]
public DateTime RegisteredAt { get; set; }
public List<SelectListItem> SportOptions { get; set; } = [];
}

View File

@@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Events.MVC.Models.Registrations;
public class RegistrationsPageViewModel
{
public int SelectedEventId { get; set; }
public string SelectedEventName { get; set; } = string.Empty;
public List<SelectListItem> EventOptions { get; set; } = [];
public List<SelectListItem> CountryOptions { get; set; } = [];
public string CountryFilter { get; set; } = string.Empty;
public PagedList<RegistrationViewModel> Registrations { get; set; } = new([], new PagingInfo
{
ItemsPerPage = 10,
CurrentPage = 1
});
public RegistrationViewModel CreateModel { get; set; } = new();
public bool CanCreate { get; set; }
public string? CreateDisabledMessage { get; set; }
}

View File

@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
using Sieve.Attributes;
namespace Events.MVC.Models.Sports;
public class SportViewModel
{
[Sieve(CanSort = true)]
public int Id { get; set; }
[Display(Name = "Name")]
[Required]
[StringLength(100)]
[Sieve(CanSort = true, CanFilter = true)]
public string Name { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,42 @@
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Models;
using Events.MVC.Util.Middleware;
using Microsoft.EntityFrameworkCore;
using Sieve.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews(options =>
options.Filters.Add<ProblemDetailsForSqlException>());
#if POSTGRES
builder.Services.AddDbContext<EventsContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("EventsPostgres")));
#else
builder.Services.AddDbContext<EventsContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("EventsMssql")));
#endif
builder.Services.AddScoped<ISieveProcessor, SieveProcessor>();
builder.Services.Configure<PagingSettings>(builder.Configuration.GetSection(PagingSettings.SectionName));
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapDefaultControllerRoute();
app.Run();
public partial class Program;

View File

@@ -0,0 +1,14 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"Events.MVC": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7126;http://localhost:5200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,28 @@
using System.Text;
namespace Events.MVC.Util.Extensions
{
/// <summary>
/// Class with useful extensions for exceptions handling
/// </summary>
public static class ExceptionExtensions
{
/// <summary>
/// return complete hierarchy of an exception. It checks whether the exception has inner exception,
/// and if it has, then it appends inner exception message.
/// Then it looks for inner exception of the inner exceptions, and so on.
/// </summary>
/// <param name="exc">Exception which message hiearchy should be obtained</param>
/// <returns>String containing all exception hierarchy messages</returns>
public static string CompleteExceptionMessage(this Exception? exc)
{
StringBuilder sb = new();
while (exc != null)
{
sb.AppendLine(exc.Message);
exc = exc.InnerException;
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,23 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Text;
namespace Events.MVC.Util.Extensions
{
public static class ModelStateExtensions
{
public static string GetErrorsString(this ModelStateDictionary modelState)
{
StringBuilder sb = new StringBuilder();
foreach (var modelStateEntry in modelState)
{
if (modelStateEntry.Value.Errors.Count > 0)
{
string key = modelStateEntry.Key;
string error = string.Join(", ", modelStateEntry.Value.Errors.Select(e => e.ErrorMessage));
sb.AppendFormat("{0}: {1}; ", key, error);
}
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,59 @@
using Sieve.Models;
namespace Events.MVC.Util.Extensions;
public static class SieveModelExtensions
{
public static void SetDefaultPagingAndSorting(this SieveModel sieveModel, int defaultPageSize, string defaultSort)
{
sieveModel.Page ??= 1;
if (sieveModel.Page < 1)
{
sieveModel.Page = 1;
}
if (sieveModel.PageSize is null || sieveModel.PageSize <= 0)
{
sieveModel.PageSize = defaultPageSize;
}
if (string.IsNullOrWhiteSpace(sieveModel.Sorts))
{
sieveModel.Sorts = defaultSort;
}
}
public static string ExtractFilterValue(this SieveModel sieveModel, string propertyName)
{
var filters = sieveModel.Filters?.Trim() ?? string.Empty;
return ExtractFilterValue(filters, propertyName);
}
public static string ExtractFilterValue(string filters, string propertyName)
{
return ExtractFilterValue(filters, propertyName, "@=*", "@=");
}
public static string ExtractFilterValue(string filters, string propertyName, params string[] operators)
{
if (string.IsNullOrWhiteSpace(filters))
{
return string.Empty;
}
foreach (var filter in filters.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
foreach (var filterOperator in operators)
{
var prefix = $"{propertyName}{filterOperator}";
if (filter.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
return filter[prefix.Length..];
}
}
}
return string.Empty;
}
}

View File

@@ -0,0 +1,10 @@
namespace Events.MVC.Util.Extensions;
public static class StringExtensions
{
public static string? TrimToNull(this string? value)
{
var trimmed = value?.Trim();
return string.IsNullOrEmpty(trimmed) ? null : trimmed;
}
}

View File

@@ -0,0 +1,73 @@
using Events.MVC.Util.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Npgsql;
namespace Events.MVC.Util.Middleware;
public class ProblemDetailsForSqlException : ExceptionFilterAttribute
{
private readonly ILogger<ProblemDetailsForSqlException> logger;
public ProblemDetailsForSqlException(ILogger<ProblemDetailsForSqlException> logger)
{
this.logger = logger;
}
public override void OnException(ExceptionContext context)
{
Exception? exception = context.Exception;
PostgresException? postgresException = null;
while (exception is not null)
{
if (exception is PostgresException currentPostgresException)
{
postgresException = currentPostgresException;
break;
}
if (exception is DbUpdateException dbUpdateException && dbUpdateException.InnerException is not null)
{
exception = dbUpdateException.InnerException;
continue;
}
exception = exception.InnerException;
}
if (postgresException is null)
{
base.OnException(context);
return;
}
ProblemDetails problemDetails = postgresException.SqlState switch
{
PostgresErrorCodes.UniqueViolation => new ProblemDetails
{
Title = "Duplicate data",
Detail = "A record with the same data already exists."
},
PostgresErrorCodes.ForeignKeyViolation => new ProblemDetails
{
Title = "Related data",
Detail = "The operation is not allowed because related data exists."
},
_ => new ProblemDetails
{
Title = "Database error",
Detail = $"An error occurred while saving data to the database. {postgresException.MessageText}"
}
};
logger.LogDebug("Database exception: {message}", context.Exception.CompleteExceptionMessage());
context.ExceptionHandled = true;
context.Result = new ObjectResult(problemDetails)
{
ContentTypes = { "application/problem+json" },
StatusCode = StatusCodes.Status500InternalServerError
};
}
}

View File

@@ -0,0 +1,157 @@
using Events.MVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Options;
namespace Events.MVC.Util.TagHelpers;
[HtmlTargetElement("pager", Attributes = "page-info,page-action")]
public class PagerTagHelper : TagHelper
{
private readonly IUrlHelperFactory urlHelperFactory;
private readonly PagingSettings pagingSettings;
public PagerTagHelper(IUrlHelperFactory urlHelperFactory, IOptions<PagingSettings> pagingSettings)
{
this.urlHelperFactory = urlHelperFactory;
this.pagingSettings = pagingSettings.Value;
}
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContext { get; set; } = null!;
public PagingInfo PageInfo { get; set; } = new();
public string PageAction { get; set; } = string.Empty;
public string PageTitle { get; set; } = "Unesite broj stranice";
public string? PageTarget { get; set; }
public string? PageSwap { get; set; }
public bool PagePushUrl { get; set; }
[HtmlAttributeName(DictionaryAttributePrefix = "page-route-")]
public Dictionary<string, string> PageRouteValues { get; set; } = [];
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "nav";
output.Attributes.SetAttribute("aria-label", "Pager");
var paginationList = new TagBuilder("ul");
paginationList.AddCssClass("pagination");
paginationList.AddCssClass("mb-0");
var firstPageInRange = Math.Max(1, PageInfo.CurrentPage - pagingSettings.PageOffset);
var lastPageInRange = Math.Min(PageInfo.TotalPages, PageInfo.CurrentPage + pagingSettings.PageOffset);
if (firstPageInRange > 1)
{
paginationList.InnerHtml.AppendHtml(BuildListItemForPage(1, "1.."));
}
for (var page = firstPageInRange; page <= lastPageInRange; page++)
{
paginationList.InnerHtml.AppendHtml(
page == PageInfo.CurrentPage
? BuildListItemForCurrentPage(page)
: BuildListItemForPage(page));
}
if (lastPageInRange < PageInfo.TotalPages)
{
paginationList.InnerHtml.AppendHtml(BuildListItemForPage(PageInfo.TotalPages, $"..{PageInfo.TotalPages}"));
}
output.Content.AppendHtml(paginationList);
}
private TagBuilder BuildListItemForPage(int page)
{
return BuildListItemForPage(page, page.ToString());
}
private TagBuilder BuildListItemForPage(int page, string text)
{
var urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
var url = urlHelper.Action(PageAction, BuildRouteValues(page)) ?? string.Empty;
var anchor = new TagBuilder("a");
anchor.InnerHtml.Append(text);
anchor.Attributes["href"] = url;
anchor.AddCssClass("page-link");
ApplyHtmxAttributes(anchor, url);
var listItem = new TagBuilder("li");
listItem.AddCssClass("page-item");
listItem.InnerHtml.AppendHtml(anchor);
return listItem;
}
private TagBuilder BuildListItemForCurrentPage(int page)
{
var urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
var urlTemplate = urlHelper.Action(PageAction, BuildRouteValues("__page__")) ?? string.Empty;
var input = new TagBuilder("input");
input.Attributes["type"] = "text";
input.Attributes["value"] = page.ToString();
input.Attributes["data-current"] = page.ToString();
input.Attributes["data-min"] = "1";
input.Attributes["data-max"] = PageInfo.TotalPages.ToString();
input.Attributes["data-url-template"] = urlTemplate;
input.Attributes["title"] = PageTitle;
if (!string.IsNullOrWhiteSpace(PageTarget))
{
input.Attributes["data-target"] = PageTarget;
}
if (!string.IsNullOrWhiteSpace(PageSwap))
{
input.Attributes["data-swap"] = PageSwap;
}
input.Attributes["data-push-url"] = PagePushUrl.ToString().ToLowerInvariant();
input.AddCssClass("page-link");
input.AddCssClass("pagebox");
var listItem = new TagBuilder("li");
listItem.AddCssClass("page-item");
listItem.AddCssClass("active");
listItem.InnerHtml.AppendHtml(input);
return listItem;
}
private void ApplyHtmxAttributes(TagBuilder tagBuilder, string url)
{
if (string.IsNullOrWhiteSpace(PageTarget))
{
return;
}
tagBuilder.Attributes["hx-get"] = url;
tagBuilder.Attributes["hx-target"] = PageTarget;
tagBuilder.Attributes["hx-swap"] = string.IsNullOrWhiteSpace(PageSwap) ? "outerHTML" : PageSwap;
if (PagePushUrl)
{
tagBuilder.Attributes["hx-push-url"] = "true";
}
}
private RouteValueDictionary BuildRouteValues(object pageValue)
{
var routeValues = new RouteValueDictionary(PageRouteValues.ToDictionary(kvp => kvp.Key, kvp => (object?)kvp.Value));
routeValues["page"] = pageValue;
routeValues["pageSize"] = PageInfo.ItemsPerPage;
routeValues["sorts"] = PageInfo.Sorts;
routeValues["filters"] = PageInfo.Filters;
return routeValues;
}
}

View File

@@ -0,0 +1,171 @@
@model PagedList<Events.MVC.Models.Countries.CountryViewModel>
@{
ViewData[Constants.ViewDataKeys.Title] = "Countries";
ViewData[Constants.ViewDataKeys.HeaderActionLabel] = "New country";
ViewData[Constants.ViewDataKeys.HeaderActionTarget] = "#create-country-panel";
}
<div class="d-flex flex-column gap-4">
<section id="create-country-panel" class="collapse">
<div class="card border-0 shadow-sm">
<div class="card-body">
<h2 class="h5 mb-3">Add a new country</h2>
<div id="create-country-form">
<partial name="_CreateCountryForm" model='new Events.MVC.Models.Countries.CountryViewModel()' />
</div>
</div>
</div>
</section>
<partial name="_CountriesList" model="Model" />
</div>
@section Scripts {
<script>
var countryToastVariantError = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastVariants.Error));
var countryToastTitleError = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastTitles.Error));
function reindexCountryTranslations(editor) {
var prefix = editor.dataset.prefix || "Translations";
var rows = editor.querySelectorAll("[data-translation-row]");
rows.forEach(function (row, index) {
row.querySelectorAll("[data-field]").forEach(function (input) {
input.name = prefix + "[" + index + "]." + input.dataset.field;
});
});
editor.querySelectorAll("[data-remove-translation]").forEach(function (button) {
button.disabled = rows.length === 1 && button.hasAttribute("data-keep-one");
});
}
function ensureCountryTranslationNames(editor) {
editor.querySelectorAll("[data-translation-row]").forEach(function (row) {
row.querySelectorAll("input[name]").forEach(function (input) {
var match = input.name.match(/\.([^.]+)$/);
if (match) {
input.dataset.field = match[1];
}
});
});
reindexCountryTranslations(editor);
}
function validateCountryTranslations(form) {
var editor = form.querySelector("[data-country-translations]");
if (!editor) {
return true;
}
var rows = editor.querySelectorAll("[data-translation-row]");
for (var i = 0; i < rows.length; i++) {
var languageInput = rows[i].querySelector("[data-field='LanguageCode'], input[name$='.LanguageCode']");
var nameInput = rows[i].querySelector("[data-field='Name'], input[name$='.Name']");
var language = languageInput ? languageInput.value.trim() : "";
var name = nameInput ? nameInput.value.trim() : "";
if ((language && !name) || (!language && name)) {
showAppToast({
variant: countryToastVariantError,
title: countryToastTitleError,
message: "Every translation row must contain both a language code and a translation."
});
if (!language && languageInput) {
languageInput.focus();
} else if (nameInput) {
nameInput.focus();
}
return false;
}
}
return true;
}
document.body.addEventListener("click", function (event) {
var addButton = event.target.closest("[data-add-translation]");
if (addButton) {
var editor = addButton.closest("[data-country-translations]");
var template = editor ? editor.querySelector("[data-translation-template]") : null;
var list = editor ? editor.querySelector("[data-translation-list]") : null;
if (!editor || !template || !list) {
return;
}
list.insertAdjacentHTML("beforeend", template.innerHTML.trim());
reindexCountryTranslations(editor);
return;
}
var removeButton = event.target.closest("[data-remove-translation]");
if (removeButton) {
var row = removeButton.closest("[data-translation-row]");
var owner = removeButton.closest("[data-country-translations]");
var rows = owner ? owner.querySelectorAll("[data-translation-row]") : [];
if (!row || !owner || rows.length <= 1) {
return;
}
row.remove();
reindexCountryTranslations(owner);
}
});
document.body.addEventListener("submit", function (event) {
var form = event.target;
if (!(form instanceof HTMLFormElement)) {
return;
}
if (!form.matches("#create-country-form form, tr[id^='country-'] form")) {
return;
}
if (!validateCountryTranslations(form)) {
event.preventDefault();
}
});
document.body.addEventListener("htmx:afterSwap", function (event) {
if (event.target && (event.target.id === "create-country-form" || event.target.id === "countries-list" || event.target.id.indexOf("country-") === 0)) {
document.querySelectorAll("[data-country-translations]").forEach(ensureCountryTranslationNames);
}
});
document.querySelectorAll("[data-country-translations]").forEach(ensureCountryTranslationNames);
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.CountryCreated)), function () {
var form = document.querySelector("#create-country-form form");
if (form) {
form.reset();
}
var editor = document.querySelector("#create-country-form [data-country-translations]");
if (editor) {
var rows = editor.querySelectorAll("[data-translation-row]");
rows.forEach(function (row, index) {
if (index > 0) {
row.remove();
} else {
row.querySelectorAll("input").forEach(function (input) {
input.value = "";
});
}
});
reindexCountryTranslations(editor);
}
var panel = document.getElementById("create-country-panel");
if (panel && window.bootstrap) {
bootstrap.Collapse.getOrCreateInstance(panel).hide();
}
});
</script>
}

View File

@@ -0,0 +1,171 @@
@model PagedList<Events.MVC.Models.Countries.CountryViewModel>
<section class="card border-0 shadow-sm" id="countries-list">
<div class="card-body">
<div id="countries-state" class="d-none">
<input type="hidden" name="page" value="@Model.PagingInfo.CurrentPage" />
<input type="hidden" name="pageSize" value="@Model.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
</div>
<form
asp-action="Index"
method="get"
class="d-flex justify-content-between align-items-start gap-3 flex-wrap flex-lg-nowrap mb-4"
hx-get="@Url.Action("Index", "Countries")"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true"
onsubmit="var input=this.querySelector('[data-name-filter-input]'); var filters=this.querySelector('[name=filters]'); filters.value=input && input.value.trim() ? 'Name' + String.fromCharCode(64) + '=*' + input.value.trim() : ''; this.querySelector('[name=page]').value='1';">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="pageSize" value="@Model.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
<div class="d-flex align-items-center gap-3 pt-2">
<h2 class="h5 mb-0">Countries list</h2>
<span class="badge text-bg-light">@(Model.PagingInfo.IsFiltered ? $"{Model.PagingInfo.FilteredItemsCount} / {Model.PagingInfo.TotalItemsCount}" : Model.PagingInfo.TotalItemsCount.ToString())</span>
</div>
<div class="d-flex align-items-center gap-2 flex-nowrap ms-auto">
<input
id="countryNameFilter"
value="@Model.PagingInfo.NameFilter"
data-name-filter-input
class="form-control"
style="max-width: 18rem;"
placeholder="Search by country name"
aria-label="Filter by country name" />
<button type="submit" class="btn btn-outline-primary">Filter</button>
@if (Model.PagingInfo.IsFiltered)
{
<a
asp-action="Index"
asp-route-page="1"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.Sorts"
asp-route-filters=""
class="btn btn-outline-secondary"
hx-get="@Url.Action("Index", "Countries", new { page = 1, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.Sorts, filters = string.Empty })"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true">
Clear
</a>
}
</div>
</form>
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead>
<tr>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("Code")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Countries", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Code"), filters = Model.PagingInfo.Filters })"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true">
Code@(Model.PagingInfo.IsSortedBy("Code") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("Alpha3")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Countries", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Alpha3"), filters = Model.PagingInfo.Filters })"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true">
Alpha-3@(Model.PagingInfo.IsSortedBy("Alpha3") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("Name")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Countries", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Name"), filters = Model.PagingInfo.Filters })"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true">
Name@(Model.PagingInfo.IsSortedBy("Name") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th class="text-end"></th>
</tr>
</thead>
<tbody>
@if (Model.Data.Count == 0)
{
<tr>
<td colspan="4" class="text-body-secondary">No countries to display.</td>
</tr>
}
else
{
@foreach (var country in Model.Data)
{
<partial name="_CountryRow" model="country" />
}
}
</tbody>
</table>
</div>
<div class="d-flex justify-content-between align-items-center mt-4 gap-3 flex-wrap">
<div class="d-flex align-items-center gap-2 flex-wrap">
<small class="text-body-secondary">Page @Model.PagingInfo.CurrentPage of @Model.PagingInfo.TotalPages</small>
<form
asp-action="Index"
method="get"
class="d-inline-flex align-items-center gap-2"
hx-get="@Url.Action("Index", "Countries")"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-push-url="true">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
<select
name="pageSize"
class="form-select form-select-sm"
style="width: auto;"
aria-label="Items per page"
onchange="this.form.requestSubmit()">
@{
int[] pageSizeOptions = [10, 20, 50, 100];
}
@foreach (var option in pageSizeOptions)
{
<option value="@option" selected="@(Model.PagingInfo.ItemsPerPage == option)">@option</option>
}
</select>
</form>
</div>
<pager
page-info="@Model.PagingInfo"
page-action="Index"
page-title="Enter a page number and press Enter"
page-target="#countries-list"
page-swap="outerHTML"
page-push-url="true">
</pager>
</div>
</div>
</section>

View File

@@ -0,0 +1,44 @@
@model Events.MVC.Models.Countries.CountryViewModel
<tr id="country-@Model.Code">
<td>@Model.Code</td>
<td colspan="3">
<form
asp-action="Edit"
asp-route-id="@Model.Code"
method="post"
hx-post="@Url.Action("Edit", "Countries", new { id = Model.Code })"
hx-target="#country-@Model.Code"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="Code" type="hidden" />
<div asp-validation-summary="ModelOnly" class="text-danger small mb-2"></div>
<div class="row g-2 align-items-start">
<div class="col-sm-3 col-lg-2">
<input asp-for="Alpha3" class="form-control text-uppercase" />
<span asp-validation-for="Alpha3" class="text-danger small"></span>
</div>
<div class="col-lg-5">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger small"></span>
</div>
<div class="col-md-auto">
<button type="submit" class="btn btn-sm btn-primary">Save</button>
</div>
<div class="col-md-auto">
<button
type="button"
class="btn btn-sm btn-outline-secondary"
hx-get="@Url.Action("Row", "Countries", new { id = Model.Code })"
hx-target="#country-@Model.Code"
hx-swap="outerHTML">
Cancel
</button>
</div>
<div class="col-12">
<partial name="_CountryTranslationsEditor" model="Model.Translations" view-data='new ViewDataDictionary(ViewData) { ["Prefix"] = "Translations" }' />
</div>
</div>
</form>
</td>
</tr>

View File

@@ -0,0 +1,33 @@
@model Events.MVC.Models.Countries.CountryViewModel
<tr id="country-@Model.Code">
<td>@Model.Code</td>
<td>@Model.Alpha3</td>
<td>@Model.Name</td>
<td class="text-end">
<div class="d-inline-flex gap-2">
<button
type="button"
class="btn btn-sm btn-outline-primary"
hx-get="@Url.Action("EditRow", "Countries", new { id = Model.Code })"
hx-target="#country-@Model.Code"
hx-swap="outerHTML">
Edit
</button>
<form
asp-action="Delete"
asp-route-id="@Model.Code"
method="post"
class="d-inline"
hx-post="@Url.Action("Delete", "Countries", new { id = Model.Code })"
hx-include="#countries-state"
hx-target="#countries-list"
hx-swap="outerHTML"
hx-confirm="Delete country '@Model.Name'?">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</div>
</td>
</tr>

View File

@@ -0,0 +1,47 @@
@model IList<Events.MVC.Models.Countries.CountryTranslationViewModel>
@{
var prefix = (string?)ViewData[Constants.ViewDataKeys.Prefix] ?? "Translations";
var canRemoveRows = (bool?)ViewData[Constants.ViewDataKeys.CanRemoveRows] ?? true;
var rows = Model.Count == 0 ? [new Events.MVC.Models.Countries.CountryTranslationViewModel()] : Model;
}
<div class="country-translations-editor" data-country-translations data-prefix="@prefix">
<div class="d-flex justify-content-between align-items-center gap-2 mb-2">
<span class="form-label mb-0">Translations</span>
<button type="button" class="btn btn-sm btn-outline-secondary" data-add-translation>Add translation</button>
</div>
<div class="d-flex flex-column gap-2" data-translation-list>
@for (var i = 0; i < rows.Count; i++)
{
<div class="row g-2 align-items-start" data-translation-row>
<div class="col-sm-3">
<input name="@($"{prefix}[{i}].LanguageCode")" value="@rows[i].LanguageCode" class="form-control" placeholder="en" />
</div>
<div class="col-sm-7">
<input name="@($"{prefix}[{i}].Name")" value="@rows[i].Name" class="form-control" placeholder="English name" />
</div>
<div class="col-sm-2 d-grid">
<button type="button" class="btn btn-outline-danger" data-remove-translation @(!canRemoveRows ? "data-keep-one" : null) @(rows.Count == 1 && !canRemoveRows ? "disabled" : null)>Remove</button>
</div>
</div>
}
</div>
<template data-translation-template>
<div class="row g-2 align-items-start" data-translation-row>
<div class="col-sm-3">
<input class="form-control" data-field="LanguageCode" placeholder="en" />
</div>
<div class="col-sm-7">
<input class="form-control" data-field="Name" placeholder="English name" />
</div>
<div class="col-sm-2 d-grid">
<button type="button" class="btn btn-outline-danger" data-remove-translation @(!canRemoveRows ? "data-keep-one" : null)>Remove</button>
</div>
</div>
</template>
<div class="form-text">Enter a language code such as <code>en</code>, <code>de</code>, or <code>hr</code>.</div>
</div>

View File

@@ -0,0 +1,36 @@
@model Events.MVC.Models.Countries.CountryViewModel
<form
asp-action="Create"
method="post"
hx-post="@Url.Action("Create", "Countries")"
hx-include="#countries-state"
hx-target="#countries-list"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<div asp-validation-summary="ModelOnly" class="text-danger small mb-3"></div>
<div class="row g-3 align-items-end">
<div class="col-sm-3 col-lg-2">
<label asp-for="Code" class="form-label"></label>
<input asp-for="Code" class="form-control text-uppercase" />
<span asp-validation-for="Code" class="text-danger small"></span>
</div>
<div class="col-sm-3 col-lg-2">
<label asp-for="Alpha3" class="form-label"></label>
<input asp-for="Alpha3" class="form-control text-uppercase" />
<span asp-validation-for="Alpha3" class="text-danger small"></span>
</div>
<div class="col-lg-5">
<label asp-for="Name" class="form-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger small"></span>
</div>
<div class="col-sm-auto">
<button type="submit" class="btn btn-primary">Add country</button>
</div>
</div>
<div class="mt-4">
<partial name="_CountryTranslationsEditor" model="Model.Translations" view-data='new ViewDataDictionary(ViewData) { ["Prefix"] = "Translations", ["CanRemoveRows"] = false }' />
</div>
</form>

View File

@@ -0,0 +1,43 @@
@model PagedList<Events.MVC.Models.Events.EventViewModel>
@{
ViewData[Constants.ViewDataKeys.Title] = "Events";
ViewData[Constants.ViewDataKeys.HeaderActionLabel] = "New event";
ViewData[Constants.ViewDataKeys.HeaderActionTarget] = "#create-event-panel";
}
<div class="d-flex flex-column gap-4">
<section id="create-event-panel" class="collapse">
<div class="card border-0 shadow-sm">
<div class="card-body">
<h2 class="h5 mb-3">Add a new event</h2>
<div id="create-event-form">
<partial name="_CreateEventForm" model='new Events.MVC.Models.Events.EventViewModel { EventDate = DateOnly.FromDateTime(DateTime.Today) }' />
</div>
</div>
</div>
</section>
<partial name="_EventsList" model="Model" />
</div>
@section Scripts {
<script>
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.EventCreated)), function () {
var form = document.querySelector("#create-event-form form");
if (form) {
form.reset();
}
var dateInput = document.querySelector("#create-event-form input[type='date']");
if (dateInput && !dateInput.value) {
dateInput.value = new Date().toISOString().split("T")[0];
}
var panel = document.getElementById("create-event-panel");
if (panel && window.bootstrap) {
bootstrap.Collapse.getOrCreateInstance(panel).hide();
}
});
</script>
}

View File

@@ -0,0 +1,26 @@
@model Events.MVC.Models.Events.EventViewModel
<form
asp-action="Create"
method="post"
hx-post="@Url.Action("Create", "Events")"
hx-include="#events-state"
hx-target="#events-list"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<div class="row g-3 align-items-end">
<div class="col-lg-5">
<label asp-for="Name" class="form-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger small"></span>
</div>
<div class="col-sm-4 col-lg-3">
<label asp-for="EventDate" class="form-label"></label>
<input asp-for="EventDate" class="form-control" type="date" />
<span asp-validation-for="EventDate" class="text-danger small"></span>
</div>
<div class="col-sm-auto">
<button type="submit" class="btn btn-primary">Add event</button>
</div>
</div>
</form>

View File

@@ -0,0 +1,40 @@
@model Events.MVC.Models.Events.EventViewModel
<tr id="event-@Model.Id">
<td>@Model.Id</td>
<td colspan="4">
<form
asp-action="Edit"
asp-route-id="@Model.Id"
method="post"
hx-post="@Url.Action("Edit", "Events", new { id = Model.Id })"
hx-target="#event-@Model.Id"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="Id" type="hidden" />
<div class="row g-2 align-items-start">
<div class="col-lg-5">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger small"></span>
</div>
<div class="col-sm-4 col-lg-3">
<input asp-for="EventDate" class="form-control" type="date" />
<span asp-validation-for="EventDate" class="text-danger small"></span>
</div>
<div class="col-md-auto">
<button type="submit" class="btn btn-sm btn-primary">Save</button>
</div>
<div class="col-md-auto">
<button
type="button"
class="btn btn-sm btn-outline-secondary"
hx-get="@Url.Action("Row", "Events", new { id = Model.Id })"
hx-target="#event-@Model.Id"
hx-swap="outerHTML">
Cancel
</button>
</div>
</div>
</form>
</td>
</tr>

View File

@@ -0,0 +1,42 @@
@model Events.MVC.Models.Events.EventViewModel
<tr id="event-@Model.Id">
<td>@Model.Id</td>
<td>@Model.Name</td>
<td>@Model.EventDate.ToString("dd.MM.yyyy.")</td>
<td>@Model.ParticipantsCount</td>
<td class="text-end">
<div class="d-inline-flex gap-2">
<a
asp-controller="Registrations"
asp-action="Index"
asp-route-eventId="@Model.Id"
class="btn btn-sm btn-outline-secondary">
Registrations
</a>
<button
type="button"
class="btn btn-sm btn-outline-primary"
hx-get="@Url.Action("EditRow", "Events", new { id = Model.Id })"
hx-target="#event-@Model.Id"
hx-swap="outerHTML">
Edit
</button>
<form
asp-action="Delete"
asp-route-id="@Model.Id"
method="post"
class="d-inline"
hx-post="@Url.Action("Delete", "Events", new { id = Model.Id })"
hx-include="#events-state"
hx-target="#events-list"
hx-swap="outerHTML"
hx-confirm="Delete event '@Model.Name'?">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</div>
</td>
</tr>

View File

@@ -0,0 +1,186 @@
@model PagedList<Events.MVC.Models.Events.EventViewModel>
<section class="card border-0 shadow-sm" id="events-list">
<div class="card-body">
<div id="events-state" class="d-none">
<input type="hidden" name="page" value="@Model.PagingInfo.CurrentPage" />
<input type="hidden" name="pageSize" value="@Model.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
</div>
<form
asp-action="Index"
method="get"
class="d-flex justify-content-between align-items-start gap-3 flex-wrap flex-lg-nowrap mb-4"
hx-get="@Url.Action("Index", "Events")"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true"
onsubmit="var input=this.querySelector('[data-name-filter-input]'); var filters=this.querySelector('[name=filters]'); filters.value=input && input.value.trim() ? 'Name' + String.fromCharCode(64) + '=*' + input.value.trim() : ''; this.querySelector('[name=page]').value='1';">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="pageSize" value="@Model.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
<div class="d-flex align-items-center gap-3 pt-2">
<h2 class="h5 mb-0">Events list</h2>
<span class="badge text-bg-light">@(Model.PagingInfo.IsFiltered ? $"{Model.PagingInfo.FilteredItemsCount} / {Model.PagingInfo.TotalItemsCount}" : Model.PagingInfo.TotalItemsCount.ToString())</span>
</div>
<div class="d-flex align-items-center gap-2 flex-nowrap ms-auto">
<input
id="eventNameFilter"
value="@Model.PagingInfo.NameFilter"
data-name-filter-input
class="form-control"
style="max-width: 18rem;"
placeholder="Search by event name"
aria-label="Filter by event name" />
<button type="submit" class="btn btn-outline-primary">Filter</button>
@if (Model.PagingInfo.IsFiltered)
{
<a
asp-action="Index"
asp-route-page="1"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.Sorts"
asp-route-filters=""
class="btn btn-outline-secondary"
hx-get="@Url.Action("Index", "Events", new { page = 1, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.Sorts, filters = string.Empty })"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true">
Clear
</a>
}
</div>
</form>
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead>
<tr>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("Id")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Events", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Id"), filters = Model.PagingInfo.Filters })"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true">
ID@(Model.PagingInfo.IsSortedBy("Id") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("Name")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Events", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Name"), filters = Model.PagingInfo.Filters })"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true">
Name@(Model.PagingInfo.IsSortedBy("Name") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("EventDate")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Events", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("EventDate"), filters = Model.PagingInfo.Filters })"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true">
Date@(Model.PagingInfo.IsSortedBy("EventDate") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("ParticipantsCount")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Events", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("ParticipantsCount"), filters = Model.PagingInfo.Filters })"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true">
Participants@(Model.PagingInfo.IsSortedBy("ParticipantsCount") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th class="text-end"></th>
</tr>
</thead>
<tbody>
@if (Model.Data.Count == 0)
{
<tr>
<td colspan="5" class="text-body-secondary">No events to display.</td>
</tr>
}
else
{
@foreach (var eventItem in Model.Data)
{
<partial name="_EventRow" model="eventItem" />
}
}
</tbody>
</table>
</div>
<div class="d-flex justify-content-between align-items-center mt-4 gap-3 flex-wrap">
<div class="d-flex align-items-center gap-2 flex-wrap">
<small class="text-body-secondary">Page @Model.PagingInfo.CurrentPage of @Model.PagingInfo.TotalPages</small>
<form
asp-action="Index"
method="get"
class="d-inline-flex align-items-center gap-2"
hx-get="@Url.Action("Index", "Events")"
hx-target="#events-list"
hx-swap="outerHTML"
hx-push-url="true">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
<select
name="pageSize"
class="form-select form-select-sm"
style="width: auto;"
aria-label="Items per page"
onchange="this.form.requestSubmit()">
@{
int[] pageSizeOptions = [10, 20, 50, 100];
}
@foreach (var option in pageSizeOptions)
{
<option value="@option" selected="@(Model.PagingInfo.ItemsPerPage == option)">@option</option>
}
</select>
</form>
</div>
<pager
page-info="@Model.PagingInfo"
page-action="Index"
page-title="Enter a page number and press Enter"
page-target="#events-list"
page-swap="outerHTML"
page-push-url="true">
</pager>
</div>
</div>
</section>

View File

@@ -0,0 +1,15 @@
@model Events.MVC.Models.ErrorViewModel
@{
ViewData[Constants.ViewDataKeys.Title] = Constants.ToastTitles.Error;
}
<div class="card border-0 shadow-sm">
<div class="card-body">
<h1 class="h4">An error occurred.</h1>
@if (Model.ShowRequestId)
{
<p class="text-body-secondary mb-0">Request ID: <code>@Model.RequestId</code></p>
}
</div>
</div>

View File

@@ -0,0 +1,10 @@
@{
ViewData[Constants.ViewDataKeys.Title] = "Home";
}
<section class="card border-0 shadow-sm">
<div class="card-body p-4">
<h1 class="h3 mb-3">Events</h1>
<p class="mb-0">This sample demonstrates an ASP.NET Core MVC application for managing sports events, countries, people, and registrations using htmx.</p>
</div>
</section>

View File

@@ -0,0 +1,38 @@
@model Events.MVC.Models.People.PeoplePageViewModel
@{
ViewData[Constants.ViewDataKeys.Title] = "People";
ViewData[Constants.ViewDataKeys.HeaderActionLabel] = "New person";
ViewData[Constants.ViewDataKeys.HeaderActionTarget] = "#create-person-panel";
}
<div class="d-flex flex-column gap-4">
<section id="create-person-panel" class="collapse">
<div class="card border-0 shadow-sm">
<div class="card-body">
<h2 class="h5 mb-3">Add a new person</h2>
<div id="create-person-form">
<partial name="_CreatePersonForm" model='(Events.MVC.Models.People.PersonViewModel)ViewData[Constants.ViewDataKeys.CreatePersonModel]!' />
</div>
</div>
</div>
</section>
<partial name="_PeopleList" model="Model" />
</div>
@section Scripts {
<script>
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.PersonCreated)), function () {
var form = document.querySelector("#create-person-form form");
if (form) {
form.reset();
}
var panel = document.getElementById("create-person-panel");
if (panel && window.bootstrap) {
bootstrap.Collapse.getOrCreateInstance(panel).hide();
}
});
</script>
}

View File

@@ -0,0 +1,84 @@
@model Events.MVC.Models.People.PersonViewModel
<form
asp-action="Create"
method="post"
hx-post="@Url.Action("Create", "People")"
hx-include="#people-state"
hx-target="#people-list"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<div asp-validation-summary="ModelOnly" class="text-danger small mb-3"></div>
<div class="row g-3 align-items-end">
<div class="col-md-3">
<label asp-for="FirstName" class="form-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="LastName" class="form-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="FirstNameTranscription" class="form-label"></label>
<input asp-for="FirstNameTranscription" class="form-control" />
<span asp-validation-for="FirstNameTranscription" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="LastNameTranscription" class="form-label"></label>
<input asp-for="LastNameTranscription" class="form-control" />
<span asp-validation-for="LastNameTranscription" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="Email" class="form-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="ContactPhone" class="form-label"></label>
<input asp-for="ContactPhone" class="form-control" />
<span asp-validation-for="ContactPhone" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="BirthDate" class="form-label"></label>
<input asp-for="BirthDate" type="date" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger small"></span>
</div>
<div class="col-md-2">
<label asp-for="CountryCode" class="form-label"></label>
<select asp-for="CountryCode" asp-items="Model.CountryOptions" class="form-select">
<option value="">Select a country</option>
</select>
<span asp-validation-for="CountryCode" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="DocumentNumber" class="form-label"></label>
<input asp-for="DocumentNumber" class="form-control" />
<span asp-validation-for="DocumentNumber" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="AddressLine" class="form-label"></label>
<input asp-for="AddressLine" class="form-control" />
<span asp-validation-for="AddressLine" class="text-danger small"></span>
</div>
<div class="col-md-2">
<label asp-for="PostalCode" class="form-label"></label>
<input asp-for="PostalCode" class="form-control" />
<span asp-validation-for="PostalCode" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="City" class="form-label"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="AddressCountry" class="form-label"></label>
<input asp-for="AddressCountry" class="form-control" />
<span asp-validation-for="AddressCountry" class="text-danger small"></span>
</div>
<div class="col-sm-auto">
<button type="submit" class="btn btn-primary">Add person</button>
</div>
</div>
</form>

View File

@@ -0,0 +1,150 @@
@model Events.MVC.Models.People.PeoplePageViewModel
<section class="card border-0 shadow-sm" id="people-list">
<div class="card-body">
<div id="people-state" class="d-none">
<input type="hidden" name="page" value="@Model.People.PagingInfo.CurrentPage" />
<input type="hidden" name="pageSize" value="@Model.People.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.People.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.People.PagingInfo.Filters" />
<input type="hidden" name="countryFilter" value="@Model.CountryFilter" />
</div>
<form
asp-action="Index"
method="get"
class="d-flex justify-content-between align-items-start gap-3 flex-wrap flex-lg-nowrap mb-4"
hx-get="@Url.Action("Index", "People")"
hx-target="#people-list"
hx-swap="outerHTML"
hx-push-url="true"
onsubmit="var input=this.querySelector('[data-name-filter-input]'); var country=this.querySelector('[name=countryFilter]'); var filters=this.querySelector('[name=filters]'); var values=[]; if (input && input.value.trim()) { values.push('FullNameTranscription' + String.fromCharCode(64) + '=*' + input.value.trim()); } if (country && country.value) { values.push('CountryCode==' + country.value); } filters.value=values.join(','); this.querySelector('[name=page]').value='1';">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="pageSize" value="@Model.People.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.People.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.People.PagingInfo.Filters" />
<div class="d-flex align-items-center gap-3 pt-2">
<h2 class="h5 mb-0">People list</h2>
<span class="badge text-bg-light">@(Model.People.PagingInfo.IsFiltered ? $"{Model.People.PagingInfo.FilteredItemsCount} / {Model.People.PagingInfo.TotalItemsCount}" : Model.People.PagingInfo.TotalItemsCount.ToString())</span>
</div>
<div class="d-flex align-items-center gap-2 flex-nowrap ms-auto">
<input
id="personNameFilter"
value="@Model.People.PagingInfo.NameFilter"
data-name-filter-input
class="form-control"
style="max-width: 18rem;"
placeholder="Search by transcribed full name"
aria-label="Filter by transcribed full name" />
<select name="countryFilter" asp-items="Model.CountryOptions" class="form-select" style="max-width: 14rem;" aria-label="Filter by country">
<option value="">All countries</option>
</select>
<button type="submit" class="btn btn-outline-primary">Filter</button>
@if (Model.People.PagingInfo.IsFiltered)
{
<a
asp-action="Index"
asp-route-page="1"
asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.People.PagingInfo.Sorts"
asp-route-filters=""
class="btn btn-outline-secondary"
hx-get="@Url.Action("Index", "People", new { page = 1, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.Sorts, filters = string.Empty })"
hx-target="#people-list"
hx-swap="outerHTML"
hx-push-url="true">
Clear
</a>
}
</div>
</form>
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead>
<tr>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("Id")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("Id"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
ID@(Model.People.PagingInfo.IsSortedBy("Id") ? (Model.People.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("FirstNameTranscription")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("FirstNameTranscription"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
First name@(Model.People.PagingInfo.IsSortedBy("FirstNameTranscription") ? (Model.People.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("LastNameTranscription")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("LastNameTranscription"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
Last name@(Model.People.PagingInfo.IsSortedBy("LastNameTranscription") ? (Model.People.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th></th>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("BirthDate")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("BirthDate"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
Birth date@(Model.People.PagingInfo.IsSortedBy("BirthDate") ? (Model.People.PagingInfo.IsDescending() ? " v" : " ^") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("CountryName")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("CountryName"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
Country@(Model.People.PagingInfo.IsSortedBy("CountryName") ? (Model.People.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-page="@Model.People.PagingInfo.CurrentPage" asp-route-pageSize="@Model.People.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.People.PagingInfo.ToggleSort("RegistrationsCount")" asp-route-filters="@Model.People.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "People", new { page = Model.People.PagingInfo.CurrentPage, pageSize = Model.People.PagingInfo.ItemsPerPage, sorts = Model.People.PagingInfo.ToggleSort("RegistrationsCount"), filters = Model.People.PagingInfo.Filters })" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
Registrations@(Model.People.PagingInfo.IsSortedBy("RegistrationsCount") ? (Model.People.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th class="text-end"></th>
</tr>
</thead>
<tbody>
@if (Model.People.Data.Count == 0)
{
<tr>
<td colspan="8" class="text-body-secondary">No people to display.</td>
</tr>
}
else
{
@foreach (var person in Model.People.Data)
{
<partial name="_PersonRow" model="person" />
}
}
</tbody>
</table>
</div>
<div class="d-flex justify-content-between align-items-center mt-4 gap-3 flex-wrap">
<div class="d-flex align-items-center gap-2 flex-wrap">
<small class="text-body-secondary">Page @Model.People.PagingInfo.CurrentPage of @Model.People.PagingInfo.TotalPages</small>
<form asp-action="Index" method="get" class="d-inline-flex align-items-center gap-2" hx-get="@Url.Action("Index", "People")" hx-target="#people-list" hx-swap="outerHTML" hx-push-url="true">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="sorts" value="@Model.People.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.People.PagingInfo.Filters" />
<select name="pageSize" class="form-select form-select-sm" style="width: auto;" aria-label="Items per page" onchange="this.form.requestSubmit()">
@{
int[] pageSizeOptions = [10, 20, 50, 100];
}
@foreach (var option in pageSizeOptions)
{
<option value="@option" selected="@(Model.People.PagingInfo.ItemsPerPage == option)">@option</option>
}
</select>
</form>
</div>
<pager
page-info="@Model.People.PagingInfo"
page-action="Index"
page-title="Enter a page number and press Enter"
page-target="#people-list"
page-swap="outerHTML"
page-push-url="true">
</pager>
</div>
</div>
</section>

View File

@@ -0,0 +1,100 @@
@model Events.MVC.Models.People.PersonViewModel
<tr id="person-@Model.Id">
<td>@Model.Id</td>
<td colspan="7">
<form
asp-action="Edit"
asp-route-id="@Model.Id"
method="post"
hx-post="@Url.Action("Edit", "People", new { id = Model.Id })"
hx-target="#person-@Model.Id"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="Id" type="hidden" />
<div asp-validation-summary="ModelOnly" class="text-danger small mb-2"></div>
<div class="row g-2 align-items-start">
<div class="col-md-3">
<label asp-for="FirstName" class="form-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="LastName" class="form-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="FirstNameTranscription" class="form-label"></label>
<input asp-for="FirstNameTranscription" class="form-control" />
<span asp-validation-for="FirstNameTranscription" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="LastNameTranscription" class="form-label"></label>
<input asp-for="LastNameTranscription" class="form-control" />
<span asp-validation-for="LastNameTranscription" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="Email" class="form-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="ContactPhone" class="form-label"></label>
<input asp-for="ContactPhone" class="form-control" />
<span asp-validation-for="ContactPhone" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="BirthDate" class="form-label"></label>
<input asp-for="BirthDate" type="date" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger small"></span>
</div>
<div class="col-md-2">
<label asp-for="CountryCode" class="form-label"></label>
<select asp-for="CountryCode" asp-items="Model.CountryOptions" class="form-select">
<option value="">Select a country</option>
</select>
<span asp-validation-for="CountryCode" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="DocumentNumber" class="form-label"></label>
<input asp-for="DocumentNumber" class="form-control" />
<span asp-validation-for="DocumentNumber" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="AddressLine" class="form-label"></label>
<input asp-for="AddressLine" class="form-control" />
<span asp-validation-for="AddressLine" class="text-danger small"></span>
</div>
<div class="col-md-2">
<label asp-for="PostalCode" class="form-label"></label>
<input asp-for="PostalCode" class="form-control" />
<span asp-validation-for="PostalCode" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="City" class="form-label"></label>
<input asp-for="City" class="form-control" />
<span asp-validation-for="City" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="AddressCountry" class="form-label"></label>
<input asp-for="AddressCountry" class="form-control" />
<span asp-validation-for="AddressCountry" class="text-danger small"></span>
</div>
<div class="col-md-auto">
<button type="submit" class="btn btn-sm btn-primary">Save</button>
</div>
<div class="col-md-auto">
<button
type="button"
class="btn btn-sm btn-outline-secondary"
hx-get="@Url.Action("Row", "People", new { id = Model.Id })"
hx-target="#person-@Model.Id"
hx-swap="outerHTML">
Cancel
</button>
</div>
</div>
</form>
</td>
</tr>

View File

@@ -0,0 +1,37 @@
@model Events.MVC.Models.People.PersonViewModel
<tr id="person-@Model.Id">
<td>@Model.Id</td>
<td>@Model.FirstNameTranscription</td>
<td>@Model.LastNameTranscription</td>
<td>@Model.FullName</td>
<td>@Model.BirthDate?.ToString("dd.MM.yyyy.")</td>
<td>@Model.CountryName</td>
<td>@Model.RegistrationsCount</td>
<td class="text-end">
<div class="d-inline-flex gap-2">
<button
type="button"
class="btn btn-sm btn-outline-primary"
hx-get="@Url.Action("EditRow", "People", new { id = Model.Id })"
hx-target="#person-@Model.Id"
hx-swap="outerHTML">
Edit
</button>
<form
asp-action="Delete"
asp-route-id="@Model.Id"
method="post"
class="d-inline"
hx-post="@Url.Action("Delete", "People", new { id = Model.Id })"
hx-include="#people-state"
hx-target="#people-list"
hx-swap="outerHTML"
hx-confirm="Delete person '@Model.FullName'?">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</div>
</td>
</tr>

View File

@@ -0,0 +1,85 @@
@model Events.MVC.Models.Registrations.RegistrationsPageViewModel
@{
ViewData[Constants.ViewDataKeys.Title] = "Registrations";
ViewData[Constants.ViewDataKeys.HeaderActionLabel] = "New registration";
ViewData[Constants.ViewDataKeys.HeaderActionTarget] = "#create-registration-panel";
}
<partial name="_RegistrationsPanel" model="Model" />
@section Scripts {
<script>
function clearRegistrationSuggestions(scope) {
(scope || document).querySelectorAll(".registration-person-suggestions").forEach(function (container) {
container.innerHTML = "";
});
}
function syncRegistrationPersonLookup(input) {
var form = input.closest("form");
var hiddenInput = form ? form.querySelector("input[name='PersonId']") : null;
if (!hiddenInput) {
return;
}
hiddenInput.value = "";
}
document.body.addEventListener("input", function (event) {
if (event.target.matches("[data-person-autocomplete]")) {
syncRegistrationPersonLookup(event.target);
}
});
document.body.addEventListener("change", function (event) {
if (event.target.matches("[data-person-autocomplete]")) {
syncRegistrationPersonLookup(event.target);
}
});
document.body.addEventListener("click", function (event) {
var suggestion = event.target.closest("[data-person-suggestion]");
if (suggestion) {
var container = suggestion.closest(".registration-person-suggestions");
var wrapper = container ? container.closest(".registration-person-autocomplete") : null;
var input = wrapper ? wrapper.querySelector("[data-person-autocomplete]") : null;
var form = wrapper ? wrapper.closest("form") : null;
var hiddenInput = form ? form.querySelector("input[name='PersonId']") : null;
if (input && hiddenInput) {
input.value = suggestion.dataset.personLabel || "";
hiddenInput.value = suggestion.dataset.personId || "";
}
if (container) {
container.innerHTML = "";
}
return;
}
if (!event.target.closest(".registration-person-autocomplete")) {
clearRegistrationSuggestions(document);
}
});
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.RegistrationCreated)), function () {
var form = document.querySelector("#create-registration-form form");
if (form) {
form.reset();
}
var eventInput = document.querySelector("#create-registration-form input[name='EventId']");
var stateEventInput = document.querySelector("#registrations-state input[name='eventId']");
if (eventInput && stateEventInput) {
eventInput.value = stateEventInput.value;
}
clearRegistrationSuggestions(document.getElementById("create-registration-form"));
var panel = document.getElementById("create-registration-panel");
if (panel && window.bootstrap) {
bootstrap.Collapse.getOrCreateInstance(panel).hide();
}
});
</script>
}

View File

@@ -0,0 +1,44 @@
@model Events.MVC.Models.Registrations.RegistrationViewModel
<form
asp-action="Create"
method="post"
hx-post="@Url.Action("Create", "Registrations")"
hx-include="#registrations-state"
hx-target="#registrations-panel"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="EventId" type="hidden" />
<div asp-validation-summary="ModelOnly" class="text-danger small mb-3"></div>
<div class="row g-3 align-items-end">
<div class="col-md-5">
<label asp-for="PersonId" class="form-label"></label>
<input asp-for="PersonId" type="hidden" />
<div class="position-relative registration-person-autocomplete">
<input
asp-for="PersonLookup"
class="form-control"
placeholder="Start typing a person's name"
autocomplete="off"
data-person-autocomplete
hx-get="@Url.Action("PersonSuggestions", "Registrations")"
hx-include="#registrations-state"
hx-trigger="input changed delay:250ms"
hx-target="#registration-person-suggestions-create"
hx-swap="innerHTML" />
<div id="registration-person-suggestions-create" class="list-group registration-person-suggestions"></div>
</div>
<span asp-validation-for="PersonId" class="text-danger small"></span>
</div>
<div class="col-md-5">
<label asp-for="SportId" class="form-label"></label>
<select asp-for="SportId" asp-items="Model.SportOptions" class="form-select">
<option value="">Select a sport</option>
</select>
<span asp-validation-for="SportId" class="text-danger small"></span>
</div>
<div class="col-sm-auto">
<button type="submit" class="btn btn-primary">Add registration</button>
</div>
</div>
</form>

View File

@@ -0,0 +1,23 @@
@model IReadOnlyList<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>
@if (Model.Count > 0)
{
@foreach (var person in Model)
{
var parts = person.Text.Split('|', 2);
var originalName = parts[0];
var transcription = parts.Length > 1 ? parts[1] : string.Empty;
<button
type="button"
class="list-group-item list-group-item-action"
data-person-suggestion
data-person-id="@person.Value"
data-person-label="@originalName (@transcription)">
<span class="d-block">@originalName</span>
@if (!string.IsNullOrWhiteSpace(transcription))
{
<small class="d-block text-body-secondary">@transcription</small>
}
</button>
}
}

View File

@@ -0,0 +1,64 @@
@model Events.MVC.Models.Registrations.RegistrationViewModel
<tr id="registration-@Model.Id">
<td>@Model.Id</td>
<td colspan="5">
<form
asp-action="Edit"
asp-route-id="@Model.Id"
method="post"
hx-post="@Url.Action("Edit", "Registrations", new { id = Model.Id })"
hx-target="#registration-@Model.Id"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="Id" type="hidden" />
<input asp-for="EventId" type="hidden" />
<div asp-validation-summary="ModelOnly" class="text-danger small mb-2"></div>
<div class="row g-2 align-items-start">
<div class="col-md-5">
<label asp-for="PersonId" class="form-label"></label>
<input asp-for="PersonId" type="hidden" />
<div class="position-relative registration-person-autocomplete">
<input
asp-for="PersonLookup"
class="form-control"
placeholder="Start typing a person's name"
autocomplete="off"
data-person-autocomplete
hx-get="@Url.Action("PersonSuggestions", "Registrations")"
hx-include="#registrations-state"
hx-trigger="input changed delay:250ms"
hx-target="#registration-person-suggestions-@Model.Id"
hx-swap="innerHTML" />
<div id="registration-person-suggestions-@Model.Id" class="list-group registration-person-suggestions"></div>
</div>
<span asp-validation-for="PersonId" class="text-danger small"></span>
</div>
<div class="col-md-4">
<label asp-for="SportId" class="form-label"></label>
<select asp-for="SportId" asp-items="Model.SportOptions" class="form-select">
<option value="">Select a sport</option>
</select>
<span asp-validation-for="SportId" class="text-danger small"></span>
</div>
<div class="col-md-3">
<label asp-for="RegisteredAt" class="form-label"></label>
<input asp-for="RegisteredAt" class="form-control" disabled />
</div>
<div class="col-md-auto">
<button type="submit" class="btn btn-sm btn-primary">Save</button>
</div>
<div class="col-md-auto">
<button
type="button"
class="btn btn-sm btn-outline-secondary"
hx-get="@Url.Action("Row", "Registrations", new { id = Model.Id, eventId = Model.EventId })"
hx-target="#registration-@Model.Id"
hx-swap="outerHTML">
Cancel
</button>
</div>
</div>
</form>
</td>
</tr>

View File

@@ -0,0 +1,39 @@
@model Events.MVC.Models.Registrations.RegistrationViewModel
<tr id="registration-@Model.Id">
<td>@Model.Id</td>
<td>
<span class="d-block">@Model.PersonName</span>
<small class="d-block text-body-secondary">@Model.PersonTranscription</small>
</td>
<td>@Model.CountryName</td>
<td>@Model.SportName</td>
<td>@Model.RegisteredAt.ToString("dd.MM.yyyy. HH:mm")</td>
<td class="text-end">
<div class="d-inline-flex gap-2">
<button
type="button"
class="btn btn-sm btn-outline-primary"
hx-get="@Url.Action("EditRow", "Registrations", new { id = Model.Id, eventId = Model.EventId })"
hx-target="#registration-@Model.Id"
hx-swap="outerHTML">
Edit
</button>
<form
asp-action="Delete"
asp-route-id="@Model.Id"
asp-route-eventId="@Model.EventId"
method="post"
class="d-inline"
hx-post="@Url.Action("Delete", "Registrations", new { id = Model.Id, eventId = Model.EventId })"
hx-include="#registrations-state"
hx-target="#registrations-panel"
hx-swap="outerHTML"
hx-confirm="Delete this registration?">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</div>
</td>
</tr>

View File

@@ -0,0 +1,149 @@
@model Events.MVC.Models.Registrations.RegistrationsPageViewModel
<section class="card border-0 shadow-sm" id="registrations-list">
<div class="card-body">
<div id="registrations-state" class="d-none">
<input type="hidden" name="eventId" value="@Model.SelectedEventId" />
<input type="hidden" name="page" value="@Model.Registrations.PagingInfo.CurrentPage" />
<input type="hidden" name="pageSize" value="@Model.Registrations.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.Registrations.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.Registrations.PagingInfo.Filters" />
<input type="hidden" name="countryFilter" value="@Model.CountryFilter" />
</div>
<form
asp-action="Index"
method="get"
class="d-flex justify-content-between align-items-start gap-3 flex-wrap flex-lg-nowrap mb-4"
hx-get="@Url.Action("Index", "Registrations")"
hx-target="#registrations-panel"
hx-swap="outerHTML"
hx-push-url="true"
onsubmit="var input=this.querySelector('[data-name-filter-input]'); var country=this.querySelector('[name=countryFilter]'); var filters=this.querySelector('[name=filters]'); var values=[]; if (input && input.value.trim()) { values.push('PersonTranscription' + String.fromCharCode(64) + '=*' + input.value.trim()); } if (country && country.value) { values.push('CountryCode==' + country.value); } filters.value=values.join(','); this.querySelector('[name=page]').value='1';">
<input type="hidden" name="eventId" value="@Model.SelectedEventId" />
<input type="hidden" name="page" value="1" />
<input type="hidden" name="pageSize" value="@Model.Registrations.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.Registrations.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.Registrations.PagingInfo.Filters" />
<div class="d-flex align-items-center gap-3 pt-2">
<h2 class="h5 mb-0">Registrations list</h2>
<span class="badge text-bg-light">@(Model.Registrations.PagingInfo.IsFiltered ? $"{Model.Registrations.PagingInfo.FilteredItemsCount} / {Model.Registrations.PagingInfo.TotalItemsCount}" : Model.Registrations.PagingInfo.TotalItemsCount.ToString())</span>
</div>
<div class="d-flex align-items-center gap-2 flex-nowrap ms-auto">
<input
value="@Model.Registrations.PagingInfo.NameFilter"
data-name-filter-input
class="form-control"
style="max-width: 18rem;"
placeholder="Search by transcription"
aria-label="Filter by transcription" />
<select name="countryFilter" asp-items="Model.CountryOptions" class="form-select" style="max-width: 14rem;" aria-label="Filter by country">
<option value="">All countries</option>
</select>
<button type="submit" class="btn btn-outline-primary">Filter</button>
@if (Model.Registrations.PagingInfo.IsFiltered)
{
<a
asp-action="Index"
asp-route-eventId="@Model.SelectedEventId"
asp-route-page="1"
asp-route-pageSize="@Model.Registrations.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.Registrations.PagingInfo.Sorts"
asp-route-filters=""
class="btn btn-outline-secondary"
hx-get="@Url.Action("Index", "Registrations", new { eventId = Model.SelectedEventId, page = 1, pageSize = Model.Registrations.PagingInfo.ItemsPerPage, sorts = Model.Registrations.PagingInfo.Sorts, filters = string.Empty })"
hx-target="#registrations-panel"
hx-swap="outerHTML"
hx-push-url="true">
Clear
</a>
}
</div>
</form>
@if (!Model.CanCreate && !string.IsNullOrWhiteSpace(Model.CreateDisabledMessage))
{
<div class="alert alert-warning mb-4">@Model.CreateDisabledMessage</div>
}
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead>
<tr>
<th>
<a asp-action="Index" asp-route-eventId="@Model.SelectedEventId" asp-route-page="@Model.Registrations.PagingInfo.CurrentPage" asp-route-pageSize="@Model.Registrations.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.Registrations.PagingInfo.ToggleSort("Id")" asp-route-filters="@Model.Registrations.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "Registrations", new { eventId = Model.SelectedEventId, page = Model.Registrations.PagingInfo.CurrentPage, pageSize = Model.Registrations.PagingInfo.ItemsPerPage, sorts = Model.Registrations.PagingInfo.ToggleSort("Id"), filters = Model.Registrations.PagingInfo.Filters })" hx-target="#registrations-panel" hx-swap="outerHTML" hx-push-url="true">
ID@(Model.Registrations.PagingInfo.IsSortedBy("Id") ? (Model.Registrations.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-eventId="@Model.SelectedEventId" asp-route-page="@Model.Registrations.PagingInfo.CurrentPage" asp-route-pageSize="@Model.Registrations.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.Registrations.PagingInfo.ToggleSort("PersonName")" asp-route-filters="@Model.Registrations.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "Registrations", new { eventId = Model.SelectedEventId, page = Model.Registrations.PagingInfo.CurrentPage, pageSize = Model.Registrations.PagingInfo.ItemsPerPage, sorts = Model.Registrations.PagingInfo.ToggleSort("PersonName"), filters = Model.Registrations.PagingInfo.Filters })" hx-target="#registrations-panel" hx-swap="outerHTML" hx-push-url="true">
Person@(Model.Registrations.PagingInfo.IsSortedBy("PersonName") ? (Model.Registrations.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>Country</th>
<th>
<a asp-action="Index" asp-route-eventId="@Model.SelectedEventId" asp-route-page="@Model.Registrations.PagingInfo.CurrentPage" asp-route-pageSize="@Model.Registrations.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.Registrations.PagingInfo.ToggleSort("SportName")" asp-route-filters="@Model.Registrations.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "Registrations", new { eventId = Model.SelectedEventId, page = Model.Registrations.PagingInfo.CurrentPage, pageSize = Model.Registrations.PagingInfo.ItemsPerPage, sorts = Model.Registrations.PagingInfo.ToggleSort("SportName"), filters = Model.Registrations.PagingInfo.Filters })" hx-target="#registrations-panel" hx-swap="outerHTML" hx-push-url="true">
Sport@(Model.Registrations.PagingInfo.IsSortedBy("SportName") ? (Model.Registrations.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a asp-action="Index" asp-route-eventId="@Model.SelectedEventId" asp-route-page="@Model.Registrations.PagingInfo.CurrentPage" asp-route-pageSize="@Model.Registrations.PagingInfo.ItemsPerPage" asp-route-sorts="@Model.Registrations.PagingInfo.ToggleSort("RegisteredAt")" asp-route-filters="@Model.Registrations.PagingInfo.Filters" class="link-dark link-underline-opacity-0" hx-get="@Url.Action("Index", "Registrations", new { eventId = Model.SelectedEventId, page = Model.Registrations.PagingInfo.CurrentPage, pageSize = Model.Registrations.PagingInfo.ItemsPerPage, sorts = Model.Registrations.PagingInfo.ToggleSort("RegisteredAt"), filters = Model.Registrations.PagingInfo.Filters })" hx-target="#registrations-panel" hx-swap="outerHTML" hx-push-url="true">
Registered at@(Model.Registrations.PagingInfo.IsSortedBy("RegisteredAt") ? (Model.Registrations.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th class="text-end"></th>
</tr>
</thead>
<tbody>
@if (Model.Registrations.Data.Count == 0)
{
<tr>
<td colspan="6" class="text-body-secondary">No registrations to display.</td>
</tr>
}
else
{
@foreach (var registration in Model.Registrations.Data)
{
<partial name="_RegistrationRow" model="registration" />
}
}
</tbody>
</table>
</div>
<div class="d-flex justify-content-between align-items-center mt-4 gap-3 flex-wrap">
<div class="d-flex align-items-center gap-2 flex-wrap">
<small class="text-body-secondary">Page @Model.Registrations.PagingInfo.CurrentPage of @Model.Registrations.PagingInfo.TotalPages</small>
<form asp-action="Index" method="get" class="d-inline-flex align-items-center gap-2" hx-get="@Url.Action("Index", "Registrations")" hx-target="#registrations-panel" hx-swap="outerHTML" hx-push-url="true">
<input type="hidden" name="eventId" value="@Model.SelectedEventId" />
<input type="hidden" name="page" value="1" />
<input type="hidden" name="sorts" value="@Model.Registrations.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.Registrations.PagingInfo.Filters" />
<select name="pageSize" class="form-select form-select-sm" style="width: auto;" aria-label="Items per page" onchange="this.form.requestSubmit()">
@{
int[] pageSizeOptions = [10, 20, 50, 100];
}
@foreach (var option in pageSizeOptions)
{
<option value="@option" selected="@(Model.Registrations.PagingInfo.ItemsPerPage == option)">@option</option>
}
</select>
</form>
</div>
<pager
page-info="@Model.Registrations.PagingInfo"
page-action="Index"
page-title="Enter a page number and press Enter"
page-target="#registrations-panel"
page-swap="outerHTML"
page-push-url="true"
page-route-event-id="@Model.SelectedEventId.ToString()">
</pager>
</div>
</div>
</section>

View File

@@ -0,0 +1,43 @@
@model Events.MVC.Models.Registrations.RegistrationsPageViewModel
<div class="d-flex flex-column gap-4" id="registrations-panel">
<section class="card border-0 shadow-sm">
<div class="card-body">
<form
asp-action="Index"
method="get"
class="row g-3 align-items-end"
hx-get="@Url.Action("Index", "Registrations")"
hx-target="#registrations-panel"
hx-swap="outerHTML"
hx-push-url="true">
<div class="col-lg-6">
<label for="selectedEventId" class="form-label">Event</label>
<select
id="selectedEventId"
name="eventId"
asp-items="Model.EventOptions"
class="form-select"
onchange="this.form.requestSubmit()">
</select>
</div>
<div class="col-auto">
<span class="badge text-bg-light">Registrations for: @Model.SelectedEventName</span>
</div>
</form>
</div>
</section>
<section id="create-registration-panel" class="collapse">
<div class="card border-0 shadow-sm">
<div class="card-body">
<h2 class="h5 mb-3">Add a new registration</h2>
<div id="create-registration-form">
<partial name="_CreateRegistrationForm" model="Model.CreateModel" />
</div>
</div>
</div>
</section>
<partial name="_RegistrationsList" model="Model" />
</div>

View File

@@ -0,0 +1,157 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData[Constants.ViewDataKeys.Title] - Events</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</head>
<body class="bg-body-tertiary">
<header class="border-bottom bg-white shadow-sm">
<nav class="navbar navbar-expand-lg">
<div class="container">
<a class="navbar-brand fw-semibold" asp-controller="Home" asp-action="Index">Events</a>
@if (ViewData[Constants.ViewDataKeys.HeaderActionLabel] is string headerActionLabel && ViewData[Constants.ViewDataKeys.HeaderActionTarget] is string headerActionTarget)
{
<div class="ms-3 d-none d-lg-flex align-items-center">
<button
type="button"
class="btn btn-sm btn-outline-primary"
data-bs-toggle="collapse"
data-bs-target="@headerActionTarget"
aria-expanded="false"
aria-controls="@headerActionTarget.TrimStart('#')">
@headerActionLabel
</button>
</div>
}
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNav" aria-controls="mainNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="mainNav">
@if (ViewData[Constants.ViewDataKeys.HeaderActionLabel] is string mobileHeaderActionLabel && ViewData[Constants.ViewDataKeys.HeaderActionTarget] is string mobileHeaderActionTarget)
{
<div class="d-lg-none mb-3">
<button
type="button"
class="btn btn-sm btn-outline-primary"
data-bs-toggle="collapse"
data-bs-target="@mobileHeaderActionTarget"
aria-expanded="false"
aria-controls="@mobileHeaderActionTarget.TrimStart('#')">
@mobileHeaderActionLabel
</button>
</div>
}
<ul class="navbar-nav ms-auto gap-lg-2">
<li class="nav-item">
<a class="nav-link" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="Events" asp-action="Index">Events</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="Sports" asp-action="Index">Sports</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="Countries" asp-action="Index">Countries</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="People" asp-action="Index">People</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="Registrations" asp-action="Index">Registrations</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<main class="container py-4">
@RenderBody()
</main>
<div class="toast-container position-fixed bottom-0 end-0 p-3">
<div id="app-toast" class="toast border-0 shadow-sm text-white" role="status" aria-live="polite" aria-atomic="true">
<div id="app-toast-header" class="toast-header">
<strong id="app-toast-title" class="me-auto">Notification</strong>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div id="app-toast-body" class="toast-body"></div>
</div>
</div>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/lib/htmx.org/dist/htmx.min.js"></script>
<script src="~/js/pager.js" asp-append-version="true"></script>
<script>
var toastVariantSuccess = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastVariants.Success));
var toastVariantError = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastVariants.Error));
var toastTitleNotification = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastTitles.Notification));
var toastTitleError = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.ToastTitles.Error));
function showAppToast(options) {
var toastElement = document.getElementById("app-toast");
var headerElement = document.getElementById("app-toast-header");
var titleElement = document.getElementById("app-toast-title");
var bodyElement = document.getElementById("app-toast-body");
if (!toastElement || !headerElement || !titleElement || !bodyElement || !window.bootstrap) {
return;
}
var variant = options.variant || toastVariantSuccess;
toastElement.classList.remove("toast-success", "toast-error");
toastElement.classList.add(variant === toastVariantError ? "toast-error" : "toast-success");
headerElement.classList.remove("text-bg-success", "text-bg-danger");
headerElement.classList.add(variant === toastVariantError ? "text-bg-danger" : "text-bg-success");
titleElement.textContent = options.title || toastTitleNotification;
bodyElement.textContent = options.message || "";
var toast = bootstrap.Toast.getOrCreateInstance(toastElement, { delay: 2500 });
toast.show();
}
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.ShowToast)), function (event) {
showAppToast(event.detail || {});
});
document.body.addEventListener("htmx:responseError", function (event) {
var xhr = event.detail.xhr;
var message = "An error occurred while processing the request.";
if (xhr && xhr.responseText) {
try {
var problem = JSON.parse(xhr.responseText);
message = problem.detail || problem.title || xhr.responseText;
}
catch {
message = xhr.responseText;
}
}
showAppToast({
variant: toastVariantError,
title: toastTitleError,
message: message
});
});
@if (TempData[Constants.TempDataKeys.ToastMessage] is string toastMessage)
{
var initialToastJson = System.Text.Json.JsonSerializer.Serialize(new
{
variant = TempData[Constants.TempDataKeys.ToastVariant] as string ?? Constants.ToastVariants.Success,
title = TempData[Constants.TempDataKeys.ToastTitle] as string ?? Constants.ToastTitles.Notification,
message = toastMessage
});
@:showAppToast(@Html.Raw(initialToastJson));
}
</script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@@ -0,0 +1,38 @@
@model PagedList<Events.MVC.Models.Sports.SportViewModel>
@{
ViewData[Constants.ViewDataKeys.Title] = "Sports";
ViewData[Constants.ViewDataKeys.HeaderActionLabel] = "New sport";
ViewData[Constants.ViewDataKeys.HeaderActionTarget] = "#create-sport-panel";
}
<div class="d-flex flex-column gap-4">
<section id="create-sport-panel" class="collapse">
<div class="card border-0 shadow-sm">
<div class="card-body">
<h2 class="h5 mb-3">Add a new sport</h2>
<div id="create-sport-form">
<partial name="_CreateSportForm" model='new Events.MVC.Models.Sports.SportViewModel()' />
</div>
</div>
</div>
</section>
<partial name="_SportsList" model="Model" />
</div>
@section Scripts {
<script>
document.body.addEventListener(@Html.Raw(System.Text.Json.JsonSerializer.Serialize(Constants.HtmxEvents.SportCreated)), function () {
var form = document.querySelector("#create-sport-form form");
if (form) {
form.reset();
}
var panel = document.getElementById("create-sport-panel");
if (panel && window.bootstrap) {
bootstrap.Collapse.getOrCreateInstance(panel).hide();
}
});
</script>
}

View File

@@ -0,0 +1,21 @@
@model Events.MVC.Models.Sports.SportViewModel
<form
asp-action="Create"
method="post"
hx-post="@Url.Action("Create", "Sports")"
hx-include="#sports-state"
hx-target="#sports-list"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<div class="row g-3 align-items-end">
<div class="col-sm-8 col-lg-6">
<label asp-for="Name" class="form-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger small"></span>
</div>
<div class="col-sm-auto">
<button type="submit" class="btn btn-primary">Add sport</button>
</div>
</div>
</form>

View File

@@ -0,0 +1,36 @@
@model Events.MVC.Models.Sports.SportViewModel
<tr id="sport-@Model.Id">
<td>@Model.Id</td>
<td colspan="2">
<form
asp-action="Edit"
asp-route-id="@Model.Id"
method="post"
hx-post="@Url.Action("Edit", "Sports", new { id = Model.Id })"
hx-target="#sport-@Model.Id"
hx-swap="outerHTML">
@Html.AntiForgeryToken()
<input asp-for="Id" type="hidden" />
<div class="row g-2 align-items-start">
<div class="col-lg-6">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger small"></span>
</div>
<div class="col-md-auto">
<button type="submit" class="btn btn-sm btn-primary">Save</button>
</div>
<div class="col-md-auto">
<button
type="button"
class="btn btn-sm btn-outline-secondary"
hx-get="@Url.Action("Row", "Sports", new { id = Model.Id })"
hx-target="#sport-@Model.Id"
hx-swap="outerHTML">
Cancel
</button>
</div>
</div>
</form>
</td>
</tr>

View File

@@ -0,0 +1,32 @@
@model Events.MVC.Models.Sports.SportViewModel
<tr id="sport-@Model.Id">
<td>@Model.Id</td>
<td>@Model.Name</td>
<td class="text-end">
<div class="d-inline-flex gap-2">
<button
type="button"
class="btn btn-sm btn-outline-primary"
hx-get="@Url.Action("EditRow", "Sports", new { id = Model.Id })"
hx-target="#sport-@Model.Id"
hx-swap="outerHTML">
Edit
</button>
<form
asp-action="Delete"
asp-route-id="@Model.Id"
method="post"
class="d-inline"
hx-post="@Url.Action("Delete", "Sports", new { id = Model.Id })"
hx-include="#sports-state"
hx-target="#sports-list"
hx-swap="outerHTML"
hx-confirm="Delete sport '@Model.Name'?">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</div>
</td>
</tr>

View File

@@ -0,0 +1,156 @@
@model PagedList<Events.MVC.Models.Sports.SportViewModel>
<section class="card border-0 shadow-sm" id="sports-list">
<div class="card-body">
<div id="sports-state" class="d-none">
<input type="hidden" name="page" value="@Model.PagingInfo.CurrentPage" />
<input type="hidden" name="pageSize" value="@Model.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
</div>
<form
asp-action="Index"
method="get"
class="d-flex justify-content-between align-items-start gap-3 flex-wrap flex-lg-nowrap mb-4"
hx-get="@Url.Action("Index", "Sports")"
hx-target="#sports-list"
hx-swap="outerHTML"
hx-push-url="true"
onsubmit="var input=this.querySelector('[data-name-filter-input]'); var filters=this.querySelector('[name=filters]'); filters.value=input && input.value.trim() ? 'Name' + String.fromCharCode(64) + '=*' + input.value.trim() : ''; this.querySelector('[name=page]').value='1';">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="pageSize" value="@Model.PagingInfo.ItemsPerPage" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
<div class="d-flex align-items-center gap-3 pt-2">
<h2 class="h5 mb-0">Sports list</h2>
<span class="badge text-bg-light">@(Model.PagingInfo.IsFiltered ? $"{Model.PagingInfo.FilteredItemsCount} / {Model.PagingInfo.TotalItemsCount}" : Model.PagingInfo.TotalItemsCount.ToString())</span>
</div>
<div class="d-flex align-items-center gap-2 flex-nowrap ms-auto">
<input
id="nameFilter"
value="@Model.PagingInfo.NameFilter"
data-name-filter-input
class="form-control"
style="max-width: 18rem;"
placeholder="Search by sport name"
aria-label="Filter by sport name" />
<button type="submit" class="btn btn-outline-primary">Filter</button>
@if (Model.PagingInfo.IsFiltered)
{
<a
asp-action="Index"
asp-route-page="1"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.Sorts"
asp-route-filters=""
class="btn btn-outline-secondary"
hx-get="@Url.Action("Index", "Sports", new { page = 1, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.Sorts, filters = string.Empty })"
hx-target="#sports-list"
hx-swap="outerHTML"
hx-push-url="true">
Clear
</a>
}
</div>
</form>
<div class="table-responsive">
<table class="table align-middle mb-0">
<thead>
<tr>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("Id")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Sports", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Id"), filters = Model.PagingInfo.Filters })"
hx-target="#sports-list"
hx-swap="outerHTML"
hx-push-url="true">
ID@(Model.PagingInfo.IsSortedBy("Id") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th>
<a
asp-action="Index"
asp-route-page="@Model.PagingInfo.CurrentPage"
asp-route-pageSize="@Model.PagingInfo.ItemsPerPage"
asp-route-sorts="@Model.PagingInfo.ToggleSort("Name")"
asp-route-filters="@Model.PagingInfo.Filters"
class="link-dark link-underline-opacity-0"
hx-get="@Url.Action("Index", "Sports", new { page = Model.PagingInfo.CurrentPage, pageSize = Model.PagingInfo.ItemsPerPage, sorts = Model.PagingInfo.ToggleSort("Name"), filters = Model.PagingInfo.Filters })"
hx-target="#sports-list"
hx-swap="outerHTML"
hx-push-url="true">
Name@(Model.PagingInfo.IsSortedBy("Name") ? (Model.PagingInfo.IsDescending() ? " ↓" : " ↑") : "")
</a>
</th>
<th class="text-end"></th>
</tr>
</thead>
<tbody id="sports-table-body">
@if (Model.Data.Count == 0)
{
<tr>
<td colspan="3" class="text-body-secondary">No sports to display.</td>
</tr>
}
else
{
@foreach (var sport in Model.Data)
{
<partial name="_SportRow" model="sport" />
}
}
</tbody>
</table>
</div>
<div class="d-flex justify-content-between align-items-center mt-4 gap-3 flex-wrap">
<div class="d-flex align-items-center gap-2 flex-wrap">
<small class="text-body-secondary">Page @Model.PagingInfo.CurrentPage of @Model.PagingInfo.TotalPages</small>
<form
asp-action="Index"
method="get"
class="d-inline-flex align-items-center gap-2"
hx-get="@Url.Action("Index", "Sports")"
hx-target="#sports-list"
hx-swap="outerHTML"
hx-push-url="true">
<input type="hidden" name="page" value="1" />
<input type="hidden" name="sorts" value="@Model.PagingInfo.Sorts" />
<input type="hidden" name="filters" value="@Model.PagingInfo.Filters" />
<select
name="pageSize"
class="form-select form-select-sm"
style="width: auto;"
aria-label="Items per page"
onchange="this.form.requestSubmit()">
@{
int[] pageSizeOptions = [10, 20, 50, 100];
}
@foreach (var option in pageSizeOptions)
{
<option value="@option" selected="@(Model.PagingInfo.ItemsPerPage == option)">@option</option>
}
</select>
</form>
</div>
<pager
page-info="@Model.PagingInfo"
page-action="Index"
page-title="Enter a page number and press Enter"
page-target="#sports-list"
page-swap="outerHTML"
page-push-url="true">
</pager>
</div>
</div>
</section>

View File

@@ -0,0 +1,5 @@
@using Events.EF.Models
@using Events.MVC
@using Events.MVC.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Events.MVC

View File

@@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,17 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Paging": {
"PageSize": 10,
"PageOffset": 5
},
"ConnectionStrings": {
"EventsMssql": "Data Source=.,1433;Initial Catalog=Events;User Id=sport;Password=go and look in the secrets file;TrustServerCertificate=True",
"EventsPostgres": "Host=localhost;Port=5432;Database=events;Username=sport;Password=go and look in the secrets file;Persist Security Info=True;"
}
}

View File

@@ -0,0 +1,21 @@
{
"version": "1.0",
"defaultProvider": "jsdelivr",
"libraries": [
{
"library": "bootstrap@5.3.3",
"destination": "wwwroot/lib/bootstrap/",
"files": [
"dist/css/bootstrap.min.css",
"dist/js/bootstrap.bundle.min.js"
]
},
{
"library": "htmx.org@2.0.4",
"destination": "wwwroot/lib/htmx.org/",
"files": [
"dist/htmx.min.js"
]
}
]
}

View File

@@ -0,0 +1,55 @@
body {
min-height: 100vh;
}
.navbar-brand {
letter-spacing: 0.02em;
}
.card {
border-radius: 1rem;
}
.table > :not(caption) > * > * {
padding-top: 0.9rem;
padding-bottom: 0.9rem;
}
.pagebox {
width: 3.5rem;
min-width: 3.5rem;
padding-left: 0.4rem;
padding-right: 0.4rem;
text-align: center;
}
#app-toast {
min-width: 18rem;
}
#app-toast.toast-success {
background-color: #198754;
}
#app-toast.toast-error {
background-color: #dc3545;
}
#app-toast .toast-body {
color: #fff;
}
#app-toast .btn-close {
filter: invert(1);
}
.registration-person-suggestions {
position: absolute;
top: calc(100% + 0.25rem);
left: 0;
right: 0;
z-index: 1050;
max-height: 16rem;
overflow-y: auto;
}

View File

@@ -0,0 +1,61 @@
(function () {
function validRange(value, min, max) {
if (!/^\d+$/.test(value)) {
return false;
}
var page = parseInt(value, 10);
return page >= min && page <= max;
}
function goToPage(input) {
var value = input.value.trim();
var min = parseInt(input.dataset.min, 10);
var max = parseInt(input.dataset.max, 10);
if (!validRange(value, min, max)) {
input.value = input.dataset.current || "";
return;
}
var url = (input.dataset.urlTemplate || "").replace("__page__", value);
if (!url) {
return;
}
var target = input.dataset.target;
var swap = input.dataset.swap || "outerHTML";
var pushUrl = input.dataset.pushUrl === "true";
if (window.htmx && target) {
htmx.ajax("GET", url, {
target: target,
swap: swap,
pushUrl: pushUrl
});
return;
}
window.location.href = url;
}
document.addEventListener("focusin", function (event) {
if (event.target.matches(".pagebox")) {
event.target.select();
}
});
document.addEventListener("keydown", function (event) {
if (!event.target.matches(".pagebox")) {
return;
}
if (event.key === "Enter") {
event.preventDefault();
goToPage(event.target);
}
else if (event.key === "Escape") {
event.target.value = event.target.dataset.current || "";
}
});
})();

View File

@@ -0,0 +1,76 @@
using System.Net;
using Events.Tests.IntegrationTests.Infrastructure;
namespace Events.Tests.IntegrationTests;
public class CountriesCrudShould
{
[Fact]
public async Task CreateCountry()
{
await using var factory = new CustomWebApplicationFactory();
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/Countries",
"/Countries/Create",
[
new("Code", "DE"),
new("Alpha3", "DEU"),
new("Name", "Germany"),
new("Translations[0].LanguageCode", "hr"),
new("Translations[0].Name", "Germany")
]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Germany", html);
}
[Fact]
public async Task EditCountry()
{
await using var factory = new CustomWebApplicationFactory(ctx => ctx.Countries.Add(TestDataSeederCountry()));
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/Countries",
"/Countries/Edit/HR",
[
new("Code", "HR"),
new("Alpha3", "HRV"),
new("Name", "Republic of Croatia"),
new("Translations[0].LanguageCode", ""),
new("Translations[0].Name", "")
]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Republic of Croatia", html);
}
[Fact]
public async Task DeleteCountry()
{
await using var factory = new CustomWebApplicationFactory(ctx => ctx.Countries.Add(TestDataSeederCountry()));
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(client, "/Countries", "/Countries/Delete/HR", []);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Croatia", html);
}
private static Events.EF.Models.Country TestDataSeederCountry()
{
return new()
{
Code = "HR",
Alpha3 = "HRV",
Name = "Croatia"
};
}
}

View File

@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="10.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.7" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.4.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Events.MVC\Events.MVC.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,54 @@
using System.Net;
using Events.Tests.IntegrationTests.Infrastructure;
namespace Events.Tests.IntegrationTests;
public class EventsCrudShould
{
[Fact]
public async Task CreateEvent()
{
await using var factory = new CustomWebApplicationFactory();
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/Events",
"/Events/Create",
[new("Name", "Autumn Cup"), new("EventDate", "2026-09-10")]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Autumn Cup", html);
}
[Fact]
public async Task EditEvent()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedEvents);
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/Events",
"/Events/Edit/100",
[new("Id", "100"), new("Name", "Updated Games"), new("EventDate", "2026-04-20")]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Updated Games", html);
}
[Fact]
public async Task DeleteEvent()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedEvents);
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(client, "/Events", "/Events/Delete/100", []);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Spring Games", html);
}
}

View File

@@ -0,0 +1,25 @@
using System.Net;
using Events.Tests.IntegrationTests.Infrastructure;
namespace Events.Tests.IntegrationTests;
public class EventsPageShould
{
[Fact]
public async Task ShowParticipantsCountAndRegistrationsLinkWhenRegistrationsExist()
{
await using var factory = new CustomWebApplicationFactory(ctx =>
{
TestDataSeeder.SeedRegistrationsScenario(ctx);
});
using var client = factory.CreateClient();
var response = await client.GetAsync("/Events");
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Spring Games", html);
Assert.Contains("/Registrations?eventId=100", html);
Assert.Contains(">2<", html);
}
}

View File

@@ -0,0 +1 @@
global using Xunit;

View File

@@ -0,0 +1,20 @@
using System.Net;
using Events.Tests.IntegrationTests.Infrastructure;
namespace Events.Tests.IntegrationTests;
public class HomePageShould
{
[Fact]
public async Task ReturnSuccessAndContainEnglishDescription()
{
await using var factory = new CustomWebApplicationFactory();
using var client = factory.CreateClient();
var response = await client.GetAsync("/");
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("This sample demonstrates an ASP.NET Core MVC application", html);
}
}

View File

@@ -0,0 +1,40 @@
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
namespace Events.Tests.IntegrationTests.Infrastructure;
internal static partial class AntiforgeryRequestHelper
{
private const string AntiforgeryFieldName = "__RequestVerificationToken";
public static async Task<HttpResponseMessage> PostFormAsync(
HttpClient client,
string pageUrl,
string postUrl,
IEnumerable<KeyValuePair<string, string?>> fields)
{
var pageHtml = await client.GetStringAsync(pageUrl);
var token = ExtractAntiforgeryToken(pageHtml);
var payload = fields
.Append(new KeyValuePair<string, string?>(AntiforgeryFieldName, token))
.ToArray();
using var request = new HttpRequestMessage(HttpMethod.Post, postUrl)
{
Content = new FormUrlEncodedContent(payload!)
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
return await client.SendAsync(request);
}
private static string ExtractAntiforgeryToken(string html)
{
var match = AntiforgeryTokenRegex().Match(html);
Assert.True(match.Success, "Expected antiforgery token field was not found in the HTML response.");
return match.Groups["token"].Value;
}
[GeneratedRegex("<input[^>]*name=\"__RequestVerificationToken\"[^>]*value=\"(?<token>[^\"]+)\"", RegexOptions.IgnoreCase | RegexOptions.Compiled)]
private static partial Regex AntiforgeryTokenRegex();
}

View File

@@ -0,0 +1,51 @@
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Events.Tests.IntegrationTests.Infrastructure;
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
private readonly Action<EventsContext>? seed;
private readonly InMemoryDatabaseRoot databaseRoot = new();
private readonly string databaseName = Guid.NewGuid().ToString();
public CustomWebApplicationFactory(Action<EventsContext>? seed = null)
{
this.seed = seed;
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Development");
builder.ConfigureServices(services =>
{
services.RemoveAll(typeof(DbContextOptions<EventsContext>));
services.RemoveAll(typeof(IDbContextOptionsConfiguration<EventsContext>));
services.RemoveAll(typeof(EventsContext));
services.AddDbContext<EventsContext>(options =>
options
.UseInMemoryDatabase(databaseName, databaseRoot)
.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning)));
var serviceProvider = services.BuildServiceProvider();
using var scope = serviceProvider.CreateScope();
var ctx = scope.ServiceProvider.GetRequiredService<EventsContext>();
ctx.Database.EnsureCreated();
seed?.Invoke(ctx);
ctx.SaveChanges();
});
}
}

View File

@@ -0,0 +1,140 @@
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
namespace Events.Tests.IntegrationTests.Infrastructure;
internal static class TestDataSeeder
{
public static void SeedSports(EventsContext ctx)
{
ctx.Sports.AddRange(
new Sport { Id = 1, Name = "Football" },
new Sport { Id = 2, Name = "Basketball" });
}
public static void SeedPeople(EventsContext ctx)
{
ctx.Countries.Add(new Country
{
Code = "HR",
Alpha3 = "HRV",
Name = "Croatia"
});
ctx.People.Add(new Person
{
Id = 1,
FirstName = "Ivan",
LastName = "Horvat",
FirstNameTranscription = "Ivan",
LastNameTranscription = "Horvat",
AddressLine = "Ilica 1",
PostalCode = "10000",
City = "Zagreb",
AddressCountry = "Croatia",
Email = "ivan.horvat@example.com",
ContactPhone = "+38591111222",
BirthDate = new DateOnly(1990, 5, 1),
DocumentNumber = "DOC-1",
CountryCode = "HR"
});
}
public static void SeedEvents(EventsContext ctx)
{
ctx.Events.AddRange(
new Event { Id = 100, Name = "Spring Games", EventDate = new DateOnly(2026, 4, 15) },
new Event { Id = 200, Name = "Summer Cup", EventDate = new DateOnly(2026, 6, 20) });
}
public static void SeedRegistrationsScenario(EventsContext ctx)
{
ctx.Countries.AddRange(
new Country
{
Code = "HR",
Alpha3 = "HRV",
Name = "Croatia"
},
new Country
{
Code = "DE",
Alpha3 = "DEU",
Name = "Germany"
});
ctx.People.AddRange(
new Person
{
Id = 1,
FirstName = "Ivan",
LastName = "Horvat",
FirstNameTranscription = "Ivan",
LastNameTranscription = "Horvat",
AddressLine = "Ilica 1",
PostalCode = "10000",
City = "Zagreb",
AddressCountry = "Croatia",
Email = "ivan.horvat@example.com",
ContactPhone = "+38591111222",
BirthDate = new DateOnly(1990, 5, 1),
DocumentNumber = "DOC-1",
CountryCode = "HR"
},
new Person
{
Id = 2,
FirstName = "Johann",
LastName = "Schmidt",
FirstNameTranscription = "Johann",
LastNameTranscription = "Schmidt",
AddressLine = "Unter den Linden 5",
PostalCode = "10117",
City = "Berlin",
AddressCountry = "Germany",
Email = "johann.schmidt@example.com",
ContactPhone = "+49170111222",
BirthDate = new DateOnly(1988, 3, 12),
DocumentNumber = "DOC-2",
CountryCode = "DE"
});
ctx.Sports.AddRange(
new Sport { Id = 10, Name = "Football" },
new Sport { Id = 20, Name = "Basketball" });
ctx.Events.AddRange(
new Event { Id = 100, Name = "Spring Games", EventDate = new DateOnly(2026, 4, 15) },
new Event { Id = 200, Name = "Summer Cup", EventDate = new DateOnly(2026, 6, 20) });
ctx.Registrations.AddRange(
new Registration
{
Id = 1000,
EventId = 100,
PersonId = 1,
SportId = 10,
RegisteredAt = new DateTime(2026, 3, 1, 9, 30, 0, DateTimeKind.Utc)
},
new Registration
{
Id = 1001,
EventId = 100,
PersonId = 2,
SportId = 20,
RegisteredAt = new DateTime(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc)
},
new Registration
{
Id = 1002,
EventId = 200,
PersonId = 1,
SportId = 20,
RegisteredAt = new DateTime(2026, 3, 3, 11, 0, 0, DateTimeKind.Utc)
});
}
}

View File

@@ -0,0 +1,89 @@
using System.Net;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.Tests.IntegrationTests.Infrastructure;
namespace Events.Tests.IntegrationTests;
public class PeopleCrudShould
{
[Fact]
public async Task CreatePerson()
{
await using var factory = new CustomWebApplicationFactory(ctx => ctx.Countries.Add(new Country { Code = "HR", Alpha3 = "HRV", Name = "Croatia" }));
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/People",
"/People/Create",
[
new("FirstName", "Ana"),
new("LastName", "Kovac"),
new("FirstNameTranscription", "Ana"),
new("LastNameTranscription", "Kovac"),
new("Email", "ana.kovac@example.com"),
new("ContactPhone", "+38591123456"),
new("BirthDate", "1995-01-01"),
new("CountryCode", "HR"),
new("DocumentNumber", "DOC-2"),
new("AddressLine", "Main Street 1"),
new("PostalCode", "10000"),
new("City", "Zagreb"),
new("AddressCountry", "Croatia")
]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Ana Kovac", html);
}
[Fact]
public async Task EditPerson()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedPeople);
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/People",
"/People/Edit/1",
[
new("Id", "1"),
new("FirstName", "Ivan"),
new("LastName", "Kovac"),
new("FirstNameTranscription", "Ivan"),
new("LastNameTranscription", "Kovac"),
new("Email", "ivan.kovac@example.com"),
new("ContactPhone", "+38591111222"),
new("BirthDate", "1990-05-01"),
new("CountryCode", "HR"),
new("DocumentNumber", "DOC-1"),
new("AddressLine", "Ilica 1"),
new("PostalCode", "10000"),
new("City", "Zagreb"),
new("AddressCountry", "Croatia")
]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Ivan Kovac", html);
}
[Fact]
public async Task DeletePerson()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedPeople);
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(client, "/People", "/People/Delete/1", []);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Ivan Horvat", html);
}
}

View File

@@ -0,0 +1,23 @@
using System.Net;
using Events.Tests.IntegrationTests.Infrastructure;
using Microsoft.AspNetCore.Mvc.Testing;
namespace Events.Tests.IntegrationTests;
public class PeopleGuardShould
{
[Fact]
public async Task RedirectToCountriesWhenPeoplePageIsRequestedWithoutCountries()
{
await using var factory = new CustomWebApplicationFactory();
using var client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var response = await client.GetAsync("/People");
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("/Countries", response.Headers.Location?.OriginalString);
}
}

View File

@@ -0,0 +1,74 @@
using System.Net;
using Events.Tests.IntegrationTests.Infrastructure;
namespace Events.Tests.IntegrationTests;
public class PeoplePageShould
{
[Fact]
public async Task ReturnPageWithPeopleListWhenCountryAndPersonExist()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedPeople);
using var client = factory.CreateClient();
var response = await client.GetAsync("/People");
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("People list", html);
Assert.Contains("First name", html);
Assert.Contains("Last name", html);
Assert.Contains("Ivan Horvat", html);
Assert.Contains("Croatia", html);
}
[Fact]
public async Task RenderNativeFullNameAndTranscribedNamesInSeparateColumns()
{
await using var factory = new CustomWebApplicationFactory(ctx =>
{
ctx.Countries.Add(new Events.EF.Models.Country
{
Code = "UA",
Alpha3 = "UKR",
Name = "Ukraine"
});
ctx.People.Add(new Events.EF.Models.Person
{
Id = 1,
FirstName = "Олексій",
LastName = "Шевченко",
FirstNameTranscription = "Oleksii",
LastNameTranscription = "Shevchenko",
AddressLine = "Khreshchatyk 1",
PostalCode = "01001",
City = "Kyiv",
AddressCountry = "Ukraine",
Email = "oleksii.shevchenko@example.com",
ContactPhone = "+38050111222",
BirthDate = new DateOnly(1991, 6, 1),
DocumentNumber = "DOC-1",
CountryCode = "UA"
});
});
using var client = factory.CreateClient();
var response = await client.GetAsync("/People");
var html = await response.Content.ReadAsStringAsync();
var decodedHtml = WebUtility.HtmlDecode(html);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("<th></th>", decodedHtml);
Assert.Contains("<td>Олексій Шевченко</td>", decodedHtml);
Assert.Contains("<td>Oleksii</td>", decodedHtml);
Assert.Contains("<td>Shevchenko</td>", decodedHtml);
var firstNameColumnIndex = decodedHtml.IndexOf("<td>Oleksii</td>", StringComparison.Ordinal);
var lastNameColumnIndex = decodedHtml.IndexOf("<td>Shevchenko</td>", StringComparison.Ordinal);
var nativeFullNameColumnIndex = decodedHtml.IndexOf("<td>Олексій Шевченко</td>", StringComparison.Ordinal);
Assert.True(firstNameColumnIndex < lastNameColumnIndex);
Assert.True(lastNameColumnIndex < nativeFullNameColumnIndex);
}
}

View File

@@ -0,0 +1,61 @@
using System.Net;
using Events.Tests.IntegrationTests.Infrastructure;
namespace Events.Tests.IntegrationTests;
public class RegistrationsCrudShould
{
[Fact]
public async Task CreateRegistration()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedRegistrationsScenario);
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/Registrations?eventId=100",
"/Registrations/Create",
[new("EventId", "100"), new("PersonId", "1"), new("SportId", "20"), new("PersonLookup", "Ivan Horvat")]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Basketball", html);
}
[Fact]
public async Task EditRegistration()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedRegistrationsScenario);
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/Registrations?eventId=100",
"/Registrations/Edit/1000",
[
new("Id", "1000"),
new("EventId", "100"),
new("PersonId", "2"),
new("SportId", "20"),
new("PersonLookup", "Johann Schmidt")
]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Johann Schmidt", html);
Assert.Contains("Basketball", html);
}
[Fact]
public async Task DeleteRegistration()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedRegistrationsScenario);
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(client, "/Registrations?eventId=100", "/Registrations/Delete/1000?eventId=100", []);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain(">1000<", html);
}
}

View File

@@ -0,0 +1,84 @@
using System.Net;
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.Tests.IntegrationTests.Infrastructure;
using Microsoft.AspNetCore.Mvc.Testing;
namespace Events.Tests.IntegrationTests;
public class RegistrationsGuardShould
{
[Fact]
public async Task RedirectToSportsWhenRegistrationsPageIsRequestedWithoutSports()
{
await using var factory = new CustomWebApplicationFactory(ctx =>
{
ctx.Countries.Add(new Country
{
Code = "HR",
Alpha3 = "HRV",
Name = "Croatia"
});
ctx.People.Add(new Person
{
Id = 1,
FirstName = "Ivan",
LastName = "Horvat",
FirstNameTranscription = "Ivan",
LastNameTranscription = "Horvat",
AddressLine = "Ilica 1",
PostalCode = "10000",
City = "Zagreb",
AddressCountry = "Croatia",
Email = "ivan.horvat@example.com",
ContactPhone = "+38591111222",
BirthDate = new DateOnly(1990, 5, 1),
DocumentNumber = "DOC-1",
CountryCode = "HR"
});
ctx.Events.Add(new Event
{
Id = 100,
Name = "Spring Games",
EventDate = new DateOnly(2026, 4, 15)
});
});
using var client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var response = await client.GetAsync("/Registrations");
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("/Sports", response.Headers.Location?.OriginalString);
}
[Fact]
public async Task RedirectToPeopleWhenRegistrationsPageIsRequestedWithoutPeople()
{
await using var factory = new CustomWebApplicationFactory(ctx =>
{
ctx.Sports.Add(new Sport { Id = 10, Name = "Football" });
ctx.Events.Add(new Event
{
Id = 100,
Name = "Spring Games",
EventDate = new DateOnly(2026, 4, 15)
});
});
using var client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var response = await client.GetAsync("/Registrations");
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("/People", response.Headers.Location?.OriginalString);
}
}

View File

@@ -0,0 +1,57 @@
using System.Net;
using Events.Tests.IntegrationTests.Infrastructure;
namespace Events.Tests.IntegrationTests;
public class RegistrationsPageShould
{
[Fact]
public async Task ReturnEventSpecificRegistrationsForSelectedEvent()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedRegistrationsScenario);
using var client = factory.CreateClient();
var response = await client.GetAsync("/Registrations?eventId=100");
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Registrations for: Spring Games", html);
Assert.Contains("Ivan Horvat", html);
Assert.Contains("Johann Schmidt", html);
Assert.Contains("Croatia", html);
Assert.Contains("Germany", html);
}
[Fact]
public async Task ReturnFilteredPartialForHtmxRequestWithCountryFilter()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedRegistrationsScenario);
using var client = factory.CreateClient();
client.DefaultRequestHeaders.Add(Events.MVC.Constants.HtmxHeaders.Request, "true");
var response = await client.GetAsync("/Registrations?eventId=100&filters=CountryCode==HR");
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("id=\"registrations-panel\"", html);
Assert.Contains("Ivan Horvat", html);
Assert.DoesNotContain("Johann Schmidt", html);
Assert.DoesNotContain("<html", html, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task ReturnOnlyMatchingCountrySuggestionsForPersonLookup()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedRegistrationsScenario);
using var client = factory.CreateClient();
var response = await client.GetAsync("/Registrations/PersonSuggestions?personLookup=jo&countryFilter=DE");
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Johann Schmidt", html);
Assert.Contains("Johann", html);
Assert.DoesNotContain("Ivan Horvat", html);
Assert.Contains("data-person-suggestion", html);
}
}

View File

@@ -0,0 +1,72 @@
using System.Net;
using Events.Tests.IntegrationTests.Infrastructure;
namespace Events.Tests.IntegrationTests;
public class SportsCrudShould
{
[Fact]
public async Task CreateSport()
{
await using var factory = new CustomWebApplicationFactory();
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/Sports",
"/Sports/Create",
[new("Name", "Volleyball")]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Volleyball", html);
}
[Fact]
public async Task ReturnValidationErrorWhenCreatingSportWithoutName()
{
await using var factory = new CustomWebApplicationFactory();
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/Sports",
"/Sports/Create",
[new("Name", string.Empty)]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("The Name field is required.", html);
Assert.DoesNotContain("was added successfully", html);
}
[Fact]
public async Task EditSport()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedSports);
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(
client,
"/Sports",
"/Sports/Edit/1",
[new("Id", "1"), new("Name", "Handball")]);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Handball", html);
}
[Fact]
public async Task DeleteSport()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedSports);
using var client = factory.CreateClient();
var response = await AntiforgeryRequestHelper.PostFormAsync(client, "/Sports", "/Sports/Delete/1", []);
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Football", html);
}
}

View File

@@ -0,0 +1,38 @@
using System.Net;
using Events.Tests.IntegrationTests.Infrastructure;
namespace Events.Tests.IntegrationTests;
public class SportsPageShould
{
[Fact]
public async Task ReturnPageWithSportsListWhenSportsExist()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedSports);
using var client = factory.CreateClient();
var response = await client.GetAsync("/Sports");
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Sports list", html);
Assert.Contains("Football", html);
Assert.Contains("Basketball", html);
}
[Fact]
public async Task ReturnOnlySportsPartialForHtmxRequest()
{
await using var factory = new CustomWebApplicationFactory(TestDataSeeder.SeedSports);
using var client = factory.CreateClient();
client.DefaultRequestHeaders.Add(Events.MVC.Constants.HtmxHeaders.Request, "true");
var response = await client.GetAsync("/Sports");
var html = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("id=\"sports-list\"", html);
Assert.DoesNotContain("<html", html, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("navbar", html, StringComparison.OrdinalIgnoreCase);
}
}

View File

@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.4.0" />
<PackageReference Include="Microsoft.Playwright" Version="1.59.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Events.MVC\Events.MVC.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="README.md" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1 @@
global using Xunit;

View File

@@ -0,0 +1,77 @@
using Events.Tests.UITests.Infrastructure;
using Microsoft.Playwright;
namespace Events.Tests.UITests;
public class HomeAndSportsPageTests
{
[Fact]
public async Task HomePageShouldDisplayEnglishDescription()
{
await using var harness = await UiTestHarness.CreateAsync();
await harness.Page.GotoAsync($"{harness.RootUrl}/");
await Assertions.Expect(harness.Page.GetByRole(AriaRole.Heading, new() { Name = "Events" })).ToBeVisibleAsync();
await Assertions.Expect(harness.Page.GetByText("This sample demonstrates an ASP.NET Core MVC application")).ToBeVisibleAsync();
await Assertions.Expect(harness.Page.GetByRole(AriaRole.Link, new() { Name = "Sports" })).ToBeVisibleAsync();
}
[Fact]
public async Task SportsPageShouldDisplayExistingSportsAndAllowOpeningCreatePanel()
{
await using var harness = await UiTestHarness.CreateAsync();
var expectedSports = new[] { "Running", "Chess", "Swimming" };
await harness.Page.GotoAsync($"{harness.RootUrl}/Sports");
await Assertions.Expect(harness.Page.GetByRole(AriaRole.Heading, new() { Name = "Sports list" })).ToBeVisibleAsync();
await Assertions.Expect(harness.Page.Locator("#sports-table-body tr").First).ToBeVisibleAsync();
await Assertions.Expect(harness.Page.GetByPlaceholder("Search by sport name")).ToBeVisibleAsync();
foreach (var expectedSport in expectedSports)
{
await Assertions.Expect(harness.Page.Locator("#sports-list")).ToContainTextAsync(expectedSport);
}
await harness.Page.GetByRole(AriaRole.Button, new() { Name = "New sport" }).ClickAsync();
await Assertions.Expect(harness.Page.GetByRole(AriaRole.Heading, new() { Name = "Add a new sport" })).ToBeVisibleAsync();
await Assertions.Expect(
harness.Page.Locator("#create-sport-form").GetByLabel("Name", new() { Exact = true }))
.ToBeVisibleAsync();
}
[Fact]
public async Task SportsPageShouldCreateSportAndShowSuccessToast()
{
await using var harness = await UiTestHarness.CreateAsync();
var sportName = $"UI Test Sport {Guid.NewGuid():N}";
await harness.Page.GotoAsync($"{harness.RootUrl}/Sports");
await harness.Page.GetByRole(AriaRole.Button, new() { Name = "New sport" }).ClickAsync();
var createForm = harness.Page.Locator("#create-sport-form");
await createForm.GetByLabel("Name", new() { Exact = true }).FillAsync(sportName);
await createForm.GetByRole(AriaRole.Button, new() { Name = "Add sport" }).ClickAsync();
await Assertions.Expect(harness.Page.Locator("#app-toast")).ToBeVisibleAsync();
await Assertions.Expect(harness.Page.Locator("#app-toast-title")).ToHaveTextAsync("Success");
await Assertions.Expect(harness.Page.Locator("#app-toast-body")).ToContainTextAsync($"Sport '{sportName}' was added successfully.");
await harness.Page.GetByPlaceholder("Search by sport name").FillAsync(sportName);
await harness.Page.GetByRole(AriaRole.Button, new() { Name = "Filter" }).ClickAsync();
await Assertions.Expect(harness.Page.Locator("#sports-list")).ToContainTextAsync(sportName);
var sportRow = harness.Page.Locator("#sports-table-body tr").Filter(new() { HasText = sportName });
await Assertions.Expect(sportRow).ToHaveCountAsync(1);
harness.Page.Dialog += async (_, dialog) => await dialog.AcceptAsync();
await sportRow.GetByRole(AriaRole.Button, new() { Name = "Delete" }).ClickAsync();
await Assertions.Expect(harness.Page.Locator("#app-toast")).ToBeVisibleAsync();
await Assertions.Expect(harness.Page.Locator("#app-toast-title")).ToHaveTextAsync("Success");
await Assertions.Expect(harness.Page.Locator("#app-toast-body")).ToContainTextAsync($"Sport '{sportName}' was deleted successfully.");
await Assertions.Expect(harness.Page.Locator("#sports-list")).Not.ToContainTextAsync(sportName);
}
}

View File

@@ -0,0 +1,196 @@
using System.Diagnostics;
using System.Net.Sockets;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Playwright;
namespace Events.Tests.UITests.Infrastructure;
internal sealed class UiTestHarness : IAsyncDisposable
{
private readonly IPlaywright playwright;
private readonly Process appProcess;
private readonly StringBuilder processOutput;
private UiTestHarness(
IPlaywright playwright,
IBrowser browser,
IBrowserContext browserContext,
IPage page,
Process appProcess,
StringBuilder processOutput,
string rootUrl)
{
this.playwright = playwright;
this.appProcess = appProcess;
this.processOutput = processOutput;
Browser = browser;
BrowserContext = browserContext;
Page = page;
RootUrl = rootUrl;
}
public IBrowser Browser { get; }
public IBrowserContext BrowserContext { get; }
public IPage Page { get; }
public string RootUrl { get; }
public static async Task<UiTestHarness> CreateAsync()
{
var port = FindFreePort();
var rootUrl = $"http://127.0.0.1:{port}";
var mvcProjectPath = Path.GetFullPath(Path.Combine(
AppContext.BaseDirectory,
"..", "..", "..", "..", "..",
"Events.MVC", "Events.MVC.csproj"));
var processOutput = new StringBuilder();
var startInfo = new ProcessStartInfo("dotnet", $"run --project \"{mvcProjectPath}\" --urls {rootUrl}")
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
startInfo.Environment["ASPNETCORE_ENVIRONMENT"] = "UITest";
#if POSTGRES
startInfo.Environment["ConnectionStrings__EventsPostgres"] = ResolveUiTestConnectionString();
#else
startInfo.Environment["ConnectionStrings__EventsMssql"] = ResolveUiTestConnectionString();
#endif
var appProcess = Process.Start(startInfo)
?? throw new InvalidOperationException("Failed to start the MVC app process for UI tests.");
appProcess.OutputDataReceived += (_, args) =>
{
if (args.Data is not null)
{
processOutput.AppendLine(args.Data);
}
};
appProcess.ErrorDataReceived += (_, args) =>
{
if (args.Data is not null)
{
processOutput.AppendLine(args.Data);
}
};
appProcess.BeginOutputReadLine();
appProcess.BeginErrorReadLine();
await WaitForServerAsync(rootUrl, appProcess, processOutput);
IPlaywright playwright;
try
{
playwright = await Playwright.CreateAsync();
}
catch
{
await StopProcessAsync(appProcess);
throw;
}
try
{
var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = true
});
var browserContext = await browser.NewContextAsync(new BrowserNewContextOptions
{
BaseURL = rootUrl
});
var page = await browserContext.NewPageAsync();
return new UiTestHarness(playwright, browser, browserContext, page, appProcess, processOutput, rootUrl);
}
catch (PlaywrightException)
{
await StopProcessAsync(appProcess);
playwright.Dispose();
throw new InvalidOperationException(
"Playwright browser is not installed. Run 'dotnet tool install --global Microsoft.Playwright.CLI' and then 'playwright install'.");
}
}
public async ValueTask DisposeAsync()
{
await BrowserContext.DisposeAsync();
await Browser.DisposeAsync();
playwright.Dispose();
await StopProcessAsync(appProcess);
}
private static int FindFreePort()
{
using var listener = new TcpListener(System.Net.IPAddress.Loopback, 0);
listener.Start();
return ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
}
private static async Task WaitForServerAsync(string rootUrl, Process appProcess, StringBuilder processOutput)
{
using var httpClient = new HttpClient();
var timeoutAt = DateTime.UtcNow.AddSeconds(30);
while (DateTime.UtcNow < timeoutAt)
{
if (appProcess.HasExited)
{
throw new InvalidOperationException(
$"MVC app process exited before the UI test server became ready.{Environment.NewLine}{processOutput}");
}
try
{
using var response = await httpClient.GetAsync(rootUrl);
if ((int)response.StatusCode < 500)
{
return;
}
}
catch
{
}
await Task.Delay(250);
}
throw new InvalidOperationException(
$"Timed out while waiting for the UI test server at {rootUrl}.{Environment.NewLine}{processOutput}");
}
private static string ResolveUiTestConnectionString()
{
var configuration = new ConfigurationBuilder()
.AddUserSecrets<Program>(optional: true)
.Build();
var connectionString = configuration.GetConnectionString("EventDB-Test");
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new InvalidOperationException(
"The EventDB-Test connection string must be available so UI tests can connect to the selected provider's test database.");
}
return connectionString;
}
private static async Task StopProcessAsync(Process appProcess)
{
if (appProcess.HasExited)
{
appProcess.Dispose();
return;
}
appProcess.Kill(entireProcessTree: true);
await appProcess.WaitForExitAsync();
appProcess.Dispose();
}
}

View File

@@ -0,0 +1,43 @@
# Events.Tests.UITests
This project contains Playwright-based UI tests for `Events-MVC`.
## Prerequisites
- .NET SDK 10.0
- Playwright CLI
- Playwright browser binaries
## Playwright Installation
Install the Playwright CLI once:
```powershell
dotnet tool install --global Microsoft.Playwright.CLI
```
Install browser binaries:
```powershell
playwright install
```
## Running the UI Tests
Run the full UI test project:
```powershell
dotnet test Events-MVC\Tests\Events.Tests.UITests\Events.Tests.UITests.csproj
```
Run a single test:
```powershell
dotnet test Events-MVC\Tests\Events.Tests.UITests\Events.Tests.UITests.csproj --filter HomeAndSportsPageTests.HomePageShouldDisplayEnglishDescription
```
## Notes
- The UI test harness starts the MVC application automatically
- UI tests connect the MVC application to the selected provider's test database from `ConnectionStrings:EventDB-Test`
- The browser is currently configured in headless mode

View File

@@ -0,0 +1,120 @@
#if POSTGRES
using Events.EF.Data.Postgres;
#else
using Events.EF.Data.MSSQL;
#endif
using Events.EF.Models;
using Events.MVC.Controllers;
using Events.MVC.Models.Countries;
using Events.Tests.UnitTests.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Events.Tests.UnitTests.Controllers;
public class CountriesControllerShould
{
[Fact]
public async Task ReturnPartialViewWithExpectedViewModelForExistingRow()
{
await using var ctx = ControllerTestContext.CreateContext();
ctx.Countries.Add(ControllerTestContext.CreateCountry());
await ctx.SaveChangesAsync();
var controller = CreateController(ctx, useSieve: false);
var result = await controller.Row("HR");
var partial = Assert.IsType<PartialViewResult>(result);
Assert.Equal("_CountryRow", partial.ViewName);
Assert.Equal("Croatia", Assert.IsType<CountryViewModel>(partial.Model).Name);
}
[Fact]
public async Task CreateCountry()
{
await using var ctx = ControllerTestContext.CreateContext();
var controller = CreateController(ctx);
var result = await controller.Create(
new CountryViewModel
{
Code = "de",
Alpha3 = "deu",
Name = "Germany",
Translations =
[
new CountryTranslationViewModel { LanguageCode = "hr", Name = "Germany" }
]
},
ControllerTestContext.EmptySieveModel());
var partial = Assert.IsType<PartialViewResult>(result);
Assert.Equal("_CountriesList", partial.ViewName);
var country = await ctx.Countries.SingleAsync();
Assert.Equal("DE", country.Code);
Assert.Equal("Germany", country.Name);
Assert.Contains("was added successfully", controller.Response.Headers[Events.MVC.Constants.HtmxHeaders.Trigger].ToString());
}
[Fact]
public async Task EditCountry()
{
await using var ctx = ControllerTestContext.CreateContext();
ctx.Countries.Add(ControllerTestContext.CreateCountry());
await ctx.SaveChangesAsync();
var controller = CreateController(ctx, useSieve: false);
var result = await controller.Edit("HR", new CountryViewModel
{
Code = "HR",
Alpha3 = "HRV",
Name = "Republic of Croatia",
Translations = []
});
var partial = Assert.IsType<PartialViewResult>(result);
Assert.Equal("_CountryRow", partial.ViewName);
Assert.Equal("Republic of Croatia", (await ctx.Countries.SingleAsync()).Name);
}
[Fact]
public async Task DeleteCountry()
{
await using var ctx = ControllerTestContext.CreateContext();
ctx.Countries.Add(ControllerTestContext.CreateCountry());
await ctx.SaveChangesAsync();
var controller = CreateController(ctx);
var result = await controller.Delete("HR", ControllerTestContext.EmptySieveModel());
var partial = Assert.IsType<PartialViewResult>(result);
Assert.Equal("_CountriesList", partial.ViewName);
Assert.Empty(ctx.Countries);
Assert.Contains("was deleted successfully", controller.Response.Headers[Events.MVC.Constants.HtmxHeaders.Trigger].ToString());
}
[Fact]
public async Task ReturnConflictWhenDeletingCountryWithRelatedPeople()
{
await using var ctx = ControllerTestContext.CreateContext();
ctx.Countries.Add(ControllerTestContext.CreateCountry());
ctx.People.Add(ControllerTestContext.CreatePerson());
await ctx.SaveChangesAsync();
var controller = CreateController(ctx);
var result = await controller.Delete("HR", ControllerTestContext.EmptySieveModel());
var content = Assert.IsType<ContentResult>(result);
Assert.Equal(409, controller.Response.StatusCode);
Assert.Equal("The country cannot be deleted because related people exist.", content.Content);
}
private static CountriesController CreateController(EventsContext ctx, bool useSieve = true)
{
return new CountriesController(
ctx,
useSieve ? ControllerTestContext.CreateSieveProcessor() : null!,
ControllerTestContext.CreatePagingOptions())
.WithTempData();
}
}

Some files were not shown because too many files have changed in this diff Show More