Compare commits
63 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 343d67802c | |||
| 517b38791b | |||
| 1351279b36 | |||
| aba4173827 | |||
| d4ee8fc0c8 | |||
| 1631786ce2 | |||
| b30dba93e8 | |||
| 1c028313ba | |||
| c5eee69018 | |||
| 7ce4087d08 | |||
| 2dd5e318d7 | |||
| d5b7605da5 | |||
| 121ebbfbcd | |||
| 5a465d7257 | |||
| 7b640fe99e | |||
| 8e81572386 | |||
| 81654c0d33 | |||
| 36810dc5f1 | |||
| 8d9ed96f2c | |||
| a684caf7f7 | |||
| 27f3603d8f | |||
| a44b98292f | |||
| b088640e9b | |||
| 26847f1e9f | |||
| 50033a5bd4 | |||
| 01c622038d | |||
| 1ceb71b9a2 | |||
| bb0de0f2c1 | |||
| d5a2e538f0 | |||
| 9d6b0717e6 | |||
| 2757869176 | |||
| b8435ac07b | |||
| cc3857a409 | |||
| 94f0d45aaf | |||
| 07f536938f | |||
| e7d3953747 | |||
| 3381fcc2f8 | |||
| 3bd952ef9e | |||
| 285cc6abb7 | |||
| 9589095760 | |||
| 25fb48ccf0 | |||
| ab042c7617 | |||
| 0861e18cec | |||
| dfa097eb43 | |||
| c18f0b7fb1 | |||
| 50828d23ec | |||
| f3966705ad | |||
| b4d8497ea7 | |||
| 7b77062aa7 | |||
| 9490718c04 | |||
| 0d1aa4f6be | |||
| 637af06a9c | |||
| 334bf2a567 | |||
| 9c2edd4712 | |||
| 5c7b5f7b10 | |||
| b07cd06477 | |||
| 9a0aaf629b | |||
| 859ae0b50d | |||
| 09c3985fad | |||
| 8dab3c0dc0 | |||
| a6f9a0a530 | |||
| c303514414 | |||
| 18f7981ccc |
+10
-9
@@ -1,9 +1,10 @@
|
||||
**/.git
|
||||
**/.vs
|
||||
**/.idea
|
||||
**/bin
|
||||
**/obj
|
||||
**/*.user
|
||||
**/*.suo
|
||||
**/TestResults
|
||||
NuGet.Config
|
||||
**/.git
|
||||
**/.vs
|
||||
**/.idea
|
||||
**/bin
|
||||
**/obj
|
||||
**/*.user
|
||||
**/*.suo
|
||||
**/TestResults
|
||||
NuGet.Config
|
||||
docker/kubernetes/
|
||||
|
||||
@@ -480,3 +480,6 @@ $RECYCLE.BIN/
|
||||
|
||||
# Vim temporary swap files
|
||||
*.swp
|
||||
|
||||
# Local Docker Compose secrets and ports
|
||||
docker/environments/.env.local
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# HrynCo Notification Service Agent Rules
|
||||
|
||||
## Git workflow
|
||||
|
||||
- Treat `main` as the only default and integration branch for this repository.
|
||||
- Start every task branch from the latest `origin/main`.
|
||||
- Before creating a task branch, fetch the remote, switch to `main`, and fast-forward it from `origin/main`.
|
||||
- Create the task branch only after confirming that local `main` matches `origin/main`.
|
||||
- Open pull requests from the task branch into `main`.
|
||||
- Do not use `development` as the base or pull-request target for new work in this repository.
|
||||
- Do not commit, push, publish, deploy, or merge unless the repository owner explicitly requests that step.
|
||||
|
||||
Recommended branch preparation:
|
||||
|
||||
```text
|
||||
git fetch origin
|
||||
git switch main
|
||||
git pull --ff-only origin main
|
||||
git switch -c <task-branch>
|
||||
```
|
||||
|
||||
## Delivery
|
||||
|
||||
- Keep changes focused and preserve backward compatibility where practical.
|
||||
- Update the matching repository documentation when behavior, contracts, configuration, routing, or workflows change.
|
||||
- Run the solution build and relevant tests before handoff.
|
||||
- Use Conventional Commit messages with a lowercase subject and finish the commit body with `Ref: <issue-id>` when an issue exists.
|
||||
@@ -4,10 +4,13 @@
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<!-- Entity Framework Core -->
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="9.0.5" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.5" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.5" />
|
||||
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
<PackageVersion Include="FirebaseAdmin" Version="3.7.0" />
|
||||
<PackageVersion Include="HrynCo.DAL.Abstract" Version="1.0.11" />
|
||||
<PackageVersion Include="HrynCo.DAL.EF" Version="1.0.11" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.7" />
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.7" />
|
||||
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1" />
|
||||
<!-- MediatR -->
|
||||
<PackageVersion Include="MediatR" Version="12.4.1" />
|
||||
<PackageVersion Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
|
||||
@@ -28,15 +31,15 @@
|
||||
<PackageVersion Include="Serilog.Sinks.Seq" Version="9.0.0" />
|
||||
<!-- HrynCo shared packages -->
|
||||
<PackageVersion Include="HrynCo.Common" Version="1.0.11" />
|
||||
<PackageVersion Include="HrynCo.RabbitMq" Version="1.0.15" />
|
||||
<PackageVersion Include="HrynCo.DAL.Abstract" Version="1.0.1" />
|
||||
<PackageVersion Include="HrynCo.DAL.EF" Version="1.0.1" />
|
||||
<PackageVersion Include="HrynCo.RabbitMq" Version="1.0.17" />
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageVersion Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageVersion Include="xunit" Version="2.9.3" />
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
<PackageVersion Include="NSubstitute" Version="5.3.0" />
|
||||
<!-- Patched test-only dependency pulled by Testcontainers. -->
|
||||
<PackageVersion Include="SSH.NET" Version="2026.0.0" />
|
||||
<PackageVersion Include="Testcontainers.PostgreSql" Version="4.6.0" />
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.5" />
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.6" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<Description>RabbitMQ message contracts for HrynCo.NotificationService.</Description>
|
||||
<PackageTags>hrynco notification email rabbitmq contracts</PackageTags>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
<RepositoryUrl>https://gitea.grynco.com.ua/hrynco/hrynco-notification-service.git</RepositoryUrl>
|
||||
<RepositoryUrl>https://gitea.hrynco.com/hrynco/hrynco-notification-service.git</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -2,6 +2,10 @@ namespace HrynCo.NotificationService.Contracts.Messages;
|
||||
|
||||
public record NotificationResultData
|
||||
{
|
||||
public Guid? PushRegistrationId { get; init; }
|
||||
public Guid? PushBindingId { get; init; }
|
||||
public string? PushTokenHash { get; init; }
|
||||
public bool InvalidPushRegistration { get; init; }
|
||||
public required string ServiceName { get; init; }
|
||||
public required string RecipientEmail { get; init; }
|
||||
public required string TemplateKey { get; init; }
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace HrynCo.NotificationService.Contracts.Messages;
|
||||
|
||||
public sealed record PushActionMetadata
|
||||
{
|
||||
public string? ObjectId { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace HrynCo.NotificationService.Contracts.Messages;
|
||||
|
||||
public sealed record PushTemplateData
|
||||
{
|
||||
public required IReadOnlyDictionary<string, string> Bindings { get; init; }
|
||||
public required IReadOnlyDictionary<string, PushActionMetadata> Actions { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace HrynCo.NotificationService.Contracts.Messages;
|
||||
|
||||
using Hrynco.RabbitMq;
|
||||
|
||||
public sealed record SendPushMessage : IRabbitMqMessage<SendPushMessageData>
|
||||
{
|
||||
public CorrelationContext CorrelationContext { get; set; } = default!;
|
||||
public SendPushMessageData Data { get; set; } = default!;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace HrynCo.NotificationService.Contracts.Messages;
|
||||
|
||||
public sealed record SendPushMessageData
|
||||
{
|
||||
public required Guid RegistrationId { get; init; }
|
||||
public required Guid BindingId { get; init; }
|
||||
public required Guid UserId { get; init; }
|
||||
public required string ServiceName { get; init; }
|
||||
public string? Title { get; init; }
|
||||
public string? Body { get; init; }
|
||||
public string Route { get; init; } = "/home";
|
||||
public string? TemplateKey { get; init; }
|
||||
public string? LanguageCode { get; init; }
|
||||
public PushTemplateData? TemplateData { get; init; }
|
||||
public int Version { get; init; } = 1;
|
||||
public required DateTimeOffset ExpiresAt { get; init; }
|
||||
public string? Token { get; init; }
|
||||
public string? TokenHash { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace HrynCo.NotificationService.Contracts.Messages;
|
||||
|
||||
public enum SupportedMessageType
|
||||
{
|
||||
SendEmailV1,
|
||||
SendPushV1
|
||||
}
|
||||
+4
-4
@@ -1,13 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="HrynCo.DAL.Abstract" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="HrynCo.DAL.Abstract" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -4,7 +4,8 @@ namespace HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||
|
||||
public class EmailChannel : Entity
|
||||
{
|
||||
public required string ServiceName { get; set; }
|
||||
public required Guid ServiceId { get; set; }
|
||||
public string ServiceName { get; set; } = string.Empty;
|
||||
public int Priority { get; set; }
|
||||
public EmailChannelType EmailChannelType { get; set; }
|
||||
public required EmailChannelSettings Settings { get; set; }
|
||||
@@ -12,4 +13,4 @@ public class EmailChannel : Entity
|
||||
public int? MonthlyLimit { get; set; }
|
||||
public int WarnThresholdPercent { get; set; } = 90;
|
||||
public bool IsActive { get; set; } = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||
|
||||
/// <summary>
|
||||
/// Tracks email send counts per EmailChannel per calendar day.
|
||||
/// Monthly counts are derived by summing daily records within a month.
|
||||
/// </summary>
|
||||
public class EmailChannelUsage : Entity
|
||||
public class EmailChannelUsage
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public DateTimeOffset Created { get; set; }
|
||||
public DateTimeOffset? Updated { get; set; }
|
||||
public Guid ProviderId { get; set; }
|
||||
public DateOnly Date { get; set; }
|
||||
public int SentCount { get; set; }
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Push;
|
||||
|
||||
public interface IPushDeliveryRepository
|
||||
{
|
||||
Task<PushDeliveryOutcome> DeliverOnceAsync(Guid messageId, string serviceName,
|
||||
Func<CancellationToken, Task<PushDeliveryOutcome>> deliver, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Push;
|
||||
|
||||
public sealed record PushDeliveryOutcome(string? Error, bool InvalidRegistration = false);
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
using System.Net.Mail;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.PushChannels;
|
||||
|
||||
// Parse only service-account fields; never honor caller-supplied OAuth endpoints.
|
||||
public sealed class FirebaseServiceAccountCredentials
|
||||
{
|
||||
public required string ProjectId { get; init; }
|
||||
public required string ClientEmail { get; init; }
|
||||
public required string PrivateKey { get; init; }
|
||||
|
||||
public static bool IsValidProjectId(string projectId) => Regex.IsMatch(projectId,
|
||||
"^[a-z][a-z0-9-]{4,28}[a-z0-9]$", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));
|
||||
|
||||
public static FirebaseServiceAccountCredentials Parse(string json, string projectId)
|
||||
{
|
||||
if (!IsValidProjectId(projectId) || json.Length > 32768)
|
||||
throw new FormatException("Invalid Firebase configuration.");
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var root = document.RootElement;
|
||||
if (Read(root, "type") != "service_account" || Read(root, "project_id") != projectId)
|
||||
throw new FormatException("The service account must belong to the selected Firebase project.");
|
||||
var email = Read(root, "client_email");
|
||||
if (!MailAddress.TryCreate(email, out var address) || address.Address != email)
|
||||
throw new FormatException("Invalid service account email.");
|
||||
var key = Read(root, "private_key");
|
||||
using var rsa = RSA.Create();
|
||||
rsa.ImportFromPem(key);
|
||||
// Exporting private parameters also rejects a public-key-only PEM.
|
||||
rsa.ExportParameters(true);
|
||||
return new FirebaseServiceAccountCredentials { ProjectId = projectId, ClientEmail = email, PrivateKey = key };
|
||||
}
|
||||
|
||||
private static string Read(JsonElement root, string name)
|
||||
{
|
||||
if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty(name, out var value)
|
||||
|| value.ValueKind != JsonValueKind.String)
|
||||
throw new FormatException("Missing service account fields.");
|
||||
return value.GetString() ?? string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.PushChannels;
|
||||
|
||||
public interface IPushChannelRepository
|
||||
{
|
||||
Task<IReadOnlyList<PushChannel>> GetAllAsync(CancellationToken ct = default);
|
||||
Task<PushChannel?> GetByIdAsync(Guid id, CancellationToken ct = default);
|
||||
Task<PushChannel?> GetActiveForServiceAsync(Guid serviceId, CancellationToken ct = default);
|
||||
Task<string?> GetCredentialsAsync(Guid id, CancellationToken ct = default);
|
||||
Task SaveAsync(PushChannel channel, string credentialsJson, bool isNew, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.PushChannels;
|
||||
|
||||
// Safe administration/read model: credentials are fetched separately by server code.
|
||||
public sealed class PushChannel : Entity
|
||||
{
|
||||
public required Guid ServiceId { get; set; }
|
||||
public string ServiceName { get; set; } = string.Empty;
|
||||
public required string FirebaseProjectId { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.PushChannels;
|
||||
|
||||
public sealed class PushChannelWriteException(string message, bool isConflict = true) : Exception(message)
|
||||
{
|
||||
public bool IsConflict { get; } = isConflict;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ namespace HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
public interface IEmailChannelRepository
|
||||
{
|
||||
Task<IReadOnlyList<EmailChannel>> GetAllAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<EmailChannel>> GetByServiceAsync(string serviceName, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<EmailChannel>> GetByServiceAsync(Guid serviceId, CancellationToken ct = default);
|
||||
Task<EmailChannel?> GetByIdAsync(Guid id, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<ChannelWithUsage>> GetAllWithUsageSummaryAsync(DateOnly today, CancellationToken ct = default);
|
||||
Task AddAsync(EmailChannel channel, CancellationToken ct = default);
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
|
||||
public interface IEmailTemplateDefinitionRepository
|
||||
{
|
||||
Task<IReadOnlyList<EmailTemplateDefinition>> GetDefinitionsAsync(string? serviceName = null, string? key = null, CancellationToken ct = default);
|
||||
Task<EmailTemplateDefinition?> GetDefinitionAsync(string serviceName, string key, CancellationToken ct = default);
|
||||
Task<EmailTemplateDefinition?> GetDefinitionAsync(Guid serviceId, string key, CancellationToken ct = default);
|
||||
Task<EmailTemplateDefinition?> UpsertDefinitionAsync(EmailTemplateDefinitionPatch patch, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<EmailTemplateDefinition>> GetDefinitionsAsync(Guid serviceId, CancellationToken ct = default);
|
||||
Task<bool> DeleteDefinitionAsync(Guid serviceId, string key, Guid revision, CancellationToken ct = default);
|
||||
Task SaveDefinitionAsync(EmailTemplateDefinition definition, bool isNew, CancellationToken ct = default);
|
||||
}
|
||||
@@ -4,10 +4,10 @@ namespace HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
|
||||
public interface IEmailTemplateRepository
|
||||
{
|
||||
Task<IReadOnlyList<EmailTemplate>> GetAllAsync(CancellationToken ct = default);
|
||||
Task<IReadOnlyList<EmailTemplate>> GetAllAsync(string? serviceName = null, string? key = null, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default);
|
||||
Task<EmailTemplate?> GetAsync(string serviceName, string key, string languageCode, CancellationToken ct = default);
|
||||
Task AddAsync(EmailTemplate template, CancellationToken ct = default);
|
||||
Task UpdateAsync(EmailTemplate template, CancellationToken ct = default);
|
||||
Task DeleteAsync(EmailTemplate template, CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
|
||||
public interface INotificationServiceRepository
|
||||
{
|
||||
Task<IReadOnlyList<NotificationServiceInfo>> GetAllAsync(CancellationToken ct = default);
|
||||
Task<NotificationServiceInfo?> GetAsync(Guid id, CancellationToken ct = default);
|
||||
Task<NotificationServiceInfo?> GetByNameAsync(string name, CancellationToken ct = default);
|
||||
Task<bool> DeleteAsync(Guid id, Guid revision, CancellationToken ct = default);
|
||||
Task SaveAsync(NotificationServiceInfo service, bool isNew, CancellationToken ct = default);
|
||||
Task RemoveLanguageAsync(Guid serviceId, Guid languageId, int expectedVersionCount, Guid expectedRevision, CancellationToken ct = default);
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
|
||||
public interface IPushTemplateDefinitionRepository
|
||||
{
|
||||
Task<PushTemplateDefinition?> UpsertDefinitionAsync(PushTemplateDefinitionPatch patch, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<PushTemplateDefinition>> GetDefinitionsAsync(Guid serviceId, CancellationToken ct = default);
|
||||
Task<PushTemplateDefinition?> GetAsync(Guid serviceId, string key, CancellationToken ct = default);
|
||||
Task SaveAsync(PushTemplateDefinition definition, bool isNew, CancellationToken ct = default);
|
||||
Task<bool> DeleteAsync(Guid serviceId, string key, Guid revision, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
public sealed class EmailTemplateDefinition : Entity
|
||||
{
|
||||
public Guid ServiceId { get; set; }
|
||||
public required string ServiceName { get; set; }
|
||||
public required string Key { get; set; }
|
||||
public Guid Revision { get; set; }
|
||||
public IReadOnlyList<EmailTemplateVariable> Variables { get; set; } = [];
|
||||
public IReadOnlyList<EmailTemplate> Languages { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
public sealed class EmailTemplateDefinitionPatch
|
||||
{
|
||||
public Guid ServiceId { get; init; }
|
||||
public required string Key { get; init; }
|
||||
public Guid? Revision { get; init; }
|
||||
public required IReadOnlyList<EmailTemplateVariable> Variables { get; init; }
|
||||
public required IReadOnlyList<EmailTemplate> Translations { get; init; }
|
||||
public IReadOnlyList<string> RemoveLanguageCodes { get; init; } = [];
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
public static class EmailTemplateValidation
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
PropertyNameCaseInsensitive = false,
|
||||
UnmappedMemberHandling = System.Text.Json.Serialization.JsonUnmappedMemberHandling.Disallow
|
||||
};
|
||||
|
||||
public static IReadOnlyList<EmailTemplateVariable> ParseVariables(string json)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
if (document.RootElement.ValueKind == JsonValueKind.Null)
|
||||
throw new EmailTemplateWriteException("Variables must be a JSON array.", false);
|
||||
if (document.RootElement.ValueKind != JsonValueKind.Array)
|
||||
throw new JsonException("Variables must be an array.");
|
||||
foreach (var item in document.RootElement.EnumerateArray())
|
||||
ValidateVariableShape(item);
|
||||
var variables = JsonSerializer.Deserialize<List<EmailTemplateVariable>>(json, JsonOptions);
|
||||
ValidateVariables(variables);
|
||||
return variables!;
|
||||
}
|
||||
|
||||
private static void ValidateVariableShape(JsonElement item)
|
||||
{
|
||||
if (item.ValueKind != JsonValueKind.Object)
|
||||
throw new JsonException("Each variable must be an object.");
|
||||
if (!item.TryGetProperty("name", out var name) || name.ValueKind != JsonValueKind.String)
|
||||
throw new JsonException("Every variable needs a name string.");
|
||||
if (!item.TryGetProperty("required", out var required) || required.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
|
||||
throw new JsonException("Every variable needs a required boolean.");
|
||||
}
|
||||
|
||||
public static void ValidateVariables(IReadOnlyList<EmailTemplateVariable>? variables)
|
||||
{
|
||||
if (variables is null)
|
||||
throw new EmailTemplateWriteException("Variables must be a JSON array.", false);
|
||||
if (variables.Any(v => v is null || string.IsNullOrWhiteSpace(v.Name)))
|
||||
throw new EmailTemplateWriteException("Every variable needs a non-empty name.", false);
|
||||
if (variables.Select(v => v.Name).Distinct(StringComparer.Ordinal).Count() != variables.Count)
|
||||
throw new EmailTemplateWriteException("Variable names must be unique.", false);
|
||||
}
|
||||
|
||||
public static bool ContractsEqual(IReadOnlyList<EmailTemplateVariable> left, IReadOnlyList<EmailTemplateVariable> right) =>
|
||||
left.OrderBy(v => v.Name, StringComparer.Ordinal).SequenceEqual(right.OrderBy(v => v.Name, StringComparer.Ordinal));
|
||||
|
||||
public static void ValidateIdentity(string serviceName, string key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(serviceName) || serviceName.Length > 100)
|
||||
throw new EmailTemplateWriteException("Service name is required and must be at most 100 characters.", false);
|
||||
if (string.IsNullOrWhiteSpace(key) || key.Length > 100)
|
||||
throw new EmailTemplateWriteException("Key is required and must be at most 100 characters.", false);
|
||||
}
|
||||
|
||||
public static void ValidateLanguage(EmailTemplate template)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(template.LanguageCode) || template.LanguageCode.Length > 10)
|
||||
throw new EmailTemplateWriteException("Language code is required and must be at most 10 characters.", false);
|
||||
if (string.IsNullOrWhiteSpace(template.Subject) || string.IsNullOrWhiteSpace(template.HtmlBody) || string.IsNullOrWhiteSpace(template.TextBody))
|
||||
throw new EmailTemplateWriteException("Every language needs a subject, HTML body, and text body.", false);
|
||||
}
|
||||
|
||||
public static void ValidateDefinition(EmailTemplateDefinition definition)
|
||||
{
|
||||
ValidateIdentity(definition.ServiceName, definition.Key);
|
||||
ValidateVariables(definition.Variables);
|
||||
foreach (var language in definition.Languages)
|
||||
ValidateLanguage(language);
|
||||
var codes = definition.Languages.Select(t => t.LanguageCode);
|
||||
if (codes.Distinct(StringComparer.Ordinal).Count() != definition.Languages.Count)
|
||||
throw new EmailTemplateWriteException("Language codes must be unique within a template.", false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
public sealed class EmailTemplateWriteException(string message, bool isConflict = true) : Exception(message)
|
||||
{
|
||||
public bool IsConflict { get; } = isConflict;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
public sealed class NotificationServiceInfo
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public Guid Revision { get; set; }
|
||||
public IReadOnlyList<ServiceLanguageInfo> Languages { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
public static class PushTemplateActionValidation
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
PropertyNameCaseInsensitive = false
|
||||
};
|
||||
|
||||
public static PushTemplateActions Parse(string json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
throw new EmailTemplateWriteException("Actions JSON is required. Use {} for no actions.", false);
|
||||
try
|
||||
{
|
||||
var actions = JsonSerializer.Deserialize<PushTemplateActions>(json, JsonOptions)
|
||||
?? throw new JsonException();
|
||||
Validate(actions);
|
||||
return actions;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
throw new EmailTemplateWriteException("Invalid actions JSON. Use defaultAction and buttons with action and label.", false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Validate(PushTemplateActions actions)
|
||||
{
|
||||
if (actions.DefaultAction is not null) ValidateKey(actions.DefaultAction);
|
||||
if (actions.Buttons is null || actions.Buttons.Count > 3)
|
||||
throw new EmailTemplateWriteException("Configure up to three push buttons.", false);
|
||||
var keys = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var button in actions.Buttons)
|
||||
{
|
||||
if (button is null) throw new EmailTemplateWriteException("A button needs an action and label.", false);
|
||||
ValidateKey(button.Action);
|
||||
if (!keys.Add(button.Action) || string.IsNullOrWhiteSpace(button.Label) || button.Label.Length > 100)
|
||||
throw new EmailTemplateWriteException("Button actions must be unique and labels must contain 1–100 characters.", false);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateKey(string key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key) || key.Length > 100 || key.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '_' and not '-' and not '.'))
|
||||
throw new EmailTemplateWriteException("Action keys need 1–100 letters, digits, dots, underscores or hyphens.", false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
|
||||
public sealed record PushTemplateActions
|
||||
{
|
||||
public string? DefaultAction { get; init; }
|
||||
public IReadOnlyList<PushTemplateButton> Buttons { get; init; } = [];
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
|
||||
public sealed record PushTemplateButton
|
||||
{
|
||||
public required string Action { get; init; }
|
||||
public required string Label { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
public sealed class PushTemplateDefinition
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid ServiceId { get; set; }
|
||||
public required string Key { get; set; }
|
||||
public Guid Revision { get; set; }
|
||||
public IReadOnlyList<EmailTemplateVariable> Variables { get; set; } = [];
|
||||
public IReadOnlyList<PushTemplateTranslation> Languages { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
public sealed class PushTemplateDefinitionPatch
|
||||
{
|
||||
public Guid ServiceId { get; init; }
|
||||
public required string Key { get; init; }
|
||||
public Guid? Revision { get; init; }
|
||||
public required IReadOnlyList<EmailTemplateVariable> Variables { get; init; }
|
||||
public required IReadOnlyList<PushTemplateTranslation> Translations { get; init; }
|
||||
public IReadOnlyList<string> RemoveLanguageCodes { get; init; } = [];
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
public sealed class PushTemplateTranslation
|
||||
{
|
||||
public string ActionsJson { get; set; } = "{}";
|
||||
public required string LanguageCode { get; set; }
|
||||
public required string Title { get; set; }
|
||||
public required string Body { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
|
||||
public sealed class ServiceLanguageInfo
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public required string Code { get; set; }
|
||||
public int VersionCount { get; set; }
|
||||
}
|
||||
@@ -13,12 +13,10 @@ internal class EmailChannelEntityConfiguration : IEntityTypeConfiguration<EmailC
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.Id).HasColumnName("id");
|
||||
|
||||
builder.Property(x => x.ServiceName)
|
||||
.HasColumnName("service_name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100);
|
||||
|
||||
builder.HasIndex(x => new { x.ServiceName, x.Priority });
|
||||
builder.Property(x => x.ServiceId).HasColumnName("service_id").IsRequired();
|
||||
builder.HasOne(x => x.Service).WithMany().HasForeignKey(x => x.ServiceId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
builder.HasIndex(x => new { x.ServiceId, x.Priority });
|
||||
|
||||
builder.Property(x => x.Priority).HasColumnName("priority");
|
||||
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Configurations;
|
||||
|
||||
internal sealed class EmailTemplateDefinitionEntityConfiguration : IEntityTypeConfiguration<EmailTemplateDefinitionEntity>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<EmailTemplateDefinitionEntity> builder)
|
||||
{
|
||||
builder.ToTable("email_template_definitions");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.Id).HasColumnName("id");
|
||||
builder.Property(x => x.ServiceId).HasColumnName("service_id");
|
||||
builder.Property(x => x.Key).HasColumnName("key").HasMaxLength(100).IsRequired();
|
||||
builder.Property(x => x.Revision).HasColumnName("revision").IsConcurrencyToken();
|
||||
builder.HasIndex(x => new { x.ServiceId, x.Key }).IsUnique();
|
||||
builder.HasAlternateKey(x => new { x.Id, x.ServiceId });
|
||||
builder.HasOne(x => x.Service).WithMany().HasForeignKey(x => x.ServiceId).OnDelete(DeleteBehavior.Restrict);
|
||||
builder.HasOne(x => x.Template).WithOne(x => x.Email)
|
||||
.HasForeignKey<EmailTemplateDefinitionEntity>(x => new { x.ServiceId, x.Key })
|
||||
.HasPrincipalKey<TemplateEntity>(x => new { x.ServiceId, x.Key }).OnDelete(DeleteBehavior.Cascade);
|
||||
builder.Property(x => x.Created).HasColumnName("created");
|
||||
builder.Property(x => x.Updated).HasColumnName("updated");
|
||||
builder.OwnsMany(x => x.Variables, v =>
|
||||
{
|
||||
v.ToJson("variables");
|
||||
v.Property(x => x.Name).HasJsonPropertyName("name");
|
||||
v.Property(x => x.Required).HasJsonPropertyName("required");
|
||||
});
|
||||
}
|
||||
}
|
||||
+14
-40
@@ -4,53 +4,27 @@ using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Configurations;
|
||||
|
||||
internal class EmailTemplateEntityConfiguration : IEntityTypeConfiguration<EmailTemplateEntity>
|
||||
internal sealed class EmailTemplateEntityConfiguration : IEntityTypeConfiguration<EmailTemplateEntity>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<EmailTemplateEntity> builder)
|
||||
{
|
||||
builder.ToTable("email_templates");
|
||||
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.Id).HasColumnName("id");
|
||||
|
||||
builder.Property(x => x.ServiceName)
|
||||
.HasColumnName("service_name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100);
|
||||
|
||||
builder.Property(x => x.Key)
|
||||
.HasColumnName("key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100);
|
||||
|
||||
builder.Property(x => x.LanguageCode)
|
||||
.HasColumnName("language_code")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10);
|
||||
|
||||
builder.HasIndex(x => new { x.ServiceName, x.Key, x.LanguageCode })
|
||||
.IsUnique();
|
||||
|
||||
builder.Property(x => x.Subject)
|
||||
.HasColumnName("subject")
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(x => x.HtmlBody)
|
||||
.HasColumnName("html_body")
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(x => x.TextBody)
|
||||
.HasColumnName("text_body")
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(x => x.DefinitionId).HasColumnName("definition_id");
|
||||
builder.Property(x => x.ServiceId).HasColumnName("service_id");
|
||||
builder.Property(x => x.ServiceLanguageId).HasColumnName("service_language_id");
|
||||
builder.HasIndex(x => new { x.DefinitionId, x.ServiceLanguageId }).IsUnique();
|
||||
builder.HasOne(x => x.Definition).WithMany(x => x.Languages)
|
||||
.HasForeignKey(x => new { x.DefinitionId, x.ServiceId })
|
||||
.HasPrincipalKey(x => new { x.Id, x.ServiceId }).OnDelete(DeleteBehavior.Cascade);
|
||||
builder.HasOne(x => x.ServiceLanguage).WithMany()
|
||||
.HasForeignKey(x => new { x.ServiceLanguageId, x.ServiceId })
|
||||
.HasPrincipalKey(x => new { x.Id, x.ServiceId }).OnDelete(DeleteBehavior.Restrict);
|
||||
builder.Property(x => x.Subject).HasColumnName("subject").IsRequired();
|
||||
builder.Property(x => x.HtmlBody).HasColumnName("html_body").IsRequired();
|
||||
builder.Property(x => x.TextBody).HasColumnName("text_body").IsRequired();
|
||||
builder.Property(x => x.Created).HasColumnName("created");
|
||||
builder.Property(x => x.Updated).HasColumnName("updated");
|
||||
|
||||
builder.OwnsMany(x => x.Variables, v =>
|
||||
{
|
||||
v.ToJson("variables");
|
||||
v.Property(x => x.Name).HasJsonPropertyName("name");
|
||||
v.Property(x => x.Required).HasJsonPropertyName("required");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Configurations;
|
||||
|
||||
internal sealed class PushChannelEntityConfiguration : IEntityTypeConfiguration<PushChannelEntity>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<PushChannelEntity> builder)
|
||||
{
|
||||
builder.ToTable("push_channels");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.Id).HasColumnName("id");
|
||||
builder.Property(x => x.ServiceId).HasColumnName("service_id");
|
||||
builder.HasIndex(x => x.ServiceId).IsUnique();
|
||||
builder.HasOne(x => x.Service).WithMany().HasForeignKey(x => x.ServiceId).OnDelete(DeleteBehavior.Restrict);
|
||||
builder.Property(x => x.FirebaseProjectId).HasColumnName("firebase_project_id").HasMaxLength(30).IsRequired();
|
||||
builder.Property(x => x.CredentialsJson).HasColumnName("credentials").HasColumnType("jsonb").IsRequired();
|
||||
builder.Property(x => x.IsActive).HasColumnName("is_active");
|
||||
builder.Property(x => x.Created).HasColumnName("created");
|
||||
builder.Property(x => x.Updated).HasColumnName("updated");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace HrynCo.NotificationService.DAL.EF.Configurations;
|
||||
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
public sealed class PushDeliveryEntityConfiguration : IEntityTypeConfiguration<PushDeliveryEntity>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<PushDeliveryEntity> builder)
|
||||
{
|
||||
builder.ToTable("PushDeliveries");
|
||||
builder.HasKey(x => new { x.ServiceName, x.MessageId });
|
||||
builder.Property(x => x.ServiceName).HasMaxLength(128);
|
||||
builder.Property(x => x.Error).HasMaxLength(256);
|
||||
builder.HasIndex(x => x.CompletedAt);
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Configurations;
|
||||
|
||||
internal sealed class PushTemplateDefinitionEntityConfiguration : IEntityTypeConfiguration<PushTemplateDefinitionEntity>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<PushTemplateDefinitionEntity> builder)
|
||||
{
|
||||
builder.ToTable("push_template_definitions");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.Id).HasColumnName("id");
|
||||
builder.Property(x => x.ServiceId).HasColumnName("service_id");
|
||||
builder.Property(x => x.Key).HasColumnName("key").HasMaxLength(100).IsRequired();
|
||||
builder.Property(x => x.Revision).HasColumnName("revision").IsConcurrencyToken();
|
||||
builder.HasIndex(x => new { x.ServiceId, x.Key }).IsUnique();
|
||||
builder.HasAlternateKey(x => new { x.Id, x.ServiceId });
|
||||
builder.HasOne(x => x.Template).WithOne(x => x.Push)
|
||||
.HasForeignKey<PushTemplateDefinitionEntity>(x => new { x.ServiceId, x.Key })
|
||||
.HasPrincipalKey<TemplateEntity>(x => new { x.ServiceId, x.Key }).OnDelete(DeleteBehavior.Cascade);
|
||||
builder.Property(x => x.Created).HasColumnName("created");
|
||||
builder.Property(x => x.Updated).HasColumnName("updated");
|
||||
builder.OwnsMany(x => x.Variables, v =>
|
||||
{
|
||||
v.ToJson("variables");
|
||||
v.Property(x => x.Name).HasJsonPropertyName("name");
|
||||
v.Property(x => x.Required).HasJsonPropertyName("required");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Configurations;
|
||||
|
||||
internal sealed class PushTemplateEntityConfiguration : IEntityTypeConfiguration<PushTemplateEntity>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<PushTemplateEntity> builder)
|
||||
{
|
||||
builder.ToTable("push_templates");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.Id).HasColumnName("id");
|
||||
builder.Property(x => x.DefinitionId).HasColumnName("definition_id");
|
||||
builder.Property(x => x.ServiceId).HasColumnName("service_id");
|
||||
builder.Property(x => x.ServiceLanguageId).HasColumnName("service_language_id");
|
||||
builder.HasIndex(x => new { x.DefinitionId, x.ServiceLanguageId }).IsUnique();
|
||||
builder.HasOne(x => x.Definition).WithMany(x => x.Languages)
|
||||
.HasForeignKey(x => new { x.DefinitionId, x.ServiceId })
|
||||
.HasPrincipalKey(x => new { x.Id, x.ServiceId }).OnDelete(DeleteBehavior.Cascade);
|
||||
builder.HasOne(x => x.ServiceLanguage).WithMany()
|
||||
.HasForeignKey(x => new { x.ServiceLanguageId, x.ServiceId })
|
||||
.HasPrincipalKey(x => new { x.Id, x.ServiceId }).OnDelete(DeleteBehavior.Restrict);
|
||||
builder.Property(x => x.Title).HasColumnName("title").IsRequired();
|
||||
builder.Property(x => x.Body).HasColumnName("body").IsRequired();
|
||||
builder.Property(x => x.ActionsJson).HasColumnName("actions").HasColumnType("jsonb").IsRequired();
|
||||
builder.Property(x => x.Created).HasColumnName("created");
|
||||
builder.Property(x => x.Updated).HasColumnName("updated");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Configurations;
|
||||
|
||||
internal sealed class ServiceEntityConfiguration : IEntityTypeConfiguration<ServiceEntity>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<ServiceEntity> builder)
|
||||
{
|
||||
builder.ToTable("services");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.Id).HasColumnName("id");
|
||||
builder.Property(x => x.Name).HasColumnName("name").HasMaxLength(100).IsRequired();
|
||||
builder.HasIndex(x => x.Name).IsUnique();
|
||||
builder.Property(x => x.Revision).HasColumnName("revision").IsConcurrencyToken();
|
||||
builder.Property(x => x.Created).HasColumnName("created");
|
||||
builder.Property(x => x.Updated).HasColumnName("updated");
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Configurations;
|
||||
|
||||
internal sealed class ServiceLanguageEntityConfiguration : IEntityTypeConfiguration<ServiceLanguageEntity>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<ServiceLanguageEntity> builder)
|
||||
{
|
||||
builder.ToTable("service_languages");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.Id).HasColumnName("id");
|
||||
builder.Property(x => x.ServiceId).HasColumnName("service_id");
|
||||
builder.Property(x => x.Code).HasColumnName("code").HasMaxLength(10).IsRequired();
|
||||
builder.HasIndex(x => new { x.ServiceId, x.Code }).IsUnique();
|
||||
builder.HasAlternateKey(x => new { x.Id, x.ServiceId });
|
||||
builder.HasOne(x => x.Service).WithMany(x => x.Languages).HasForeignKey(x => x.ServiceId).OnDelete(DeleteBehavior.Restrict);
|
||||
builder.Property(x => x.Created).HasColumnName("created");
|
||||
builder.Property(x => x.Updated).HasColumnName("updated");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Configurations;
|
||||
|
||||
internal sealed class TemplateEntityConfiguration : IEntityTypeConfiguration<TemplateEntity>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<TemplateEntity> builder)
|
||||
{
|
||||
builder.ToTable("templates");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.Id).HasColumnName("id");
|
||||
builder.Property(x => x.ServiceId).HasColumnName("service_id");
|
||||
builder.Property(x => x.Key).HasColumnName("key").HasMaxLength(100).IsRequired();
|
||||
builder.HasAlternateKey(x => new { x.ServiceId, x.Key });
|
||||
builder.HasOne(x => x.Service).WithMany().HasForeignKey(x => x.ServiceId).OnDelete(DeleteBehavior.Restrict);
|
||||
builder.Property(x => x.Created).HasColumnName("created");
|
||||
builder.Property(x => x.Updated).HasColumnName("updated");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace HrynCo.NotificationService.DAL.EF.Core;
|
||||
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
using HrynCo.DAL.EF.Core;
|
||||
|
||||
public abstract class NotificationBaseRepository<TEntity>
|
||||
: BaseRepository<NotificationEfRepository<TEntity>, NotificationDbContext, TEntity, Guid> where TEntity : Entity
|
||||
{
|
||||
protected NotificationBaseRepository(NotificationDbContext dbContext)
|
||||
{
|
||||
DbContext = dbContext;
|
||||
}
|
||||
|
||||
private NotificationDbContext DbContext { get; set; }
|
||||
|
||||
protected override NotificationEfRepository<TEntity> CreateEfRepository()
|
||||
{
|
||||
return new NotificationEfRepository<TEntity>(DbContext);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace HrynCo.NotificationService.DAL.EF.Core;
|
||||
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
using HrynCo.DAL.EF.Core;
|
||||
|
||||
public class NotificationEfRepository<TEntity> : BaseEfRepository<NotificationDbContext, TEntity, Guid>
|
||||
where TEntity : class, IEntity<Guid>
|
||||
{
|
||||
public NotificationEfRepository(NotificationDbContext dbContext) :
|
||||
base(dbContext)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
using HrynCo.DAL.EF.Core;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Core;
|
||||
|
||||
internal sealed class UnitOfWork : EfUnitOfWork<NotificationDbContext>
|
||||
{
|
||||
public UnitOfWork(NotificationDbContext context) : base(context)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,8 @@ namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal class EmailChannelEntity : Entity
|
||||
{
|
||||
public required string ServiceName { get; set; }
|
||||
public Guid ServiceId { get; set; }
|
||||
public ServiceEntity Service { get; set; } = null!;
|
||||
public int Priority { get; set; }
|
||||
public EmailChannelType EmailChannelType { get; set; }
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal sealed class EmailTemplateDefinitionEntity : Entity
|
||||
{
|
||||
public TemplateEntity Template { get; set; } = null!;
|
||||
public Guid ServiceId { get; set; }
|
||||
public ServiceEntity Service { get; set; } = null!;
|
||||
public required string Key { get; set; }
|
||||
public Guid Revision { get; set; } = Guid.NewGuid();
|
||||
public List<EmailTemplateVariableData> Variables { get; set; } = [];
|
||||
public List<EmailTemplateEntity> Languages { get; set; } = [];
|
||||
}
|
||||
@@ -4,17 +4,12 @@ namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal class EmailTemplateEntity : Entity
|
||||
{
|
||||
public required string ServiceName { get; set; }
|
||||
public required string Key { get; set; }
|
||||
public required string LanguageCode { get; set; }
|
||||
public Guid DefinitionId { get; set; }
|
||||
public EmailTemplateDefinitionEntity Definition { get; set; } = null!;
|
||||
public Guid ServiceId { get; set; }
|
||||
public Guid ServiceLanguageId { get; set; }
|
||||
public ServiceLanguageEntity ServiceLanguage { get; set; } = null!;
|
||||
public required string Subject { get; set; }
|
||||
public required string HtmlBody { get; set; }
|
||||
public required string TextBody { get; set; }
|
||||
public List<EmailTemplateVariableData> Variables { get; set; } = [];
|
||||
}
|
||||
|
||||
internal class EmailTemplateVariableData
|
||||
{
|
||||
public required string Name { get; set; }
|
||||
public bool Required { get; set; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal sealed class EmailTemplateVariableData
|
||||
{
|
||||
public required string Name { get; set; }
|
||||
public bool Required { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal sealed class PushChannelEntity : Entity
|
||||
{
|
||||
public Guid ServiceId { get; set; }
|
||||
public ServiceEntity Service { get; set; } = null!;
|
||||
public required string FirebaseProjectId { get; set; }
|
||||
public required string CredentialsJson { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
public sealed class PushDeliveryEntity
|
||||
{
|
||||
public Guid MessageId { get; set; }
|
||||
public string ServiceName { get; set; } = "";
|
||||
public string? Error { get; set; }
|
||||
public bool InvalidRegistration { get; set; }
|
||||
public DateTimeOffset CompletedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal sealed class PushTemplateDefinitionEntity : Entity
|
||||
{
|
||||
public Guid ServiceId { get; set; }
|
||||
public required string Key { get; set; }
|
||||
public TemplateEntity Template { get; set; } = null!;
|
||||
public Guid Revision { get; set; } = Guid.NewGuid();
|
||||
public List<PushTemplateVariableData> Variables { get; set; } = [];
|
||||
public List<PushTemplateEntity> Languages { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal sealed class PushTemplateEntity : Entity
|
||||
{
|
||||
public Guid DefinitionId { get; set; }
|
||||
public PushTemplateDefinitionEntity Definition { get; set; } = null!;
|
||||
public Guid ServiceId { get; set; }
|
||||
public Guid ServiceLanguageId { get; set; }
|
||||
public ServiceLanguageEntity ServiceLanguage { get; set; } = null!;
|
||||
public required string Title { get; set; }
|
||||
public required string Body { get; set; }
|
||||
public string ActionsJson { get; set; } = "{}";
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal sealed class PushTemplateVariableData
|
||||
{
|
||||
public required string Name { get; set; }
|
||||
public bool Required { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal sealed class ServiceEntity : Entity
|
||||
{
|
||||
public required string Name { get; set; }
|
||||
public Guid Revision { get; set; } = Guid.NewGuid();
|
||||
public List<ServiceLanguageEntity> Languages { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal sealed class ServiceLanguageEntity : Entity
|
||||
{
|
||||
public Guid ServiceId { get; set; }
|
||||
public ServiceEntity Service { get; set; } = null!;
|
||||
public required string Code { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using HrynCo.DAL.Abstract.Entities;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Entities;
|
||||
|
||||
internal sealed class TemplateEntity : Entity
|
||||
{
|
||||
public Guid ServiceId { get; set; }
|
||||
public ServiceEntity Service { get; set; } = null!;
|
||||
public required string Key { get; set; }
|
||||
public EmailTemplateDefinitionEntity? Email { get; set; }
|
||||
public PushTemplateDefinitionEntity? Push { get; set; }
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="HrynCo.DAL.EF" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
|
||||
Generated
+376
@@ -0,0 +1,376 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
[DbContext(typeof(NotificationDbContext))]
|
||||
[Migration("20261017072410_EmailTemplateLocalizations")]
|
||||
partial class EmailTemplateLocalizations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.7")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<int?>("DailyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("daily_limit");
|
||||
|
||||
b.Property<int>("EmailChannelType")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("provider_type");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_active");
|
||||
|
||||
b.Property<int?>("MonthlyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("monthly_limit");
|
||||
|
||||
b.Property<int>("Priority")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("priority");
|
||||
|
||||
b.Property<string>("ServiceName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("service_name");
|
||||
|
||||
b.Property<string>("SettingsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("settings");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.Property<int>("WarnThresholdPercent")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("warn_threshold_percent");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceName", "Priority");
|
||||
|
||||
b.ToTable("email_channels", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<DateOnly>("Date")
|
||||
.HasColumnType("date")
|
||||
.HasColumnName("date");
|
||||
|
||||
b.Property<Guid>("ProviderId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("provider_id");
|
||||
|
||||
b.Property<int>("SentCount")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("sent_count");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProviderId", "Date")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_channel_usage", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_template_definitions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("DefinitionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("definition_id");
|
||||
|
||||
b.Property<string>("HtmlBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("html_body");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<Guid>("ServiceLanguageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_language_id");
|
||||
|
||||
b.Property<string>("Subject")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("subject");
|
||||
|
||||
b.Property<string>("TextBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("text_body");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceId");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceLanguageId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ServiceLanguageId", "ServiceId");
|
||||
|
||||
b.ToTable("email_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("services", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Code")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasColumnName("code");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Code")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("service_languages", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", null)
|
||||
.WithMany("UsageRecords")
|
||||
.HasForeignKey("ProviderId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateVariableData", "Variables", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("EmailTemplateDefinitionEntityId");
|
||||
|
||||
b1.Property<int>("__synthesizedOrdinal")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b1.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasJsonPropertyName("name");
|
||||
|
||||
b1.Property<bool>("Required")
|
||||
.HasJsonPropertyName("required");
|
||||
|
||||
b1.HasKey("EmailTemplateDefinitionEntityId", "__synthesizedOrdinal");
|
||||
|
||||
b1.ToTable("email_template_definitions");
|
||||
|
||||
b1
|
||||
.ToJson("variables")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("EmailTemplateDefinitionEntityId");
|
||||
});
|
||||
|
||||
b.Navigation("Service");
|
||||
|
||||
b.Navigation("Variables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", "Definition")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("DefinitionId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", "ServiceLanguage")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceLanguageId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Definition");
|
||||
|
||||
b.Navigation("ServiceLanguage");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Navigation("UsageRecords");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations;
|
||||
|
||||
public partial class EmailTemplateLocalizations : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.Sql(SourceLayoutGuard());
|
||||
migrationBuilder.Sql("DO $upgrade$ BEGIN IF (SELECT layout FROM it1601_migration_origin) = 'flat' THEN\n"
|
||||
+ FlatUpgrade() + "\nELSE\n" + InterimUpgrade() + "\nEND IF; END $upgrade$;");
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.Sql("""
|
||||
LOCK TABLE email_templates IN ACCESS EXCLUSIVE MODE;
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20261017070315_EmailTemplateLocalizations') THEN
|
||||
RAISE EXCEPTION 'Cannot downgrade an interim-origin database to the flat legacy model. Restore a verified backup instead.';
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM email_template_definitions d WHERE NOT EXISTS (SELECT 1 FROM email_templates t WHERE t.definition_id = d.id))
|
||||
OR EXISTS (SELECT 1 FROM service_languages l WHERE NOT EXISTS (SELECT 1 FROM email_templates t WHERE t.service_language_id = l.id))
|
||||
OR EXISTS (SELECT 1 FROM services s WHERE NOT EXISTS (SELECT 1 FROM email_templates t WHERE t.service_id = s.id)) THEN
|
||||
RAISE EXCEPTION 'Cannot downgrade catalog-only data or empty definitions to the legacy model. Restore a verified backup instead.';
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE email_templates ADD COLUMN service_name varchar(100), ADD COLUMN key varchar(100),
|
||||
ADD COLUMN language_code varchar(10), ADD COLUMN variables jsonb;
|
||||
UPDATE email_templates t SET service_name = s.name, key = d.key, variables = d.variables, language_code = l.code
|
||||
FROM email_template_definitions d JOIN services s ON s.id = d.service_id
|
||||
JOIN service_languages l ON l.service_id = s.id
|
||||
WHERE d.id = t.definition_id AND l.id = t.service_language_id;
|
||||
ALTER TABLE email_templates ALTER COLUMN service_name SET NOT NULL, ALTER COLUMN key SET NOT NULL, ALTER COLUMN language_code SET NOT NULL;
|
||||
ALTER TABLE email_templates DROP COLUMN definition_id, DROP COLUMN service_id, DROP COLUMN service_language_id;
|
||||
DROP TABLE email_template_definitions;
|
||||
DROP TABLE service_languages;
|
||||
DROP TABLE services;
|
||||
CREATE UNIQUE INDEX "IX_email_templates_service_name_key_language_code" ON email_templates(service_name, key, language_code);
|
||||
""");
|
||||
}
|
||||
|
||||
private static string FlatUpgrade() => """
|
||||
DO $audit$
|
||||
DECLARE row_record record;
|
||||
BEGIN
|
||||
FOR row_record IN SELECT id, service_name, key, language_code, variables FROM email_templates LOOP
|
||||
IF btrim(row_record.service_name) = '' OR btrim(row_record.key) = ''
|
||||
OR btrim(row_record.language_code) = '' OR row_record.variables IS NULL
|
||||
OR jsonb_typeof(row_record.variables) <> 'array' THEN
|
||||
RAISE EXCEPTION 'Invalid template identity or variables array: service=%, key=%, language=%, id=%',
|
||||
row_record.service_name, row_record.key, row_record.language_code, row_record.id;
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM jsonb_array_elements(row_record.variables) v
|
||||
WHERE jsonb_typeof(v) <> 'object'
|
||||
OR jsonb_typeof(v->'name') IS DISTINCT FROM 'string'
|
||||
OR btrim(v->>'name') = ''
|
||||
OR jsonb_typeof(v->'required') IS DISTINCT FROM 'boolean'
|
||||
OR (v - 'name' - 'required') <> '{}'::jsonb) THEN
|
||||
RAISE EXCEPTION 'Invalid variables shape: service=%, key=%, language=%, id=%',
|
||||
row_record.service_name, row_record.key, row_record.language_code, row_record.id;
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM jsonb_array_elements(row_record.variables) v GROUP BY v->>'name' HAVING count(*) > 1) THEN
|
||||
RAISE EXCEPTION 'Duplicate variable names: service=%, key=%, language=%, id=%',
|
||||
row_record.service_name, row_record.key, row_record.language_code, row_record.id;
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $audit$;
|
||||
CREATE TEMP TABLE template_contract_audit ON COMMIT DROP AS
|
||||
SELECT t.*, COALESCE((SELECT jsonb_agg(v ORDER BY v->>'name')
|
||||
FROM jsonb_array_elements(t.variables) v), '[]'::jsonb) AS contract
|
||||
FROM email_templates t;
|
||||
DO $conflicts$
|
||||
DECLARE conflict_record record;
|
||||
BEGIN
|
||||
SELECT service_name, key, string_agg(language_code || ':' || id::text, ', ' ORDER BY language_code) AS records
|
||||
INTO conflict_record FROM template_contract_audit
|
||||
GROUP BY service_name, key HAVING count(DISTINCT contract) > 1 LIMIT 1;
|
||||
IF FOUND THEN
|
||||
RAISE EXCEPTION 'Conflicting shared variables: service=%, key=%, records=%',
|
||||
conflict_record.service_name, conflict_record.key, conflict_record.records;
|
||||
END IF;
|
||||
END $conflicts$;
|
||||
CREATE TABLE services (
|
||||
id uuid CONSTRAINT "PK_services" PRIMARY KEY, name varchar(100) NOT NULL, revision uuid NOT NULL,
|
||||
created timestamptz NOT NULL, updated timestamptz NULL);
|
||||
CREATE UNIQUE INDEX "IX_services_name" ON services(name);
|
||||
CREATE TABLE service_languages (
|
||||
id uuid CONSTRAINT "PK_service_languages" PRIMARY KEY, service_id uuid NOT NULL,
|
||||
code varchar(10) NOT NULL, created timestamptz NOT NULL, updated timestamptz NULL,
|
||||
CONSTRAINT "AK_service_languages_id_service_id" UNIQUE(id, service_id),
|
||||
CONSTRAINT "FK_service_languages_services_service_id" FOREIGN KEY(service_id) REFERENCES services(id) ON DELETE RESTRICT);
|
||||
CREATE UNIQUE INDEX "IX_service_languages_service_id_code" ON service_languages(service_id, code);
|
||||
CREATE TABLE email_template_definitions (
|
||||
id uuid CONSTRAINT "PK_email_template_definitions" PRIMARY KEY, service_id uuid NOT NULL,
|
||||
key varchar(100) NOT NULL, revision uuid NOT NULL, variables jsonb NOT NULL,
|
||||
created timestamptz NOT NULL, updated timestamptz NULL,
|
||||
CONSTRAINT "AK_email_template_definitions_id_service_id" UNIQUE(id, service_id),
|
||||
CONSTRAINT "FK_email_template_definitions_services_service_id" FOREIGN KEY(service_id) REFERENCES services(id) ON DELETE RESTRICT);
|
||||
CREATE UNIQUE INDEX "IX_email_template_definitions_service_id_key" ON email_template_definitions(service_id, key);
|
||||
INSERT INTO services(id, name, revision, created)
|
||||
SELECT gen_random_uuid(), service_name, gen_random_uuid(), min(created) FROM email_templates GROUP BY service_name;
|
||||
INSERT INTO service_languages(id, service_id, code, created)
|
||||
SELECT gen_random_uuid(), s.id, t.language_code, min(t.created)
|
||||
FROM email_templates t JOIN services s ON s.name = t.service_name GROUP BY s.id, t.language_code;
|
||||
INSERT INTO email_template_definitions(id, service_id, key, revision, variables, created, updated)
|
||||
SELECT DISTINCT ON (t.service_name, t.key) t.id, s.id, t.key, gen_random_uuid(), t.contract,
|
||||
min(t.created) OVER (PARTITION BY t.service_name, t.key),
|
||||
max(t.updated) OVER (PARTITION BY t.service_name, t.key)
|
||||
FROM template_contract_audit t JOIN services s ON s.name = t.service_name
|
||||
ORDER BY t.service_name, t.key, t.id;
|
||||
ALTER TABLE email_templates ADD COLUMN definition_id uuid, ADD COLUMN service_id uuid, ADD COLUMN service_language_id uuid;
|
||||
UPDATE email_templates t SET definition_id = d.id, service_id = s.id, service_language_id = l.id
|
||||
FROM email_template_definitions d JOIN services s ON s.id = d.service_id
|
||||
JOIN service_languages l ON l.service_id = s.id
|
||||
WHERE t.service_name = s.name AND t.key = d.key AND t.language_code = l.code;
|
||||
ALTER TABLE email_templates ALTER COLUMN definition_id SET NOT NULL,
|
||||
ALTER COLUMN service_id SET NOT NULL, ALTER COLUMN service_language_id SET NOT NULL;
|
||||
ALTER TABLE email_templates ADD CONSTRAINT "FK_email_templates_email_template_definitions_definition_id_se~"
|
||||
FOREIGN KEY (definition_id, service_id) REFERENCES email_template_definitions(id, service_id) ON DELETE CASCADE;
|
||||
ALTER TABLE email_templates ADD CONSTRAINT "FK_email_templates_service_languages_service_language_id_servi~"
|
||||
FOREIGN KEY (service_language_id, service_id) REFERENCES service_languages(id, service_id) ON DELETE RESTRICT;
|
||||
DROP INDEX "IX_email_templates_service_name_key_language_code";
|
||||
ALTER TABLE email_templates DROP COLUMN service_name, DROP COLUMN key, DROP COLUMN variables, DROP COLUMN language_code;
|
||||
CREATE UNIQUE INDEX "IX_email_templates_definition_id_service_language_id" ON email_templates(definition_id, service_language_id);
|
||||
CREATE INDEX "IX_email_templates_definition_id_service_id" ON email_templates(definition_id, service_id);
|
||||
CREATE INDEX "IX_email_templates_service_language_id_service_id" ON email_templates(service_language_id, service_id);
|
||||
""";
|
||||
|
||||
private static string SourceLayoutGuard() => """
|
||||
SET LOCAL search_path = public;
|
||||
DO $layout$
|
||||
DECLARE
|
||||
template_columns text[];
|
||||
service_columns text[];
|
||||
definition_columns text[];
|
||||
source_constraints text[];
|
||||
source_indexes text[];
|
||||
known_interim_history boolean;
|
||||
source_layout text;
|
||||
BEGIN
|
||||
SELECT array_agg(column_name || ':' || udt_name || ':' || coalesce(character_maximum_length::text, '') || ':' || is_nullable ORDER BY column_name)
|
||||
INTO template_columns FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'email_templates';
|
||||
SELECT array_agg(column_name || ':' || udt_name || ':' || coalesce(character_maximum_length::text, '') || ':' || is_nullable ORDER BY column_name)
|
||||
INTO service_columns FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'services';
|
||||
SELECT array_agg(column_name || ':' || udt_name || ':' || coalesce(character_maximum_length::text, '') || ':' || is_nullable ORDER BY column_name)
|
||||
INTO definition_columns FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'email_template_definitions';
|
||||
SELECT EXISTS (SELECT 1 FROM "__EFMigrationsHistory" WHERE "MigrationId" = '20261017070315_EmailTemplateLocalizations') INTO known_interim_history;
|
||||
SELECT array_agg(c.relname || ':' || p.conname || ':' || pg_get_constraintdef(p.oid) ORDER BY c.relname, p.conname)
|
||||
INTO source_constraints FROM pg_constraint p JOIN pg_class c ON c.oid = p.conrelid
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public'
|
||||
AND c.relname IN ('services', 'email_template_definitions', 'email_templates');
|
||||
SELECT array_agg(indexdef ORDER BY indexname) INTO source_indexes FROM pg_indexes
|
||||
WHERE schemaname = 'public' AND tablename IN ('services', 'email_template_definitions', 'email_templates');
|
||||
IF to_regclass('public.service_languages') IS NOT NULL THEN
|
||||
RAISE EXCEPTION 'Unsupported email-template source layout: service language catalog already exists without the current migration history.';
|
||||
END IF;
|
||||
IF template_columns = ARRAY['created:timestamptz::NO',
|
||||
'html_body:text::NO',
|
||||
'id:uuid::NO',
|
||||
'key:varchar:100:NO',
|
||||
'language_code:varchar:10:NO',
|
||||
'service_name:varchar:100:NO',
|
||||
'subject:text::NO',
|
||||
'text_body:text::NO',
|
||||
'updated:timestamptz::YES',
|
||||
'variables:jsonb::YES']
|
||||
AND service_columns IS NULL AND definition_columns IS NULL AND NOT known_interim_history
|
||||
AND source_constraints = ARRAY['email_templates:PK_email_templates:PRIMARY KEY (id)']
|
||||
AND source_indexes = ARRAY[
|
||||
'CREATE UNIQUE INDEX "IX_email_templates_service_name_key_language_code" ON public.email_templates USING btree (service_name, key, language_code)',
|
||||
'CREATE UNIQUE INDEX "PK_email_templates" ON public.email_templates USING btree (id)'] THEN
|
||||
source_layout := 'flat';
|
||||
ELSIF template_columns = ARRAY['created:timestamptz::NO',
|
||||
'definition_id:uuid::NO',
|
||||
'html_body:text::NO',
|
||||
'id:uuid::NO',
|
||||
'language_code:varchar:10:NO',
|
||||
'subject:text::NO',
|
||||
'text_body:text::NO',
|
||||
'updated:timestamptz::YES']
|
||||
AND service_columns = ARRAY['created:timestamptz::NO',
|
||||
'id:uuid::NO',
|
||||
'name:varchar:100:NO',
|
||||
'updated:timestamptz::YES']
|
||||
AND definition_columns = ARRAY['created:timestamptz::NO',
|
||||
'id:uuid::NO',
|
||||
'key:varchar:100:NO',
|
||||
'revision:uuid::NO',
|
||||
'service_id:uuid::NO',
|
||||
'updated:timestamptz::YES',
|
||||
'variables:jsonb::NO']
|
||||
AND known_interim_history
|
||||
AND source_constraints = ARRAY[
|
||||
'email_template_definitions:email_template_definitions_pkey:PRIMARY KEY (id)',
|
||||
'email_template_definitions:email_template_definitions_service_id_fkey:FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE RESTRICT',
|
||||
'email_templates:FK_email_templates_email_template_definitions_definition_id:FOREIGN KEY (definition_id) REFERENCES email_template_definitions(id) ON DELETE CASCADE',
|
||||
'email_templates:PK_email_templates:PRIMARY KEY (id)',
|
||||
'services:services_pkey:PRIMARY KEY (id)']
|
||||
AND source_indexes = ARRAY[
|
||||
'CREATE UNIQUE INDEX "IX_email_template_definitions_service_id_key" ON public.email_template_definitions USING btree (service_id, key)',
|
||||
'CREATE UNIQUE INDEX "IX_email_templates_definition_id_language_code" ON public.email_templates USING btree (definition_id, language_code)',
|
||||
'CREATE UNIQUE INDEX "IX_services_name" ON public.services USING btree (name)',
|
||||
'CREATE UNIQUE INDEX "PK_email_templates" ON public.email_templates USING btree (id)',
|
||||
'CREATE UNIQUE INDEX email_template_definitions_pkey ON public.email_template_definitions USING btree (id)',
|
||||
'CREATE UNIQUE INDEX services_pkey ON public.services USING btree (id)'] THEN
|
||||
source_layout := 'interim';
|
||||
ELSE
|
||||
RAISE EXCEPTION 'Unsupported email-template source layout or history. Expected the flat legacy schema or the known 20261017070315 interim schema; no changes were made.';
|
||||
END IF;
|
||||
LOCK TABLE email_templates IN ACCESS EXCLUSIVE MODE;
|
||||
IF source_layout = 'interim' THEN
|
||||
LOCK TABLE services, email_template_definitions IN ACCESS EXCLUSIVE MODE;
|
||||
END IF;
|
||||
CREATE TEMP TABLE it1601_migration_origin (layout text NOT NULL) ON COMMIT DROP;
|
||||
INSERT INTO it1601_migration_origin VALUES (source_layout);
|
||||
END $layout$;
|
||||
""";
|
||||
|
||||
private static string InterimUpgrade() => """
|
||||
DO $interim_audit$
|
||||
DECLARE row_record record;
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM services WHERE btrim(name) = '')
|
||||
OR EXISTS (SELECT 1 FROM email_template_definitions WHERE btrim(key) = '')
|
||||
OR EXISTS (SELECT 1 FROM email_templates WHERE btrim(language_code) = '') THEN
|
||||
RAISE EXCEPTION 'Invalid blank identity in interim email-template data; no changes were made.';
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM email_template_definitions d LEFT JOIN services s ON s.id = d.service_id WHERE s.id IS NULL)
|
||||
OR EXISTS (SELECT 1 FROM email_templates t LEFT JOIN email_template_definitions d ON d.id = t.definition_id WHERE d.id IS NULL) THEN
|
||||
RAISE EXCEPTION 'Invalid orphaned reference in interim email-template data; no changes were made.';
|
||||
END IF;
|
||||
FOR row_record IN SELECT d.id, s.name AS service_name, d.key, d.variables FROM email_template_definitions d JOIN services s ON s.id = d.service_id LOOP
|
||||
IF row_record.variables IS NULL OR jsonb_typeof(row_record.variables) <> 'array' THEN
|
||||
RAISE EXCEPTION 'Invalid interim shared variables array: service=%, key=%, definition=%', row_record.service_name, row_record.key, row_record.id;
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM jsonb_array_elements(row_record.variables) v
|
||||
WHERE jsonb_typeof(v) <> 'object'
|
||||
OR jsonb_typeof(v->'name') IS DISTINCT FROM 'string'
|
||||
OR btrim(v->>'name') = ''
|
||||
OR jsonb_typeof(v->'required') IS DISTINCT FROM 'boolean'
|
||||
OR (v - 'name' - 'required') <> '{}'::jsonb) THEN
|
||||
RAISE EXCEPTION 'Invalid interim shared variables shape: service=%, key=%, definition=%', row_record.service_name, row_record.key, row_record.id;
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM jsonb_array_elements(row_record.variables) v GROUP BY v->>'name' HAVING count(*) > 1) THEN
|
||||
RAISE EXCEPTION 'Duplicate interim shared variable names: service=%, key=%, definition=%', row_record.service_name, row_record.key, row_record.id;
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $interim_audit$;
|
||||
ALTER TABLE services ADD COLUMN revision uuid;
|
||||
UPDATE services SET revision = gen_random_uuid();
|
||||
ALTER TABLE services ALTER COLUMN revision SET NOT NULL;
|
||||
ALTER TABLE services RENAME CONSTRAINT services_pkey TO "PK_services";
|
||||
ALTER TABLE email_template_definitions RENAME CONSTRAINT email_template_definitions_pkey TO "PK_email_template_definitions";
|
||||
ALTER TABLE email_template_definitions RENAME CONSTRAINT email_template_definitions_service_id_fkey TO "FK_email_template_definitions_services_service_id";
|
||||
ALTER TABLE email_template_definitions ADD CONSTRAINT "AK_email_template_definitions_id_service_id" UNIQUE(id, service_id);
|
||||
CREATE TABLE service_languages (
|
||||
id uuid CONSTRAINT "PK_service_languages" PRIMARY KEY, service_id uuid NOT NULL,
|
||||
code varchar(10) NOT NULL, created timestamptz NOT NULL, updated timestamptz NULL,
|
||||
CONSTRAINT "AK_service_languages_id_service_id" UNIQUE(id, service_id),
|
||||
CONSTRAINT "FK_service_languages_services_service_id" FOREIGN KEY(service_id) REFERENCES services(id) ON DELETE RESTRICT);
|
||||
CREATE UNIQUE INDEX "IX_service_languages_service_id_code" ON service_languages(service_id, code);
|
||||
INSERT INTO service_languages(id, service_id, code, created, updated)
|
||||
SELECT gen_random_uuid(), d.service_id, t.language_code, min(t.created), max(t.updated)
|
||||
FROM email_templates t JOIN email_template_definitions d ON d.id = t.definition_id GROUP BY d.service_id, t.language_code;
|
||||
ALTER TABLE email_templates ADD COLUMN service_id uuid, ADD COLUMN service_language_id uuid;
|
||||
UPDATE email_templates t SET service_id = d.service_id, service_language_id = l.id
|
||||
FROM email_template_definitions d JOIN service_languages l ON l.service_id = d.service_id
|
||||
WHERE t.definition_id = d.id AND t.language_code = l.code;
|
||||
ALTER TABLE email_templates ALTER COLUMN service_id SET NOT NULL, ALTER COLUMN service_language_id SET NOT NULL;
|
||||
ALTER TABLE email_templates ADD CONSTRAINT "FK_email_templates_email_template_definitions_definition_id_se~"
|
||||
FOREIGN KEY (definition_id, service_id) REFERENCES email_template_definitions(id, service_id) ON DELETE CASCADE;
|
||||
ALTER TABLE email_templates ADD CONSTRAINT "FK_email_templates_service_languages_service_language_id_servi~"
|
||||
FOREIGN KEY (service_language_id, service_id) REFERENCES service_languages(id, service_id) ON DELETE RESTRICT;
|
||||
ALTER TABLE email_templates DROP CONSTRAINT "FK_email_templates_email_template_definitions_definition_id";
|
||||
DROP INDEX "IX_email_templates_definition_id_language_code";
|
||||
ALTER TABLE email_templates DROP COLUMN language_code;
|
||||
CREATE UNIQUE INDEX "IX_email_templates_definition_id_service_language_id" ON email_templates(definition_id, service_language_id);
|
||||
CREATE INDEX "IX_email_templates_definition_id_service_id" ON email_templates(definition_id, service_id);
|
||||
CREATE INDEX "IX_email_templates_service_language_id_service_id" ON email_templates(service_language_id, service_id);
|
||||
""";
|
||||
}
|
||||
+402
@@ -0,0 +1,402 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
[DbContext(typeof(NotificationDbContext))]
|
||||
[Migration("20261023223753_AddPushDeliveries")]
|
||||
partial class AddPushDeliveries
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.7")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<int?>("DailyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("daily_limit");
|
||||
|
||||
b.Property<int>("EmailChannelType")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("provider_type");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_active");
|
||||
|
||||
b.Property<int?>("MonthlyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("monthly_limit");
|
||||
|
||||
b.Property<int>("Priority")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("priority");
|
||||
|
||||
b.Property<string>("ServiceName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("service_name");
|
||||
|
||||
b.Property<string>("SettingsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("settings");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.Property<int>("WarnThresholdPercent")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("warn_threshold_percent");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceName", "Priority");
|
||||
|
||||
b.ToTable("email_channels", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<DateOnly>("Date")
|
||||
.HasColumnType("date")
|
||||
.HasColumnName("date");
|
||||
|
||||
b.Property<Guid>("ProviderId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("provider_id");
|
||||
|
||||
b.Property<int>("SentCount")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("sent_count");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProviderId", "Date")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_channel_usage", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_template_definitions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("DefinitionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("definition_id");
|
||||
|
||||
b.Property<string>("HtmlBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("html_body");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<Guid>("ServiceLanguageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_language_id");
|
||||
|
||||
b.Property<string>("Subject")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("subject");
|
||||
|
||||
b.Property<string>("TextBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("text_body");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceId");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceLanguageId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ServiceLanguageId", "ServiceId");
|
||||
|
||||
b.ToTable("email_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushDeliveryEntity", b =>
|
||||
{
|
||||
b.Property<string>("ServiceName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<Guid>("MessageId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CompletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Error")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("InvalidRegistration")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.HasKey("ServiceName", "MessageId");
|
||||
|
||||
b.HasIndex("CompletedAt");
|
||||
|
||||
b.ToTable("PushDeliveries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("services", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Code")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasColumnName("code");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Code")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("service_languages", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", null)
|
||||
.WithMany("UsageRecords")
|
||||
.HasForeignKey("ProviderId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateVariableData", "Variables", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("EmailTemplateDefinitionEntityId");
|
||||
|
||||
b1.Property<int>("__synthesizedOrdinal")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b1.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasJsonPropertyName("name");
|
||||
|
||||
b1.Property<bool>("Required")
|
||||
.HasJsonPropertyName("required");
|
||||
|
||||
b1.HasKey("EmailTemplateDefinitionEntityId", "__synthesizedOrdinal");
|
||||
|
||||
b1.ToTable("email_template_definitions");
|
||||
|
||||
b1
|
||||
.ToJson("variables")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("EmailTemplateDefinitionEntityId");
|
||||
});
|
||||
|
||||
b.Navigation("Service");
|
||||
|
||||
b.Navigation("Variables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", "Definition")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("DefinitionId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", "ServiceLanguage")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceLanguageId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Definition");
|
||||
|
||||
b.Navigation("ServiceLanguage");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Navigation("UsageRecords");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddPushDeliveries : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "PushDeliveries",
|
||||
columns: table => new
|
||||
{
|
||||
MessageId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
ServiceName = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
|
||||
Error = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
|
||||
InvalidRegistration = table.Column<bool>(type: "boolean", nullable: false),
|
||||
CompletedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_PushDeliveries", x => new { x.ServiceName, x.MessageId });
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_PushDeliveries_CompletedAt",
|
||||
table: "PushDeliveries",
|
||||
column: "CompletedAt");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "PushDeliveries");
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+411
@@ -0,0 +1,411 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
[DbContext(typeof(NotificationDbContext))]
|
||||
[Migration("20261024073202_LinkEmailChannelsToServices")]
|
||||
partial class LinkEmailChannelsToServices
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.7")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<int?>("DailyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("daily_limit");
|
||||
|
||||
b.Property<int>("EmailChannelType")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("provider_type");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_active");
|
||||
|
||||
b.Property<int?>("MonthlyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("monthly_limit");
|
||||
|
||||
b.Property<int>("Priority")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("priority");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<string>("SettingsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("settings");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.Property<int>("WarnThresholdPercent")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("warn_threshold_percent");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Priority");
|
||||
|
||||
b.ToTable("email_channels", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<DateOnly>("Date")
|
||||
.HasColumnType("date")
|
||||
.HasColumnName("date");
|
||||
|
||||
b.Property<Guid>("ProviderId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("provider_id");
|
||||
|
||||
b.Property<int>("SentCount")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("sent_count");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProviderId", "Date")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_channel_usage", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_template_definitions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("DefinitionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("definition_id");
|
||||
|
||||
b.Property<string>("HtmlBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("html_body");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<Guid>("ServiceLanguageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_language_id");
|
||||
|
||||
b.Property<string>("Subject")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("subject");
|
||||
|
||||
b.Property<string>("TextBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("text_body");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceId");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceLanguageId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ServiceLanguageId", "ServiceId");
|
||||
|
||||
b.ToTable("email_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushDeliveryEntity", b =>
|
||||
{
|
||||
b.Property<string>("ServiceName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<Guid>("MessageId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CompletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Error")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("InvalidRegistration")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.HasKey("ServiceName", "MessageId");
|
||||
|
||||
b.HasIndex("CompletedAt");
|
||||
|
||||
b.ToTable("PushDeliveries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("services", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Code")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasColumnName("code");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Code")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("service_languages", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", null)
|
||||
.WithMany("UsageRecords")
|
||||
.HasForeignKey("ProviderId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateVariableData", "Variables", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("EmailTemplateDefinitionEntityId");
|
||||
|
||||
b1.Property<int>("__synthesizedOrdinal")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b1.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasJsonPropertyName("name");
|
||||
|
||||
b1.Property<bool>("Required")
|
||||
.HasJsonPropertyName("required");
|
||||
|
||||
b1.HasKey("EmailTemplateDefinitionEntityId", "__synthesizedOrdinal");
|
||||
|
||||
b1.ToTable("email_template_definitions");
|
||||
|
||||
b1
|
||||
.ToJson("variables")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("EmailTemplateDefinitionEntityId");
|
||||
});
|
||||
|
||||
b.Navigation("Service");
|
||||
|
||||
b.Navigation("Variables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", "Definition")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("DefinitionId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", "ServiceLanguage")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceLanguageId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Definition");
|
||||
|
||||
b.Navigation("ServiceLanguage");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Navigation("UsageRecords");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations;
|
||||
|
||||
public partial class LinkEmailChannelsToServices : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
// EF runs this whole migration in one transaction. Lock the source rows so a
|
||||
// concurrent rename or channel write cannot invalidate the verified mapping.
|
||||
migrationBuilder.Sql("""
|
||||
LOCK TABLE services IN SHARE ROW EXCLUSIVE MODE;
|
||||
LOCK TABLE email_channels IN ACCESS EXCLUSIVE MODE;
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM email_channels c
|
||||
WHERE (SELECT count(*) FROM services s
|
||||
WHERE s.name = c.service_name
|
||||
OR (c.service_name = 'StoreMate-Prod' AND s.name = 'Invemory-Prod')) <> 1
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Email channel migration stopped: every legacy service name must have exactly one existing service (including the approved StoreMate-Prod -> Invemory-Prod alias). Resolve missing or ambiguous names before retrying.';
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE email_channels ADD COLUMN service_id uuid;
|
||||
UPDATE email_channels c SET service_id = s.id
|
||||
FROM services s
|
||||
WHERE s.name = c.service_name
|
||||
OR (c.service_name = 'StoreMate-Prod' AND s.name = 'Invemory-Prod');
|
||||
ALTER TABLE email_channels ALTER COLUMN service_id SET NOT NULL;
|
||||
""");
|
||||
migrationBuilder.DropIndex("IX_email_channels_service_name_priority", "email_channels");
|
||||
migrationBuilder.DropColumn("service_name", "email_channels");
|
||||
migrationBuilder.CreateIndex("IX_email_channels_service_id_priority", "email_channels", new[] { "service_id", "priority" });
|
||||
migrationBuilder.AddForeignKey("FK_email_channels_services_service_id", "email_channels", "service_id",
|
||||
"services", principalColumn: "id", onDelete: ReferentialAction.Restrict);
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
// Restore current service names; historical names are intentionally not retained.
|
||||
migrationBuilder.Sql("""
|
||||
ALTER TABLE email_channels ADD COLUMN service_name character varying(100);
|
||||
UPDATE email_channels c SET service_name = s.name FROM services s WHERE s.id = c.service_id;
|
||||
ALTER TABLE email_channels ALTER COLUMN service_name SET NOT NULL;
|
||||
""");
|
||||
migrationBuilder.DropForeignKey("FK_email_channels_services_service_id", "email_channels");
|
||||
migrationBuilder.DropIndex("IX_email_channels_service_id_priority", "email_channels");
|
||||
migrationBuilder.DropColumn("service_id", "email_channels");
|
||||
migrationBuilder.CreateIndex("IX_email_channels_service_name_priority", "email_channels", new[] { "service_name", "priority" });
|
||||
}
|
||||
}
|
||||
+464
@@ -0,0 +1,464 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
[DbContext(typeof(NotificationDbContext))]
|
||||
[Migration("20261024080457_AddPushChannels")]
|
||||
partial class AddPushChannels
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.7")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<int?>("DailyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("daily_limit");
|
||||
|
||||
b.Property<int>("EmailChannelType")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("provider_type");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_active");
|
||||
|
||||
b.Property<int?>("MonthlyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("monthly_limit");
|
||||
|
||||
b.Property<int>("Priority")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("priority");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<string>("SettingsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("settings");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.Property<int>("WarnThresholdPercent")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("warn_threshold_percent");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Priority");
|
||||
|
||||
b.ToTable("email_channels", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<DateOnly>("Date")
|
||||
.HasColumnType("date")
|
||||
.HasColumnName("date");
|
||||
|
||||
b.Property<Guid>("ProviderId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("provider_id");
|
||||
|
||||
b.Property<int>("SentCount")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("sent_count");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProviderId", "Date")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_channel_usage", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_template_definitions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("DefinitionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("definition_id");
|
||||
|
||||
b.Property<string>("HtmlBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("html_body");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<Guid>("ServiceLanguageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_language_id");
|
||||
|
||||
b.Property<string>("Subject")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("subject");
|
||||
|
||||
b.Property<string>("TextBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("text_body");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceId");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceLanguageId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ServiceLanguageId", "ServiceId");
|
||||
|
||||
b.ToTable("email_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushChannelEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("CredentialsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("credentials");
|
||||
|
||||
b.Property<string>("FirebaseProjectId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(30)
|
||||
.HasColumnType("character varying(30)")
|
||||
.HasColumnName("firebase_project_id");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_active");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("push_channels", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushDeliveryEntity", b =>
|
||||
{
|
||||
b.Property<string>("ServiceName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<Guid>("MessageId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CompletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Error")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("InvalidRegistration")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.HasKey("ServiceName", "MessageId");
|
||||
|
||||
b.HasIndex("CompletedAt");
|
||||
|
||||
b.ToTable("PushDeliveries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("services", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Code")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasColumnName("code");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Code")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("service_languages", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", null)
|
||||
.WithMany("UsageRecords")
|
||||
.HasForeignKey("ProviderId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateVariableData", "Variables", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("EmailTemplateDefinitionEntityId");
|
||||
|
||||
b1.Property<int>("__synthesizedOrdinal")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b1.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasJsonPropertyName("name");
|
||||
|
||||
b1.Property<bool>("Required")
|
||||
.HasJsonPropertyName("required");
|
||||
|
||||
b1.HasKey("EmailTemplateDefinitionEntityId", "__synthesizedOrdinal");
|
||||
|
||||
b1.ToTable("email_template_definitions");
|
||||
|
||||
b1
|
||||
.ToJson("variables")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("EmailTemplateDefinitionEntityId");
|
||||
});
|
||||
|
||||
b.Navigation("Service");
|
||||
|
||||
b.Navigation("Variables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", "Definition")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("DefinitionId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", "ServiceLanguage")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceLanguageId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Definition");
|
||||
|
||||
b.Navigation("ServiceLanguage");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushChannelEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Navigation("UsageRecords");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddPushChannels : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "push_channels",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
service_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
firebase_project_id = table.Column<string>(type: "character varying(30)", maxLength: 30, nullable: false),
|
||||
credentials = table.Column<string>(type: "jsonb", nullable: false),
|
||||
is_active = table.Column<bool>(type: "boolean", nullable: false),
|
||||
created = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
updated = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_push_channels", x => x.id);
|
||||
table.ForeignKey(
|
||||
name: "FK_push_channels_services_service_id",
|
||||
column: x => x.service_id,
|
||||
principalTable: "services",
|
||||
principalColumn: "id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_push_channels_service_id",
|
||||
table: "push_channels",
|
||||
column: "service_id",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "push_channels");
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+674
@@ -0,0 +1,674 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
[DbContext(typeof(NotificationDbContext))]
|
||||
[Migration("20261030215421_AddChannelTemplates")]
|
||||
partial class AddChannelTemplates
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.7")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<int?>("DailyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("daily_limit");
|
||||
|
||||
b.Property<int>("EmailChannelType")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("provider_type");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_active");
|
||||
|
||||
b.Property<int?>("MonthlyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("monthly_limit");
|
||||
|
||||
b.Property<int>("Priority")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("priority");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<string>("SettingsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("settings");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.Property<int>("WarnThresholdPercent")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("warn_threshold_percent");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Priority");
|
||||
|
||||
b.ToTable("email_channels", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<DateOnly>("Date")
|
||||
.HasColumnType("date")
|
||||
.HasColumnName("date");
|
||||
|
||||
b.Property<Guid>("ProviderId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("provider_id");
|
||||
|
||||
b.Property<int>("SentCount")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("sent_count");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProviderId", "Date")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_channel_usage", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_template_definitions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("DefinitionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("definition_id");
|
||||
|
||||
b.Property<string>("HtmlBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("html_body");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<Guid>("ServiceLanguageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_language_id");
|
||||
|
||||
b.Property<string>("Subject")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("subject");
|
||||
|
||||
b.Property<string>("TextBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("text_body");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceId");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceLanguageId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ServiceLanguageId", "ServiceId");
|
||||
|
||||
b.ToTable("email_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushChannelEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("CredentialsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("credentials");
|
||||
|
||||
b.Property<string>("FirebaseProjectId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(30)
|
||||
.HasColumnType("character varying(30)")
|
||||
.HasColumnName("firebase_project_id");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_active");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("push_channels", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushDeliveryEntity", b =>
|
||||
{
|
||||
b.Property<string>("ServiceName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<Guid>("MessageId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CompletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Error")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("InvalidRegistration")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.HasKey("ServiceName", "MessageId");
|
||||
|
||||
b.HasIndex("CompletedAt");
|
||||
|
||||
b.ToTable("PushDeliveries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("push_template_definitions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Body")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("body");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("DefinitionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("definition_id");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<Guid>("ServiceLanguageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_language_id");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("title");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceId");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceLanguageId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ServiceLanguageId", "ServiceId");
|
||||
|
||||
b.ToTable("push_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("services", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Code")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasColumnName("code");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Code")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("service_languages", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", null)
|
||||
.WithMany("UsageRecords")
|
||||
.HasForeignKey("ProviderId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "Template")
|
||||
.WithOne("Email")
|
||||
.HasForeignKey("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", "ServiceId", "Key")
|
||||
.HasPrincipalKey("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "ServiceId", "Key")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateVariableData", "Variables", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("EmailTemplateDefinitionEntityId");
|
||||
|
||||
b1.Property<int>("__synthesizedOrdinal")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b1.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasJsonPropertyName("name");
|
||||
|
||||
b1.Property<bool>("Required")
|
||||
.HasJsonPropertyName("required");
|
||||
|
||||
b1.HasKey("EmailTemplateDefinitionEntityId", "__synthesizedOrdinal");
|
||||
|
||||
b1.ToTable("email_template_definitions");
|
||||
|
||||
b1
|
||||
.ToJson("variables")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("EmailTemplateDefinitionEntityId");
|
||||
});
|
||||
|
||||
b.Navigation("Service");
|
||||
|
||||
b.Navigation("Template");
|
||||
|
||||
b.Navigation("Variables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", "Definition")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("DefinitionId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", "ServiceLanguage")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceLanguageId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Definition");
|
||||
|
||||
b.Navigation("ServiceLanguage");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushChannelEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "Template")
|
||||
.WithOne("Push")
|
||||
.HasForeignKey("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", "ServiceId", "Key")
|
||||
.HasPrincipalKey("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "ServiceId", "Key")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateVariableData", "Variables", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("PushTemplateDefinitionEntityId");
|
||||
|
||||
b1.Property<int>("__synthesizedOrdinal")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b1.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasJsonPropertyName("name");
|
||||
|
||||
b1.Property<bool>("Required")
|
||||
.HasJsonPropertyName("required");
|
||||
|
||||
b1.HasKey("PushTemplateDefinitionEntityId", "__synthesizedOrdinal");
|
||||
|
||||
b1.ToTable("push_template_definitions");
|
||||
|
||||
b1
|
||||
.ToJson("variables")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("PushTemplateDefinitionEntityId");
|
||||
});
|
||||
|
||||
b.Navigation("Template");
|
||||
|
||||
b.Navigation("Variables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", "Definition")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("DefinitionId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", "ServiceLanguage")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceLanguageId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Definition");
|
||||
|
||||
b.Navigation("ServiceLanguage");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Navigation("UsageRecords");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", b =>
|
||||
{
|
||||
b.Navigation("Email");
|
||||
|
||||
b.Navigation("Push");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddChannelTemplates : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "templates",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
service_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
key = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
|
||||
created = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
updated = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_templates", x => x.id);
|
||||
table.UniqueConstraint("AK_templates_service_id_key", x => new { x.service_id, x.key });
|
||||
table.ForeignKey(
|
||||
name: "FK_templates_services_service_id",
|
||||
column: x => x.service_id,
|
||||
principalTable: "services",
|
||||
principalColumn: "id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "push_template_definitions",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
service_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
key = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
|
||||
revision = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
created = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
updated = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
|
||||
variables = table.Column<string>(type: "jsonb", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_push_template_definitions", x => x.id);
|
||||
table.UniqueConstraint("AK_push_template_definitions_id_service_id", x => new { x.id, x.service_id });
|
||||
table.ForeignKey(
|
||||
name: "FK_push_template_definitions_templates_service_id_key",
|
||||
columns: x => new { x.service_id, x.key },
|
||||
principalTable: "templates",
|
||||
principalColumns: new[] { "service_id", "key" },
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "push_templates",
|
||||
columns: table => new
|
||||
{
|
||||
id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
definition_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
service_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
service_language_id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
title = table.Column<string>(type: "text", nullable: false),
|
||||
body = table.Column<string>(type: "text", nullable: false),
|
||||
created = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
updated = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_push_templates", x => x.id);
|
||||
table.ForeignKey(
|
||||
name: "FK_push_templates_push_template_definitions_definition_id_serv~",
|
||||
columns: x => new { x.definition_id, x.service_id },
|
||||
principalTable: "push_template_definitions",
|
||||
principalColumns: new[] { "id", "service_id" },
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_push_templates_service_languages_service_language_id_servic~",
|
||||
columns: x => new { x.service_language_id, x.service_id },
|
||||
principalTable: "service_languages",
|
||||
principalColumns: new[] { "id", "service_id" },
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_push_template_definitions_service_id_key",
|
||||
table: "push_template_definitions",
|
||||
columns: new[] { "service_id", "key" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_push_templates_definition_id_service_id",
|
||||
table: "push_templates",
|
||||
columns: new[] { "definition_id", "service_id" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_push_templates_definition_id_service_language_id",
|
||||
table: "push_templates",
|
||||
columns: new[] { "definition_id", "service_language_id" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_push_templates_service_language_id_service_id",
|
||||
table: "push_templates",
|
||||
columns: new[] { "service_language_id", "service_id" });
|
||||
|
||||
// Preserve existing email identity, variables, revisions and translations in place.
|
||||
migrationBuilder.Sql("""
|
||||
INSERT INTO templates (id, service_id, key, created, updated)
|
||||
SELECT id, service_id, key, created, updated FROM email_template_definitions;
|
||||
""");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_email_template_definitions_templates_service_id_key",
|
||||
table: "email_template_definitions",
|
||||
columns: new[] { "service_id", "key" },
|
||||
principalTable: "templates",
|
||||
principalColumns: new[] { "service_id", "key" },
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.Sql("""
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM push_template_definitions) THEN
|
||||
RAISE EXCEPTION 'Cannot roll back channel templates while push definitions exist. Export and explicitly remove them first.';
|
||||
END IF;
|
||||
END $$;
|
||||
""");
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_email_template_definitions_templates_service_id_key",
|
||||
table: "email_template_definitions");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "push_templates");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "push_template_definitions");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "templates");
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+679
@@ -0,0 +1,679 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
[DbContext(typeof(NotificationDbContext))]
|
||||
[Migration("20261030235620_AddPushTemplateActions")]
|
||||
partial class AddPushTemplateActions
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.7")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<int?>("DailyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("daily_limit");
|
||||
|
||||
b.Property<int>("EmailChannelType")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("provider_type");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_active");
|
||||
|
||||
b.Property<int?>("MonthlyLimit")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("monthly_limit");
|
||||
|
||||
b.Property<int>("Priority")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("priority");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<string>("SettingsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("settings");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.Property<int>("WarnThresholdPercent")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("warn_threshold_percent");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Priority");
|
||||
|
||||
b.ToTable("email_channels", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<DateOnly>("Date")
|
||||
.HasColumnType("date")
|
||||
.HasColumnName("date");
|
||||
|
||||
b.Property<Guid>("ProviderId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("provider_id");
|
||||
|
||||
b.Property<int>("SentCount")
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("sent_count");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ProviderId", "Date")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_channel_usage", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_template_definitions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("DefinitionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("definition_id");
|
||||
|
||||
b.Property<string>("HtmlBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("html_body");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<Guid>("ServiceLanguageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_language_id");
|
||||
|
||||
b.Property<string>("Subject")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("subject");
|
||||
|
||||
b.Property<string>("TextBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("text_body");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceId");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceLanguageId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ServiceLanguageId", "ServiceId");
|
||||
|
||||
b.ToTable("email_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushChannelEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("CredentialsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("credentials");
|
||||
|
||||
b.Property<string>("FirebaseProjectId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(30)
|
||||
.HasColumnType("character varying(30)")
|
||||
.HasColumnName("firebase_project_id");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_active");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("push_channels", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushDeliveryEntity", b =>
|
||||
{
|
||||
b.Property<string>("ServiceName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<Guid>("MessageId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CompletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Error")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("InvalidRegistration")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.HasKey("ServiceName", "MessageId");
|
||||
|
||||
b.HasIndex("CompletedAt");
|
||||
|
||||
b.ToTable("PushDeliveries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("push_template_definitions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("ActionsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("actions");
|
||||
|
||||
b.Property<string>("Body")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("body");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("DefinitionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("definition_id");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<Guid>("ServiceLanguageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_language_id");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("title");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceId");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceLanguageId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ServiceLanguageId", "ServiceId");
|
||||
|
||||
b.ToTable("push_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("services", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Code")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasColumnName("code");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Code")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("service_languages", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", null)
|
||||
.WithMany("UsageRecords")
|
||||
.HasForeignKey("ProviderId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "Template")
|
||||
.WithOne("Email")
|
||||
.HasForeignKey("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", "ServiceId", "Key")
|
||||
.HasPrincipalKey("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "ServiceId", "Key")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateVariableData", "Variables", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("EmailTemplateDefinitionEntityId");
|
||||
|
||||
b1.Property<int>("__synthesizedOrdinal")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b1.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasJsonPropertyName("name");
|
||||
|
||||
b1.Property<bool>("Required")
|
||||
.HasJsonPropertyName("required");
|
||||
|
||||
b1.HasKey("EmailTemplateDefinitionEntityId", "__synthesizedOrdinal");
|
||||
|
||||
b1.ToTable("email_template_definitions");
|
||||
|
||||
b1
|
||||
.ToJson("variables")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("EmailTemplateDefinitionEntityId");
|
||||
});
|
||||
|
||||
b.Navigation("Service");
|
||||
|
||||
b.Navigation("Template");
|
||||
|
||||
b.Navigation("Variables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", "Definition")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("DefinitionId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", "ServiceLanguage")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceLanguageId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Definition");
|
||||
|
||||
b.Navigation("ServiceLanguage");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushChannelEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "Template")
|
||||
.WithOne("Push")
|
||||
.HasForeignKey("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", "ServiceId", "Key")
|
||||
.HasPrincipalKey("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "ServiceId", "Key")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateVariableData", "Variables", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("PushTemplateDefinitionEntityId");
|
||||
|
||||
b1.Property<int>("__synthesizedOrdinal")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b1.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasJsonPropertyName("name");
|
||||
|
||||
b1.Property<bool>("Required")
|
||||
.HasJsonPropertyName("required");
|
||||
|
||||
b1.HasKey("PushTemplateDefinitionEntityId", "__synthesizedOrdinal");
|
||||
|
||||
b1.ToTable("push_template_definitions");
|
||||
|
||||
b1
|
||||
.ToJson("variables")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("PushTemplateDefinitionEntityId");
|
||||
});
|
||||
|
||||
b.Navigation("Template");
|
||||
|
||||
b.Navigation("Variables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", "Definition")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("DefinitionId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", "ServiceLanguage")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceLanguageId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Definition");
|
||||
|
||||
b.Navigation("ServiceLanguage");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Navigation("UsageRecords");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", b =>
|
||||
{
|
||||
b.Navigation("Email");
|
||||
|
||||
b.Navigation("Push");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddPushTemplateActions : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "actions",
|
||||
table: "push_templates",
|
||||
type: "jsonb",
|
||||
nullable: false,
|
||||
defaultValue: "{}");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "actions",
|
||||
table: "push_templates");
|
||||
}
|
||||
}
|
||||
}
|
||||
+491
-37
@@ -17,7 +17,7 @@ namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "9.0.5")
|
||||
.HasAnnotation("ProductVersion", "10.0.7")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
@@ -53,11 +53,9 @@ namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
.HasColumnType("integer")
|
||||
.HasColumnName("priority");
|
||||
|
||||
b.Property<string>("ServiceName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("service_name");
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<string>("SettingsJson")
|
||||
.IsRequired()
|
||||
@@ -74,7 +72,7 @@ namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceName", "Priority");
|
||||
b.HasIndex("ServiceId", "Priority");
|
||||
|
||||
b.ToTable("email_channels", (string)null);
|
||||
});
|
||||
@@ -114,6 +112,44 @@ namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
b.ToTable("email_channel_usage", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("email_template_definitions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -125,28 +161,22 @@ namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("DefinitionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("definition_id");
|
||||
|
||||
b.Property<string>("HtmlBody")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("html_body");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<string>("LanguageCode")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasColumnName("language_code");
|
||||
|
||||
b.Property<string>("ServiceName")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("service_name");
|
||||
b.Property<Guid>("ServiceLanguageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_language_id");
|
||||
|
||||
b.Property<string>("Subject")
|
||||
.IsRequired()
|
||||
@@ -164,12 +194,284 @@ namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceName", "Key", "LanguageCode")
|
||||
b.HasIndex("DefinitionId", "ServiceId");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceLanguageId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ServiceLanguageId", "ServiceId");
|
||||
|
||||
b.ToTable("email_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushChannelEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("CredentialsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("credentials");
|
||||
|
||||
b.Property<string>("FirebaseProjectId")
|
||||
.IsRequired()
|
||||
.HasMaxLength(30)
|
||||
.HasColumnType("character varying(30)")
|
||||
.HasColumnName("firebase_project_id");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_active");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("push_channels", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushDeliveryEntity", b =>
|
||||
{
|
||||
b.Property<string>("ServiceName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)");
|
||||
|
||||
b.Property<Guid>("MessageId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CompletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Error")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)");
|
||||
|
||||
b.Property<bool>("InvalidRegistration")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.HasKey("ServiceName", "MessageId");
|
||||
|
||||
b.HasIndex("CompletedAt");
|
||||
|
||||
b.ToTable("PushDeliveries", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Key")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("push_template_definitions", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("ActionsJson")
|
||||
.IsRequired()
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("actions");
|
||||
|
||||
b.Property<string>("Body")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("body");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("DefinitionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("definition_id");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<Guid>("ServiceLanguageId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_language_id");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("title");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceId");
|
||||
|
||||
b.HasIndex("DefinitionId", "ServiceLanguageId")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ServiceLanguageId", "ServiceId");
|
||||
|
||||
b.ToTable("push_templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<Guid>("Revision")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("revision");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Name")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("services", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Code")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasColumnName("code");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ServiceId", "Code")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("service_languages", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("Created")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created");
|
||||
|
||||
b.Property<string>("Key")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("key");
|
||||
|
||||
b.Property<Guid>("ServiceId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("service_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("Updated")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("templates", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelUsageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", null)
|
||||
@@ -179,43 +481,195 @@ namespace HrynCo.NotificationService.DAL.EF.Migrations
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "Template")
|
||||
.WithOne("Email")
|
||||
.HasForeignKey("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", "ServiceId", "Key")
|
||||
.HasPrincipalKey("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "ServiceId", "Key")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateVariableData", "Variables", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("EmailTemplateEntityId")
|
||||
.HasColumnType("uuid");
|
||||
b1.Property<Guid>("EmailTemplateDefinitionEntityId");
|
||||
|
||||
b1.Property<int>("__synthesizedOrdinal")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("integer");
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b1.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasAnnotation("Relational:JsonPropertyName", "name");
|
||||
.HasJsonPropertyName("name");
|
||||
|
||||
b1.Property<bool>("Required")
|
||||
.HasColumnType("boolean")
|
||||
.HasAnnotation("Relational:JsonPropertyName", "required");
|
||||
.HasJsonPropertyName("required");
|
||||
|
||||
b1.HasKey("EmailTemplateEntityId", "__synthesizedOrdinal");
|
||||
b1.HasKey("EmailTemplateDefinitionEntityId", "__synthesizedOrdinal");
|
||||
|
||||
b1.ToTable("email_templates");
|
||||
b1.ToTable("email_template_definitions");
|
||||
|
||||
b1.ToJson("variables");
|
||||
b1
|
||||
.ToJson("variables")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("EmailTemplateEntityId");
|
||||
.HasForeignKey("EmailTemplateDefinitionEntityId");
|
||||
});
|
||||
|
||||
b.Navigation("Service");
|
||||
|
||||
b.Navigation("Template");
|
||||
|
||||
b.Navigation("Variables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", "Definition")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("DefinitionId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", "ServiceLanguage")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceLanguageId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Definition");
|
||||
|
||||
b.Navigation("ServiceLanguage");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushChannelEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "Template")
|
||||
.WithOne("Push")
|
||||
.HasForeignKey("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", "ServiceId", "Key")
|
||||
.HasPrincipalKey("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", "ServiceId", "Key")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.OwnsMany("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateVariableData", "Variables", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("PushTemplateDefinitionEntityId");
|
||||
|
||||
b1.Property<int>("__synthesizedOrdinal")
|
||||
.ValueGeneratedOnAdd();
|
||||
|
||||
b1.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasJsonPropertyName("name");
|
||||
|
||||
b1.Property<bool>("Required")
|
||||
.HasJsonPropertyName("required");
|
||||
|
||||
b1.HasKey("PushTemplateDefinitionEntityId", "__synthesizedOrdinal");
|
||||
|
||||
b1.ToTable("push_template_definitions");
|
||||
|
||||
b1
|
||||
.ToJson("variables")
|
||||
.HasColumnType("jsonb");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("PushTemplateDefinitionEntityId");
|
||||
});
|
||||
|
||||
b.Navigation("Template");
|
||||
|
||||
b.Navigation("Variables");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", "Definition")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("DefinitionId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", "ServiceLanguage")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceLanguageId", "ServiceId")
|
||||
.HasPrincipalKey("Id", "ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Definition");
|
||||
|
||||
b.Navigation("ServiceLanguage");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceLanguageEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany("Languages")
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", b =>
|
||||
{
|
||||
b.HasOne("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", "Service")
|
||||
.WithMany()
|
||||
.HasForeignKey("ServiceId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Service");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailChannelEntity", b =>
|
||||
{
|
||||
b.Navigation("UsageRecords");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.EmailTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.PushTemplateDefinitionEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.ServiceEntity", b =>
|
||||
{
|
||||
b.Navigation("Languages");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("HrynCo.NotificationService.DAL.EF.Entities.TemplateEntity", b =>
|
||||
{
|
||||
b.Navigation("Email");
|
||||
|
||||
b.Navigation("Push");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,13 @@ public class NotificationDbContext : DbContext
|
||||
{
|
||||
}
|
||||
|
||||
internal DbSet<TemplateEntity> TemplateCatalog => Set<TemplateEntity>();
|
||||
internal DbSet<PushTemplateDefinitionEntity> PushTemplateDefinitions => Set<PushTemplateDefinitionEntity>();
|
||||
internal DbSet<PushTemplateEntity> PushTemplates => Set<PushTemplateEntity>();
|
||||
internal DbSet<ServiceLanguageEntity> ServiceLanguages => Set<ServiceLanguageEntity>();
|
||||
internal DbSet<PushChannelEntity> PushChannels => Set<PushChannelEntity>();
|
||||
internal DbSet<ServiceEntity> Services => Set<ServiceEntity>();
|
||||
internal DbSet<EmailTemplateDefinitionEntity> TemplateDefinitions => Set<EmailTemplateDefinitionEntity>();
|
||||
internal DbSet<EmailTemplateEntity> Templates => Set<EmailTemplateEntity>();
|
||||
internal DbSet<EmailChannelEntity> Providers => Set<EmailChannelEntity>();
|
||||
internal DbSet<EmailChannelUsageEntity> EmailChannelUsage => Set<EmailChannelUsageEntity>();
|
||||
|
||||
@@ -8,9 +8,10 @@ internal sealed class NotificationDbContextFactory : IDesignTimeDbContextFactory
|
||||
public NotificationDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<NotificationDbContext>()
|
||||
.UseNpgsql("Host=localhost;Port=5432;Database=notification_service;Username=postgres;Password=postgres")
|
||||
.UseNpgsql(Environment.GetEnvironmentVariable("App__ConnectionString")
|
||||
?? "Host=localhost;Port=5432;Database=notification_service;Username=postgres;Password=postgres")
|
||||
.Options;
|
||||
|
||||
return new NotificationDbContext(options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace HrynCo.NotificationService.DAL.EF;
|
||||
|
||||
using HrynCo.DAL.EF.Core;
|
||||
|
||||
public class NotificationUnitOfWork : EfUnitOfWork<NotificationDbContext>
|
||||
{
|
||||
public NotificationUnitOfWork(NotificationDbContext context) : base(context)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||
|
||||
using System.Text.Json;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.DAL.EF.Core;
|
||||
using HrynCo.NotificationService.DAL.EF.Core;
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||
|
||||
internal sealed class EmailChannelRepository : EfRepository<NotificationDbContext, EmailChannelEntity>, IEmailChannelRepository
|
||||
internal sealed class EmailChannelRepository : NotificationBaseRepository<EmailChannelEntity>, IEmailChannelRepository
|
||||
{
|
||||
public EmailChannelRepository(NotificationDbContext dbContext) : base(dbContext)
|
||||
{
|
||||
@@ -15,20 +15,14 @@ internal sealed class EmailChannelRepository : EfRepository<NotificationDbContex
|
||||
|
||||
public async Task<IReadOnlyList<EmailChannel>> GetAllAsync(CancellationToken ct = default)
|
||||
{
|
||||
var entities = await DbSet
|
||||
.AsNoTracking()
|
||||
.OrderBy(x => x.ServiceName)
|
||||
.ThenBy(x => x.Priority)
|
||||
.ToListAsync(ct);
|
||||
var entities = await EfRepository.Get().AsNoTracking().Include(x => x.Service).ToListAsync(ct);
|
||||
|
||||
return entities.Select(MapToDomain).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<EmailChannel>> GetByServiceAsync(string serviceName, CancellationToken ct = default)
|
||||
public async Task<IReadOnlyList<EmailChannel>> GetByServiceAsync(Guid serviceId, CancellationToken ct = default)
|
||||
{
|
||||
var entities = await DbSet
|
||||
.AsNoTracking()
|
||||
.Where(x => x.ServiceName == serviceName)
|
||||
var entities = await EfRepository.Get(x => x.ServiceId == serviceId).Include(x => x.Service)
|
||||
.OrderBy(x => x.Priority)
|
||||
.ToListAsync(ct);
|
||||
|
||||
@@ -38,9 +32,8 @@ internal sealed class EmailChannelRepository : EfRepository<NotificationDbContex
|
||||
public async Task<IReadOnlyList<ChannelWithUsage>> GetAllWithUsageSummaryAsync(
|
||||
DateOnly today, CancellationToken ct = default)
|
||||
{
|
||||
var rows = await DbSet
|
||||
.AsNoTracking()
|
||||
.OrderBy(c => c.ServiceName)
|
||||
var rows = await EfRepository.Get().AsNoTracking().Include(c => c.Service)
|
||||
.OrderBy(c => c.Service.Name)
|
||||
.ThenBy(c => c.Priority)
|
||||
.Select(c => new
|
||||
{
|
||||
@@ -61,30 +54,24 @@ internal sealed class EmailChannelRepository : EfRepository<NotificationDbContex
|
||||
|
||||
public async Task<EmailChannel?> GetByIdAsync(Guid id, CancellationToken ct = default)
|
||||
{
|
||||
EmailChannelEntity? entity = await DbSet.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct);
|
||||
EmailChannelEntity? entity = await EfRepository.Get().AsNoTracking().Include(c => c.Service).SingleOrDefaultAsync(c => c.Id == id, ct);
|
||||
return entity is null ? null : MapToDomain(entity);
|
||||
}
|
||||
|
||||
public Task AddAsync(EmailChannel channel, CancellationToken ct = default)
|
||||
{
|
||||
return base.AddAsync(MapToEntity(channel), ct);
|
||||
return EfRepository.AddAsync(MapToEntity(channel));
|
||||
}
|
||||
|
||||
public Task UpdateAsync(EmailChannel channel, CancellationToken ct = default)
|
||||
public async Task UpdateAsync(EmailChannel channel, CancellationToken ct = default)
|
||||
{
|
||||
EmailChannelEntity entity = MapToEntity(channel);
|
||||
entity.Updated = DateTimeOffset.UtcNow;
|
||||
Update(entity);
|
||||
return Task.CompletedTask;
|
||||
await EfRepository.UpdateAsync(entity);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(EmailChannel channel, CancellationToken ct = default)
|
||||
{
|
||||
EmailChannelEntity? entity = await DbSet.FindAsync([channel.Id], ct);
|
||||
if (entity is not null)
|
||||
{
|
||||
Delete(entity);
|
||||
}
|
||||
await EfRepository.DeleteAsync(channel.Id);
|
||||
}
|
||||
|
||||
private static EmailChannel MapToDomain(EmailChannelEntity e)
|
||||
@@ -92,7 +79,8 @@ internal sealed class EmailChannelRepository : EfRepository<NotificationDbContex
|
||||
return new EmailChannel
|
||||
{
|
||||
Id = e.Id,
|
||||
ServiceName = e.ServiceName,
|
||||
ServiceId = e.ServiceId,
|
||||
ServiceName = e.Service.Name,
|
||||
Priority = e.Priority,
|
||||
EmailChannelType = e.EmailChannelType,
|
||||
Settings = DeserializeSettings(e.EmailChannelType, e.SettingsJson),
|
||||
@@ -110,7 +98,7 @@ internal sealed class EmailChannelRepository : EfRepository<NotificationDbContex
|
||||
return new EmailChannelEntity
|
||||
{
|
||||
Id = p.Id,
|
||||
ServiceName = p.ServiceName,
|
||||
ServiceId = p.ServiceId,
|
||||
Priority = p.Priority,
|
||||
EmailChannelType = p.EmailChannelType,
|
||||
SettingsJson = JsonSerializer.Serialize(p.Settings, p.Settings.GetType()),
|
||||
@@ -128,8 +116,8 @@ internal sealed class EmailChannelRepository : EfRepository<NotificationDbContex
|
||||
return type switch
|
||||
{
|
||||
EmailChannelType.Smtp => JsonSerializer.Deserialize<SmtpChannelSettings>(json)
|
||||
?? throw new InvalidOperationException(
|
||||
"Failed to deserialize SMTP EmailChannel settings."),
|
||||
?? throw new InvalidOperationException(
|
||||
"Failed to deserialize SMTP EmailChannel settings."),
|
||||
_ => throw new InvalidOperationException($"Unknown or undefined email channel type: {type}")
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.DAL.EF.Core;
|
||||
using HrynCo.NotificationService.DAL.EF.Core;
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||
|
||||
internal sealed class EmailChannelUsageRepository : EfRepository<NotificationDbContext, EmailChannelUsageEntity>, IEmailChannelUsageRepository
|
||||
internal sealed class EmailChannelUsageRepository : NotificationBaseRepository<EmailChannelUsageEntity>, IEmailChannelUsageRepository
|
||||
{
|
||||
public EmailChannelUsageRepository(NotificationDbContext dbContext) : base(dbContext)
|
||||
{
|
||||
@@ -13,7 +13,8 @@ internal sealed class EmailChannelUsageRepository : EfRepository<NotificationDbC
|
||||
|
||||
public async Task<int> GetDailyCountAsync(Guid providerId, DateOnly date, CancellationToken ct = default)
|
||||
{
|
||||
EmailChannelUsageEntity? entity = await DbSet
|
||||
EmailChannelUsageEntity? entity = await EfRepository.Get()
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.ProviderId == providerId && x.Date == date, ct);
|
||||
|
||||
return entity?.SentCount ?? 0;
|
||||
@@ -21,7 +22,7 @@ internal sealed class EmailChannelUsageRepository : EfRepository<NotificationDbC
|
||||
|
||||
public async Task<int> GetMonthlyCountAsync(Guid providerId, int year, int month, CancellationToken ct = default)
|
||||
{
|
||||
return await DbSet
|
||||
return await EfRepository.Get()
|
||||
.Where(x => x.ProviderId == providerId
|
||||
&& x.Date.Year == year
|
||||
&& x.Date.Month == month)
|
||||
@@ -30,15 +31,16 @@ internal sealed class EmailChannelUsageRepository : EfRepository<NotificationDbC
|
||||
|
||||
public async Task IncrementUsageAsync(Guid providerId, DateOnly date, CancellationToken ct = default)
|
||||
{
|
||||
EmailChannelUsageEntity? entity = await DbSet
|
||||
EmailChannelUsageEntity? entity = await EfRepository.Get()
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.ProviderId == providerId && x.Date == date, ct);
|
||||
|
||||
if (entity is null)
|
||||
await AddAsync(new EmailChannelUsageEntity { ProviderId = providerId, Date = date, SentCount = 1 }, ct);
|
||||
await EfRepository.AddAsync(new EmailChannelUsageEntity { ProviderId = providerId, Date = date, SentCount = 1 });
|
||||
else
|
||||
{
|
||||
entity.SentCount++;
|
||||
Update(entity);
|
||||
await EfRepository.UpdateAsync(entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,83 +1,345 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.DAL.EF.Core;
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||
|
||||
internal sealed class EmailTemplateRepository : EfRepository<NotificationDbContext, EmailTemplateEntity>, IEmailTemplateRepository
|
||||
internal sealed class EmailTemplateRepository(NotificationDbContext db, TemplateMutationRunner mutations)
|
||||
: IEmailTemplateRepository, IEmailTemplateDefinitionRepository
|
||||
{
|
||||
public EmailTemplateRepository(NotificationDbContext dbContext) : base(dbContext)
|
||||
private IQueryable<EmailTemplateEntity> Languages => db.Templates
|
||||
.Include(t => t.Definition).ThenInclude(d => d.Service).Include(t => t.ServiceLanguage);
|
||||
private IQueryable<EmailTemplateDefinitionEntity> Definitions => db.TemplateDefinitions
|
||||
.Include(d => d.Service).ThenInclude(s => s.Languages)
|
||||
.Include(d => d.Languages).ThenInclude(t => t.ServiceLanguage);
|
||||
|
||||
public async Task<IReadOnlyList<EmailTemplate>> GetAllAsync(string? serviceName = null, string? key = null, CancellationToken ct = default)
|
||||
{
|
||||
var query = Languages.AsNoTracking();
|
||||
if (!string.IsNullOrWhiteSpace(serviceName))
|
||||
query = query.Where(t => t.Definition.Service.Name == serviceName);
|
||||
if (!string.IsNullOrWhiteSpace(key))
|
||||
query = query.Where(t => t.Definition.Key == key);
|
||||
var entities = await query.OrderBy(t => t.Definition.Service.Name).ThenBy(t => t.Definition.Key)
|
||||
.ThenBy(t => t.ServiceLanguage.Code).ToListAsync(ct);
|
||||
return entities.Select(MapLanguage).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<EmailTemplate>> GetAllAsync(CancellationToken ct = default)
|
||||
{
|
||||
List<EmailTemplateEntity> entities = await DbSet.ToListAsync(ct);
|
||||
return entities.Select(MapToDomain).ToList();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default)
|
||||
{
|
||||
List<EmailTemplateEntity> entities = await DbSet
|
||||
.Where(x => x.ServiceName == serviceName)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return entities.Select(MapToDomain).ToList();
|
||||
}
|
||||
public Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default) =>
|
||||
GetAllAsync(serviceName, ct: ct);
|
||||
|
||||
public async Task<EmailTemplate?> GetAsync(string serviceName, string key, string languageCode, CancellationToken ct = default)
|
||||
{
|
||||
EmailTemplateEntity? entity = await DbSet.FirstOrDefaultAsync(
|
||||
x => x.ServiceName == serviceName && x.Key == key && x.LanguageCode == languageCode, ct);
|
||||
|
||||
return entity is null ? null : MapToDomain(entity);
|
||||
var code = languageCode;
|
||||
var entity = await Languages.AsNoTracking().SingleOrDefaultAsync(t =>
|
||||
t.Definition.Service.Name == serviceName && t.Definition.Key == key && t.ServiceLanguage.Code == code, ct);
|
||||
return entity is null ? null : MapLanguage(entity);
|
||||
}
|
||||
|
||||
public Task AddAsync(EmailTemplate EmailTemplate, CancellationToken ct = default) =>
|
||||
base.AddAsync(MapToEntity(EmailTemplate), ct);
|
||||
|
||||
public Task UpdateAsync(EmailTemplate EmailTemplate, CancellationToken ct = default)
|
||||
public async Task<EmailTemplateDefinition?> GetDefinitionAsync(string serviceName, string key, CancellationToken ct = default)
|
||||
{
|
||||
EmailTemplateEntity entity = MapToEntity(EmailTemplate);
|
||||
var entity = await Definitions.AsNoTracking().SingleOrDefaultAsync(d => d.Service.Name == serviceName && d.Key == key, ct);
|
||||
return entity is null ? null : MapDefinition(entity);
|
||||
}
|
||||
|
||||
public async Task<EmailTemplateDefinition?> GetDefinitionAsync(Guid serviceId, string key, CancellationToken ct = default)
|
||||
{
|
||||
var entity = await Definitions.AsNoTracking().SingleOrDefaultAsync(d => d.ServiceId == serviceId && d.Key == key, ct);
|
||||
return entity is null ? null : MapDefinition(entity);
|
||||
}
|
||||
|
||||
public async Task<EmailTemplateDefinition?> UpsertDefinitionAsync(EmailTemplateDefinitionPatch patch, CancellationToken ct = default)
|
||||
{
|
||||
EmailTemplateDefinitionEntity? saved = null;
|
||||
await mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
var service = await db.Services.Include(s => s.Languages).SingleOrDefaultAsync(s => s.Id == patch.ServiceId, ct);
|
||||
if (service is null)
|
||||
return;
|
||||
ValidatePatch(patch, service);
|
||||
var entity = await LoadForUpsertAsync(patch, service, ct);
|
||||
entity.Variables = MapVariables(patch.Variables);
|
||||
var removed = patch.RemoveLanguageCodes.ToHashSet(StringComparer.Ordinal);
|
||||
db.Templates.RemoveRange(entity.Languages.Where(t => removed.Contains(t.ServiceLanguage.Code)));
|
||||
// Omitted translations are retained. Only explicitly supplied content is changed.
|
||||
UpsertLanguages(entity, patch.Translations);
|
||||
Touch(entity);
|
||||
saved = entity;
|
||||
}, ct);
|
||||
return saved is null ? null : MapDefinition(saved);
|
||||
}
|
||||
|
||||
private async Task<EmailTemplateDefinitionEntity> LoadForUpsertAsync(EmailTemplateDefinitionPatch patch, ServiceEntity service, CancellationToken ct)
|
||||
{
|
||||
var entity = await Definitions.SingleOrDefaultAsync(d => d.ServiceId == patch.ServiceId && d.Key == patch.Key, ct);
|
||||
if (patch.Revision is null)
|
||||
{
|
||||
if (entity is not null)
|
||||
throw new EmailTemplateWriteException("A definition with this service and key already exists. Read its revision before updating.");
|
||||
entity = new EmailTemplateDefinitionEntity { Service = service, ServiceId = service.Id, Key = patch.Key, Created = DateTimeOffset.UtcNow };
|
||||
entity.Template = await GetOrCreateTemplateAsync(service, patch.Key, ct);
|
||||
db.TemplateDefinitions.Add(entity);
|
||||
return entity;
|
||||
}
|
||||
if (entity is null || entity.Revision != patch.Revision)
|
||||
throw new EmailTemplateWriteException("The definition is missing or its revision changed. Read it again before updating.");
|
||||
return entity;
|
||||
}
|
||||
|
||||
private static void ValidatePatch(EmailTemplateDefinitionPatch patch, ServiceEntity service)
|
||||
{
|
||||
EmailTemplateValidation.ValidateDefinition(new EmailTemplateDefinition
|
||||
{
|
||||
ServiceId = service.Id, ServiceName = service.Name, Key = patch.Key,
|
||||
Variables = patch.Variables, Languages = patch.Translations
|
||||
});
|
||||
if (patch.Revision == Guid.Empty)
|
||||
throw new EmailTemplateWriteException("Revision must be null for creation or a nonempty revision from the last read for update.", false);
|
||||
var removed = patch.RemoveLanguageCodes;
|
||||
if (removed.Any(string.IsNullOrWhiteSpace) || removed.Distinct(StringComparer.Ordinal).Count() != removed.Count)
|
||||
throw new EmailTemplateWriteException("removeLanguageCodes must contain unique nonblank language codes.", false);
|
||||
var supplied = patch.Translations.Select(t => t.LanguageCode).ToHashSet(StringComparer.Ordinal);
|
||||
if (removed.Any(supplied.Contains))
|
||||
throw new EmailTemplateWriteException("A language cannot be supplied and removed in the same request.", false);
|
||||
var supported = service.Languages.Select(l => l.Code).ToHashSet(StringComparer.Ordinal);
|
||||
if (supplied.Concat(removed).Any(code => !supported.Contains(code)))
|
||||
throw new EmailTemplateWriteException("Every supplied or removed language must exactly match a code in this service's catalog.", false);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<EmailTemplateDefinition>> GetDefinitionsAsync(Guid serviceId, CancellationToken ct = default)
|
||||
{
|
||||
var entities = await Definitions.AsNoTracking().Where(d => d.ServiceId == serviceId).OrderBy(d => d.Key).ToListAsync(ct);
|
||||
return entities.Select(MapDefinition).ToList();
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteDefinitionAsync(Guid serviceId, string key, Guid revision, CancellationToken ct = default)
|
||||
{
|
||||
var removed = false;
|
||||
await mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key) || key.Length > 100 || revision == Guid.Empty)
|
||||
throw new EmailTemplateWriteException("An exact key (at most 100 characters) and a nonempty revision are required.", false);
|
||||
var definition = await Definitions.SingleOrDefaultAsync(d => d.ServiceId == serviceId && d.Key == key, ct);
|
||||
if (definition is null)
|
||||
return;
|
||||
if (definition.Revision != revision)
|
||||
throw new EmailTemplateWriteException("The definition revision changed. Read it again before deleting.");
|
||||
db.TemplateDefinitions.Remove(definition);
|
||||
await RemoveEmptyTemplateAsync(serviceId, key, ct);
|
||||
removed = true;
|
||||
}, ct);
|
||||
return removed;
|
||||
}
|
||||
|
||||
public Task AddAsync(EmailTemplate template, CancellationToken ct = default) => mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
ValidateLegacy(template);
|
||||
var definition = await FindDefinitionAsync(template.ServiceName, template.Key, ct);
|
||||
if (definition is null)
|
||||
{
|
||||
await RequireServiceLanguageAsync(template.ServiceName, template.LanguageCode, ct);
|
||||
definition = await CreateDefinitionAsync(template.ServiceName, template.Key, template.Variables, ct);
|
||||
}
|
||||
EnsureMatchingContract(definition, template.Variables);
|
||||
await RequireServiceLanguageAsync(template.ServiceName, template.LanguageCode, ct);
|
||||
var code = template.LanguageCode;
|
||||
if (definition.Languages.Any(t => t.ServiceLanguage.Code == code))
|
||||
throw new EmailTemplateWriteException("This language already exists for the template.");
|
||||
var language = NewLanguage(template, definition);
|
||||
definition.Languages.Add(language);
|
||||
db.Templates.Add(language);
|
||||
Touch(definition);
|
||||
}, ct);
|
||||
|
||||
public Task UpdateAsync(EmailTemplate template, CancellationToken ct = default) => mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
ValidateLegacy(template);
|
||||
var definition = await RequireDefinitionAsync(template.ServiceName, template.Key, ct);
|
||||
EnsureMatchingContract(definition, template.Variables);
|
||||
var language = definition.Languages.SingleOrDefault(t => t.Id == template.Id)
|
||||
?? throw new EmailTemplateWriteException("The language changed or was removed. Reload the template.");
|
||||
SetContent(language, template);
|
||||
Touch(definition);
|
||||
}, ct);
|
||||
|
||||
public Task DeleteAsync(EmailTemplate template, CancellationToken ct = default) => mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
var definition = await RequireDefinitionAsync(template.ServiceName, template.Key, ct);
|
||||
var language = definition.Languages.SingleOrDefault(t => t.Id == template.Id)
|
||||
?? throw new EmailTemplateWriteException("The language changed or was removed. Reload the template.");
|
||||
db.Templates.Remove(language);
|
||||
Touch(definition);
|
||||
}, ct);
|
||||
|
||||
public Task SaveDefinitionAsync(EmailTemplateDefinition definition, bool isNew, CancellationToken ct = default) => mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
EmailTemplateValidation.ValidateDefinition(definition);
|
||||
await ValidateServiceLanguagesAsync(definition, ct);
|
||||
var entity = await LoadForSaveAsync(definition, isNew, ct);
|
||||
entity.Variables = MapVariables(definition.Variables);
|
||||
SynchronizeLanguages(entity, definition.Languages);
|
||||
Touch(entity);
|
||||
definition.Id = entity.Id;
|
||||
definition.Revision = entity.Revision;
|
||||
}, ct);
|
||||
|
||||
private async Task<EmailTemplateDefinitionEntity> LoadForSaveAsync(EmailTemplateDefinition model, bool isNew, CancellationToken ct)
|
||||
{
|
||||
var entity = await FindDefinitionAsync(model.ServiceName, model.Key, ct);
|
||||
if (isNew)
|
||||
{
|
||||
if (entity is not null)
|
||||
throw new EmailTemplateWriteException("A template with this service and key already exists.");
|
||||
return await CreateDefinitionAsync(model.ServiceName, model.Key, model.Variables, ct);
|
||||
}
|
||||
if (entity is null || entity.Id != model.Id || entity.Revision != model.Revision)
|
||||
throw new EmailTemplateWriteException("This template changed after you opened it. Reload before saving; your entered values are retained.");
|
||||
return entity;
|
||||
}
|
||||
|
||||
private void SynchronizeLanguages(EmailTemplateDefinitionEntity definition, IReadOnlyList<EmailTemplate> languages)
|
||||
{
|
||||
var codes = languages.Select(t => t.LanguageCode).ToHashSet(StringComparer.Ordinal);
|
||||
db.Templates.RemoveRange(definition.Languages.Where(t => !codes.Contains(t.ServiceLanguage.Code)));
|
||||
UpsertLanguages(definition, languages);
|
||||
}
|
||||
|
||||
private void UpsertLanguages(EmailTemplateDefinitionEntity definition, IReadOnlyList<EmailTemplate> languages)
|
||||
{
|
||||
foreach (var model in languages)
|
||||
{
|
||||
var code = model.LanguageCode;
|
||||
var entity = definition.Languages.SingleOrDefault(t => t.ServiceLanguage.Code == code);
|
||||
if (entity is null)
|
||||
{
|
||||
var language = NewLanguage(model, definition);
|
||||
definition.Languages.Add(language);
|
||||
db.Templates.Add(language);
|
||||
}
|
||||
else
|
||||
SetContent(entity, model);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<EmailTemplateDefinition>> GetDefinitionsAsync(string? serviceName = null, string? key = null, CancellationToken ct = default)
|
||||
{
|
||||
var query = Definitions.AsNoTracking();
|
||||
if (!string.IsNullOrWhiteSpace(serviceName))
|
||||
query = query.Where(d => d.Service.Name == serviceName);
|
||||
if (!string.IsNullOrWhiteSpace(key))
|
||||
query = query.Where(d => d.Key == key);
|
||||
var entities = await query.OrderBy(d => d.Service.Name).ThenBy(d => d.Key).ToListAsync(ct);
|
||||
return entities.Select(MapDefinition).ToList();
|
||||
}
|
||||
|
||||
private async Task RequireServiceLanguageAsync(string serviceName, string code, CancellationToken ct)
|
||||
{
|
||||
if (!await db.ServiceLanguages.AnyAsync(l => l.Service.Name == serviceName && l.Code == code, ct))
|
||||
throw new EmailTemplateWriteException("Language is not in this service's catalog. Add it in the service editor first.", false);
|
||||
}
|
||||
|
||||
private async Task ValidateServiceLanguagesAsync(EmailTemplateDefinition definition, CancellationToken ct)
|
||||
{
|
||||
var service = await db.Services.Include(s => s.Languages).SingleOrDefaultAsync(s => s.Name == definition.ServiceName
|
||||
&& (definition.ServiceId == Guid.Empty || s.Id == definition.ServiceId), ct)
|
||||
?? throw new EmailTemplateWriteException("Service does not exist. Create the service first.", false);
|
||||
var codes = service.Languages.Select(l => l.Code).ToHashSet(StringComparer.Ordinal);
|
||||
if (definition.Languages.Any(l => !codes.Contains(l.LanguageCode)))
|
||||
throw new EmailTemplateWriteException("Language is not in this service's catalog. Add it in the service editor first.", false);
|
||||
}
|
||||
|
||||
private Task<EmailTemplateDefinitionEntity?> FindDefinitionAsync(string serviceName, string key, CancellationToken ct) =>
|
||||
Definitions.SingleOrDefaultAsync(d => d.Service.Name == serviceName && d.Key == key, ct);
|
||||
|
||||
private async Task<EmailTemplateDefinitionEntity> RequireDefinitionAsync(string serviceName, string key, CancellationToken ct) =>
|
||||
await FindDefinitionAsync(serviceName, key, ct)
|
||||
?? throw new EmailTemplateWriteException("The template was removed. Reload the template list.");
|
||||
|
||||
private async Task<EmailTemplateDefinitionEntity> CreateDefinitionAsync(string serviceName, string key,
|
||||
IReadOnlyList<EmailTemplateVariable> variables, CancellationToken ct)
|
||||
{
|
||||
var service = await db.Services.Include(s => s.Languages).SingleOrDefaultAsync(s => s.Name == serviceName, ct)
|
||||
?? throw new EmailTemplateWriteException("Service does not exist. Create the service and its language codes first.", false);
|
||||
var entity = new EmailTemplateDefinitionEntity
|
||||
{
|
||||
Template = await GetOrCreateTemplateAsync(service, key, ct),
|
||||
Service = service, Key = key, Variables = MapVariables(variables), Created = DateTimeOffset.UtcNow
|
||||
};
|
||||
db.TemplateDefinitions.Add(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private async Task<TemplateEntity> GetOrCreateTemplateAsync(ServiceEntity service, string key, CancellationToken ct)
|
||||
{
|
||||
var template = await db.TemplateCatalog.SingleOrDefaultAsync(t => t.ServiceId == service.Id && t.Key == key, ct);
|
||||
if (template is not null)
|
||||
return template;
|
||||
template = new TemplateEntity { Service = service, ServiceId = service.Id, Key = key, Created = DateTimeOffset.UtcNow };
|
||||
db.TemplateCatalog.Add(template);
|
||||
return template;
|
||||
}
|
||||
|
||||
private async Task RemoveEmptyTemplateAsync(Guid serviceId, string key, CancellationToken ct)
|
||||
{
|
||||
if (await db.PushTemplateDefinitions.AnyAsync(t => t.ServiceId == serviceId && t.Key == key, ct))
|
||||
return;
|
||||
var template = await db.TemplateCatalog.SingleAsync(t => t.ServiceId == serviceId && t.Key == key, ct);
|
||||
db.TemplateCatalog.Remove(template);
|
||||
}
|
||||
|
||||
private static void ValidateLegacy(EmailTemplate template)
|
||||
{
|
||||
EmailTemplateValidation.ValidateIdentity(template.ServiceName, template.Key);
|
||||
EmailTemplateValidation.ValidateLanguage(template);
|
||||
EmailTemplateValidation.ValidateVariables(template.Variables);
|
||||
}
|
||||
|
||||
private static void EnsureMatchingContract(EmailTemplateDefinitionEntity definition, IReadOnlyList<EmailTemplateVariable> variables)
|
||||
{
|
||||
var shared = definition.Variables.Select(v => new EmailTemplateVariable { Name = v.Name, Required = v.Required }).ToList();
|
||||
if (!EmailTemplateValidation.ContractsEqual(shared, variables))
|
||||
throw new EmailTemplateWriteException("Variables conflict with the shared template contract. Edit shared variables in the template editor.");
|
||||
}
|
||||
|
||||
private static void Touch(EmailTemplateDefinitionEntity definition)
|
||||
{
|
||||
definition.Revision = Guid.NewGuid();
|
||||
definition.Updated = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
private static List<EmailTemplateVariableData> MapVariables(IReadOnlyList<EmailTemplateVariable> variables) =>
|
||||
variables.Select(v => new EmailTemplateVariableData { Name = v.Name, Required = v.Required }).ToList();
|
||||
|
||||
private static EmailTemplateEntity NewLanguage(EmailTemplate model, EmailTemplateDefinitionEntity definition) => new()
|
||||
{
|
||||
Id = model.Id, Definition = definition, ServiceId = definition.Service.Id,
|
||||
ServiceLanguage = definition.Service.Languages.SingleOrDefault(l => l.Code == model.LanguageCode)
|
||||
?? throw new EmailTemplateWriteException("Language is not in this service's catalog. Add it in the service editor first.", false),
|
||||
Subject = model.Subject, HtmlBody = model.HtmlBody, TextBody = model.TextBody, Created = model.Created
|
||||
};
|
||||
|
||||
private static void SetContent(EmailTemplateEntity entity, EmailTemplate model)
|
||||
{
|
||||
entity.Subject = model.Subject;
|
||||
entity.HtmlBody = model.HtmlBody;
|
||||
entity.TextBody = model.TextBody;
|
||||
entity.Updated = DateTimeOffset.UtcNow;
|
||||
Update(entity);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(EmailTemplate EmailTemplate, CancellationToken ct = default)
|
||||
private static EmailTemplate MapLanguage(EmailTemplateEntity entity) => new()
|
||||
{
|
||||
EmailTemplateEntity? entity = await DbSet.FindAsync([EmailTemplate.Id], ct);
|
||||
if (entity is not null)
|
||||
Delete(entity);
|
||||
}
|
||||
|
||||
private static EmailTemplate MapToDomain(EmailTemplateEntity e) => new()
|
||||
{
|
||||
Id = e.Id,
|
||||
ServiceName = e.ServiceName,
|
||||
Key = e.Key,
|
||||
LanguageCode = e.LanguageCode,
|
||||
Subject = e.Subject,
|
||||
HtmlBody = e.HtmlBody,
|
||||
TextBody = e.TextBody,
|
||||
Variables = e.Variables.Select(v => new EmailTemplateVariable { Name = v.Name, Required = v.Required }).ToList(),
|
||||
Created = e.Created,
|
||||
Updated = e.Updated
|
||||
Id = entity.Id, ServiceName = entity.Definition.Service.Name, Key = entity.Definition.Key,
|
||||
LanguageCode = entity.ServiceLanguage.Code, Subject = entity.Subject, HtmlBody = entity.HtmlBody, TextBody = entity.TextBody,
|
||||
Variables = entity.Definition.Variables.Select(v => new EmailTemplateVariable { Name = v.Name, Required = v.Required }).ToList(),
|
||||
Created = entity.Created, Updated = entity.Updated
|
||||
};
|
||||
|
||||
private static EmailTemplateEntity MapToEntity(EmailTemplate t) => new()
|
||||
private static EmailTemplateDefinition MapDefinition(EmailTemplateDefinitionEntity entity) => new()
|
||||
{
|
||||
Id = t.Id,
|
||||
ServiceName = t.ServiceName,
|
||||
Key = t.Key,
|
||||
LanguageCode = t.LanguageCode,
|
||||
Subject = t.Subject,
|
||||
HtmlBody = t.HtmlBody,
|
||||
TextBody = t.TextBody,
|
||||
Variables = t.Variables.Select(v => new EmailTemplateVariableData { Name = v.Name, Required = v.Required }).ToList(),
|
||||
Created = t.Created,
|
||||
Updated = t.Updated
|
||||
Id = entity.Id, ServiceId = entity.ServiceId, ServiceName = entity.Service.Name, Key = entity.Key, Revision = entity.Revision,
|
||||
Variables = entity.Variables.Select(v => new EmailTemplateVariable { Name = v.Name, Required = v.Required }).ToList(),
|
||||
Languages = entity.Languages.OrderBy(t => t.ServiceLanguage.Code).Select(MapLanguage).ToList(),
|
||||
Created = entity.Created, Updated = entity.Updated
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||
|
||||
internal sealed class NotificationServiceRepository(NotificationDbContext db, TemplateMutationRunner mutations) : INotificationServiceRepository
|
||||
{
|
||||
public async Task<IReadOnlyList<NotificationServiceInfo>> GetAllAsync(CancellationToken ct = default)
|
||||
{
|
||||
var services = await db.Services.AsNoTracking().Include(s => s.Languages).OrderBy(s => s.Name).ToListAsync(ct);
|
||||
var counts = await VersionCountsAsync(ct);
|
||||
return services.Select(s => Map(s, counts)).ToList();
|
||||
}
|
||||
|
||||
public async Task<NotificationServiceInfo?> GetAsync(Guid id, CancellationToken ct = default)
|
||||
{
|
||||
var service = await db.Services.AsNoTracking().Include(s => s.Languages).SingleOrDefaultAsync(s => s.Id == id, ct);
|
||||
return service is null ? null : Map(service, await VersionCountsAsync(ct));
|
||||
}
|
||||
|
||||
public async Task<NotificationServiceInfo?> GetByNameAsync(string name, CancellationToken ct = default)
|
||||
{
|
||||
var service = await db.Services.AsNoTracking().Include(s => s.Languages).SingleOrDefaultAsync(s => s.Name == name, ct);
|
||||
return service is null ? null : Map(service, await VersionCountsAsync(ct));
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(Guid id, Guid revision, CancellationToken ct = default)
|
||||
{
|
||||
var removed = false;
|
||||
await mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
if (revision == Guid.Empty)
|
||||
throw new EmailTemplateWriteException("A nonempty service revision is required.", false);
|
||||
var service = await db.Services.Include(s => s.Languages).SingleOrDefaultAsync(s => s.Id == id, ct);
|
||||
if (service is null)
|
||||
return;
|
||||
if (service.Revision != revision)
|
||||
throw new EmailTemplateWriteException("The service revision changed. Read it again before deleting.");
|
||||
await EnsureServiceIsEmptyAsync(id, ct);
|
||||
db.ServiceLanguages.RemoveRange(service.Languages);
|
||||
db.Services.Remove(service);
|
||||
removed = true;
|
||||
}, ct);
|
||||
return removed;
|
||||
}
|
||||
|
||||
private async Task EnsureServiceIsEmptyAsync(Guid id, CancellationToken ct)
|
||||
{
|
||||
if (await db.TemplateCatalog.AnyAsync(d => d.ServiceId == id, ct))
|
||||
throw new EmailTemplateWriteException("Remove every template definition before deleting this service, including definitions without translations.");
|
||||
if (await db.Providers.AnyAsync(c => c.ServiceId == id, ct) || await db.PushChannels.AnyAsync(c => c.ServiceId == id, ct))
|
||||
throw new EmailTemplateWriteException("Reassign or remove every notification channel before deleting this service.");
|
||||
}
|
||||
|
||||
public Task SaveAsync(NotificationServiceInfo model, bool isNew, CancellationToken ct = default) => mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
Validate(model);
|
||||
var service = await LoadForSaveAsync(model, isNew, ct);
|
||||
await ValidateLanguageChangesAsync(service, model, ct);
|
||||
await StageLanguageCodeChangesAsync(service, model.Languages, ct);
|
||||
service.Name = model.Name;
|
||||
SynchronizeLanguages(service, model.Languages);
|
||||
Touch(service);
|
||||
await TouchDefinitionsAsync(service.Id, ct);
|
||||
model.Id = service.Id;
|
||||
model.Revision = service.Revision;
|
||||
}, ct);
|
||||
|
||||
public Task RemoveLanguageAsync(Guid serviceId, Guid languageId, int expectedVersionCount, Guid expectedRevision, CancellationToken ct = default) =>
|
||||
mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
var service = await db.Services.Include(s => s.Languages).SingleOrDefaultAsync(s => s.Id == serviceId, ct)
|
||||
?? throw new EmailTemplateWriteException("Service no longer exists. Reload services.");
|
||||
var language = service.Languages.SingleOrDefault(l => l.Id == languageId)
|
||||
?? throw new EmailTemplateWriteException("Language no longer exists. Reload the service.");
|
||||
var versions = await db.Templates.Where(t => t.ServiceLanguageId == languageId).ToListAsync(ct);
|
||||
var pushVersions = await db.PushTemplates.Where(t => t.ServiceLanguageId == languageId).ToListAsync(ct);
|
||||
if (service.Revision != expectedRevision || versions.Count + pushVersions.Count != expectedVersionCount)
|
||||
throw new EmailTemplateWriteException("The service or affected version count changed. Review the current count and confirm again.");
|
||||
db.Templates.RemoveRange(versions);
|
||||
db.PushTemplates.RemoveRange(pushVersions);
|
||||
// Save dependent removals first because language deletion is restricted by its FK.
|
||||
await db.SaveChangesAsync(ct);
|
||||
db.ServiceLanguages.Remove(language);
|
||||
Touch(service);
|
||||
await TouchDefinitionsAsync(serviceId, ct);
|
||||
}, ct);
|
||||
|
||||
private async Task<ServiceEntity> LoadForSaveAsync(NotificationServiceInfo model, bool isNew, CancellationToken ct)
|
||||
{
|
||||
if (await db.Services.AnyAsync(s => s.Name == model.Name && s.Id != model.Id, ct))
|
||||
throw new EmailTemplateWriteException("A service with this name already exists.");
|
||||
if (isNew)
|
||||
{
|
||||
var created = new ServiceEntity { Name = model.Name, Created = DateTimeOffset.UtcNow };
|
||||
db.Services.Add(created);
|
||||
return created;
|
||||
}
|
||||
var service = await db.Services.Include(s => s.Languages).SingleOrDefaultAsync(s => s.Id == model.Id, ct);
|
||||
if (service is null || service.Revision != model.Revision)
|
||||
throw new EmailTemplateWriteException("This service changed after you opened it. Reload before saving.");
|
||||
return service;
|
||||
}
|
||||
|
||||
private async Task ValidateLanguageChangesAsync(ServiceEntity service, NotificationServiceInfo model, CancellationToken ct)
|
||||
{
|
||||
var ids = service.Languages.Select(l => l.Id).ToHashSet();
|
||||
if (model.Languages.Any(l => l.Id != Guid.Empty && !ids.Contains(l.Id)))
|
||||
throw new EmailTemplateWriteException("A language changed or was removed. Reload the service.");
|
||||
ValidateChangedCodes(service, model.Languages);
|
||||
var retained = model.Languages.Select(l => l.Id).ToHashSet();
|
||||
var removed = service.Languages.Where(l => !retained.Contains(l.Id)).ToList();
|
||||
foreach (var language in removed)
|
||||
{
|
||||
var count = await db.Templates.CountAsync(t => t.ServiceLanguageId == language.Id, ct)
|
||||
+ await db.PushTemplates.CountAsync(t => t.ServiceLanguageId == language.Id, ct);
|
||||
if (count > 0)
|
||||
throw new EmailTemplateWriteException($"Cannot remove language '{language.Code}': {count} version(s) use it. Use the separate delete-with-versions confirmation.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StageLanguageCodeChangesAsync(ServiceEntity service, IReadOnlyList<ServiceLanguageInfo> languages, CancellationToken ct)
|
||||
{
|
||||
var requested = languages.Where(l => l.Id != Guid.Empty).ToDictionary(l => l.Id, l => l.Code);
|
||||
var removed = service.Languages.Where(l => !requested.ContainsKey(l.Id)).ToList();
|
||||
var changed = service.Languages.Where(l => requested.TryGetValue(l.Id, out var code) && code != l.Code).ToList();
|
||||
if (removed.Count == 0 && changed.Count == 0)
|
||||
return;
|
||||
foreach (var language in removed)
|
||||
{
|
||||
db.ServiceLanguages.Remove(language);
|
||||
service.Languages.Remove(language);
|
||||
}
|
||||
var reserved = service.Languages.Select(l => l.Code).Concat(languages.Select(l => l.Code)).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var language in changed)
|
||||
language.Code = TemporaryCode(reserved);
|
||||
// Free old codes before final assignments, supporting swaps and replacing unused rows.
|
||||
// These temporary identifiers remain invisible outside this transaction.
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
private static string TemporaryCode(HashSet<string> reserved)
|
||||
{
|
||||
string code;
|
||||
do { code = "~" + Guid.NewGuid().ToString("N")[..9]; }
|
||||
while (!reserved.Add(code));
|
||||
return code;
|
||||
}
|
||||
|
||||
private void SynchronizeLanguages(ServiceEntity service, IReadOnlyList<ServiceLanguageInfo> languages)
|
||||
{
|
||||
var retained = languages.Select(l => l.Id).ToHashSet();
|
||||
db.ServiceLanguages.RemoveRange(service.Languages.Where(l => !retained.Contains(l.Id)));
|
||||
foreach (var model in languages)
|
||||
{
|
||||
var entity = service.Languages.SingleOrDefault(l => l.Id == model.Id);
|
||||
if (entity is null)
|
||||
db.ServiceLanguages.Add(new ServiceLanguageEntity { Service = service, Code = model.Code, Created = DateTimeOffset.UtcNow });
|
||||
else
|
||||
entity.Code = model.Code;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TouchDefinitionsAsync(Guid serviceId, CancellationToken ct)
|
||||
{
|
||||
var definitions = await db.TemplateDefinitions.Where(d => d.ServiceId == serviceId).ToListAsync(ct);
|
||||
foreach (var definition in definitions)
|
||||
{
|
||||
definition.Revision = Guid.NewGuid();
|
||||
definition.Updated = DateTimeOffset.UtcNow;
|
||||
}
|
||||
var pushDefinitions = await db.PushTemplateDefinitions.Where(d => d.ServiceId == serviceId).ToListAsync(ct);
|
||||
foreach (var definition in pushDefinitions)
|
||||
{
|
||||
definition.Revision = Guid.NewGuid();
|
||||
definition.Updated = DateTimeOffset.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
private Task<Dictionary<Guid, int>> VersionCountsAsync(CancellationToken ct) => db.Templates.AsNoTracking()
|
||||
.Select(t => t.ServiceLanguageId).Concat(db.PushTemplates.Select(t => t.ServiceLanguageId))
|
||||
.GroupBy(id => id).Select(g => new { Id = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(g => g.Id, g => g.Count, ct);
|
||||
|
||||
private static void Validate(NotificationServiceInfo service)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(service.Name) || service.Name.Length > 100)
|
||||
throw new EmailTemplateWriteException("Service name is required and must be at most 100 characters.", false);
|
||||
foreach (var language in service.Languages)
|
||||
ValidateCode(language.Code);
|
||||
if (service.Languages.Select(l => l.Code).Distinct(StringComparer.Ordinal).Count() != service.Languages.Count)
|
||||
throw new EmailTemplateWriteException("Language codes must be unique within the service.", false);
|
||||
var ids = service.Languages.Where(l => l.Id != Guid.Empty).Select(l => l.Id).ToList();
|
||||
if (ids.Distinct().Count() != ids.Count)
|
||||
throw new EmailTemplateWriteException("Each service language can appear only once.", false);
|
||||
}
|
||||
|
||||
private static void ValidateCode(string code)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(code) || code.Length > 10)
|
||||
throw new EmailTemplateWriteException("Language codes are required and must be at most 10 characters.", false);
|
||||
}
|
||||
|
||||
private static void ValidateChangedCodes(ServiceEntity service, IReadOnlyList<ServiceLanguageInfo> languages)
|
||||
{
|
||||
var persisted = service.Languages.ToDictionary(l => l.Id, l => l.Code);
|
||||
foreach (var language in languages)
|
||||
{
|
||||
if (persisted.TryGetValue(language.Id, out var original) && original == language.Code)
|
||||
continue;
|
||||
if (!System.Text.RegularExpressions.Regex.IsMatch(language.Code, "^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$"))
|
||||
throw new EmailTemplateWriteException("Use letters, numbers and hyphens in new or renamed language codes, without spaces. Codes are case-sensitive.", false);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Touch(ServiceEntity service)
|
||||
{
|
||||
service.Revision = Guid.NewGuid();
|
||||
service.Updated = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
private static NotificationServiceInfo Map(ServiceEntity service, IReadOnlyDictionary<Guid, int> counts) => new()
|
||||
{
|
||||
Id = service.Id, Name = service.Name, Revision = service.Revision,
|
||||
Languages = service.Languages.OrderBy(l => l.Code).Select(l => new ServiceLanguageInfo
|
||||
{
|
||||
Id = l.Id, Code = l.Code, VersionCount = counts.GetValueOrDefault(l.Id)
|
||||
}).ToList()
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.PushChannels;
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||
|
||||
internal sealed class PushChannelRepository(NotificationDbContext db, TemplateMutationRunner mutations) : IPushChannelRepository
|
||||
{
|
||||
public async Task<IReadOnlyList<PushChannel>> GetAllAsync(CancellationToken ct = default) =>
|
||||
await ReadModels().OrderBy(c => c.ServiceName).ToListAsync(ct);
|
||||
|
||||
public Task<PushChannel?> GetByIdAsync(Guid id, CancellationToken ct = default) =>
|
||||
ReadModels().SingleOrDefaultAsync(c => c.Id == id, ct);
|
||||
|
||||
public Task<PushChannel?> GetActiveForServiceAsync(Guid serviceId, CancellationToken ct = default) =>
|
||||
ReadModels().SingleOrDefaultAsync(c => c.ServiceId == serviceId && c.IsActive, ct);
|
||||
|
||||
public Task<string?> GetCredentialsAsync(Guid id, CancellationToken ct = default) =>
|
||||
db.PushChannels.AsNoTracking().Where(c => c.Id == id).Select(c => c.CredentialsJson).SingleOrDefaultAsync(ct);
|
||||
|
||||
public Task SaveAsync(PushChannel channel, string credentialsJson, bool isNew, CancellationToken ct = default) =>
|
||||
mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
await ValidateServiceAsync(channel, ct);
|
||||
var entity = await LoadForSaveAsync(channel.Id, isNew, ct);
|
||||
entity.ServiceId = channel.ServiceId;
|
||||
entity.FirebaseProjectId = channel.FirebaseProjectId;
|
||||
entity.CredentialsJson = credentialsJson;
|
||||
entity.IsActive = channel.IsActive;
|
||||
entity.Updated = isNew ? null : DateTimeOffset.UtcNow;
|
||||
channel.Id = entity.Id;
|
||||
}, ct);
|
||||
|
||||
private async Task ValidateServiceAsync(PushChannel channel, CancellationToken ct)
|
||||
{
|
||||
if (!await db.Services.AnyAsync(s => s.Id == channel.ServiceId, ct))
|
||||
throw new PushChannelWriteException("Select an existing service.", false);
|
||||
if (await db.PushChannels.AnyAsync(c => c.ServiceId == channel.ServiceId && c.Id != channel.Id, ct))
|
||||
throw new PushChannelWriteException("This service already has a push channel. Edit that channel instead.");
|
||||
}
|
||||
|
||||
private async Task<PushChannelEntity> LoadForSaveAsync(Guid id, bool isNew, CancellationToken ct)
|
||||
{
|
||||
if (!isNew)
|
||||
return await db.PushChannels.SingleOrDefaultAsync(c => c.Id == id, ct)
|
||||
?? throw new PushChannelWriteException("The push channel no longer exists. Reload the list.");
|
||||
var entity = new PushChannelEntity
|
||||
{
|
||||
Id = id, FirebaseProjectId = string.Empty, CredentialsJson = "{}", Created = DateTimeOffset.UtcNow
|
||||
};
|
||||
db.PushChannels.Add(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private IQueryable<PushChannel> ReadModels() => db.PushChannels.AsNoTracking().Select(c => new PushChannel
|
||||
{
|
||||
Id = c.Id, ServiceId = c.ServiceId, ServiceName = c.Service.Name,
|
||||
FirebaseProjectId = c.FirebaseProjectId, IsActive = c.IsActive, Created = c.Created, Updated = c.Updated
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||
|
||||
using HrynCo.NotificationService.DAL.Abstract.Push;
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
public sealed class PushDeliveryRepository(NotificationDbContext db) : IPushDeliveryRepository
|
||||
{
|
||||
public async Task<PushDeliveryOutcome> DeliverOnceAsync(Guid messageId, string serviceName,
|
||||
Func<CancellationToken, Task<PushDeliveryOutcome>> deliver, CancellationToken cancellationToken)
|
||||
{
|
||||
// Thirty days exceeds the maximum payload lifetime; old replays cannot send expired data.
|
||||
var cutoff = DateTimeOffset.UtcNow.AddDays(-30);
|
||||
await db.Set<PushDeliveryEntity>().Where(x => x.CompletedAt < cutoff).ExecuteDeleteAsync(cancellationToken);
|
||||
await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken);
|
||||
var identity = $"{serviceName}:{messageId:D}";
|
||||
await db.Database.ExecuteSqlInterpolatedAsync(
|
||||
$"SELECT pg_advisory_xact_lock(hashtextextended({identity}, 1074))", cancellationToken);
|
||||
var previous = await db.Set<PushDeliveryEntity>().AsNoTracking()
|
||||
.SingleOrDefaultAsync(x => x.MessageId == messageId && x.ServiceName == serviceName, cancellationToken);
|
||||
if (previous is not null)
|
||||
return new PushDeliveryOutcome(previous.Error, previous.InvalidRegistration);
|
||||
|
||||
// One bounded provider call while holding this message's lock prevents concurrent sends.
|
||||
// A crash after FCM accepts still requires client-side message-id deduplication.
|
||||
var outcome = await deliver(cancellationToken);
|
||||
db.Add(new PushDeliveryEntity
|
||||
{
|
||||
MessageId = messageId, ServiceName = serviceName, Error = outcome.Error,
|
||||
InvalidRegistration = outcome.InvalidRegistration, CompletedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
await transaction.CommitAsync(cancellationToken);
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||
|
||||
internal sealed class PushTemplateDefinitionRepository(NotificationDbContext db, TemplateMutationRunner mutations)
|
||||
: IPushTemplateDefinitionRepository
|
||||
{
|
||||
private IQueryable<PushTemplateDefinitionEntity> Definitions => db.PushTemplateDefinitions
|
||||
.Include(d => d.Languages).ThenInclude(l => l.ServiceLanguage);
|
||||
|
||||
public async Task<IReadOnlyList<PushTemplateDefinition>> GetDefinitionsAsync(Guid serviceId, CancellationToken ct = default) =>
|
||||
(await Definitions.AsNoTracking().Where(d => d.ServiceId == serviceId).OrderBy(d => d.Key).ToListAsync(ct)).Select(Map).ToList();
|
||||
|
||||
public async Task<PushTemplateDefinition?> GetAsync(Guid serviceId, string key, CancellationToken ct = default)
|
||||
{
|
||||
var entity = await Definitions.AsNoTracking().SingleOrDefaultAsync(d => d.ServiceId == serviceId && d.Key == key, ct);
|
||||
return entity is null ? null : Map(entity);
|
||||
}
|
||||
|
||||
public Task SaveAsync(PushTemplateDefinition definition, bool isNew, CancellationToken ct = default) =>
|
||||
mutations.ExecuteAsync(() => SaveCoreAsync(definition, isNew, ct), ct);
|
||||
|
||||
private async Task SaveCoreAsync(PushTemplateDefinition definition, bool isNew, CancellationToken ct)
|
||||
{
|
||||
PushTemplateValidation.Validate(definition);
|
||||
var service = await db.Services.Include(s => s.Languages).SingleOrDefaultAsync(s => s.Id == definition.ServiceId, ct)
|
||||
?? throw new EmailTemplateWriteException("Service no longer exists. Reload services.");
|
||||
if (definition.Languages.Any(l => !service.Languages.Any(s => s.Code == l.LanguageCode)))
|
||||
throw new EmailTemplateWriteException("Every language must exactly match this service's catalog.", false);
|
||||
var entity = await LoadForSaveAsync(definition, service, isNew, ct);
|
||||
entity.Variables = definition.Variables.Select(v => new PushTemplateVariableData { Name = v.Name, Required = v.Required }).ToList();
|
||||
SynchronizeLanguages(entity, service, definition.Languages);
|
||||
entity.Revision = Guid.NewGuid();
|
||||
entity.Updated = DateTimeOffset.UtcNow;
|
||||
definition.Id = entity.Id;
|
||||
definition.Revision = entity.Revision;
|
||||
}
|
||||
|
||||
public async Task<PushTemplateDefinition?> UpsertDefinitionAsync(PushTemplateDefinitionPatch patch, CancellationToken ct = default)
|
||||
{
|
||||
PushTemplateDefinition? saved = null;
|
||||
await mutations.ExecuteAsync(async () =>
|
||||
{
|
||||
var service = await db.Services.Include(s => s.Languages).SingleOrDefaultAsync(s => s.Id == patch.ServiceId, ct);
|
||||
if (service is null) return;
|
||||
ValidatePatch(patch, service);
|
||||
var current = await GetAsync(patch.ServiceId, patch.Key, ct);
|
||||
var supplied = patch.Translations.Select(t => t.LanguageCode).ToHashSet(StringComparer.Ordinal);
|
||||
var removed = patch.RemoveLanguageCodes.ToHashSet(StringComparer.Ordinal);
|
||||
saved = new PushTemplateDefinition
|
||||
{
|
||||
Id = current?.Id ?? Guid.Empty, ServiceId = patch.ServiceId, Key = patch.Key,
|
||||
Revision = patch.Revision ?? Guid.Empty, Variables = patch.Variables,
|
||||
Languages = (current?.Languages ?? []).Where(l => !supplied.Contains(l.LanguageCode) && !removed.Contains(l.LanguageCode))
|
||||
.Concat(patch.Translations).OrderBy(l => l.LanguageCode, StringComparer.Ordinal).ToList()
|
||||
};
|
||||
await SaveCoreAsync(saved, patch.Revision is null, ct);
|
||||
}, ct);
|
||||
return saved;
|
||||
}
|
||||
|
||||
private static void ValidatePatch(PushTemplateDefinitionPatch patch, ServiceEntity service)
|
||||
{
|
||||
PushTemplateValidation.Validate(new PushTemplateDefinition
|
||||
{
|
||||
ServiceId = patch.ServiceId, Key = patch.Key, Variables = patch.Variables, Languages = patch.Translations
|
||||
});
|
||||
if (patch.Revision == Guid.Empty)
|
||||
throw new EmailTemplateWriteException("Revision must be null for creation or a nonempty revision from the last read for update.", false);
|
||||
var removed = patch.RemoveLanguageCodes;
|
||||
if (removed.Any(string.IsNullOrWhiteSpace) || removed.Distinct(StringComparer.Ordinal).Count() != removed.Count)
|
||||
throw new EmailTemplateWriteException("removeLanguageCodes must contain unique nonblank language codes.", false);
|
||||
var supplied = patch.Translations.Select(t => t.LanguageCode).ToHashSet(StringComparer.Ordinal);
|
||||
if (removed.Any(supplied.Contains))
|
||||
throw new EmailTemplateWriteException("A language cannot be supplied and removed in the same request.", false);
|
||||
var supported = service.Languages.Select(l => l.Code).ToHashSet(StringComparer.Ordinal);
|
||||
if (supplied.Concat(removed).Any(code => !supported.Contains(code)))
|
||||
throw new EmailTemplateWriteException("Every supplied or removed language must exactly match a code in this service's catalog.", false);
|
||||
}
|
||||
|
||||
private async Task<PushTemplateDefinitionEntity> LoadForSaveAsync(PushTemplateDefinition model, ServiceEntity service, bool isNew, CancellationToken ct)
|
||||
{
|
||||
var entity = await Definitions.SingleOrDefaultAsync(d => d.ServiceId == service.Id && d.Key == model.Key, ct);
|
||||
if (!isNew)
|
||||
{
|
||||
if (entity is null || entity.Id != model.Id || entity.Revision != model.Revision)
|
||||
throw new EmailTemplateWriteException("This push template changed after you opened it. Reload before saving; your entered values are retained.");
|
||||
return entity;
|
||||
}
|
||||
if (entity is not null)
|
||||
throw new EmailTemplateWriteException("A push template with this key already exists.");
|
||||
var template = await db.TemplateCatalog.SingleOrDefaultAsync(t => t.ServiceId == service.Id && t.Key == model.Key, ct)
|
||||
?? new TemplateEntity { Service = service, ServiceId = service.Id, Key = model.Key, Created = DateTimeOffset.UtcNow };
|
||||
entity = new PushTemplateDefinitionEntity { Template = template, ServiceId = service.Id, Key = model.Key, Created = DateTimeOffset.UtcNow };
|
||||
db.PushTemplateDefinitions.Add(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private void SynchronizeLanguages(PushTemplateDefinitionEntity definition, ServiceEntity service, IReadOnlyList<PushTemplateTranslation> translations)
|
||||
{
|
||||
var codes = translations.Select(l => l.LanguageCode).ToHashSet(StringComparer.Ordinal);
|
||||
db.PushTemplates.RemoveRange(definition.Languages.Where(l => !codes.Contains(l.ServiceLanguage.Code)));
|
||||
foreach (var translation in translations)
|
||||
{
|
||||
var entity = definition.Languages.SingleOrDefault(l => l.ServiceLanguage.Code == translation.LanguageCode);
|
||||
if (entity is null)
|
||||
{
|
||||
entity = new PushTemplateEntity
|
||||
{
|
||||
Definition = definition, ServiceId = service.Id,
|
||||
ServiceLanguage = service.Languages.Single(l => l.Code == translation.LanguageCode),
|
||||
Title = translation.Title, Body = translation.Body, Created = DateTimeOffset.UtcNow
|
||||
};
|
||||
definition.Languages.Add(entity);
|
||||
db.PushTemplates.Add(entity);
|
||||
}
|
||||
entity.Title = translation.Title;
|
||||
entity.Body = translation.Body;
|
||||
entity.ActionsJson = translation.ActionsJson;
|
||||
entity.Updated = DateTimeOffset.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(Guid serviceId, string key, Guid revision, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key) || key.Length > 100 || revision == Guid.Empty)
|
||||
throw new EmailTemplateWriteException("An exact key (at most 100 characters) and a nonempty revision are required.", false);
|
||||
var removed = false;
|
||||
await mutations.ExecuteAsync(async () => removed = await DeleteCoreAsync(serviceId, key, revision, ct), ct);
|
||||
return removed;
|
||||
}
|
||||
|
||||
private async Task<bool> DeleteCoreAsync(Guid serviceId, string key, Guid revision, CancellationToken ct)
|
||||
{
|
||||
var entity = await Definitions.SingleOrDefaultAsync(d => d.ServiceId == serviceId && d.Key == key, ct);
|
||||
if (entity is null) return false;
|
||||
if (entity.Revision != revision)
|
||||
throw new EmailTemplateWriteException("The push template revision changed. Reload before deleting.");
|
||||
db.PushTemplateDefinitions.Remove(entity);
|
||||
if (!await db.TemplateDefinitions.AnyAsync(d => d.ServiceId == serviceId && d.Key == key, ct))
|
||||
db.TemplateCatalog.Remove(await db.TemplateCatalog.SingleAsync(t => t.ServiceId == serviceId && t.Key == key, ct));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static PushTemplateDefinition Map(PushTemplateDefinitionEntity entity) => new()
|
||||
{
|
||||
Id = entity.Id, ServiceId = entity.ServiceId, Key = entity.Key, Revision = entity.Revision,
|
||||
Variables = entity.Variables.Select(v => new EmailTemplateVariable { Name = v.Name, Required = v.Required }).ToList(),
|
||||
Languages = entity.Languages.OrderBy(l => l.ServiceLanguage.Code).Select(l => new PushTemplateTranslation
|
||||
{
|
||||
LanguageCode = l.ServiceLanguage.Code, Title = l.Title, Body = l.Body, ActionsJson = l.ActionsJson
|
||||
}).ToList()
|
||||
};
|
||||
}
|
||||
@@ -16,10 +16,16 @@ public static class ServiceCollectionExtensions
|
||||
services.AddDbContext<NotificationDbContext>(options =>
|
||||
options.UseNpgsql(connectionString));
|
||||
|
||||
services.AddScoped<IUnitOfWork, UnitOfWork>();
|
||||
services.AddScoped<TemplateMutationRunner>();
|
||||
services.AddScoped<HrynCo.NotificationService.DAL.Abstract.PushChannels.IPushChannelRepository, PushChannelRepository>();
|
||||
services.AddScoped<HrynCo.NotificationService.DAL.Abstract.Push.IPushDeliveryRepository, PushDeliveryRepository>();
|
||||
services.AddScoped<INotificationServiceRepository, NotificationServiceRepository>();
|
||||
services.AddScoped<IPushTemplateDefinitionRepository, PushTemplateDefinitionRepository>();
|
||||
services.AddScoped<IEmailTemplateRepository, EmailTemplateRepository>();
|
||||
services.AddScoped<IEmailTemplateDefinitionRepository, EmailTemplateRepository>();
|
||||
services.AddScoped<IEmailChannelRepository, EmailChannelRepository>();
|
||||
services.AddScoped<IEmailChannelUsageRepository, EmailChannelUsageRepository>();
|
||||
services.AddScoped<IUnitOfWork, NotificationUnitOfWork>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace HrynCo.NotificationService.DAL.EF;
|
||||
|
||||
internal sealed class TemplateMutationRunner(NotificationDbContext db)
|
||||
{
|
||||
public async Task ExecuteAsync(Func<Task> write, CancellationToken ct)
|
||||
{
|
||||
await using var transaction = db.Database.CurrentTransaction is null
|
||||
? await db.Database.BeginTransactionAsync(ct) : null;
|
||||
// Service/language administration and template writes share the same transaction lock.
|
||||
// Counts, catalog membership and revision checks are therefore valid until commit.
|
||||
await db.Database.ExecuteSqlRawAsync("SELECT pg_advisory_xact_lock(1601)", ct);
|
||||
await write();
|
||||
await db.SaveChangesAsync(ct);
|
||||
if (transaction is not null)
|
||||
await transaction.CommitAsync(ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
setlocal DisableDelayedExpansion
|
||||
set "NOTIFICATION_EF_DIR=%~dp0"
|
||||
powershell.exe -NoProfile -Command "$ErrorActionPreference = 'Stop'; Set-Location -LiteralPath $env:NOTIFICATION_EF_DIR; $config = Get-Content -LiteralPath '..\HrynCo.NotificationService.Web\appsettings.Development.json' -Raw | ConvertFrom-Json; $connection = New-Object System.Data.Common.DbConnectionStringBuilder; $connection.set_ConnectionString($config.App.ConnectionString); if ([string]$connection.get_Item('Host') -notin @('localhost', '127.0.0.1', '::1') -or [string]::IsNullOrWhiteSpace([string]$connection.get_Item('Database'))) { throw 'Refusing update: Development configuration must specify a loopback host and a database name.' }; $env:App__ConnectionString = $connection.get_ConnectionString(); dotnet ef database update --project 'HrynCo.NotificationService.DAL.EF.csproj' --configuration Release; exit $LASTEXITCODE"
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,133 @@
|
||||
namespace HrynCo.NotificationService.Migrator;
|
||||
|
||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
internal sealed class DevelopmentDataSeeder
|
||||
{
|
||||
internal const string DefaultServiceName = "TestService";
|
||||
internal const string DefaultLanguageCode = "en";
|
||||
|
||||
private readonly IEmailChannelRepository _channels;
|
||||
private readonly IEmailTemplateRepository _templates;
|
||||
private readonly INotificationServiceRepository _services;
|
||||
private readonly ILogger<DevelopmentDataSeeder> _logger;
|
||||
|
||||
public DevelopmentDataSeeder(
|
||||
IEmailChannelRepository channels,
|
||||
IEmailTemplateRepository templates,
|
||||
INotificationServiceRepository services,
|
||||
ILogger<DevelopmentDataSeeder> logger)
|
||||
{
|
||||
_channels = channels;
|
||||
_templates = templates;
|
||||
_services = services;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task SeedAsync(string serviceName, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(serviceName))
|
||||
throw new InvalidOperationException("Development seed service name is not configured.");
|
||||
|
||||
var serviceId = await SeedServiceAsync(serviceName, cancellationToken);
|
||||
await SeedMailpitChannelAsync(serviceId, serviceName, cancellationToken);
|
||||
|
||||
foreach (EmailTemplate template in CreateTemplates(serviceName))
|
||||
{
|
||||
EmailTemplate? existing = await _templates.GetAsync(
|
||||
template.ServiceName, template.Key, template.LanguageCode, cancellationToken);
|
||||
|
||||
if (existing is not null)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Development email template already exists; leaving it unchanged [ServiceName={ServiceName}, Key={TemplateKey}, LanguageCode={LanguageCode}]",
|
||||
template.ServiceName, template.Key, template.LanguageCode);
|
||||
continue;
|
||||
}
|
||||
|
||||
await _templates.AddAsync(template, cancellationToken);
|
||||
_logger.LogInformation(
|
||||
"Created development email template [ServiceName={ServiceName}, Key={TemplateKey}, LanguageCode={LanguageCode}]",
|
||||
template.ServiceName, template.Key, template.LanguageCode);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Guid> SeedServiceAsync(string serviceName, CancellationToken ct)
|
||||
{
|
||||
var services = await _services.GetAllAsync(ct);
|
||||
var service = services.SingleOrDefault(s => s.Name == serviceName);
|
||||
if (service?.Languages.Any(l => l.Code == DefaultLanguageCode) == true)
|
||||
return service.Id;
|
||||
var isNew = service is null;
|
||||
service ??= new NotificationServiceInfo { Name = serviceName };
|
||||
service.Languages = [..service.Languages, new ServiceLanguageInfo { Code = DefaultLanguageCode }];
|
||||
await _services.SaveAsync(service, isNew, ct);
|
||||
return service.Id;
|
||||
}
|
||||
|
||||
private async Task SeedMailpitChannelAsync(Guid serviceId, string serviceName, CancellationToken cancellationToken)
|
||||
{
|
||||
IReadOnlyList<EmailChannel> existingChannels = await _channels.GetByServiceAsync(
|
||||
serviceId, cancellationToken);
|
||||
|
||||
if (existingChannels.Count > 0)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Development email channel already exists; leaving all channels unchanged [ServiceName={ServiceName}]",
|
||||
serviceName);
|
||||
return;
|
||||
}
|
||||
|
||||
var channel = new EmailChannel
|
||||
{
|
||||
ServiceId = serviceId,
|
||||
Priority = 1,
|
||||
EmailChannelType = EmailChannelType.Smtp,
|
||||
Settings = new SmtpChannelSettings
|
||||
{
|
||||
Host = "mailpit",
|
||||
Port = 1025,
|
||||
Username = string.Empty,
|
||||
Password = string.Empty,
|
||||
UseSsl = false,
|
||||
FromEmail = "no-reply@local.hrynco.test",
|
||||
FromName = "HrynCo Development"
|
||||
},
|
||||
WarnThresholdPercent = 90,
|
||||
IsActive = true,
|
||||
Created = DateTimeOffset.UtcNow
|
||||
};
|
||||
|
||||
await _channels.AddAsync(channel, cancellationToken);
|
||||
_logger.LogInformation(
|
||||
"Created Mailpit development email channel [ServiceName={ServiceName}]",
|
||||
serviceName);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<EmailTemplate> CreateTemplates(string serviceName)
|
||||
{
|
||||
DateTimeOffset created = DateTimeOffset.UtcNow;
|
||||
|
||||
return
|
||||
[
|
||||
new EmailTemplate
|
||||
{
|
||||
ServiceName = serviceName,
|
||||
Key = "TestEmail",
|
||||
LanguageCode = DefaultLanguageCode,
|
||||
Subject = "Test notification",
|
||||
HtmlBody = "<p>Hello {{RecipientName}},</p><p>{{Message}}</p>",
|
||||
TextBody = "Hello {{RecipientName}}, {{Message}}",
|
||||
Variables =
|
||||
[
|
||||
new EmailTemplateVariable { Name = "RecipientName", Required = true },
|
||||
new EmailTemplateVariable { Name = "Message", Required = true }
|
||||
],
|
||||
Created = created
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using HrynCo.NotificationService.DAL.EF;
|
||||
using HrynCo.NotificationService.Migrator;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Serilog;
|
||||
@@ -21,8 +23,8 @@ try
|
||||
var connectionString = ctx.Configuration["App:ConnectionString"]
|
||||
?? throw new InvalidOperationException("App:ConnectionString is not configured.");
|
||||
|
||||
services.AddDbContext<NotificationDbContext>(options =>
|
||||
options.UseNpgsql(connectionString));
|
||||
services.AddNotificationDataAccess(connectionString);
|
||||
services.AddScoped<DevelopmentDataSeeder>();
|
||||
})
|
||||
.Build();
|
||||
|
||||
@@ -32,6 +34,18 @@ try
|
||||
Log.Information("Applying migrations...");
|
||||
await db.Database.MigrateAsync();
|
||||
Log.Information("Migrations applied successfully.");
|
||||
|
||||
var environment = scope.ServiceProvider.GetRequiredService<IHostEnvironment>();
|
||||
if (environment.IsDevelopment())
|
||||
{
|
||||
string serviceName = host.Services.GetRequiredService<IConfiguration>()["DevelopmentSeed:ServiceName"]
|
||||
?? DevelopmentDataSeeder.DefaultServiceName;
|
||||
|
||||
Log.Information("Seeding development email configuration...");
|
||||
var seeder = scope.ServiceProvider.GetRequiredService<DevelopmentDataSeeder>();
|
||||
await seeder.SeedAsync(serviceName);
|
||||
Log.Information("Development email configuration is ready.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("HrynCo.NotificationService.Services.Tests")]
|
||||
@@ -0,0 +1,91 @@
|
||||
namespace HrynCo.NotificationService.Services.Tests;
|
||||
|
||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.Migrator;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
|
||||
public sealed class DevelopmentDataSeederTests
|
||||
{
|
||||
private readonly IEmailChannelRepository _channels = Substitute.For<IEmailChannelRepository>();
|
||||
private readonly IEmailTemplateRepository _templates = Substitute.For<IEmailTemplateRepository>();
|
||||
private readonly INotificationServiceRepository _services = Substitute.For<INotificationServiceRepository>();
|
||||
|
||||
public DevelopmentDataSeederTests()
|
||||
{
|
||||
_services.SaveAsync(Arg.Any<NotificationServiceInfo>(), true, Arg.Any<CancellationToken>())
|
||||
.Returns(call => { call.Arg<NotificationServiceInfo>().Id = Guid.NewGuid(); return Task.CompletedTask; });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedAsync_WhenConfigurationIsMissing_CreatesMailpitChannelAndTestTemplate()
|
||||
{
|
||||
_channels.GetByServiceAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Array.Empty<EmailChannel>());
|
||||
_templates.GetAsync("TestService", "TestEmail", "en", Arg.Any<CancellationToken>())
|
||||
.Returns((EmailTemplate?)null);
|
||||
|
||||
DevelopmentDataSeeder seeder = CreateSeeder();
|
||||
|
||||
await seeder.SeedAsync("TestService", CancellationToken.None);
|
||||
|
||||
await _channels.Received(1).AddAsync(
|
||||
Arg.Is<EmailChannel>(channel => IsMailpitChannel(channel)),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _templates.Received(1).AddAsync(
|
||||
Arg.Is<EmailTemplate>(template =>
|
||||
template.ServiceName == "TestService" &&
|
||||
template.Key == "TestEmail" &&
|
||||
template.Variables.Any(variable => variable.Name == "Message" && variable.Required)),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SeedAsync_WhenConfigurationExists_DoesNotDuplicateOrOverwriteIt()
|
||||
{
|
||||
_channels.GetByServiceAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns([new EmailChannel
|
||||
{
|
||||
ServiceId = Guid.NewGuid(),
|
||||
EmailChannelType = EmailChannelType.Smtp,
|
||||
Settings = new SmtpChannelSettings()
|
||||
}]);
|
||||
_templates.GetAsync("TestService", "TestEmail", "en", Arg.Any<CancellationToken>())
|
||||
.Returns(new EmailTemplate
|
||||
{
|
||||
ServiceName = "TestService",
|
||||
Key = "TestEmail",
|
||||
LanguageCode = "en",
|
||||
Subject = "Existing",
|
||||
HtmlBody = "Existing",
|
||||
TextBody = "Existing"
|
||||
});
|
||||
|
||||
DevelopmentDataSeeder seeder = CreateSeeder();
|
||||
|
||||
await seeder.SeedAsync("TestService", CancellationToken.None);
|
||||
|
||||
await _channels.DidNotReceive().AddAsync(Arg.Any<EmailChannel>(), Arg.Any<CancellationToken>());
|
||||
await _templates.DidNotReceive().AddAsync(Arg.Any<EmailTemplate>(), Arg.Any<CancellationToken>());
|
||||
await _channels.DidNotReceive().UpdateAsync(Arg.Any<EmailChannel>(), Arg.Any<CancellationToken>());
|
||||
await _templates.DidNotReceive().UpdateAsync(Arg.Any<EmailTemplate>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
private DevelopmentDataSeeder CreateSeeder() => new(
|
||||
_channels,
|
||||
_templates,
|
||||
_services,
|
||||
NullLogger<DevelopmentDataSeeder>.Instance);
|
||||
|
||||
private static bool IsMailpitChannel(EmailChannel channel)
|
||||
{
|
||||
return channel.ServiceId != Guid.Empty &&
|
||||
channel.IsActive &&
|
||||
channel.Settings is SmtpChannelSettings smtp &&
|
||||
smtp.Host == "mailpit" &&
|
||||
smtp.Port == 1025 &&
|
||||
!smtp.UseSsl;
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||
|
||||
using HrynCo.NotificationService.Contracts.Messages;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||
|
||||
public sealed class EmailTemplateRenderingServiceTests
|
||||
{
|
||||
private readonly EmailTemplateRenderingService _service = new();
|
||||
|
||||
[Fact]
|
||||
public void Render_InterpolatesItemTrackerVariables()
|
||||
{
|
||||
EmailTemplate template = CreateTemplate();
|
||||
SendEmailMessageData data = CreateData(new Dictionary<string, string>
|
||||
{
|
||||
["AppName"] = "StoreMate",
|
||||
["VerificationUrl"] = "https://example.invalid/verify"
|
||||
});
|
||||
|
||||
RenderedEmail result = _service.Render(template, data);
|
||||
|
||||
Assert.Equal("Verify StoreMate", result.Subject);
|
||||
Assert.Equal("<a href=\"https://example.invalid/verify\">Verify</a>", result.HtmlBody);
|
||||
Assert.Equal("Verify at https://example.invalid/verify", result.TextBody);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_WhenRequiredVariableIsMissing_ThrowsObservableFailure()
|
||||
{
|
||||
EmailTemplate template = CreateTemplate();
|
||||
SendEmailMessageData data = CreateData(new Dictionary<string, string>
|
||||
{
|
||||
["AppName"] = "StoreMate"
|
||||
});
|
||||
|
||||
InvalidDataException exception = Assert.Throws<InvalidDataException>(
|
||||
() => _service.Render(template, data));
|
||||
|
||||
Assert.Equal("Required template variables are missing: VerificationUrl.", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_HtmlEncodesVariablesWithoutChangingSubjectOrTextBody()
|
||||
{
|
||||
EmailTemplate template = CreateTemplate();
|
||||
SendEmailMessageData data = CreateData(new Dictionary<string, string>
|
||||
{
|
||||
["AppName"] = "Invemory <script>alert('xss')</script>",
|
||||
["VerificationUrl"] = "https://example.invalid/verify?next=\" onclick=\"alert('xss')"
|
||||
});
|
||||
|
||||
RenderedEmail result = _service.Render(template, data);
|
||||
|
||||
Assert.Equal("Verify Invemory <script>alert('xss')</script>", result.Subject);
|
||||
Assert.Equal(
|
||||
"<a href=\"https://example.invalid/verify?next=" onclick="alert('xss')\">Verify</a>",
|
||||
result.HtmlBody);
|
||||
Assert.Equal(
|
||||
"Verify at https://example.invalid/verify?next=\" onclick=\"alert('xss')",
|
||||
result.TextBody);
|
||||
}
|
||||
|
||||
private static EmailTemplate CreateTemplate() => new()
|
||||
{
|
||||
ServiceName = "StoreMate-Prod",
|
||||
Key = "EmailVerification",
|
||||
LanguageCode = "uk",
|
||||
Subject = "Verify {{AppName}}",
|
||||
HtmlBody = "<a href=\"{{VerificationUrl}}\">Verify</a>",
|
||||
TextBody = "Verify at {{VerificationUrl}}",
|
||||
Variables =
|
||||
[
|
||||
new EmailTemplateVariable { Name = "AppName", Required = true },
|
||||
new EmailTemplateVariable { Name = "VerificationUrl", Required = true }
|
||||
]
|
||||
};
|
||||
|
||||
private static SendEmailMessageData CreateData(IReadOnlyDictionary<string, string> variables) => new()
|
||||
{
|
||||
ServiceName = "StoreMate-Prod",
|
||||
TemplateKey = "EmailVerification",
|
||||
RecipientEmail = "owner@example.com",
|
||||
RecipientName = "Owner",
|
||||
LanguageCode = "uk",
|
||||
Variables = variables
|
||||
};
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||
|
||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||
using NSubstitute;
|
||||
|
||||
public sealed class EmailTemplateServiceTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("RU")]
|
||||
[InlineData(" ru ")]
|
||||
[InlineData(" RU ")]
|
||||
public async Task GetAsync_WhenExactVersionIsMissing_RetriesLegacyTrimmedLowercaseCode(string requestedCode)
|
||||
{
|
||||
IEmailTemplateRepository repository = Substitute.For<IEmailTemplateRepository>();
|
||||
var expected = Template("ru");
|
||||
repository.GetAsync("TestService", "Welcome", "ru", Arg.Any<CancellationToken>()).Returns(expected);
|
||||
var service = new EmailTemplateService(repository);
|
||||
|
||||
Assert.Same(expected, await service.GetAsync("TestService", "Welcome", requestedCode, default));
|
||||
Assert.Equal(new[] { requestedCode, "ru" }, RequestedCodes(repository));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenBothExactAndLowercaseVersionsExist_PrefersExactVersion()
|
||||
{
|
||||
IEmailTemplateRepository repository = Substitute.For<IEmailTemplateRepository>();
|
||||
var expected = Template("RU");
|
||||
repository.GetAsync("TestService", "Welcome", "RU", Arg.Any<CancellationToken>()).Returns(expected);
|
||||
repository.GetAsync("TestService", "Welcome", "ru", Arg.Any<CancellationToken>()).Returns(Template("ru"));
|
||||
var service = new EmailTemplateService(repository);
|
||||
|
||||
Assert.Same(expected, await service.GetAsync("TestService", "Welcome", "RU", default));
|
||||
Assert.Equal(new[] { "RU" }, RequestedCodes(repository));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenExactRegionalVersionExists_DoesNotNormalizeIt()
|
||||
{
|
||||
IEmailTemplateRepository repository = Substitute.For<IEmailTemplateRepository>();
|
||||
var expected = Template("ru-RU");
|
||||
repository.GetAsync("TestService", "Welcome", "ru-RU", Arg.Any<CancellationToken>()).Returns(expected);
|
||||
var service = new EmailTemplateService(repository);
|
||||
|
||||
Assert.Same(expected, await service.GetAsync("TestService", "Welcome", "ru-RU", default));
|
||||
Assert.Equal(new[] { "ru-RU" }, RequestedCodes(repository));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenMissingCodeIsAlreadyCanonical_QueriesOnlyOnce()
|
||||
{
|
||||
IEmailTemplateRepository repository = Substitute.For<IEmailTemplateRepository>();
|
||||
var service = new EmailTemplateService(repository);
|
||||
|
||||
var error = await Assert.ThrowsAsync<InvalidOperationException>(() => service.GetAsync("TestService", "Welcome", "zz", default));
|
||||
|
||||
Assert.Contains("language='zz'", error.Message);
|
||||
Assert.Equal(new[] { "zz" }, RequestedCodes(repository));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_WhenRegionalLookupMisses_DoesNotScanOtherCaseOrRegionalVariants()
|
||||
{
|
||||
IEmailTemplateRepository repository = Substitute.For<IEmailTemplateRepository>();
|
||||
repository.GetAsync("TestService", "Welcome", "ru-RU", Arg.Any<CancellationToken>()).Returns(Template("ru-RU"));
|
||||
repository.GetAsync("TestService", "Welcome", "ru", Arg.Any<CancellationToken>()).Returns(Template("ru"));
|
||||
var service = new EmailTemplateService(repository);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.GetAsync("TestService", "Welcome", "RU-ru", default));
|
||||
|
||||
Assert.Equal(new[] { "RU-ru", "ru-ru" }, RequestedCodes(repository));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task GetAsync_WhenCodeIsBlank_RejectsBeforeRepositoryLookup(string? code)
|
||||
{
|
||||
IEmailTemplateRepository repository = Substitute.For<IEmailTemplateRepository>();
|
||||
var service = new EmailTemplateService(repository);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidDataException>(() => service.GetAsync("TestService", "Welcome", code, default));
|
||||
|
||||
Assert.Empty(repository.ReceivedCalls());
|
||||
}
|
||||
|
||||
private static EmailTemplate Template(string code) => new()
|
||||
{
|
||||
ServiceName = "TestService", Key = "Welcome", LanguageCode = code, Subject = "Subject " + code,
|
||||
HtmlBody = "<p>Hello</p>", TextBody = "Hello"
|
||||
};
|
||||
|
||||
private static string[] RequestedCodes(IEmailTemplateRepository repository) => repository.ReceivedCalls()
|
||||
.Select(call => (string)call.GetArguments()[2]!).ToArray();
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||
|
||||
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||
using System.Net.Mail;
|
||||
using System.Net.Sockets;
|
||||
|
||||
public sealed class NotificationDeliveryErrorFormatterTests
|
||||
{
|
||||
[Fact]
|
||||
public void Format_UsesInnermostMessageAndRemovesLineBreaks()
|
||||
{
|
||||
var exception = new InvalidOperationException(
|
||||
"outer",
|
||||
new Exception("provider failed\r\nretry rejected"));
|
||||
|
||||
string result = NotificationDeliveryErrorFormatter.Format(exception);
|
||||
|
||||
Assert.Equal(
|
||||
"Notification delivery failed after all retry attempts (provider failed retry rejected).",
|
||||
result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Format_UnresolvedSmtpHost_AddsSafeChannelContext()
|
||||
{
|
||||
var socketException = new SocketException((int)SocketError.HostNotFound);
|
||||
var exception = new SmtpException("Failure sending mail.", socketException);
|
||||
|
||||
string result = NotificationDeliveryErrorFormatter.Format(exception);
|
||||
|
||||
Assert.Equal(
|
||||
$"SMTP delivery failed after all retry attempts: the configured SMTP server host could not be resolved ({socketException.Message}).",
|
||||
result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Format_RefusedSmtpConnection_AddsSafeChannelContext()
|
||||
{
|
||||
var socketException = new SocketException((int)SocketError.ConnectionRefused);
|
||||
var exception = new SmtpException("Failure sending mail.", socketException);
|
||||
|
||||
string result = NotificationDeliveryErrorFormatter.Format(exception);
|
||||
|
||||
Assert.Equal(
|
||||
$"SMTP delivery failed after all retry attempts: the configured SMTP server refused the connection ({socketException.Message}).",
|
||||
result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Format_LongError_IsBoundedToOutboxColumnLength()
|
||||
{
|
||||
var exception = new Exception(new string('x', 2100));
|
||||
|
||||
string result = NotificationDeliveryErrorFormatter.Format(exception);
|
||||
|
||||
Assert.Equal(2000, result.Length);
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||
|
||||
using HrynCo.NotificationService.Contracts.Messages;
|
||||
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||
using Hrynco.RabbitMq;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using NSubstitute;
|
||||
|
||||
public sealed class NotificationResultPublisherTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task PublishAsync_TerminalFailure_PublishesNeutralFailureResultToReplyQueue()
|
||||
{
|
||||
IRabbitMqPublisher rabbitMqPublisher = Substitute.For<IRabbitMqPublisher>();
|
||||
var publisher = new NotificationResultPublisher(
|
||||
rabbitMqPublisher,
|
||||
NullLogger<NotificationResultPublisher>.Instance);
|
||||
SendEmailMessage message = CreateMessage();
|
||||
NotificationResultMessage? publishedResult = null;
|
||||
rabbitMqPublisher
|
||||
.When(x => x.PublishAsync(
|
||||
"item-tracker.notifications.result",
|
||||
Arg.Any<NotificationResultMessage>(),
|
||||
Arg.Any<CancellationToken>()))
|
||||
.Do(call => publishedResult = call.ArgAt<NotificationResultMessage>(1));
|
||||
|
||||
await publisher.PublishAsync(
|
||||
message,
|
||||
"Email provider could not deliver the notification.",
|
||||
CancellationToken.None);
|
||||
|
||||
await rabbitMqPublisher.Received(1).PublishAsync(
|
||||
"item-tracker.notifications.result",
|
||||
Arg.Any<NotificationResultMessage>(),
|
||||
CancellationToken.None);
|
||||
Assert.NotNull(publishedResult);
|
||||
Assert.Equal(message.CorrelationContext.CorrelationId, publishedResult.CorrelationContext.CorrelationId);
|
||||
Assert.Null(publishedResult.CorrelationContext.ReplyTo);
|
||||
Assert.Equal(message.Data.ServiceName, publishedResult.Data.ServiceName);
|
||||
Assert.Equal(message.Data.TemplateKey, publishedResult.Data.TemplateKey);
|
||||
Assert.Equal(message.Data.RecipientEmail, publishedResult.Data.RecipientEmail);
|
||||
Assert.Equal("Email provider could not deliver the notification.", publishedResult.Data.ErrorMessage);
|
||||
Assert.False(publishedResult.Data.IsSuccess);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PublishAsync_NoReplyQueue_DoesNotPublish()
|
||||
{
|
||||
IRabbitMqPublisher rabbitMqPublisher = Substitute.For<IRabbitMqPublisher>();
|
||||
var publisher = new NotificationResultPublisher(
|
||||
rabbitMqPublisher,
|
||||
NullLogger<NotificationResultPublisher>.Instance);
|
||||
SendEmailMessage message = CreateMessage();
|
||||
message.CorrelationContext = message.CorrelationContext with { ReplyTo = null };
|
||||
|
||||
await publisher.PublishAsync(message, "delivery failed", CancellationToken.None);
|
||||
|
||||
await rabbitMqPublisher.DidNotReceive()
|
||||
.PublishAsync<NotificationResultData>(
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<NotificationResultMessage>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PublishAsync_ResultBrokerFailure_IsBestEffort()
|
||||
{
|
||||
IRabbitMqPublisher rabbitMqPublisher = Substitute.For<IRabbitMqPublisher>();
|
||||
rabbitMqPublisher
|
||||
.PublishAsync(
|
||||
Arg.Any<string>(),
|
||||
Arg.Any<NotificationResultMessage>(),
|
||||
Arg.Any<CancellationToken>())
|
||||
.Returns<Task>(_ => throw new InvalidOperationException("reply broker unavailable"));
|
||||
var publisher = new NotificationResultPublisher(
|
||||
rabbitMqPublisher,
|
||||
NullLogger<NotificationResultPublisher>.Instance);
|
||||
|
||||
Exception? exception = await Record.ExceptionAsync(() => publisher.PublishAsync(
|
||||
CreateMessage(),
|
||||
"delivery failed",
|
||||
CancellationToken.None));
|
||||
|
||||
Assert.Null(exception);
|
||||
}
|
||||
|
||||
private static SendEmailMessage CreateMessage()
|
||||
{
|
||||
return new SendEmailMessage
|
||||
{
|
||||
CorrelationContext = new CorrelationContext
|
||||
{
|
||||
CorrelationId = "correlation-id",
|
||||
ReplyTo = "item-tracker.notifications.result"
|
||||
},
|
||||
Data = new SendEmailMessageData
|
||||
{
|
||||
ServiceName = "TestService",
|
||||
TemplateKey = "TestEmail",
|
||||
RecipientEmail = "test.user@itemtracker.local",
|
||||
RecipientName = "Test User",
|
||||
LanguageCode = "en",
|
||||
Variables = new Dictionary<string, string>()
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||
|
||||
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||
|
||||
public sealed class RecipientAddressRedactorTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("owner@example.com", "o***@e***.com")]
|
||||
[InlineData("a@b.test", "a***@b***.test")]
|
||||
[InlineData("invalid", "***")]
|
||||
[InlineData(null, "<missing>")]
|
||||
public void Redact_DoesNotExposeFullAddress(string? address, string expected)
|
||||
{
|
||||
Assert.Equal(expected, RecipientAddressRedactor.Redact(address));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user