Prac2026_Email/ListmonkIntegration/Pages/Templates/Create.cshtml.cs
2026-07-15 17:17:03 +03:00

99 lines
3.3 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using ListmonkIntegration.Services;
using ListmonkIntegration.Models;
namespace ListmonkIntegration.Pages.Templates
{
public class CreateModel : PageModel
{
private readonly IListmonkService _listmonkService;
private readonly ILogger<CreateModel> _logger;
[BindProperty]
public string TemplateName { get; set; } = string.Empty;
[BindProperty]
public string Subject { get; set; } = string.Empty;
[BindProperty]
public string Body { get; set; } = string.Empty;
[BindProperty]
public int? SelectedListId { get; set; }
public SelectList Lists { get; set; } = new SelectList(Enumerable.Empty<SelectListItem>());
public string? DebugInfo { get; set; }
public CreateModel(IListmonkService listmonkService, ILogger<CreateModel> logger)
{
_listmonkService = listmonkService;
_logger = logger;
}
public async Task OnGetAsync()
{
_logger.LogInformation("OnGetAsync called, loading lists...");
await LoadListsAsync();
}
public async Task<IActionResult> OnPostAsync()
{
if (string.IsNullOrWhiteSpace(TemplateName) || string.IsNullOrWhiteSpace(Subject) || string.IsNullOrWhiteSpace(Body))
{
TempData["ErrorMessage"] = "Çàïîëíèòå âñå îáÿçàòåëüíûå ïîëÿ";
await LoadListsAsync();
return Page();
}
try
{
_logger.LogInformation($"Creating template: {TemplateName}");
var templateId = await _listmonkService.CreateTemplateAsync(
TemplateName,
Subject,
Body
);
_logger.LogInformation($"Template created successfully with ID: {templateId}");
TempData["SuccessMessage"] = $"Øàáëîí \"{TemplateName}\" óñïåøíî ñîçäàí!";
return RedirectToPage("/Campaigns/Index");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating template");
TempData["ErrorMessage"] = $"Îøèáêà ïðè ñîçäàíèè øàáëîíà: {ex.Message}";
await LoadListsAsync();
return Page();
}
}
private async Task LoadListsAsync()
{
try
{
_logger.LogInformation("Calling GetListsAsync...");
var lists = await _listmonkService.GetListsAsync();
_logger.LogInformation($"Got {lists.Count} lists from Listmonk");
foreach (var list in lists)
{
_logger.LogInformation($" List: ID={list.Id}, Name={list.Name}, Subscribers={list.SubscriberCount}");
}
Lists = new SelectList(lists, "Id", "Name");
DebugInfo = $"Çàãðóæåíî ñïèñêîâ: {lists.Count}";
}
catch (Exception ex)
{
_logger.LogError(ex, "Error loading lists");
DebugInfo = $"Îøèáêà çàãðóçêè ñïèñêîâ: {ex.Message}";
Lists = new SelectList(Enumerable.Empty<SelectListItem>());
}
}
}
}