Files
hrynco-notification-service/HrynCo.NotificationService.DAL.Abstract/Templates/PushTemplateValidation.cs
T
agrynco aba4173827 feat(templates): add localized push templates and actions
Share template keys across email and push with independent editors and revisions. Render localized actions and preserve version-one delivery.

Ref: IT-1627
2026-10-31 09:38:05 +02:00

43 lines
2.3 KiB
C#

using System.Text.RegularExpressions;
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
public static partial class PushTemplateValidation
{
public static void Validate(PushTemplateDefinition definition)
{
EmailTemplateValidation.ValidateIdentity("Push", definition.Key);
EmailTemplateValidation.ValidateVariables(definition.Variables);
var names = definition.Variables.Select(v => v.Name).ToHashSet(StringComparer.Ordinal);
foreach (var language in definition.Languages)
ValidateTranslation(language, names);
if (definition.Languages.Select(l => l.LanguageCode).Distinct(StringComparer.Ordinal).Count() != definition.Languages.Count)
throw new EmailTemplateWriteException("Language codes must be unique within a template.", false);
}
private static void ValidateTranslation(PushTemplateTranslation translation, HashSet<string> names)
{
if (string.IsNullOrWhiteSpace(translation.LanguageCode) || translation.LanguageCode.Length > 10)
throw new EmailTemplateWriteException("A valid language code is required.", false);
if (string.IsNullOrWhiteSpace(translation.Title) || string.IsNullOrWhiteSpace(translation.Body))
throw new EmailTemplateWriteException("Every populated push language needs both Title and Body.", false);
ValidatePlaceholders(translation.Title, names);
ValidatePlaceholders(translation.Body, names);
var actions = PushTemplateActionValidation.Parse(translation.ActionsJson);
foreach (var button in actions.Buttons) ValidatePlaceholders(button.Label, names);
}
private static void ValidatePlaceholders(string text, HashSet<string> names)
{
foreach (Match match in Placeholder().Matches(text))
if (!names.Contains(match.Groups[1].Value))
throw new EmailTemplateWriteException("Every placeholder must be declared in this channel's variables.", false);
var remainder = Placeholder().Replace(text, "");
if (remainder.Contains("{{", StringComparison.Ordinal) || remainder.Contains("}}", StringComparison.Ordinal))
throw new EmailTemplateWriteException("Use complete placeholders in the form {{VariableName}}.", false);
}
[GeneratedRegex(@"\{\{([^{}]+)\}\}")]
private static partial Regex Placeholder();
}