109 lines
2.9 KiB
C#
109 lines
2.9 KiB
C#
using System.ComponentModel.DataAnnotations;
|
|
using maintenance.Data;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.RazorPages;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace maintenance.Pages.Admin.Templates;
|
|
|
|
[Authorize(Policy = "AdminOnly")]
|
|
public sealed class EditModel : PageModel
|
|
{
|
|
private readonly AppDbContext _dbContext;
|
|
|
|
public EditModel(AppDbContext dbContext)
|
|
{
|
|
_dbContext = dbContext;
|
|
}
|
|
|
|
[BindProperty]
|
|
public InputModel Input { get; set; } = new();
|
|
|
|
public string PreviewUrl { get; private set; } = "/errors/template";
|
|
|
|
public sealed class InputModel
|
|
{
|
|
public Guid Id { get; set; }
|
|
|
|
public string Name { get; set; } = string.Empty;
|
|
|
|
[Required]
|
|
[StringLength(200)]
|
|
public string Title { get; set; } = string.Empty;
|
|
|
|
[Required]
|
|
public string Body { get; set; } = string.Empty;
|
|
|
|
public string? SupportContactBlock { get; set; }
|
|
}
|
|
|
|
public async Task<IActionResult> OnGetAsync(Guid id)
|
|
{
|
|
var template = await _dbContext.Templates
|
|
.AsNoTracking()
|
|
.FirstOrDefaultAsync(t => t.Id == id, HttpContext.RequestAborted);
|
|
|
|
if (template is null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
Input = new InputModel
|
|
{
|
|
Id = template.Id,
|
|
Name = template.Name,
|
|
Title = template.Title,
|
|
Body = template.Body,
|
|
SupportContactBlock = template.SupportContactBlock
|
|
};
|
|
|
|
PreviewUrl = BuildPreviewUrl(template.Name);
|
|
|
|
return Page();
|
|
}
|
|
|
|
public async Task<IActionResult> OnPostAsync()
|
|
{
|
|
if (!ModelState.IsValid)
|
|
{
|
|
return Page();
|
|
}
|
|
|
|
var template = await _dbContext.Templates
|
|
.FirstOrDefaultAsync(t => t.Id == Input.Id, HttpContext.RequestAborted);
|
|
|
|
if (template is null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
template.Title = Input.Title.Trim();
|
|
template.Body = Input.Body.Trim();
|
|
template.SupportContactBlock = string.IsNullOrWhiteSpace(Input.SupportContactBlock)
|
|
? null
|
|
: Input.SupportContactBlock.Trim();
|
|
template.LastUpdatedAtUtc = DateTime.UtcNow;
|
|
template.LastUpdatedBy = User.Identity?.Name ?? "unknown";
|
|
|
|
await _dbContext.SaveChangesAsync(HttpContext.RequestAborted);
|
|
|
|
return RedirectToPage("./Index");
|
|
}
|
|
|
|
private static string BuildPreviewUrl(string templateName)
|
|
{
|
|
if (templateName.Equals("generic", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return "/errors/generic";
|
|
}
|
|
|
|
if (templateName.Equals("unavailable", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return "/errors/unavailable";
|
|
}
|
|
|
|
return $"/errors/template?template={Uri.EscapeDataString(templateName)}";
|
|
}
|
|
}
|