Compare commits

...
32 Commits
Author SHA1 Message Date
khwezi 184c7c252a Merge pull request 'Set misfireThreshold to 2min and eased Cluster node checkin limit' (#23) from emailjobs into master
Reviewed-on: #23
2026-05-15 22:29:08 +02:00
Khwezi Mngoma dfc62c8fe1 Set misfireThreshold to 2min and eased Cluster node checkin limit
continuous-integration/drone/pr Build is passing
2026-05-15 22:28:18 +02:00
khwezi bfe8c458d6 Merge pull request 'Optimised quartz' (#22) from emailjobs into master
Reviewed-on: #22
2026-05-15 09:52:06 +02:00
Khwezi Mngoma 0f91f102e5 Optimised quartz
continuous-integration/drone/pr Build is passing
2026-05-15 09:51:26 +02:00
khwezi e6e0475db1 Merge pull request 'emailjobs' (#21) from emailjobs into master
Reviewed-on: #21
2026-05-15 08:39:36 +02:00
Khwezi Mngoma be9c83c8a3 Removed Abstractions listing from Git Tag
continuous-integration/drone/pr Build is passing
2026-05-15 08:39:10 +02:00
Khwezi Mngoma 65687d231e Ensured UTC is used 2026-05-15 08:37:58 +02:00
khwezi 5090c60797 Merge pull request 'Fixed Lead->Customer Relationship' (#20) from emailjobs into master
Reviewed-on: #20
2026-05-15 07:55:56 +02:00
Khwezi Mngoma 4523ef6151 Fixed Lead->Customer Relationship
continuous-integration/drone/pr Build is passing
2026-05-15 07:54:35 +02:00
khwezi 9432252e15 Merge pull request 'Added khongisa host entry on pipeline commands' (#19) from emailjobs into master
Reviewed-on: #19
2026-05-14 02:54:00 +02:00
Khwezi Mngoma 36b3656886 Added khongisa host entry on pipeline commands
continuous-integration/drone/pr Build is passing
2026-05-14 02:53:36 +02:00
khwezi 47111a1a3a Merge pull request 'emailjobs' (#18) from emailjobs into master
Reviewed-on: #18
2026-05-14 02:49:34 +02:00
Khwezi Mngoma f606b8fd3c Removed other packages from pipeline
continuous-integration/drone/pr Build is failing
2026-05-14 02:48:46 +02:00
Khwezi Mngoma 2610275bef Stable run on Notification creation 2026-05-14 02:46:07 +02:00
Khwezi Mngoma 134d8429c0 Completed refactor 2026-05-14 01:33:21 +02:00
khwezi 6eb3d50375 Merge pull request 'Updated job scheduler' (#17) from emailjobs into master
Reviewed-on: #17
2026-05-10 17:33:23 +02:00
khwezi 4deb732804 Merge pull request 'emailjobs' (#16) from emailjobs into master
Reviewed-on: #16
2026-05-10 16:51:24 +02:00
khwezi 20d9387d0b Merge pull request 'Migrated database changes' (#15) from develop into master
Reviewed-on: #15
2026-05-10 11:17:54 +02:00
khwezi 9f6d0ccaa0 Merge pull request 'Populated README' (#14) from develop into master
Reviewed-on: #14
2026-05-10 09:48:35 +02:00
khwezi 1acbc4d213 Merge pull request 'fixed git repo naming' (#13) from develop into master
Reviewed-on: #13
2026-05-10 09:22:37 +02:00
khwezi 8c99668fac Merge pull request 'Added tag and release step after publish' (#12) from develop into master
Reviewed-on: #12
2026-05-10 09:19:33 +02:00
khwezi ad44f46204 Merge pull request 'Refactored Quartz instance id to AUTO, removed constant' (#11) from develop into master
Reviewed-on: #11
2026-05-10 08:21:08 +02:00
khwezi 49d999c1e3 Merge pull request 'Refactored postgres extension' (#10) from develop into master
Reviewed-on: #10
2026-05-09 17:45:00 +02:00
khwezi 9ed4777a18 Merge pull request 'Refactored database references' (#9) from develop into master
Reviewed-on: #9
2026-05-09 17:01:02 +02:00
khwezi 0cf44f68cc Merge pull request 'Added scheduler constants' (#8) from develop into master
Reviewed-on: #8
2026-05-09 15:27:50 +02:00
khwezi 41ed5a4288 Merge pull request 'Fixed quartz host config table prefix' (#7) from develop into master
Reviewed-on: #7
2026-05-09 13:30:33 +02:00
khwezi bbcba5e06c Merge pull request 'Fixed quartz table name prefix' (#6) from develop into master
Reviewed-on: #6
2026-05-09 13:28:29 +02:00
khwezi 502cc326dd Merge pull request 'Updated pipeline to use major version with minor always 0' (#5) from develop into master
Reviewed-on: #5
2026-05-09 12:02:19 +02:00
khwezi 4675d4c5fc Merge pull request 'Updated pipeline to use major versions only' (#4) from develop into master
continuous-integration/drone/push Build was killed
continuous-integration/drone Build is failing
Reviewed-on: #4
2026-05-09 11:56:20 +02:00
khwezi f80bb2fff9 Merge pull request 'Changed target branch from nain to master' (#3) from dronepipeline into master
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is passing
Reviewed-on: #3
2026-05-09 11:37:39 +02:00
khwezi 6767906b0d Merge pull request 'Added pipeline separator' (#2) from dronepipeline into master
Reviewed-on: #2
2026-05-09 11:25:34 +02:00
khwezi a344af4498 Merge pull request 'Added .drone.yml pipeline' (#1) from dronepipeline into master
Reviewed-on: #1
2026-05-09 11:12:38 +02:00
167 changed files with 4941 additions and 3431 deletions
+2 -22
View File
@@ -17,30 +17,9 @@ steps:
NEXUS_URL: https://nexus.khongisa.co.za/repository/nuget-hosted/ NEXUS_URL: https://nexus.khongisa.co.za/repository/nuget-hosted/
VERSION: 1.${DRONE_BUILD_NUMBER}.0 VERSION: 1.${DRONE_BUILD_NUMBER}.0
commands: commands:
# Abstractions
- dotnet pack LiteCharms.Abstractions/LiteCharms.Abstractions.csproj -c Release -p:PackageVersion=$VERSION -o dist/
- dotnet nuget push dist/LiteCharms.Abstractions.$VERSION.nupkg --api-key $NEXUS_KEY --source $NEXUS_URL
# Models
- dotnet pack LiteCharms.Models/LiteCharms.Models.csproj -c Release -p:PackageVersion=$VERSION -o dist/
- dotnet nuget push dist/LiteCharms.Models.$VERSION.nupkg --api-key $NEXUS_KEY --source $NEXUS_URL
# Infrastructure
- dotnet pack LiteCharms.Infrastructure/LiteCharms.Infrastructure.csproj -c Release -p:PackageVersion=$VERSION -o dist/
- dotnet nuget push dist/LiteCharms.Infrastructure.$VERSION.nupkg --api-key $NEXUS_KEY --source $NEXUS_URL
# Features
- dotnet pack LiteCharms.Features/LiteCharms.Features.csproj -c Release -p:PackageVersion=$VERSION -o dist/ - dotnet pack LiteCharms.Features/LiteCharms.Features.csproj -c Release -p:PackageVersion=$VERSION -o dist/
- dotnet nuget push dist/LiteCharms.Features.$VERSION.nupkg --api-key $NEXUS_KEY --source $NEXUS_URL - dotnet nuget push dist/LiteCharms.Features.$VERSION.nupkg --api-key $NEXUS_KEY --source $NEXUS_URL
# Extensions
- dotnet pack LiteCharms.Extensions/LiteCharms.Extensions.csproj -c Release -p:PackageVersion=$VERSION -o dist/
- dotnet nuget push dist/LiteCharms.Extensions.$VERSION.nupkg --api-key $NEXUS_KEY --source $NEXUS_URL
# Entities
- dotnet pack LiteCharms.Entities/LiteCharms.Entities.csproj -c Release -p:PackageVersion=$VERSION -o dist/
- dotnet nuget push dist/LiteCharms.Entities.$VERSION.nupkg --api-key $NEXUS_KEY --source $NEXUS_URL
- name: gitea-tag-release - name: gitea-tag-release
image: alpine/git image: alpine/git
environment: environment:
@@ -49,6 +28,7 @@ steps:
GITEA_PASS: { from_secret: git_password } GITEA_PASS: { from_secret: git_password }
VERSION: 1.${DRONE_BUILD_NUMBER}.0 VERSION: 1.${DRONE_BUILD_NUMBER}.0
commands: commands:
- echo "169.255.58.144 gitea.khongisa.co.za" >> /etc/hosts
- apk add --no-cache curl - apk add --no-cache curl
- git remote set-url origin https://$${GITEA_USER}:$${GITEA_PASS}@gitea.khongisa.co.za/litecharms/components.git - git remote set-url origin https://$${GITEA_USER}:$${GITEA_PASS}@gitea.khongisa.co.za/litecharms/components.git
- git tag $VERSION - git tag $VERSION
@@ -61,7 +41,7 @@ steps:
\"tag_name\": \"$VERSION\", \"tag_name\": \"$VERSION\",
\"target_commitish\": \"${DRONE_COMMIT_SHA}\", \"target_commitish\": \"${DRONE_COMMIT_SHA}\",
\"name\": \"Library Suite $VERSION\", \"name\": \"Library Suite $VERSION\",
\"body\": \"### Published NuGet Packages\nAll packages versioned as **$VERSION**:\n* LiteCharms.Abstractions\n* LiteCharms.Models\n* LiteCharms.Infrastructure\n* LiteCharms.Features\n* LiteCharms.Extensions\n* LiteCharms.Entities\n\n[View in Nexus](https://nexus.khongisa.co.za/repository/nuget-group/)\", \"body\": \"### Published NuGet Packages\nAll packages versioned as **$VERSION**:\n* LiteCharms.Features\n\n[View in Nexus](https://nexus.khongisa.co.za/repository/nuget-group/)\",
\"draft\": false, \"draft\": false,
\"prerelease\": false \"prerelease\": false
}" }"
@@ -22,6 +22,7 @@ public class CommonFixture : IDisposable
Services = new ServiceCollection() Services = new ServiceCollection()
.AddMediator() .AddMediator()
.AddLogging() .AddLogging()
.AddShopServices()
.AddEmailServiceBus() .AddEmailServiceBus()
.AddShopDatabase(Configuration) .AddShopDatabase(Configuration)
.AddEmailServices(Configuration) .AddEmailServices(Configuration)
@@ -1,19 +1,35 @@
using LiteCharms.Features.Notifications.Commands; using LiteCharms.Features.Shop.Notifications;
namespace LiteCharms.Features.Tests; namespace LiteCharms.Features.Tests;
public class NotificationsFeatureTests(CommonFixture fixture) : IClassFixture<CommonFixture> public class NotificationsFeatureTests(CommonFixture fixture, ITestOutputHelper output) : IClassFixture<CommonFixture>
{ {
private readonly NotificationService notificationService = fixture.Services.GetRequiredService<NotificationService>();
[Fact] [Fact]
public async Task CreateNotificationCommand_ShouldSucceed() public async Task CreateNotificationCommand_ShouldSucceed()
{ {
var command = CreateNotification.Create(Models.NotificationDirection.Outgoing, "UnitTest", "khwezi@mngoma.co.za", Shop.Notifications.Models.CreateNotification request = new()
"CreateNotificationCommand_ShouldSucceed Test", "Test Message", Models.NotificationPlatforms.Email, Models.Priorities.Medium, {
"Khngisa Shop - Test", "shop@litecharms.co.za", Guid.NewGuid().ToString(), Models.CorrelationIdTypes.None, CorrelationId = Guid.CreateVersion7().ToString(),
true, false); CorrelationIdType = Shop.CorrelationIdTypes.None,
Direction = Shop.NotificationDirection.Outgoing,
Platform = Shop.NotificationPlatforms.Email,
Priority = Shop.Priorities.Medium,
Sender = "xUnit Test",
SenderAddress = "khwezi@mngoma.africa",
Recipient = $"{Email.Extensions.Constants.ShopEmailFromName} [Test]",
RecipientAddress = Email.Extensions.Constants.ShopEmailFromAddress,
Subject = "Test Message",
Message = "This is an automation test",
IsHtml = false,
IsInternal = true,
};
var result = await fixture.Mediator.Send(command); var createResult = await notificationService.CreateNotificationAsync(request);
Assert.True(result.IsSuccess); Assert.True(createResult.IsSuccess);
foreach (var error in createResult.Errors) output.WriteLine(error.Message);
} }
} }
+4 -4
View File
@@ -5,7 +5,7 @@ using LiteCharms.Features.Shop;
namespace LiteCharms.Features.Email; namespace LiteCharms.Features.Email;
public class EmailService(IOptions<SmtpSettings> options) : IEmailService public class EmailService(IOptions<SmtpSettings> options) : IDisposable
{ {
private readonly SmtpSettings settings = options.Value; private readonly SmtpSettings settings = options.Value;
private readonly SmtpClient client = new(); private readonly SmtpClient client = new();
@@ -14,7 +14,7 @@ public class EmailService(IOptions<SmtpSettings> options) : IEmailService
public EmailStatuses Status { get; private set; } = EmailStatuses.Disconnected; public EmailStatuses Status { get; private set; } = EmailStatuses.Disconnected;
public async Task<Result<Response>> SendEmailAsync(Message message, CancellationToken cancellationToken = default) public async ValueTask<Result<Response>> SendEmailAsync(Message message, CancellationToken cancellationToken = default)
{ {
using var activity = EmailTelemetry.Source.StartActivity("Email Send"); using var activity = EmailTelemetry.Source.StartActivity("Email Send");
activity?.SetTag("email.recipient", message.Recipient?.Address); activity?.SetTag("email.recipient", message.Recipient?.Address);
@@ -100,7 +100,7 @@ public class EmailService(IOptions<SmtpSettings> options) : IEmailService
} }
} }
public async Task<Result<Response>> ConnectAsync(CancellationToken cancellationToken = default) public async ValueTask<Result<Response>> ConnectAsync(CancellationToken cancellationToken = default)
{ {
using var activity = EmailTelemetry.Source.StartActivity("Email Connect"); using var activity = EmailTelemetry.Source.StartActivity("Email Connect");
activity?.SetTag("email.smtp.connect", settings.Host); activity?.SetTag("email.smtp.connect", settings.Host);
@@ -153,7 +153,7 @@ public class EmailService(IOptions<SmtpSettings> options) : IEmailService
} }
} }
public async Task<Result> DisconnectAsync(CancellationToken cancellationToken = default) public async ValueTask<Result> DisconnectAsync(CancellationToken cancellationToken = default)
{ {
using var activity = EmailTelemetry.Source.StartActivity("Email Disconnect"); using var activity = EmailTelemetry.Source.StartActivity("Email Disconnect");
activity?.SetTag("email.smtp.disconnect", settings.Host); activity?.SetTag("email.smtp.disconnect", settings.Host);
@@ -1,22 +1,27 @@
using LiteCharms.Features.Notifications.Commands; using LiteCharms.Features.Shop;
using LiteCharms.Features.Shop; using LiteCharms.Features.Shop.Notifications;
using static LiteCharms.Features.Email.Extensions.Constants; using static LiteCharms.Features.Email.Extensions.Constants;
namespace LiteCharms.Features.Email.Events.Handlers; namespace LiteCharms.Features.Email.Events.Handlers;
// TODO: Inject the INotificationService public class SendShopEmailEnquiryEventHandler(NotificationService notificationService) :
public class SendShopEmailEnquiryEventHandler(ISender mediator) :
INotificationHandler<SendShopEmailEnquiryEvent> INotificationHandler<SendShopEmailEnquiryEvent>
{ {
public async ValueTask Handle(SendShopEmailEnquiryEvent notification, CancellationToken cancellationToken) public async ValueTask Handle(SendShopEmailEnquiryEvent notification, CancellationToken cancellationToken) =>
{ await notificationService.CreateNotificationAsync(new Shop.Notifications.Models.CreateNotification
// TODO: Refactor this to use the NotificationService {
var command = CreateNotification.Create(NotificationDirection.Outgoing, notification.SenderName!, CorrelationId = notification.CorrelationId,
notification.SenderAddress!, notification.Subject!, notification.Message!, NotificationPlatforms.Email, CorrelationIdType = CorrelationIdTypes.None,
notification.Priority, ShopEmailFromName, ShopEmailFromAddress, Guid.CreateVersion7().ToString(), Direction = NotificationDirection.Outgoing,
CorrelationIdTypes.None, isInternal: true, isHtml: false); IsHtml = false,
IsInternal = true,
// TODO: Remove, deprecated Message = notification.Message,
await mediator.Send(command, cancellationToken); Platform = NotificationPlatforms.Email,
} Priority = notification.Priority,
Subject = notification.Subject!,
Sender = notification.SenderName!,
SenderAddress = notification.SenderAddress!,
Recipient = ShopEmailFromName,
RecipientAddress = ShopEmailFromAddress
}, cancellationToken);
} }
@@ -1,15 +0,0 @@
using LiteCharms.Features.Email.Models;
using LiteCharms.Features.Shop;
namespace LiteCharms.Features.Email;
public interface IEmailService : IDisposable
{
EmailStatuses Status { get; }
Task<Result<Response>> SendEmailAsync(Message message, CancellationToken cancellationToken = default);
Task<Result<Response>> ConnectAsync(CancellationToken cancellationToken = default);
Task<Result> DisconnectAsync(CancellationToken cancellationToken = default);
}
@@ -1,14 +1,15 @@
using LiteCharms.Features.Email.Configuration; using LiteCharms.Features.Email;
using LiteCharms.Features.Email.Configuration;
namespace LiteCharms.Features.Email.Extensions; namespace LiteCharms.Features.Extensions;
public static class Setup public static class Email
{ {
public static IServiceCollection AddEmailServices(this IServiceCollection services, IConfiguration configuration) public static IServiceCollection AddEmailServices(this IServiceCollection services, IConfiguration configuration)
{ {
services.Configure<SmtpSettings>(configuration.GetSection("Email")); services.Configure<SmtpSettings>(configuration.GetSection("Email"));
services.AddSingleton<IEmailService, EmailService>(); services.AddSingleton<EmailService>();
services.AddOpenTelemetry() services.AddOpenTelemetry()
.WithTracing(tracing => tracing.AddSource("LiteCharms.EmailService")) .WithTracing(tracing => tracing.AddSource("LiteCharms.EmailService"))
@@ -11,7 +11,7 @@ namespace LiteCharms.Features.Extensions;
public static class EntityModeMappers public static class EntityModeMappers
{ {
public static ShoppingCartPackage ToModel(this Shop.ShoppingCarts.Entities.ShoppingCartPackage entity) => public static ShoppingCartPackage ToModel(this Features.Shop.ShoppingCarts.Entities.ShoppingCartPackage entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -20,7 +20,7 @@ public static class EntityModeMappers
ShoppingCartId = entity.ShoppingCartId ShoppingCartId = entity.ShoppingCartId
}; };
public static PackageItem ToModel(this Shop.CartPackages.Entities.PackageItem entity) => public static PackageItem ToModel(this Features.Shop.CartPackages.Entities.PackageItem entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -30,7 +30,7 @@ public static class EntityModeMappers
ProductPriceId = entity.ProductPriceId ProductPriceId = entity.ProductPriceId
}; };
public static Package ToModel(this Shop.CartPackages.Entities.Package entity) => public static Package ToModel(this Features.Shop.CartPackages.Entities.Package entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -43,7 +43,7 @@ public static class EntityModeMappers
Summary = entity.Summary Summary = entity.Summary
}; };
public static ShoppingCartItem ToModel(this Shop.ShoppingCarts.Entities.ShoppingCartItem entity) => public static ShoppingCartItem ToModel(this Features.Shop.ShoppingCarts.Entities.ShoppingCartItem entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -54,7 +54,7 @@ public static class EntityModeMappers
ShoppingCartId = entity.ShoppingCartId ShoppingCartId = entity.ShoppingCartId
}; };
public static ShoppingCart ToModel(this Shop.ShoppingCarts.Entities.ShoppingCart entity) => public static ShoppingCart ToModel(this Features.Shop.ShoppingCarts.Entities.ShoppingCart entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -64,7 +64,7 @@ public static class EntityModeMappers
OrderId = entity.OrderId OrderId = entity.OrderId
}; };
public static Quote ToModel(this Shop.Quotes.Entities.Quote entity) => public static Quote ToModel(this Features.Shop.Quotes.Entities.Quote entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -79,7 +79,7 @@ public static class EntityModeMappers
OrderId = entity.OrderId OrderId = entity.OrderId
}; };
public static Notification ToModel(this Shop.Notifications.Entities.Notification entity) => public static Notification ToModel(this Features.Shop.Notifications.Entities.Notification entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -89,9 +89,9 @@ public static class EntityModeMappers
CorrelationId = entity.CorrelationId, CorrelationId = entity.CorrelationId,
CorrelationIdType = entity.CorrelationIdType, CorrelationIdType = entity.CorrelationIdType,
IsInternal = entity.IsInternal, IsInternal = entity.IsInternal,
Sender = entity.Sender, SenderAddress = entity.SenderAddress,
Platform = entity.Platform, Platform = entity.Platform,
Recipient = entity.Recipient, RecipientName = entity.RecipientName,
Subject = entity.Subject, Subject = entity.Subject,
Processed = entity.Processed, Processed = entity.Processed,
SenderName = entity.SenderName, SenderName = entity.SenderName,
@@ -103,7 +103,7 @@ public static class EntityModeMappers
Errors = entity.Errors Errors = entity.Errors
}; };
public static Customer ToModel(this Shop.Customers.Entities.Customer entity) => public static Customer ToModel(this Features.Shop.Customers.Entities.Customer entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -128,7 +128,7 @@ public static class EntityModeMappers
Whatsapp = entity.Whatsapp Whatsapp = entity.Whatsapp
}; };
public static Lead ToModel(this Shop.Leads.Entities.Lead entity) => public static Lead ToModel(this Features.Shop.Leads.Entities.Lead entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -149,7 +149,7 @@ public static class EntityModeMappers
Status = entity.Status Status = entity.Status
}; };
public static Order ToModel(this Shop.Orders.Entities.Order entity) => public static Order ToModel(this Features.Shop.Orders.Entities.Order entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -163,7 +163,7 @@ public static class EntityModeMappers
InvoiceUrl = entity.InvoiceUrl InvoiceUrl = entity.InvoiceUrl
}; };
public static OrderRefund ToModel(this Shop.Orders.Entities.OrderRefund entity) => public static OrderRefund ToModel(this Features.Shop.Orders.Entities.OrderRefund entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -173,7 +173,7 @@ public static class EntityModeMappers
Amount = entity.Amount Amount = entity.Amount
}; };
public static Product ToModel(this Shop.Products.Entities.Product entity) => public static Product ToModel(this Features.Shop.Products.Entities.Product entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
@@ -185,7 +185,7 @@ public static class EntityModeMappers
Thumbnails = entity.Thumbnails Thumbnails = entity.Thumbnails
}; };
public static ProductPrice ToModel(this Shop.Products.Entities.ProductPrice entity) => public static ProductPrice ToModel(this Features.Shop.Products.Entities.ProductPrice entity) =>
new() new()
{ {
Id = entity.Id, Id = entity.Id,
+7 -3
View File
@@ -34,7 +34,7 @@ public static class Quartz
storage.UseClustering(cluster => storage.UseClustering(cluster =>
{ {
cluster.CheckinInterval = TimeSpan.FromSeconds(30); cluster.CheckinInterval = TimeSpan.FromSeconds(30);
cluster.CheckinMisfireThreshold = TimeSpan.FromSeconds(2); cluster.CheckinMisfireThreshold = TimeSpan.FromSeconds(90);
}); });
}); });
}); });
@@ -48,6 +48,8 @@ public static class Quartz
services.ConfigureCommon(); services.ConfigureCommon();
services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);
services.AddQuartz(config => services.AddQuartz(config =>
{ {
config.SchedulerName = schedulerName; config.SchedulerName = schedulerName;
@@ -60,6 +62,8 @@ public static class Quartz
config.UseDefaultThreadPool(options => options.MaxConcurrency = 1); config.UseDefaultThreadPool(options => options.MaxConcurrency = 1);
config.UseTimeZoneConverter(); config.UseTimeZoneConverter();
config.SetProperty("quartz.jobStore.misfireThreshold", TimeSpan.FromMinutes(2).TotalMilliseconds.ToString());
config.UsePersistentStore(storage => config.UsePersistentStore(storage =>
{ {
storage.PerformSchemaValidation = false; storage.PerformSchemaValidation = false;
@@ -72,7 +76,7 @@ public static class Quartz
storage.UseClustering(cluster => storage.UseClustering(cluster =>
{ {
cluster.CheckinInterval = TimeSpan.FromSeconds(30); cluster.CheckinInterval = TimeSpan.FromSeconds(30);
cluster.CheckinMisfireThreshold = TimeSpan.FromSeconds(2); cluster.CheckinMisfireThreshold = TimeSpan.FromSeconds(90);
}); });
}); });
}); });
@@ -86,13 +90,13 @@ public static class Quartz
{ {
options.Scheduling.IgnoreDuplicates = true; options.Scheduling.IgnoreDuplicates = true;
options.Scheduling.OverWriteExistingData = true; options.Scheduling.OverWriteExistingData = true;
options["quartz.plugin.jobHistory.type"] = "Quartz.Plugin.History.LoggingJobHistoryPlugin, Quartz.Plugins"; options["quartz.plugin.jobHistory.type"] = "Quartz.Plugin.History.LoggingJobHistoryPlugin, Quartz.Plugins";
options["quartz.plugin.triggerHistory.type"] = "Quartz.Plugin.History.LoggingTriggerHistoryPlugin, Quartz.Plugins"; options["quartz.plugin.triggerHistory.type"] = "Quartz.Plugin.History.LoggingTriggerHistoryPlugin, Quartz.Plugins";
}); });
services.AddTransient<RetryJobListener>(); services.AddTransient<RetryJobListener>();
services.AddTransient<IJobOrchestrator, JobOrchestrator>(); services.AddTransient<IJobOrchestrator, JobOrchestrator>();
services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true);
return services; return services;
} }
+27
View File
@@ -0,0 +1,27 @@
using LiteCharms.Features.Shop.CartPackages;
using LiteCharms.Features.Shop.Customers;
using LiteCharms.Features.Shop.Leads;
using LiteCharms.Features.Shop.Notifications;
using LiteCharms.Features.Shop.Orders;
using LiteCharms.Features.Shop.Products;
using LiteCharms.Features.Shop.Quotes;
using LiteCharms.Features.Shop.ShoppingCarts;
namespace LiteCharms.Features.Extensions;
public static class Shop
{
public static IServiceCollection AddShopServices(this IServiceCollection services)
{
services.AddSingleton<PackageService>()
.AddSingleton<LeadService>()
.AddSingleton<NotificationService>()
.AddSingleton<OrderService>()
.AddSingleton<ProductService>()
.AddSingleton<QuoteService>()
.AddSingleton<ShoppingCartService>()
.AddSingleton<CustomerService>();
return services;
}
}
+1 -1
View File
@@ -23,5 +23,5 @@ public static class Timezones
return DateTimeOffset.Parse(localised!); return DateTimeOffset.Parse(localised!);
} }
public static DateTimeOffset UtcNow(this TimeZoneInfo timezone) => ToDateTimeWithTimeZone(DateTime.Now, timezone); public static DateTime UtcNow(this TimeZoneInfo timezone) => ToDateTimeWithTimeZone(DateTime.Now, timezone).UtcDateTime;
} }
@@ -21,6 +21,7 @@
<PackageLicenseFile>LICENSE</PackageLicenseFile> <PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageTags>utility;dotnet</PackageTags> <PackageTags>utility;dotnet</PackageTags>
<PackageIcon>icon.png</PackageIcon> <PackageIcon>icon.png</PackageIcon>
<UserSecretsId>8a78916e-c86b-4f4b-9f4e-d8e7769b5d23</UserSecretsId>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -143,5 +144,13 @@
<Using Include="Microsoft.Extensions.Options" /> <Using Include="Microsoft.Extensions.Options" />
<Using Include="Microsoft.Extensions.Logging" /> <Using Include="Microsoft.Extensions.Logging" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="Shop\Postgres\Migrations\" />
</ItemGroup>
</Project> </Project>
+10
View File
@@ -0,0 +1,10 @@
namespace LiteCharms.Features.Models;
public class DateRange
{
public DateOnly From { get; set; }
public DateOnly To { get; set; }
public int MaxRecords { get; set; }
}
@@ -1,6 +1,5 @@
using LiteCharms.Features.Abstractions; using LiteCharms.Features.Abstractions;
using LiteCharms.Features.Quartz.Abstractions; using LiteCharms.Features.Quartz.Abstractions;
using static LiteCharms.Features.Extensions.Timezones;
namespace LiteCharms.Features.Quartz; namespace LiteCharms.Features.Quartz;
@@ -47,13 +46,13 @@ public class JobOrchestrator(ISchedulerFactory schedulerFactory) : IJobOrchestra
.StoreDurably() .StoreDurably()
.Build(); .Build();
var now = SouthAfricanTimeZone.UtcNow(); var now = DateTime.UtcNow;
var trigger = global::Quartz.TriggerBuilder.Create() var trigger = global::Quartz.TriggerBuilder.Create()
.WithIdentity(triggerKey) .WithIdentity(triggerKey)
.WithDescription($"Scheduled via Main Job at {now:g}") .WithDescription($"Scheduled via Main Job at {now:g} UTC")
.WithCronSchedule(cronExpression, cron => cron.InTimeZone(SouthAfricanTimeZone) .WithCronSchedule(cronExpression, cron => cron
.WithMisfireHandlingInstructionFireAndProceed()) .WithMisfireHandlingInstructionIgnoreMisfires())
.StartAt(now) .StartAt(now)
.Build(); .Build();
+7 -3
View File
@@ -1,4 +1,5 @@
using LiteCharms.Features.Abstractions; using LiteCharms.Features.Abstractions;
using LiteCharms.Features.Mediator;
namespace LiteCharms.Features.Quartz; namespace LiteCharms.Features.Quartz;
@@ -13,9 +14,12 @@ public class MediatorJob<TNotification>(IMediator mediator) : IJob where TNotifi
var notification = JsonSerializer.Deserialize<TNotification>(data); var notification = JsonSerializer.Deserialize<TNotification>(data);
if(notification is null) return; if (notification is null) return;
if(notification is TNotification) using var activity = MediatorTelemetry.Source.StartActivity($"Quartz: {typeof(TNotification).Name}");
await mediator.Publish(notification, context.CancellationToken);
activity?.SetTag("event.correlation_id", notification.CorrelationId);
await mediator.Publish(notification, context.CancellationToken);
} }
} }
@@ -1,25 +0,0 @@
namespace LiteCharms.Features.CartPackages.Commands;
public class AddPackageItemCommand : IRequest<Result<Guid>>
{
public Guid PackageId { get; set; }
public Guid ProductPriceId { get; set; }
private AddPackageItemCommand(Guid packageId, Guid productPriceId)
{
PackageId = packageId;
ProductPriceId = productPriceId;
}
public static AddPackageItemCommand Create(Guid packageId, Guid productPriceId)
{
if (packageId == Guid.Empty)
throw new ArgumentException("Package id is required", nameof(packageId));
if (productPriceId == Guid.Empty)
throw new ArgumentException("Product price id is required", nameof(productPriceId));
return new(packageId, productPriceId);
}
}
@@ -1,23 +0,0 @@
namespace LiteCharms.Features.CartPackages.Commands;
public class CreatePackageCommand : IRequest<Result<Guid>>
{
public string? Name { get; set; }
public string? Description { get; set; }
private CreatePackageCommand(string? name, string? description)
{
Name = name;
Description = description;
}
public static CreatePackageCommand Create(string? name, string? description)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name, nameof(name));
ArgumentException.ThrowIfNullOrWhiteSpace(description, nameof(description));
return new(name, description);
}
}
@@ -1,25 +0,0 @@
namespace LiteCharms.Features.CartPackages.Commands;
public class DeletePackageItemCommand : IRequest<Result>
{
public Guid PackageId { get; set; }
public Guid PackageItemId { get; set; }
private DeletePackageItemCommand(Guid packageId, Guid packageItemId)
{
PackageId = packageId;
PackageItemId = packageItemId;
}
public static DeletePackageItemCommand Create(Guid packageId, Guid packageItemId)
{
if (packageId == Guid.Empty)
throw new ArgumentException("Package id is required", nameof(packageId));
if (packageItemId == Guid.Empty)
throw new ArgumentException("Product price id is required", nameof(packageItemId));
return new(packageId, packageItemId);
}
}
@@ -1,16 +0,0 @@
namespace LiteCharms.Features.CartPackages.Commands;
public class DeletePackageItemsCommand : IRequest<Result>
{
public Guid PackageId { get; set; }
private DeletePackageItemsCommand(Guid packageId) => PackageId = packageId;
public static DeletePackageItemsCommand Create(Guid packageId)
{
if (packageId == Guid.Empty)
throw new ArgumentException("Package ID is required", nameof(packageId));
return new(packageId);
}
}
@@ -1,38 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.CartPackages.Commands.Handlers;
public class AddPackageItemCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<AddPackageItemCommand, Result<Guid>>
{
public async ValueTask<Result<Guid>> Handle(AddPackageItemCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Packages.AnyAsync(p => p.Id == request.PackageId, cancellationToken))
return Result.Fail($"Could not find package by ID {request.PackageId}");
if (!await context.ProductPrices.AnyAsync(p => p.Id == request.ProductPriceId && p.Active == true, cancellationToken))
return Result.Fail($"Could not find an active product price by ID {request.ProductPriceId}");
if (await context.PackageItems.AnyAsync(p => p.ProductPriceId == request.ProductPriceId && p.PackageId == request.PackageId, cancellationToken))
return Result.Fail<Guid>($"Product price {request.ProductPriceId} is already added to this package {request.PackageId}");
var newPackageItem = context.PackageItems.Add(new Entities.PackageItem
{
PackageId = request.PackageId,
ProductPriceId = request.ProductPriceId,
Active = true
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newPackageItem.Entity.Id)
: Result.Fail<Guid>($"Failed to add new package item by ID {request.ProductPriceId}");
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,32 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.CartPackages.Commands.Handlers;
public class CreatePackageCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<CreatePackageCommand, Result<Guid>>
{
public async ValueTask<Result<Guid>> Handle(CreatePackageCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (await context.Packages.AnyAsync(p => p.Name == request.Name, cancellationToken))
return Result.Fail($"A package by the same name already exists: {request.Name}");
var newPackage = context.Packages.Add(new Entities.Package
{
Name = request.Name,
Description = request.Description,
Active = true
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newPackage.Entity.Id)
: Result.Fail($"Failed to create a new package by the name: {request.Name}");
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,32 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.CartPackages.Commands.Handlers;
public class DeletePackageItemCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<DeletePackageItemCommand, Result>
{
public async ValueTask<Result> Handle(DeletePackageItemCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Packages.AnyAsync(p => p.Id == request.PackageId, cancellationToken))
return Result.Fail($"Could not find package by ID {request.PackageId}");
var item = await context.PackageItems.FirstOrDefaultAsync(p => p.Id == request.PackageItemId && p.PackageId == request.PackageId, cancellationToken);
if(item is null)
return Result.Fail($"Product item {request.PackageItemId} is already added to this package {request.PackageId}");
context.PackageItems.Remove(item);
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to delete package item by id {request.PackageItemId}");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,29 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.CartPackages.Commands.Handlers;
public class DeletePackageItemsCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<DeletePackageItemsCommand, Result>
{
public async ValueTask<Result> Handle(DeletePackageItemsCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Packages.AnyAsync(p => p.Id == request.PackageId, cancellationToken))
return Result.Fail($"Could not find package by ID {request.PackageId}");
var items = await context.PackageItems.Where(i => i.PackageId == request.PackageId).ToArrayAsync(cancellationToken);
context.PackageItems.RemoveRange(items);
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to delete package {request.PackageId} items");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,33 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.CartPackages.Commands.Handlers;
public class UpdatePackageCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<UpdatePackageCommand, Result>
{
public async ValueTask<Result> Handle(UpdatePackageCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (await context.Packages.AnyAsync(p => p.Name == request.Name, cancellationToken))
return Result.Fail($"A package by the same name already exists: {request.Name}");
var package = await context.Packages.FirstOrDefaultAsync(p => p.Id == request.PackageId, cancellationToken);
if (package is null)
return Result.Fail($"Could not find package by id {request.PackageId}");
package.Name = request.Name;
package.Description = request.Description;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to update package with id {request.PackageId}");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,29 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.CartPackages.Commands.Handlers;
public class UpdatePackageStatusCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<UpdatePackageStatusCommand, Result>
{
public async ValueTask<Result> Handle(UpdatePackageStatusCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var package = await context.Packages.FirstOrDefaultAsync(p => p.Id == request.PackageId, cancellationToken);
if (package is null)
return Result.Fail($"Could not find package by id {request.PackageId}");
package.Active = request.Active;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to update package with id {request.PackageId}");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,28 +0,0 @@
namespace LiteCharms.Features.CartPackages.Commands;
public class UpdatePackageCommand : IRequest<Result>
{
public Guid PackageId { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
private UpdatePackageCommand(Guid packageId, string? name, string? description)
{
PackageId = packageId;
Name = name;
Description = description;
}
public static UpdatePackageCommand Create(Guid packageId, string? name, string? description)
{
if (packageId == Guid.Empty)
throw new ArgumentException($"Package ID is required", nameof(packageId));
ArgumentNullException.ThrowIfNullOrWhiteSpace(name, nameof(name));
ArgumentNullException.ThrowIfNullOrWhiteSpace(description, nameof(description));
return new(packageId, name, description);
}
}
@@ -1,22 +0,0 @@
namespace LiteCharms.Features.CartPackages.Commands;
public class UpdatePackageStatusCommand : IRequest<Result>
{
public Guid PackageId { get; set; }
public bool Active { get; set; }
private UpdatePackageStatusCommand(Guid packageId, bool active)
{
PackageId = packageId;
Active = active;
}
public static UpdatePackageStatusCommand Create(Guid packageId, bool active)
{
if(packageId == Guid.Empty)
throw new ArgumentException($"Package id is required", nameof(packageId));
return new(packageId, active);
}
}
@@ -8,7 +8,7 @@ public class PackageConfirguration : IEntityTypeConfiguration<Package>
builder.HasKey(f => f.Id); builder.HasKey(f => f.Id);
builder.Property(f => f.CreatedAt).IsRequired().ValueGeneratedOnAdd().HasDefaultValueSql("now()"); builder.Property(f => f.CreatedAt).IsRequired().ValueGeneratedOnAdd().HasDefaultValueSql("now()");
builder.Property(f => f.UpdatedAt).IsRequired(false); builder.Property(f => f.UpdatedAt).IsRequired(false).HasDefaultValueSql(null);
builder.Property(f => f.Name).IsRequired(); builder.Property(f => f.Name).IsRequired();
builder.Property(f => f.Summary).IsRequired().HasMaxLength(512); builder.Property(f => f.Summary).IsRequired().HasMaxLength(512);
builder.Property(f => f.Description).IsRequired().HasMaxLength(2048); builder.Property(f => f.Description).IsRequired().HasMaxLength(2048);
@@ -4,9 +4,9 @@ public class Package
{ {
public Guid Id { get; set; } public Guid Id { get; set; }
public DateTimeOffset CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; } public DateTime? UpdatedAt { get; set; }
public string? Name { get; set; } public string? Name { get; set; }
@@ -0,0 +1,242 @@
using LiteCharms.Features.Extensions;
using LiteCharms.Features.Models;
using LiteCharms.Features.Shop.CartPackages.Models;
using LiteCharms.Features.Shop.Postgres;
using static LiteCharms.Features.Extensions.Timezones;
namespace LiteCharms.Features.Shop.CartPackages;
public class PackageService(IDbContextFactory<ShopDbContext> contextFactory)
{
public async ValueTask<Result<Guid>> AddPackageItemAsync(Guid packageId, Guid productPriceId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Packages.AnyAsync(p => p.Id == packageId, cancellationToken))
return Result.Fail($"Could not find package by ID {packageId}");
if (!await context.ProductPrices.AnyAsync(p => p.Id == productPriceId && p.Active == true, cancellationToken))
return Result.Fail($"Could not find an active product price by ID {productPriceId}");
if (await context.PackageItems.AnyAsync(p => p.ProductPriceId == productPriceId && p.PackageId == packageId, cancellationToken))
return Result.Fail<Guid>($"Product price {productPriceId} is already added to this package {packageId}");
var newPackageItem = context.PackageItems.Add(new Entities.PackageItem
{
PackageId = packageId,
ProductPriceId = productPriceId,
Active = true
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newPackageItem.Entity.Id)
: Result.Fail<Guid>($"Failed to add new package item by ID {productPriceId}");
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Guid>> CreatePackageAsync(string? name, string? summary, string? description, string? ImageUrl, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (await context.Packages.AnyAsync(p => p.Name == name, cancellationToken))
return Result.Fail($"A package by the same name already exists: {name}");
var newPackage = context.Packages.Add(new Entities.Package
{
Name = name,
Summary = summary,
Description = description,
ImageUrl = ImageUrl,
Active = true
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newPackage.Entity.Id)
: Result.Fail($"Failed to create a new package by the name: {name}");
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result> DeletePackageItemAsync(Guid packageId, Guid packageItemId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Packages.AnyAsync(p => p.Id == packageId, cancellationToken))
return Result.Fail($"Could not find package by ID {packageId}");
var item = await context.PackageItems.FirstOrDefaultAsync(p => p.Id == packageItemId && p.PackageId == packageId, cancellationToken);
if (item is null)
return Result.Fail($"Product item {packageItemId} is already added to this package {packageId}");
context.PackageItems.Remove(item);
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to delete package item by id {packageItemId}");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result> DeletePackageItemsAsync(Guid packageId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Packages.AnyAsync(p => p.Id == packageId, cancellationToken))
return Result.Fail($"Could not find package by ID {packageId}");
var items = await context.PackageItems.Where(i => i.PackageId == packageId).ToArrayAsync(cancellationToken);
context.PackageItems.RemoveRange(items);
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to delete package {packageId} items");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Package>> GetPackageAsync(Guid packageId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var package = await context.Packages.FirstOrDefaultAsync(p => p.Id == packageId, cancellationToken);
return package is not null
? Result.Ok(package.ToModel())
: Result.Fail($"Failed to find package by ID {packageId}");
}
catch (Exception ex)
{
return Result.Fail<Package>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<PackageItem[]>> GetPackageItemsAsync(Guid packageId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Packages.AnyAsync(p => p.Id == packageId, cancellationToken))
return Result.Fail<PackageItem[]>($"Package could not be found with ID {packageId}");
var items = await context.PackageItems.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(p => p.PackageId == packageId)
.ToArrayAsync(cancellationToken);
return items?.Length > 0
? Result.Ok(items.Select(i => i.ToModel()).ToArray())
: Result.Fail<PackageItem[]>($"Could not find package items by package ID {packageId}");
}
catch (Exception ex)
{
return Result.Fail<PackageItem[]>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Package[]>> GetPackagesAsync(Guid packageId, DateRange range, bool active, CancellationToken cancellationToken = default)
{
try
{
var fromDate = range.From.ToDateTime(TimeOnly.MinValue);
var toDate = range.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var packages = await context.Packages
.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(p => p.CreatedAt >= fromDate && p.CreatedAt <= toDate)
.Where(p => p.Active == active)
.Take(range.MaxRecords)
.ToArrayAsync(cancellationToken);
return packages?.Length > 0
? Result.Ok(packages.Select(o => o.ToModel()).ToArray())
: Result.Fail<Package[]>(new Error($"No packages found for the specified date range {range.From} - {range.To}."));
}
catch (Exception ex)
{
return Result.Fail<Package[]>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Guid>> UpdatePackageAsync(Guid packageId, string? name, string? summary, string? description, string? ImageUrl, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (await context.Packages.AnyAsync(p => p.Name == name, cancellationToken))
return Result.Fail($"A package by the same name already exists: {name}");
var package = await context.Packages.FirstOrDefaultAsync(p => p.Id == packageId, cancellationToken);
if (package is null)
return Result.Fail($"Could not find package by id {packageId}");
package.Name = name;
package.Summary = summary;
package.Description = description;
package.ImageUrl = ImageUrl;
package.UpdatedAt = DateTime.UtcNow;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to update package with id {packageId}");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Guid>> UpdatePackageStatusAsync(Guid packageId, bool active, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var package = await context.Packages.FirstOrDefaultAsync(p => p.Id == packageId, cancellationToken);
if (package is null)
return Result.Fail($"Could not find package by id {packageId}");
package.Active = active;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to update package with id {packageId}");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,18 +0,0 @@
using LiteCharms.Features.Shop.CartPackages.Models;
namespace LiteCharms.Features.CartPackages.Queries;
public class GetPackageItemsQuery : IRequest<Result<PackageItem[]>>
{
public Guid PackageId { get; set; }
private GetPackageItemsQuery(Guid packageId) => PackageId = packageId;
public static GetPackageItemsQuery Create(Guid packageId)
{
if (packageId == Guid.Empty)
throw new ArgumentException("Package ID is required", nameof(packageId));
return new(packageId);
}
}
@@ -1,18 +0,0 @@
using LiteCharms.Features.Shop.CartPackages.Models;
namespace LiteCharms.Features.CartPackages.Queries;
public class GetPackageQuery : IRequest<Result<Package>>
{
public Guid PackageId { get; set; }
private GetPackageQuery(Guid packageId) => PackageId = packageId;
public static GetPackageQuery Create(Guid packageId)
{
if(packageId == Guid.Empty)
throw new ArgumentException("Package ID is required", nameof(packageId));
return new(packageId);
}
}
@@ -1,33 +0,0 @@
using LiteCharms.Features.Shop.CartPackages.Models;
namespace LiteCharms.Features.CartPackages.Queries;
public class GetPackagesQuery : IRequest<Result<Package[]>>
{
public DateOnly From { get; set; }
public DateOnly To { get; set; }
public int MaxRecords { get; set; }
public bool Active { get; set; }
private GetPackagesQuery(DateOnly from, DateOnly to, int maxRecords = 1000, bool active = true)
{
From = from;
To = to;
MaxRecords = maxRecords;
Active = active;
}
public static GetPackagesQuery Create(DateOnly from, DateOnly to, int maxRecords = 1000, bool active = true)
{
if (from > to)
throw new ArgumentException("From date cannot be greater than To date.");
if (maxRecords <= 0)
throw new ArgumentException("MaxRecords must be a positive integer.");
return new(from, to, maxRecords, active);
}
}
@@ -1,32 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.CartPackages.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.CartPackages.Queries.Handlers;
public class GetPackageItemsQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetPackageItemsQuery, Result<PackageItem[]>>
{
public async ValueTask<Result<PackageItem[]>> Handle(GetPackageItemsQuery request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Packages.AnyAsync(p => p.Id == request.PackageId, cancellationToken))
return Result.Fail<PackageItem[]>($"Package could not be found with ID {request.PackageId}");
var items = await context.PackageItems.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(p => p.PackageId == request.PackageId)
.ToArrayAsync(cancellationToken);
return items?.Length > 0
? Result.Ok(items.Select(i => i.ToModel()).ToArray())
: Result.Fail<PackageItem[]>($"Could not find package items by package ID {request.PackageId}");
}
catch (Exception ex)
{
return Result.Fail<PackageItem[]>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,27 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.CartPackages.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.CartPackages.Queries.Handlers;
public class GetPackageQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetPackageQuery, Result<Package>>
{
public async ValueTask<Result<Package>> Handle(GetPackageQuery request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var package = await context.Packages.FirstOrDefaultAsync(p => p.Id == request.PackageId, cancellationToken);
return package is not null
? Result.Ok(package.ToModel())
: Result.Fail($"Failed to find package by ID {request.PackageId}");
}
catch (Exception ex)
{
return Result.Fail<Package>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,35 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.CartPackages.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.CartPackages.Queries.Handlers;
public class GetPackagesQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetPackagesQuery, Result<Package[]>>
{
public async ValueTask<Result<Package[]>> Handle(GetPackagesQuery request, CancellationToken cancellationToken)
{
try
{
var fromDate = request.From.ToDateTime(TimeOnly.MinValue);
var toDate = request.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var packages = await context.Packages
.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(p => p.CreatedAt >= fromDate && p.CreatedAt <= toDate)
.Where(p => p.Active == request.Active)
.Take(request.MaxRecords)
.ToArrayAsync(cancellationToken);
return packages?.Length > 0
? Result.Ok(packages.Select(o => o.ToModel()).ToArray())
: Result.Fail<Package[]>(new Error($"No packages found for the specified date range {request.From} - {request.To}."));
}
catch (Exception ex)
{
return Result.Fail<Package[]>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,64 +0,0 @@
namespace LiteCharms.Features.Customers.Commands;
public class CreateCustomerCommand : IRequest<Result<Guid>>
{
public string? Company { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string? Tax { get; set; }
public string Email { get; set; }
public string? Discord { get; set; }
public string? Slack { get; set; }
public string? LinkedIn { get; set; }
public string? Whatsapp { get; set; }
public string? Website { get; set; }
public string? Phone { get; set; }
public string? Address { get; set; }
public string? City { get; set; }
public string? Region { get; set; }
public string? Country { get; set; }
public string? PostalCode { get; set; }
private CreateCustomerCommand(string name, string lastName, string? company, string? tax, string email, string? discord, string? slack, string? linkedIn, string? whatsapp, string? website, string? phone, string? address, string? city, string? region, string? country, string? postalCode)
{
Name = name;
LastName = lastName;
Company = company;
Tax = tax;
Email = email;
Discord = discord;
Slack = slack;
LinkedIn = linkedIn;
Whatsapp = whatsapp;
Website = website;
Phone = phone;
Address = address;
City = city;
Region = region;
Country = country;
PostalCode = postalCode;
}
public static CreateCustomerCommand Create(string name, string lastName, string? company, string? tax, string email, string? discord, string? slack, string? linkedIn, string? whatsapp, string? website, string? phone, string? address, string? city, string? region, string? country, string? postalCode)
{
if (string.IsNullOrWhiteSpace(name) && string.IsNullOrWhiteSpace(lastName) && string.IsNullOrWhiteSpace(email))
throw new ArgumentException("At the following fields must be provided: Name, LastName, Email");
return new(name, lastName, company, tax, email, discord, slack, linkedIn, whatsapp, website, phone, address, city, region, country, postalCode);
}
}
@@ -1,48 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Customers.Commands.Handlers;
public class CreateCustomerCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<CreateCustomerCommand, Result<Guid>>
{
public async ValueTask<Result<Guid>> Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var customerEmail = request.Email.ToLower().Trim();
if (await context.Customers.AnyAsync(c => c.Email == customerEmail, cancellationToken))
return Result.Fail<Guid>(new Error($"A customer with the email {customerEmail} already exists"));
var newCustomer = context.Customers.Add(new Entities.Customer
{
Company = request.Company,
Name = request.Name,
LastName = request.LastName,
Tax = request.Tax,
Email = customerEmail,
Discord = request.Discord,
Slack = request.Slack,
LinkedIn = request.LinkedIn,
Whatsapp = request.Whatsapp,
Website = request.Website,
Phone = request.Phone,
Address = request.Address,
City = request.City,
Region = request.Region,
Country = request.Country,
PostalCode = request.PostalCode,
Active = true,
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newCustomer.Entity.Id)
: Result.Fail<Guid>(new Error($"Failed to create customer {customerEmail}"));
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,44 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Customers.Commands.Handlers;
public class UpdateCustomerCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<UpdateCustomerCommand, Result>
{
public async ValueTask<Result> Handle(UpdateCustomerCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var customer = await context.Customers.FirstOrDefaultAsync(c => c.Id == request.CustomerId, cancellationToken);
if (customer is null)
return Result.Fail(new Error($"Customer with ID {request.CustomerId} not found."));
customer.Name = request.Name;
customer.LastName = request.LastName;
customer.Email = request.Email;
customer.Company = request.Company;
customer.Address = request.Address;
customer.City = request.City;
customer.Region = request.Region;
customer.Country = request.Country;
customer.PostalCode = request.PostalCode;
customer.Phone = request.Phone;
customer.Tax = request.Tax;
customer.City = request.City;
customer.Discord = request.Discord;
customer.Slack = request.Slack;
customer.LinkedIn = request.LinkedIn;
customer.Whatsapp = request.Whatsapp;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail(new Error($"Failed to update the customer {request.CustomerId}."));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,70 +0,0 @@
namespace LiteCharms.Features.Customers.Commands;
public class UpdateCustomerCommand : IRequest<Result>
{
public Guid CustomerId { get; set; }
public string? Company { get; set; }
public string? Name { get; set; }
public string? LastName { get; set; }
public string? Tax { get; set; }
public string? Email { get; set; }
public string? Discord { get; set; }
public string? Slack { get; set; }
public string? LinkedIn { get; set; }
public string? Whatsapp { get; set; }
public string? Website { get; set; }
public string? Phone { get; set; }
public string? Address { get; set; }
public string? City { get; set; }
public string? Region { get; set; }
public string? Country { get; set; }
public string? PostalCode { get; set; }
private UpdateCustomerCommand(Guid customerId, string name, string lastName, string? company, string? tax, string email, string? discord, string? slack, string? linkedIn, string? whatsapp, string? website, string? phone, string? address, string? city, string? region, string? country, string? postalCode)
{
CustomerId = customerId;
Name = name;
LastName = lastName;
Company = company;
Tax = tax;
Email = email;
Discord = discord;
Slack = slack;
LinkedIn = linkedIn;
Whatsapp = whatsapp;
Website = website;
Phone = phone;
Address = address;
City = city;
Region = region;
Country = country;
PostalCode = postalCode;
}
public static UpdateCustomerCommand Create(Guid customerId, string name, string lastName, string? company, string? tax, string email, string? discord, string? slack, string? linkedIn, string? whatsapp, string? website, string? phone, string? address, string? city, string? region, string? country, string? postalCode)
{
if (customerId == Guid.Empty)
throw new ArgumentException("Customer ID is required.", nameof(customerId));
if (string.IsNullOrWhiteSpace(name) && string.IsNullOrWhiteSpace(lastName) && string.IsNullOrWhiteSpace(email))
throw new ArgumentException("At the following fields must be provided: Name, LastName, Email");
return new(customerId, name, lastName, company, tax, email, discord, slack, linkedIn, whatsapp, website, phone, address, city, region, country, postalCode);
}
}
@@ -0,0 +1,132 @@
using LiteCharms.Features.Extensions;
using LiteCharms.Features.Models;
using LiteCharms.Features.Shop.Customers.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Shop.Customers;
public class CustomerService(IDbContextFactory<ShopDbContext> contextFactory)
{
public async ValueTask<Result<Guid>> CreateCustomerAsync(CreateCustomer request, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var customerEmail = request.Email.ToLower().Trim();
if (await context.Customers.AnyAsync(c => c.Email == customerEmail, cancellationToken))
return Result.Fail<Guid>(new Error($"A customer with the email {customerEmail} already exists"));
var newCustomer = context.Customers.Add(new Entities.Customer
{
Company = request.Company,
Name = request.Name,
LastName = request.LastName,
Tax = request.Tax,
Email = customerEmail,
Discord = request.Discord,
Slack = request.Slack,
LinkedIn = request.LinkedIn,
Whatsapp = request.Whatsapp,
Website = request.Website,
Phone = request.Phone,
Address = request.Address,
City = request.City,
Region = request.Region,
Country = request.Country,
PostalCode = request.PostalCode,
Active = true,
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newCustomer.Entity.Id)
: Result.Fail<Guid>(new Error($"Failed to create customer {customerEmail}"));
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Customer>> GetCustomerAsync(Guid customerId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var customer = await context.Customers.FirstOrDefaultAsync(c => c.Id == customerId, cancellationToken);
return customer is not null
? Result.Ok(customer.ToModel())
: Result.Fail<Customer>($"Customer not found with id {customerId}");
}
catch (Exception ex)
{
return Result.Fail<Customer>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Customer[]>> GetCustomersAsync(DateRange range, CancellationToken cancellationToken = default)
{
try
{
var fromDate = range.From.ToDateTime(TimeOnly.MinValue);
var toDate = range.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var customers = await context.Customers.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(c => c.CreatedAt >= fromDate && c.CreatedAt <= toDate)
.Take(range.MaxRecords)
.ToArrayAsync(cancellationToken);
return customers?.Length > 0
? Result.Ok(customers.Select(c => c.ToModel()).ToArray())
: Result.Fail<Customer[]>(new Error("No customers found in the specified date range."));
}
catch (Exception ex)
{
return Result.Fail<Customer[]>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result> UpdateCustomerAsync(UpdateCustomer request, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var customer = await context.Customers.FirstOrDefaultAsync(c => c.Id == request.CustomerId, cancellationToken);
if (customer is null)
return Result.Fail(new Error($"Customer with ID {request.CustomerId} not found."));
customer.Name = request.Name;
customer.LastName = request.LastName;
customer.Email = request.Email;
customer.Company = request.Company;
customer.Address = request.Address;
customer.City = request.City;
customer.Region = request.Region;
customer.Country = request.Country;
customer.PostalCode = request.PostalCode;
customer.Phone = request.Phone;
customer.Tax = request.Tax;
customer.City = request.City;
customer.Discord = request.Discord;
customer.Slack = request.Slack;
customer.LinkedIn = request.LinkedIn;
customer.Whatsapp = request.Whatsapp;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail(new Error($"Failed to update the customer {request.CustomerId}."));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -4,11 +4,11 @@ public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{ {
public void Configure(EntityTypeBuilder<Customer> builder) public void Configure(EntityTypeBuilder<Customer> builder)
{ {
builder.ToTable(nameof(Customer)); builder.ToTable("Customers");
builder.HasKey(f => f.Id); builder.HasKey(f => f.Id);
builder.Property(f => f.CreatedAt).ValueGeneratedOnAdd().HasDefaultValueSql("now()"); builder.Property(f => f.CreatedAt).ValueGeneratedOnAdd().HasDefaultValueSql("now()");
builder.Property(f => f.UpdatedAt).IsRequired(false); builder.Property(f => f.UpdatedAt).IsRequired(false).HasDefaultValueSql(null);
builder.Property(f => f.Company); builder.Property(f => f.Company);
builder.Property(f => f.Name).IsRequired(); builder.Property(f => f.Name).IsRequired();
builder.Property(f => f.LastName).IsRequired(); builder.Property(f => f.LastName).IsRequired();
@@ -4,9 +4,9 @@ public class Customer
{ {
public Guid Id { get; set; } public Guid Id { get; set; }
public DateTimeOffset CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; } public DateTime? UpdatedAt { get; set; }
public string? Company { get; set; } public string? Company { get; set; }
@@ -0,0 +1,73 @@
namespace LiteCharms.Features.Shop.Customers.Models;
public record CreateCustomer
{
public string? Company { get; set; }
public required string Name { get; set; }
public required string LastName { get; set; }
public string? Tax { get; set; }
public required string Email { get; set; }
public string? Discord { get; set; }
public string? Slack { get; set; }
public string? LinkedIn { get; set; }
public string? Whatsapp { get; set; }
public string? Website { get; set; }
public string? Phone { get; set; }
public string? Address { get; set; }
public string? City { get; set; }
public string? Region { get; set; }
public string? Country { get; set; }
public string? PostalCode { get; set; }
}
public record UpdateCustomer
{
public required Guid CustomerId { get; set; }
public string? Company { get; set; }
public string? Name { get; set; }
public string? LastName { get; set; }
public string? Tax { get; set; }
public string? Email { get; set; }
public string? Discord { get; set; }
public string? Slack { get; set; }
public string? LinkedIn { get; set; }
public string? Whatsapp { get; set; }
public string? Website { get; set; }
public string? Phone { get; set; }
public string? Address { get; set; }
public string? City { get; set; }
public string? Region { get; set; }
public string? Country { get; set; }
public string? PostalCode { get; set; }
}
@@ -1,18 +0,0 @@
using LiteCharms.Features.Shop.Customers.Models;
namespace LiteCharms.Features.Customers.Queries;
public class GetCustomerQuery : IRequest<Result<Customer>>
{
public Guid CustomerId { get; set; }
private GetCustomerQuery(Guid customerId) => CustomerId = customerId;
public static GetCustomerQuery Create(Guid customerId)
{
if(customerId == Guid.Empty)
throw new ArgumentException("Customer ID is required.", nameof(customerId));
return new(customerId);
}
}
@@ -1,30 +0,0 @@
using LiteCharms.Features.Shop.Customers.Models;
namespace LiteCharms.Features.Customers.Queries;
public class GetCustomersQuery : IRequest<Result<Customer[]>>
{
public DateOnly From { get; set; }
public DateOnly To { get; set; }
public int MaxRecords { get; set; }
private GetCustomersQuery(DateOnly from, DateOnly to, int maxRecords = 1000)
{
From = from;
To = to;
MaxRecords = maxRecords;
}
public static GetCustomersQuery Create(DateOnly from, DateOnly to, int maxRecords = 1000)
{
if (from > to)
throw new ArgumentException("From date cannot be greater than To date.");
if(maxRecords <= 0)
throw new ArgumentException("MaxRecords must be a positive integer.");
return new(from, to, maxRecords);
}
}
@@ -1,26 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Customers.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Customers.Queries.Handlers;
public class GetCustomerQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetCustomerQuery, Result<Customer>>
{
public async ValueTask<Result<Customer>> Handle(GetCustomerQuery request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var customer = await context.Customers.FirstOrDefaultAsync(c => c.Id == request.CustomerId, cancellationToken);
return customer is not null
? Result.Ok(customer.ToModel())
: Result.Fail<Customer>($"Customer not found with id {request.CustomerId}");
}
catch (Exception ex)
{
return Result.Fail<Customer>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,33 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Customers.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Customers.Queries.Handlers;
public class GetCustomersQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetCustomersQuery, Result<Customer[]>>
{
public async ValueTask<Result<Customer[]>> Handle(GetCustomersQuery request, CancellationToken cancellationToken)
{
try
{
var fromDate = request.From.ToDateTime(TimeOnly.MinValue);
var toDate = request.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var customers = await context.Customers.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(c => c.CreatedAt >= fromDate && c.CreatedAt <= toDate)
.Take(request.MaxRecords)
.ToArrayAsync(cancellationToken);
return customers?.Length > 0
? Result.Ok(customers.Select(c => c.ToModel()).ToArray())
: Result.Fail<Customer[]>(new Error("No customers found in the specified date range."));
}
catch (Exception ex)
{
return Result.Fail<Customer[]>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,55 +0,0 @@
namespace LiteCharms.Features.Leads.Commands;
public class CreateLeadCommand : IRequest<Result<Guid>>
{
public Guid? CustomerId { get; set; }
public string? Source { get; set; }
public string? ClickId { get; set; }
public string? WebClickId { get; set; }
public string? AppClickId { get; set; }
public long? CampaignId { get; set; }
public long? AdGroupId { get; set; }
public long? AdName { get; set; }
public long? TargetId { get; set; }
public long? FeedItemId { get; set; }
public string? ClickLocation { get; set; }
public string? AttribusionHash { get; set; }
private CreateLeadCommand(Guid? customerId, string source, string clickId, string webClickId, string appClickId, long? campaignId, long? adGroupId, long? adName, long? targetId, long? feedItemId, string? clickLocation, string? attribusionHash)
{
CustomerId = customerId;
Source = source;
ClickId = clickId;
WebClickId = webClickId;
AppClickId = appClickId;
CampaignId = campaignId;
AdGroupId = adGroupId;
AdName = adName;
TargetId = targetId;
FeedItemId = feedItemId;
ClickLocation = clickLocation;
AttribusionHash = attribusionHash;
}
public static CreateLeadCommand Create(Guid? customerId, string source, string clickId, string webClickId, string appClickId, long? campaignId, long? adGroupId, long? adName, long? targetId, long? feedItemId, string? clickLocation, string? attribusionHash)
{
if(string.IsNullOrWhiteSpace(source))
throw new ArgumentNullException("Lead source is required to create a lead.", nameof(source));
if (string.IsNullOrWhiteSpace(clickId) || string.IsNullOrWhiteSpace(appClickId) || string.IsNullOrWhiteSpace(webClickId))
throw new ArgumentException("ClickId, App ClickId and Web ClickId are required to create a lead.");
return new(customerId, source, clickId, webClickId, appClickId, campaignId, adGroupId, adName, targetId, feedItemId, clickLocation, attribusionHash);
}
}
@@ -1,47 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
using LiteCharms.Features.Utilities.Hash.Commands;
namespace LiteCharms.Features.Leads.Commands.Handlers;
public class CreateLeadCommandHandler(IDbContextFactory<ShopDbContext> contextFactory, ISender mediator) : IRequestHandler<CreateLeadCommand, Result<Guid>>
{
public async ValueTask<Result<Guid>> Handle(CreateLeadCommand request, CancellationToken cancellationToken)
{
try
{
var hashCommand = ComputeHashCommand.Create($"{request.ClickId}{request.AppClickId}{request.WebClickId}");
var hashResult = await mediator.Send(hashCommand, cancellationToken);
if(hashResult.IsFailed)
return Result.Fail<Guid>(new Error($"Failed to compute hash for lead -> Google ClickId: {request.ClickId}, App ClickId: {request.AppClickId}, Web ClickId: {request.WebClickId}")
.CausedBy(hashResult.Errors));
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var newLead = context.Leads.Add(new Entities.Lead
{
WebClickId = request.WebClickId,
AppClickId = request.AppClickId,
Source = request.Source,
ClickId = request.ClickId,
AdGroupId = request.AdGroupId,
AdName = request.AdName,
CampaignId = request.CampaignId,
ClickLocation = request.ClickLocation,
CustomerId = request.CustomerId,
FeedItemId = request.FeedItemId,
Status = Models.LeadStatus.New,
TargetId = request.TargetId,
AttributionHash = hashResult.Value
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newLead.Entity.Id)
: Result.Fail<Guid>(new Error($"Failed to create lead -> Google ClickId: {request.ClickId}, App ClickId: {request.AppClickId}, Web ClickId: {request.WebClickId}"));
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,29 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Leads.Commands.Handlers;
public class UpdateLeadCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<UpdateLeadCommand, Result>
{
public async ValueTask<Result> Handle(UpdateLeadCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var lead = await context.Leads.FirstOrDefaultAsync(l => l.Id == request.LeadId, cancellationToken);
if (lead is null)
return Result.Fail(new Error($"Lead with ID {request.LeadId} not found."));
lead.Status = request.Status;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail(new Error($"Failed to update the lead {request.LeadId}."));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,28 +0,0 @@
using LiteCharms.Features.Shop;
using LiteCharms.Models;
namespace LiteCharms.Features.Leads.Commands;
public class UpdateLeadCommand : IRequest<Result>
{
public Guid LeadId { get; set; }
public LeadStatus Status { get; set; }
private UpdateLeadCommand(Guid leadId, LeadStatus status)
{
LeadId = leadId;
Status = status;
}
public static UpdateLeadCommand Create(Guid leadId, LeadStatus status)
{
if (leadId == Guid.Empty)
throw new ArgumentException("Lead ID cannot be empty.", nameof(leadId));
if (!Enum.IsDefined(typeof(LeadStatus), status))
throw new ArgumentException("Invalid lead status.", nameof(status));
return new(leadId, status);
}
}
@@ -1,4 +1,4 @@
using LiteCharms.Features.Shop.Customers.Models; using LiteCharms.Features.Shop.Customers.Entities;
namespace LiteCharms.Features.Shop.Leads.Entities; namespace LiteCharms.Features.Shop.Leads.Entities;
@@ -4,12 +4,12 @@ public class LeadConfiguration : IEntityTypeConfiguration<Lead>
{ {
public void Configure(EntityTypeBuilder<Lead> builder) public void Configure(EntityTypeBuilder<Lead> builder)
{ {
builder.ToTable(nameof(Lead)); builder.ToTable("Leads");
builder.HasKey(f => f.Id); builder.HasKey(f => f.Id);
builder.Property(f => f.CreatedAt).ValueGeneratedOnAdd().HasDefaultValueSql("now()"); builder.Property(f => f.CreatedAt).ValueGeneratedOnAdd().HasDefaultValueSql("now()");
builder.Property(f => f.UpdatedAt).IsRequired(false); builder.Property(f => f.UpdatedAt).IsRequired(false).HasDefaultValueSql(null);
builder.Property(f => f.CustomerId).IsRequired(false); builder.Property(f => f.CustomerId);
builder.Property(f => f.Source); builder.Property(f => f.Source);
builder.Property(f => f.ClickId); builder.Property(f => f.ClickId);
builder.Property(f => f.WebClickId); builder.Property(f => f.WebClickId);
@@ -22,5 +22,10 @@ public class LeadConfiguration : IEntityTypeConfiguration<Lead>
builder.Property(f => f.ClickLocation); builder.Property(f => f.ClickLocation);
builder.Property(f => f.Status).IsRequired(); builder.Property(f => f.Status).IsRequired();
builder.Property(f => f.AttributionHash).IsRequired(true); builder.Property(f => f.AttributionHash).IsRequired(true);
builder.HasOne(f => f.Customer)
.WithMany(f => f.Leads)
.HasForeignKey(f => f.CustomerId)
.OnDelete(DeleteBehavior.Restrict);
} }
} }
@@ -0,0 +1,117 @@
using LiteCharms.Features.Extensions;
using LiteCharms.Features.Models;
using LiteCharms.Features.Shop.Leads.Models;
using LiteCharms.Features.Shop.Postgres;
using static LiteCharms.Features.Extensions.Hash;
namespace LiteCharms.Features.Shop.Leads;
public class LeadService(IDbContextFactory<ShopDbContext> contextFactory)
{
public async ValueTask<Result<Guid>> CreateLeadAsync(CreateLead request, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var newLead = context.Leads.Add(new Entities.Lead
{
WebClickId = request.WebClickId,
AppClickId = request.AppClickId,
Source = request.Source,
ClickId = request.ClickId,
AdGroupId = request.AdGroupId,
AdName = request.AdName,
CampaignId = request.CampaignId,
ClickLocation = request.ClickLocation,
CustomerId = request.CustomerId,
FeedItemId = request.FeedItemId,
Status = LeadStatus.New,
TargetId = request.TargetId,
AttributionHash = GenerateSha256HashString.Invoke($"{request.ClickId}{request.AppClickId}{request.WebClickId}")
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newLead.Entity.Id)
: Result.Fail<Guid>(new Error($"Failed to create lead -> Google ClickId: {request.ClickId}, App ClickId: {request.AppClickId}, Web ClickId: {request.WebClickId}"));
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Lead[]>> GetCustomerLeadsAsync(Guid customerId, DateRange range, CancellationToken cancellationToken = default)
{
try
{
var fromDate = range.From.ToDateTime(TimeOnly.MinValue);
var toDate = range.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var leads = await context.Leads.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(lead => lead.CustomerId == customerId)
.Where(lead => lead.CreatedAt.Date >= fromDate && lead.CreatedAt.Date <= toDate)
.ToArrayAsync(cancellationToken);
return leads?.Length > 0
? Result.Ok(leads.Select(l => l.ToModel()).ToArray())
: Result.Fail(new Error($"No customer {customerId} leads found for the specified date range {range.From} to {range.To}."));
}
catch (Exception ex)
{
return Result.Fail<Lead[]>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Lead[]>> GetLeadsAsync(DateRange range, CancellationToken cancellationToken = default)
{
try
{
var fromDate = range.From.ToDateTime(TimeOnly.MinValue);
var toDate = range.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var leads = await context.Leads.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(l => l.CreatedAt.Date >= fromDate && l.CreatedAt.Date <= toDate)
.Take(range.MaxRecords)
.ToArrayAsync(cancellationToken);
return leads?.Length > 0
? Result.Ok(leads.Select(l => l.ToModel()).ToArray())
: Result.Fail(new Error($"No leads found for the specified date range {range.From} to {range.To}."));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result> UpdateLeadAsync(Guid leadId, LeadStatus status, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var lead = await context.Leads.FirstOrDefaultAsync(l => l.Id == leadId, cancellationToken);
if (lead is null)
return Result.Fail(new Error($"Lead with ID {leadId} not found."));
lead.Status = status;
lead.UpdatedAt = DateTime.UtcNow;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail(new Error($"Failed to update the lead {leadId}."));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -4,9 +4,9 @@ public class Lead
{ {
public Guid Id { get; set; } public Guid Id { get; set; }
public DateTimeOffset CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; } public DateTime? UpdatedAt { get; set; }
public Guid? CustomerId { get; set; } public Guid? CustomerId { get; set; }
@@ -0,0 +1,28 @@
namespace LiteCharms.Features.Shop.Leads.Models;
public record CreateLead
{
public Guid? CustomerId { get; set; }
public required string Source { get; set; }
public required string ClickId { get; set; }
public required string WebClickId { get; set; }
public required string AppClickId { get; set; }
public long? CampaignId { get; set; }
public long? AdGroupId { get; set; }
public long? AdName { get; set; }
public long? TargetId { get; set; }
public long? FeedItemId { get; set; }
public string? ClickLocation { get; set; }
public string? AttribusionHash { get; set; }
}
@@ -1,30 +0,0 @@
using LiteCharms.Features.Shop.Leads.Models;
namespace LiteCharms.Features.Leads.Queries;
public class GetCustomerLeadsQuery : IRequest<Result<Lead[]>>
{
public Guid CustomerId { get; }
public DateOnly From { get; set; }
public DateOnly To { get; set; }
private GetCustomerLeadsQuery(Guid customerId, DateOnly from, DateOnly to)
{
CustomerId = customerId;
From = from;
To = to;
}
public static GetCustomerLeadsQuery Create(Guid customerId, DateOnly from, DateOnly to)
{
if(customerId == Guid.Empty)
throw new ArgumentException("Customer ID cannot be empty.", nameof(customerId));
if(from > to)
throw new ArgumentException("The 'From' date cannot be later than the 'To' date.");
return new(customerId, from, to);
}
}
@@ -1,30 +0,0 @@
using LiteCharms.Features.Shop.Leads.Models;
namespace LiteCharms.Features.Leads.Queries;
public class GetLeadsQuery : IRequest<Result<Lead[]>>
{
public DateOnly From { get; set; }
public DateOnly To { get; set; }
public int MaxRecords { get; set; }
private GetLeadsQuery(DateOnly from, DateOnly to, int maxRecords = 1000)
{
From = from;
To = to;
MaxRecords = maxRecords;
}
public static GetLeadsQuery Create(DateOnly from, DateOnly to, int maxRecords = 1000)
{
if (from > to)
throw new ArgumentException("From date cannot be greater than To date.");
if(maxRecords <= 0)
throw new ArgumentException("MaxRecords must be a positive integer.");
return new(from, to, maxRecords);
}
}
@@ -1,33 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Leads.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Leads.Queries.Handlers;
public class GetCustomerLeadsQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetCustomerLeadsQuery, Result<Lead[]>>
{
public async ValueTask<Result<Lead[]>> Handle(GetCustomerLeadsQuery request, CancellationToken cancellationToken)
{
try
{
var fromDate = request.From.ToDateTime(TimeOnly.MinValue);
var toDate = request.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var leads = await context.Leads.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(lead => lead.CustomerId == request.CustomerId)
.Where(lead => lead.CreatedAt.Date >= fromDate && lead.CreatedAt.Date <= toDate)
.ToArrayAsync(cancellationToken);
return leads?.Length > 0
? Result.Ok(leads.Select(l => l.ToModel()).ToArray())
: Result.Fail(new Error($"No customer {request.CustomerId} leads found for the specified date range {request.From} to {request.To}."));
}
catch (Exception ex)
{
return Result.Fail<Lead[]>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,33 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Leads.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Leads.Queries.Handlers;
public class GetLeadsQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetLeadsQuery, Result<Lead[]>>
{
public async ValueTask<Result<Lead[]>> Handle(GetLeadsQuery request, CancellationToken cancellationToken)
{
try
{
var fromDate = request.From.ToDateTime(TimeOnly.MinValue);
var toDate = request.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var leads = await context.Leads.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(l => l.CreatedAt.Date >= fromDate && l.CreatedAt.Date <= toDate)
.Take(request.MaxRecords)
.ToArrayAsync(cancellationToken);
return leads?.Length > 0
? Result.Ok(leads.Select(l => l.ToModel()).ToArray())
: Result.Fail(new Error($"No leads found for the specified date range {request.From} to {request.To}."));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,73 +0,0 @@
using LiteCharms.Features.Shop;
using LiteCharms.Models;
namespace LiteCharms.Features.Notifications.Commands;
public class CreateNotification : IRequest<Result<Guid>>
{
public NotificationDirection Direction { get; set; }
public string? Sender { get; set; }
public string? SenderAddress { get; set; }
public string? Subject { get; set; }
public string? Message { get; set; }
public NotificationPlatforms Platform { get; set; }
public Priorities Priority { get; set; }
public string? Recipient { get; set; }
public string? RecipientAddress { get; set; }
public string? CorrelationId { get; set; }
public CorrelationIdTypes CorrelationIdType { get; set; }
public bool IsInternal { get; set; }
public bool IsHtml { get; set; }
private CreateNotification(NotificationDirection direction, string sender, string senderAddress, string subject, string message, NotificationPlatforms platform, Priorities priority, string recipient, string recipientAddress, string correlationId, CorrelationIdTypes correlationIdType, bool isInternal, bool isHtml = false)
{
Direction = direction;
Sender = sender;
SenderAddress = senderAddress;
Subject = subject;
Message = message;
Platform = platform;
Priority = priority;
Recipient = recipient;
RecipientAddress = recipientAddress;
CorrelationId = correlationId;
CorrelationIdType = correlationIdType;
IsInternal = isInternal;
IsHtml = isHtml;
}
public static CreateNotification Create(NotificationDirection direction, string sender, string senderAddress, string subject, string message, NotificationPlatforms platform, Priorities priority, string recipient, string recipientAddress, string correlationId, CorrelationIdTypes correlationIdType, bool isInternal, bool isHtml = false)
{
if (string.IsNullOrWhiteSpace(sender))
throw new ArgumentException("Sender name is required.", nameof(sender));
if (string.IsNullOrWhiteSpace(subject))
throw new ArgumentException("Subject is required.", nameof(subject));
if (string.IsNullOrWhiteSpace(message))
throw new ArgumentException("Message is required.", nameof(message));
if (string.IsNullOrWhiteSpace(recipient))
throw new ArgumentException("Recipient name is required.", nameof(recipient));
if (string.IsNullOrWhiteSpace(recipientAddress))
throw new ArgumentException("Recipient address is required.", nameof(recipientAddress));
if (string.IsNullOrWhiteSpace(correlationId))
throw new ArgumentException("CorrelationId is required.", nameof(correlationId));
return new(direction, sender, senderAddress, subject, message, platform, priority, recipient, recipientAddress, correlationId, correlationIdType, isInternal, isHtml);
}
}
@@ -1,40 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Notifications.Commands.Handlers;
public class CreateNotificationCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<CreateNotification, Result<Guid>>
{
public async ValueTask<Result<Guid>> Handle(CreateNotification request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var newNotification = context.Notifications.Add(new Entities.Notification
{
Direction = request.Direction,
SenderName = request.Sender,
Sender = request.SenderAddress,
Recipient = request.Recipient,
RecipientAddress = request.RecipientAddress,
Subject = request.Subject,
Message = request.Message,
Platform = request.Platform,
Priority = request.Priority,
CorrelationId = request.CorrelationId,
CorrelationIdType = request.CorrelationIdType,
IsInternal = request.IsInternal,
IsHtml = request.IsHtml,
Processed = false
});
return newNotification is not null
? Result.Ok(newNotification.Entity.Id)
: Result.Fail(new Error("Failed to create notification"));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,35 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Notifications.Commands.Handlers;
public class UpdateNotificationCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<UpdateNotificationCommand, Result>
{
public async ValueTask<Result> Handle(UpdateNotificationCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var notification = await context.Notifications.FirstOrDefaultAsync(n => n.Id == request.NotificationId, cancellationToken);
if(notification is null)
return Result.Fail(new Error($"Notification with id {request.NotificationId} not found."));
notification.Processed = request.Processed;
if (request.HasError)
{
notification.HasError = request.HasError;
notification.Errors = request.Errors;
}
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail(new Error($"Failed to update notification with id {request.NotificationId}."));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,28 +0,0 @@
namespace LiteCharms.Features.Notifications.Commands;
public class UpdateNotificationCommand : IRequest<Result>
{
public Guid NotificationId { get; set; }
public bool Processed { get; set; }
public bool HasError { get; set; }
public string[]? Errors { get; set; }
private UpdateNotificationCommand(Guid notificationId, bool processed, bool hasError = false, string[]? errors = null)
{
NotificationId = notificationId;
Processed = processed;
HasError = hasError;
Errors = errors;
}
public static UpdateNotificationCommand Create(Guid notificationId, bool processed, bool hasError = false, string[]? errors = null)
{
if(notificationId == Guid.Empty)
throw new ArgumentException("Notification ID cannot be empty.", nameof(notificationId));
return new(notificationId, processed);
}
}
@@ -4,19 +4,19 @@ public class NotificationConfiguration : IEntityTypeConfiguration<Notification>
{ {
public void Configure(EntityTypeBuilder<Notification> builder) public void Configure(EntityTypeBuilder<Notification> builder)
{ {
builder.ToTable(nameof(Notification)); builder.ToTable("Notification");
builder.HasKey(f => f.Id); builder.HasKey(f => f.Id);
builder.Property(f => f.CreatedAt).IsRequired().ValueGeneratedOnAdd().HasDefaultValueSql("now()"); builder.Property(f => f.CreatedAt).IsRequired().ValueGeneratedOnAdd().HasDefaultValueSql("now()");
builder.Property(f => f.UpdatedAt).IsRequired(false); builder.Property(f => f.UpdatedAt).IsRequired(false).HasDefaultValueSql(null);
builder.Property(f => f.Direction).IsRequired().HasConversion<int>(); builder.Property(f => f.Direction).IsRequired().HasConversion<int>();
builder.Property(f => f.Platform).IsRequired().HasConversion<int>(); builder.Property(f => f.Platform).IsRequired().HasConversion<int>();
builder.Property(f => f.Priority).IsRequired().HasConversion<int>(); builder.Property(f => f.Priority).IsRequired().HasConversion<int>();
builder.Property(f => f.CorrelationIdType).IsRequired().HasConversion<int>(); builder.Property(f => f.CorrelationIdType).IsRequired().HasConversion<int>();
builder.Property(f => f.Sender).IsRequired(); builder.Property(f => f.SenderAddress).IsRequired();
builder.Property(f => f.Subject).IsRequired(); builder.Property(f => f.Subject).IsRequired();
builder.Property(f => f.Message).IsRequired(); builder.Property(f => f.Message).IsRequired();
builder.Property(f => f.Recipient).IsRequired(); builder.Property(f => f.RecipientName).IsRequired();
builder.Property(f => f.RecipientAddress).IsRequired(); builder.Property(f => f.RecipientAddress).IsRequired();
builder.Property(f => f.CorrelationId).IsRequired(); builder.Property(f => f.CorrelationId).IsRequired();
builder.Property(f => f.IsHtml).HasDefaultValue(false); builder.Property(f => f.IsHtml).HasDefaultValue(false);
@@ -1,13 +1,14 @@
using LiteCharms.Features.Email.Commands; using LiteCharms.Features.Email;
using LiteCharms.Features.Shop.Notifications.Entities; using LiteCharms.Features.Shop.Notifications.Models;
using LiteCharms.Features.Shop.Postgres; using LiteCharms.Features.Shop.Postgres;
using static LiteCharms.Features.ServiceBus.Constants;
namespace LiteCharms.Features.Notifications.Events.Handlers; namespace LiteCharms.Features.Shop.Notifications.Events.Handlers;
public class ProcessEmailNotificationsEventHandler(IDbContextFactory<ShopDbContext> contextFactory, ILogger<ProcessEmailNotificationsEvent> logger, ISender mediator) : public class ProcessEmailNotificationsEventHandler(IDbContextFactory<ShopDbContext> contextFactory, ILogger<ProcessEmailNotificationsEvent> logger,
INotificationHandler<ProcessEmailNotificationsEvent> EmailService emailService) : INotificationHandler<ProcessEmailNotificationsEvent>
{ {
private bool dropBatch = false;
public async ValueTask Handle(ProcessEmailNotificationsEvent message, CancellationToken cancellationToken) public async ValueTask Handle(ProcessEmailNotificationsEvent message, CancellationToken cancellationToken)
{ {
try try
@@ -15,16 +16,18 @@ public class ProcessEmailNotificationsEventHandler(IDbContextFactory<ShopDbConte
using var context = await contextFactory.CreateDbContextAsync(cancellationToken); using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var notifications = await context.Notifications var notifications = await context.Notifications
.OrderByDescending(o => o.Priority) .OrderByDescending(o => o.CreatedAt)
.ThenBy(o => o.CreatedAt) .ThenBy(o => o.Priority)
.Where(n => n.CorrelationIdType == Models.CorrelationIdTypes.Email) .Where(n => n.CorrelationIdType == CorrelationIdTypes.Email)
.Where(n => n.Direction == Models.NotificationDirection.Outgoing) .Where(n => n.Direction == NotificationDirection.Outgoing)
.Take(message.MaxRecords) .Take(message.MaxRecords)
.ToListAsync(cancellationToken); .ToListAsync(cancellationToken);
foreach (var notification in notifications) foreach (var notification in notifications)
{ {
var sendResult = await SendEmailAsync(notification, cancellationToken); if (dropBatch || cancellationToken.IsCancellationRequested) break;
var sendResult = await SendEmailAsync(notification,emailService, cancellationToken);
if(sendResult.IsFailed) if(sendResult.IsFailed)
{ {
@@ -40,6 +43,7 @@ public class ProcessEmailNotificationsEventHandler(IDbContextFactory<ShopDbConte
} }
notification.Processed = true; notification.Processed = true;
notification.UpdatedAt = DateTime.UtcNow;
} }
await context.SaveChangesAsync(cancellationToken); await context.SaveChangesAsync(cancellationToken);
@@ -50,17 +54,23 @@ public class ProcessEmailNotificationsEventHandler(IDbContextFactory<ShopDbConte
} }
} }
private async Task<Result> SendEmailAsync(Notification notification, CancellationToken cancellationToken = default) private async Task<Result> SendEmailAsync(Notification notification, EmailService service, CancellationToken cancellationToken = default)
{ {
try try
{ {
var request = SendEmailCommand.Create(notification.Sender!, notification.SenderName!, ShopEmailFromAddress, using Email.Models.Message message = CreateMessage(notification);
ShopEmailFromName, notification.Subject!, notification.Message!);
var result = await mediator.Send(request, cancellationToken); var sendResult = await service.SendEmailAsync(message, cancellationToken);
return result.IsFailed if (sendResult.IsFailed)
? Result.Fail(result.Errors) {
if (emailService.Status != EmailStatuses.Success && emailService.Status != EmailStatuses.Connected) dropBatch = true;
return Result.Fail(sendResult.Errors);
}
return sendResult.IsFailed
? Result.Fail(sendResult.Errors)
: Result.Ok(); : Result.Ok();
} }
catch (Exception ex) catch (Exception ex)
@@ -68,4 +78,29 @@ public class ProcessEmailNotificationsEventHandler(IDbContextFactory<ShopDbConte
return Result.Fail(new Error(ex.Message).CausedBy(ex)); return Result.Fail(new Error(ex.Message).CausedBy(ex));
} }
} }
private static Email.Models.Message CreateMessage(Notification notification) =>
new()
{
Sender = new Email.Models.Party
{
Name = notification.SenderName,
Address = notification.SenderAddress
},
Recipient = new Email.Models.Party
{
Name = notification.RecipientName,
Address = notification.RecipientAddress
},
Subject = notification.Subject,
Body = new Email.Models.Body
{
Properties = new Email.Models.BodyProperties
{
HasAttachments = false,
IsHtml = notification.IsHtml
},
Message = notification.Message
}
};
} }
@@ -1,6 +1,6 @@
using LiteCharms.Features.Abstractions; using LiteCharms.Features.Abstractions;
namespace LiteCharms.Features.Notifications.Events; namespace LiteCharms.Features.Shop.Notifications.Events;
public class ProcessEmailNotificationsEvent : EventBase, IEvent public class ProcessEmailNotificationsEvent : EventBase, IEvent
{ {
@@ -1,9 +0,0 @@
using LiteCharms.Features.Shop.Notifications.Models;
namespace LiteCharms.Features.Shop.Notifications;
public interface INotificationService
{
Task<Result<Guid>> CreateNotificationAsync(CreateNotification request, CancellationToken cancellationToken = default);
Task<Result> UpdateNotificationAsync(UpdateNotification request, CancellationToken cancellationToken = default);
}
@@ -4,9 +4,9 @@ public class Notification
{ {
public Guid Id { get; set; } public Guid Id { get; set; }
public DateTimeOffset CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; } public DateTime? UpdatedAt { get; set; }
public NotificationDirection Direction { get; set; } public NotificationDirection Direction { get; set; }
@@ -16,7 +16,7 @@ public class Notification
public CorrelationIdTypes CorrelationIdType { get; set; } public CorrelationIdTypes CorrelationIdType { get; set; }
public string? Sender { get; set; } public string? SenderAddress { get; set; }
public string? SenderName { get; set; } public string? SenderName { get; set; }
@@ -24,7 +24,7 @@ public class Notification
public string? Message { get; set; } public string? Message { get; set; }
public string? Recipient { get; set; } public string? RecipientName { get; set; }
public string? RecipientAddress { get; set; } public string? RecipientAddress { get; set; }
@@ -2,23 +2,23 @@
public record CreateNotification public record CreateNotification
{ {
public NotificationDirection Direction { get; set; } public required NotificationDirection Direction { get; set; }
public string? Sender { get; set; } public required string Sender { get; set; }
public string? SenderAddress { get; set; } public required string SenderAddress { get; set; }
public string? Subject { get; set; } public required string Subject { get; set; }
public string? Message { get; set; } public string? Message { get; set; }
public NotificationPlatforms Platform { get; set; } public required NotificationPlatforms Platform { get; set; }
public Priorities Priority { get; set; } public required Priorities Priority { get; set; }
public string? Recipient { get; set; } public required string Recipient { get; set; }
public string? RecipientAddress { get; set; } public required string RecipientAddress { get; set; }
public string? CorrelationId { get; set; } public string? CorrelationId { get; set; }
@@ -31,9 +31,9 @@ public record CreateNotification
public class UpdateNotification public class UpdateNotification
{ {
public Guid NotificationId { get; set; } public required Guid NotificationId { get; set; }
public bool Processed { get; set; } public required bool Processed { get; set; }
public bool HasError { get; set; } public bool HasError { get; set; }
@@ -1,5 +1,115 @@
namespace LiteCharms.Features.Shop.Notifications; using LiteCharms.Features.Extensions;
using LiteCharms.Features.Models;
using LiteCharms.Features.Shop.Notifications.Models;
using LiteCharms.Features.Shop.Postgres;
public class NotificationService : INotificationService namespace LiteCharms.Features.Shop.Notifications;
public class NotificationService(IDbContextFactory<ShopDbContext> contextFactory)
{ {
public async ValueTask<Result<Guid>> CreateNotificationAsync(CreateNotification request, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var newNotification = context.Notifications.Add(new Entities.Notification
{
Direction = request.Direction,
SenderName = request.Sender,
SenderAddress = request.SenderAddress,
RecipientName = request.Recipient,
RecipientAddress = request.RecipientAddress,
Subject = request.Subject,
Message = request.Message,
Platform = request.Platform,
Priority = request.Priority,
CorrelationId = request.CorrelationId,
CorrelationIdType = request.CorrelationIdType,
IsInternal = request.IsInternal,
IsHtml = request.IsHtml,
Processed = false
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newNotification.Entity.Id)
: Result.Fail(new Error("Failed to create notification"));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Notification>> GetNotificationAsync(Guid notificationId, CancellationToken cancellationToken = default)
{
try
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var notification = await context.Notifications.FirstOrDefaultAsync(n => n.Id == notificationId, cancellationToken);
return notification is not null
? Result.Ok(notification.ToModel())
: Result.Fail<Notification>(new Error($"Notification with id {notificationId} not found"));
}
catch (Exception ex)
{
return Result.Fail<Notification>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Notification[]>> GetNotificationsAsync(DateRange range, CancellationToken cancellationToken = default)
{
try
{
var fromDate = range.From.ToDateTime(TimeOnly.MinValue);
var toDate = range.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var notifications = await context.Notifications.AsNoTracking()
.Where(n => n.CreatedAt >= fromDate && n.CreatedAt <= toDate)
.OrderByDescending(n => n.CreatedAt)
.Take(range.MaxRecords)
.ToArrayAsync(cancellationToken);
return notifications?.Length > 0
? Result.Ok(notifications.Select(n => n.ToModel()).ToArray())
: Result.Fail(new Error($"No notifications found for the specified date range {range.From} to {range.To}."));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result> UpdateNotificationAsync(UpdateNotification request, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var notification = await context.Notifications.FirstOrDefaultAsync(n => n.Id == request.NotificationId, cancellationToken);
if (notification is null)
return Result.Fail(new Error($"Notification with id {request.NotificationId} not found."));
notification.Processed = request.Processed;
if (request.HasError)
{
notification.HasError = request.HasError;
notification.Errors = request.Errors;
}
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail(new Error($"Failed to update notification with id {request.NotificationId}."));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
} }
@@ -1,18 +0,0 @@
using LiteCharms.Features.Shop.Notifications.Models;
namespace LiteCharms.Features.Notifications.Queries;
public class GetNotificationQuery : IRequest<Result<Notification>>
{
public Guid NotificationId { get; set; }
private GetNotificationQuery(Guid notificationId) => NotificationId = notificationId;
public static GetNotificationQuery Create(Guid notificationId)
{
if (notificationId == Guid.Empty)
throw new ArgumentException("Notification ID is required.", nameof(notificationId));
return new(notificationId);
}
}
@@ -1,30 +0,0 @@
using LiteCharms.Features.Shop.Notifications.Models;
namespace LiteCharms.Features.Notifications.Queries;
public class GetNotificationsQuery : IRequest<Result<Notification[]>>
{
public DateOnly From { get; set; }
public DateOnly To { get; set; }
public int MaxRecords { get; set; }
private GetNotificationsQuery(DateOnly from, DateOnly to, int maxRecords = 1000)
{
From = from;
To = to;
MaxRecords = maxRecords;
}
public static GetNotificationsQuery Create(DateOnly from, DateOnly to, int maxRecords = 1000)
{
if (from > to)
throw new ArgumentException("From date cannot be greater than To date.");
if(maxRecords <= 0)
throw new ArgumentException("MaxRecords must be a positive integer.", nameof(maxRecords));
return new(from, to, maxRecords);
}
}
@@ -1,26 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Notifications.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Notifications.Queries.Handlers;
public class GetNotificationQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetNotificationQuery, Result<Notification>>
{
public async ValueTask<Result<Notification>> Handle(GetNotificationQuery request, CancellationToken cancellationToken)
{
try
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var notification = await context.Notifications.FirstOrDefaultAsync(n => n.Id == request.NotificationId, cancellationToken);
return notification is not null
? Result.Ok(notification.ToModel())
: Result.Fail<Notification>(new Error($"Notification with id {request.NotificationId} not found"));
}
catch (Exception ex)
{
return Result.Fail<Notification>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,33 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Notifications.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Notifications.Queries.Handlers;
public class GetNotificationsQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetNotificationsQuery, Result<Notification[]>>
{
public async ValueTask<Result<Notification[]>> Handle(GetNotificationsQuery request, CancellationToken cancellationToken)
{
try
{
var fromDate = request.From.ToDateTime(TimeOnly.MinValue);
var toDate = request.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var notifications = await context.Notifications.AsNoTracking()
.Where(n => n.CreatedAt >= fromDate && n.CreatedAt <= toDate)
.OrderByDescending(n => n.CreatedAt)
.Take(request.MaxRecords)
.ToArrayAsync(cancellationToken);
return notifications?.Length > 0
? Result.Ok(notifications.Select(n => n.ToModel()).ToArray())
: Result.Fail(new Error($"No notifications found for the specified date range {request.From} to {request.To}."));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,40 +0,0 @@
namespace LiteCharms.Features.Orders.Commands;
public class CreateOrderCommand : IRequest<Result<Guid>>
{
public Guid CustomerId { get; set; }
public Guid ShoppingCartId { get; set; }
public Guid? QuoteId { get; set; }
public string[]? Requirements { get; set; }
public string[]? Notes { get; set; }
public string[]? Terms { get; set; }
public bool DepositRequired { get; set; }
private CreateOrderCommand(Guid customerId, Guid shoppingCartId, bool depositRequired, Guid? quoteId = null, string[]? requirements = null, string[]? notes = null, string[]? terms = null)
{
CustomerId = customerId;
ShoppingCartId = shoppingCartId;
DepositRequired = depositRequired;
QuoteId = quoteId;
Requirements = requirements;
Notes = notes;
Terms = terms;
}
public static CreateOrderCommand Create(Guid customerId, Guid shoppingCartId, bool depositRequired, Guid? quoteId = null, string[]? requirements = null, string[]? notes = null, string[]? terms = null)
{
if (customerId == Guid.Empty)
throw new ArgumentException("CustomerId is required.", nameof(customerId));
if (shoppingCartId == Guid.Empty)
throw new ArgumentException("ShoppingCartId is required.", nameof(shoppingCartId));
return new(customerId, shoppingCartId, depositRequired, quoteId, requirements, notes, terms);
}
}
@@ -1,46 +0,0 @@
using LiteCharms.Features.Shop;
using LiteCharms.Features.Shop.Postgres;
using LiteCharms.Models;
namespace LiteCharms.Features.Orders.Commands.Handlers;
public class CreateOrderCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<CreateOrderCommand, Result<Guid>>
{
public async ValueTask<Result<Guid>> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if(!await context.Customers.AnyAsync(c => c.Id == request.CustomerId, cancellationToken))
return Result.Fail<Guid>(new Error($"Customer {request.CustomerId} does not exist."));
if(!await context.ShoppingCarts.AnyAsync(sc => sc.Id == request.ShoppingCartId, cancellationToken))
return Result.Fail<Guid>(new Error($"Shopping cart {request.ShoppingCartId} does not exist."));
if(request.QuoteId.HasValue && !await context.Quotes.AnyAsync(q => q.Id == request.QuoteId.Value, cancellationToken))
return Result.Fail<Guid>(new Error($"Quote {request.QuoteId.Value} does not exist."));
var newOrder = context.Orders.Add(new Entities.Order
{
CreatedAt = DateTime.UtcNow,
Status = OrderStatus.Pending,
CustomerId = request.CustomerId,
QuoteId = request.QuoteId,
ShoppingCartId = request.ShoppingCartId,
DepositRequired = request.DepositRequired,
Requirements = request.Requirements,
Notes = request.Notes,
Terms = request.Terms
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newOrder.Entity.Id)
: Result.Fail<Guid>(new Error($"Failed to create customer {request.CustomerId} order using shopping cart {request.ShoppingCartId}."));
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,29 +0,0 @@
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Orders.Commands.Handlers;
public class UpdateOrderStatusCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<UpdateOrderStatusCommand, Result>
{
public async ValueTask<Result> Handle(UpdateOrderStatusCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var order = await context.Orders.FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
if (order is null)
return Result.Fail(new Error($"Order {request.OrderId} not found"));
order.Status = request.Status;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail(new Error($"Failed to update order {request.OrderId}"));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,31 +0,0 @@
using LiteCharms.Features.Shop;
using LiteCharms.Models;
namespace LiteCharms.Features.Orders.Commands;
public class UpdateOrderStatusCommand : IRequest<Result>
{
public Guid OrderId { get; set; }
public OrderStatus Status { get; set; }
public string? Note { get; set; }
private UpdateOrderStatusCommand(Guid orderId, OrderStatus status, string? note)
{
OrderId = orderId;
Status = status;
Note = note;
}
public static UpdateOrderStatusCommand Create(Guid orderId, OrderStatus status, string? note)
{
if (orderId == Guid.Empty)
throw new ArgumentException("OrderId is required.", nameof(orderId));
if (!Enum.IsDefined(typeof(OrderStatus), status))
throw new ArgumentException("Invalid order status.", nameof(status));
return new(orderId, status, note);
}
}
@@ -4,11 +4,11 @@ public class OrderConfiguration : IEntityTypeConfiguration<Order>
{ {
public void Configure(EntityTypeBuilder<Order> builder) public void Configure(EntityTypeBuilder<Order> builder)
{ {
builder.ToTable(nameof(Order)); builder.ToTable("Orders");
builder.HasKey(f => f.Id); builder.HasKey(f => f.Id);
builder.Property(f => f.CreatedAt).ValueGeneratedOnAdd().HasDefaultValueSql("now()"); builder.Property(f => f.CreatedAt).ValueGeneratedOnAdd().HasDefaultValueSql("now()");
builder.Property(f => f.UpdatedAt).IsRequired(false); builder.Property(f => f.UpdatedAt).IsRequired(false).HasDefaultValueSql(null);
builder.Property(f => f.CustomerId).IsRequired(); builder.Property(f => f.CustomerId).IsRequired();
builder.Property(f => f.Status).HasConversion<int>().IsRequired(); builder.Property(f => f.Status).HasConversion<int>().IsRequired();
builder.Property(f => f.Requirements).HasColumnType("jsonb").IsRequired(false); builder.Property(f => f.Requirements).HasColumnType("jsonb").IsRequired(false);
@@ -3,5 +3,6 @@
[EntityTypeConfiguration<OrderRefundConfiguration, OrderRefund>] [EntityTypeConfiguration<OrderRefundConfiguration, OrderRefund>]
public class OrderRefund : Models.OrderRefund public class OrderRefund : Models.OrderRefund
{ {
public virtual Order? Order { get; set; } public virtual Order? Order { get; set; }
} }
@@ -4,7 +4,7 @@ public class OrderRefundConfiguration : IEntityTypeConfiguration<OrderRefund>
{ {
public void Configure(EntityTypeBuilder<OrderRefund> builder) public void Configure(EntityTypeBuilder<OrderRefund> builder)
{ {
builder.ToTable(nameof(OrderRefund)); builder.ToTable("OrderRefunds");
builder.HasKey(f => f.Id); builder.HasKey(f => f.Id);
builder.Property(f => f.CreatedAt).ValueGeneratedOnAdd().HasDefaultValueSql("now()"); builder.Property(f => f.CreatedAt).ValueGeneratedOnAdd().HasDefaultValueSql("now()");
@@ -4,9 +4,9 @@ public class Order
{ {
public Guid Id { get; set; } public Guid Id { get; set; }
public DateTimeOffset CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; } public DateTime? UpdatedAt { get; set; }
public Guid CustomerId { get; set; } public Guid CustomerId { get; set; }
@@ -4,7 +4,7 @@ public class OrderRefund
{ {
public Guid Id { get; set; } public Guid Id { get; set; }
public DateTimeOffset CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public Guid OrderId { get; set; } public Guid OrderId { get; set; }
@@ -0,0 +1,40 @@
namespace LiteCharms.Features.Shop.Orders.Models;
public record CreateOrder
{
public required Guid CustomerId { get; set; }
public required Guid ShoppingCartId { get; set; }
public Guid? QuoteId { get; set; }
public string[]? Requirements { get; set; }
public string[]? Notes { get; set; }
public string[]? Terms { get; set; }
}
public record UpdateOrder
{
public required Guid OrderId { get; set; }
public required OrderStatus Status { get; set; }
public string? InvoiceUrl { get; set; }
public string[]? Notes { get; set; }
public string[]? Requirements { get; set; }
}
public record RefundCustomer
{
public required Guid OrderId { get; set; }
public required Guid CustomerId { get; set; }
public required string Reason { get; set; }
public required decimal Amount { get; set; }
}
@@ -0,0 +1,259 @@
using LiteCharms.Features.Extensions;
using LiteCharms.Features.Models;
using LiteCharms.Features.Shop.Orders.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Shop.Orders;
public class OrderService(IDbContextFactory<ShopDbContext> contextFactory)
{
public async ValueTask<Result<Guid>> CreateOrderAsync(CreateOrder request, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Customers.AnyAsync(c => c.Id == request.CustomerId, cancellationToken))
return Result.Fail<Guid>(new Error($"Customer {request.CustomerId} does not exist."));
if (!await context.ShoppingCarts.AnyAsync(sc => sc.Id == request.ShoppingCartId, cancellationToken))
return Result.Fail<Guid>(new Error($"Shopping cart {request.ShoppingCartId} does not exist."));
if (request.QuoteId.HasValue && !await context.Quotes.AnyAsync(q => q.Id == request.QuoteId.Value, cancellationToken))
return Result.Fail<Guid>(new Error($"Quote {request.QuoteId.Value} does not exist."));
var newOrder = context.Orders.Add(new Entities.Order
{
Status = OrderStatus.Pending,
CustomerId = request.CustomerId,
Requirements = request.Requirements,
Notes = request.Notes,
Terms = request.Terms
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(newOrder.Entity.Id)
: Result.Fail<Guid>(new Error($"Failed to create customer {request.CustomerId} order using shopping cart {request.ShoppingCartId}."));
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<OrderRefund[]>> GetCustomerOrderRefundsAsync(Guid customerId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Customers.AnyAsync(c => c.Id == customerId, cancellationToken))
return Result.Fail<OrderRefund[]>(new Error($"Customer with Id {customerId} does not exist."));
var refunds = await context.OrderRefunds.AsNoTracking().AsSplitQuery()
.OrderByDescending(o => o.CreatedAt)
.Where(r => r.Order!.CustomerId == customerId).ToArrayAsync(cancellationToken);
return refunds?.Length > 0
? Result.Ok(refunds.Select(r => r.ToModel()).ToArray())
: Result.Fail<OrderRefund[]>(new Error($"No refunds found for customer with Id {customerId}."));
}
catch (Exception ex)
{
return Result.Fail<OrderRefund[]>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Order[]>> GetCustomerOrdersAsync(Guid customerId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Customers.AsNoTracking().AnyAsync(c => c.Id == customerId, cancellationToken))
return Result.Fail<Order[]>(new Error($"Customer with Id {customerId} does not exist."));
var orders = await context.Orders.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(o => o.CustomerId == customerId)
.ToArrayAsync(cancellationToken);
return orders?.Length > 0
? Result.Ok(orders.Select(o => o.ToModel()).ToArray())
: Result.Fail<Order[]>(new Error($"No orders found for customer with Id {customerId}."));
}
catch (Exception ex)
{
return Result.Fail<Order[]>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<OrderRefund>> GetOrderRefundAsync(Guid orderId, Guid orderRefundId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var refund = await context.OrderRefunds.AsNoTracking()
.FirstOrDefaultAsync(r => r.OrderId == orderId && r.Id == orderRefundId, cancellationToken);
return refund is not null
? Result.Ok(refund.ToModel())
: Result.Fail<OrderRefund>(new Error($"Refund {orderRefundId} not found for the given OrderId: {orderId}"));
}
catch (Exception ex)
{
return Result.Fail<OrderRefund>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<OrderRefund>> GetOrderRefundAsync(Guid orderRefundId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var refund = await context.OrderRefunds.AsNoTracking().FirstOrDefaultAsync(r => r.Id == orderRefundId, cancellationToken);
return refund is not null
? Result.Ok(refund.ToModel())
: Result.Fail<OrderRefund>($"Order refund could not be found with id {orderRefundId}");
}
catch (Exception ex)
{
return Result.Fail<OrderRefund>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<OrderRefund[]>> GetOrderRefundsAsync(Guid orderId, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var refunds = await context.OrderRefunds.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(r => r.OrderId == orderId)
.ToArrayAsync(cancellationToken);
return refunds?.Length > 0
? Result.Ok(refunds.Select(r => r.ToModel()).ToArray())
: Result.Fail<OrderRefund[]>($"Order refunds could not be found with order id {orderId}");
}
catch (Exception ex)
{
return Result.Fail<OrderRefund[]>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Order[]>> GetOrdersAsync(DateRange range, CancellationToken cancellationToken = default)
{
try
{
var fromDate = range.From.ToDateTime(TimeOnly.MinValue);
var toDate = range.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var orders = await context.Orders
.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(o => o.CreatedAt >= fromDate && o.CreatedAt <= toDate)
.Take(range.MaxRecords)
.ToArrayAsync(cancellationToken);
return orders?.Length > 0
? Result.Ok(orders.Select(o => o.ToModel()).ToArray())
: Result.Fail<Order[]>(new Error($"No orders found for the specified date range {range.From} - {range.To}."));
}
catch (Exception ex)
{
return Result.Fail<Order[]>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result<Guid>> RefundCustomerAsync(RefundCustomer request, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!await context.Orders.AnyAsync(o => o.Id == request.OrderId, cancellationToken))
return Result.Fail<Guid>(new Error($"Order with Id: {request.OrderId} does not exist"));
if (!await context.Customers.AnyAsync(c => c.Id == request.CustomerId, cancellationToken))
return Result.Fail<Guid>(new Error($"Customer with Id: {request.CustomerId} does not exist"));
if (!await context.Orders.AnyAsync(o => o.Id == request.OrderId && o.CustomerId == request.CustomerId, cancellationToken))
return Result.Fail<Guid>(new Error($"Order with Id: {request.OrderId} does not belong to Customer with Id: {request.CustomerId}"));
var refund = context.OrderRefunds.Add(new Entities.OrderRefund
{
OrderId = request.OrderId,
Reason = request.Reason,
Amount = request.Amount
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(refund.Entity.Id)
: Result.Fail<Guid>(new Error($"Failed to create refund for OrderId: {request.OrderId}"));
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result> UpdateOrderRefundAsync(Guid orderRefundId, string reason, decimal amount, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var refund = await context.OrderRefunds.FirstOrDefaultAsync(r => r.Id == orderRefundId, cancellationToken);
if (refund is null)
return Result.Fail($"Order refund not found with id {orderRefundId}");
refund.Reason = reason;
refund.Amount = amount;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to update order refund {orderRefundId}");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
public async ValueTask<Result> UpdateOrderStatusAsync(UpdateOrder request, CancellationToken cancellationToken = default)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var order = await context.Orders.FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
if (order is null)
return Result.Fail(new Error($"Order {request.OrderId} not found"));
order.Status = request.Status;
order.UpdatedAt = DateTime.UtcNow;
if(!string.IsNullOrWhiteSpace(request.InvoiceUrl)) order.InvoiceUrl = request.InvoiceUrl;
if(request.Requirements?.Length > 0) order.Requirements = request.Requirements;
if(request.Notes?.Length > 0) order.Notes = request.Notes;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail(new Error($"Failed to update order {request.OrderId}"));
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,18 +0,0 @@
using LiteCharms.Features.Shop.Orders.Models;
namespace LiteCharms.Features.Orders.Queries;
public class GetCustomerOrdersQuery : IRequest<Result<Order[]>>
{
public Guid CustomerId { get; }
private GetCustomerOrdersQuery(Guid customerId) => CustomerId = customerId;
public static GetCustomerOrdersQuery Create(Guid customerId)
{
if (customerId == Guid.Empty)
throw new ArgumentException("CustomerId is required.", nameof(customerId));
return new(customerId);
}
}
@@ -1,27 +0,0 @@
using LiteCharms.Features.Shop.Orders.Models;
namespace LiteCharms.Features.Orders.Queries;
public class GetOrderRefundQuery : IRequest<Result<OrderRefund>>
{
public Guid OrderId { get; set; }
public Guid OrderRefundId { get; set; }
private GetOrderRefundQuery(Guid orderId, Guid orderRefundId)
{
OrderId = orderId;
OrderRefundId = orderRefundId;
}
public static GetOrderRefundQuery Create(Guid orderId, Guid orderRefundId)
{
if (orderId == Guid.Empty)
throw new ArgumentException("OrderId is required.", nameof(orderId));
if (orderRefundId == Guid.Empty)
throw new ArgumentException("OrderRefundId is required.", nameof(orderRefundId));
return new(orderId, orderRefundId);
}
}
@@ -1,30 +0,0 @@
using LiteCharms.Features.Shop.Orders.Models;
namespace LiteCharms.Features.Orders.Queries;
public class GetOrdersQuery : IRequest<Result<Order[]>>
{
public DateOnly From { get; set; }
public DateOnly To { get; set; }
public int MaxRecords { get; set; }
private GetOrdersQuery(DateOnly from, DateOnly to, int maxRecords = 1000)
{
From = from;
To = to;
MaxRecords = maxRecords;
}
public static GetOrdersQuery Create(DateOnly from, DateOnly to, int maxRecords = 1000)
{
if (from > to)
throw new ArgumentException("From date cannot be greater than To date.");
if(maxRecords <= 0)
throw new ArgumentException("MaxRecords must be a positive integer.");
return new(from, to, maxRecords);
}
}
@@ -1,32 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Orders.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Orders.Queries.Handlers;
public class GetCustomerOrdersQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetCustomerOrdersQuery, Result<Order[]>>
{
public async ValueTask<Result<Order[]>> Handle(GetCustomerOrdersQuery request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if(!await context.Customers.AsNoTracking().AnyAsync(c => c.Id == request.CustomerId, cancellationToken))
return Result.Fail<Order[]>(new Error($"Customer with Id {request.CustomerId} does not exist."));
var orders = await context.Orders.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(o => o.CustomerId == request.CustomerId)
.ToArrayAsync(cancellationToken);
return orders?.Length > 0
? Result.Ok(orders.Select(o => o.ToModel()).ToArray())
: Result.Fail<Order[]>(new Error($"No orders found for customer with Id {request.CustomerId}."));
}
catch (Exception ex)
{
return Result.Fail<Order[]>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,27 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Orders.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Orders.Queries.Handlers;
public class GetOrderRefundQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetOrderRefundQuery, Result<OrderRefund>>
{
public async ValueTask<Result<OrderRefund>> Handle(GetOrderRefundQuery request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var refund = await context.OrderRefunds.AsNoTracking()
.FirstOrDefaultAsync(r => r.OrderId == request.OrderId && r.Id == request.OrderRefundId, cancellationToken);
return refund is not null
? Result.Ok(refund.ToModel())
: Result.Fail<OrderRefund>(new Error($"Refund {request.OrderRefundId} not found for the given OrderId: {request.OrderId}"));
}
catch (Exception ex)
{
return Result.Fail<OrderRefund>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,34 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Orders.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Orders.Queries.Handlers;
public class GetOrdersQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetOrdersQuery, Result<Order[]>>
{
public async ValueTask<Result<Order[]>> Handle(GetOrdersQuery request, CancellationToken cancellationToken)
{
try
{
var fromDate = request.From.ToDateTime(TimeOnly.MinValue);
var toDate = request.To.ToDateTime(TimeOnly.MaxValue);
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var orders = await context.Orders
.AsNoTracking()
.OrderByDescending(o => o.CreatedAt)
.Where(o => o.CreatedAt >= fromDate && o.CreatedAt <= toDate)
.Take(request.MaxRecords)
.ToArrayAsync(cancellationToken);
return orders?.Length > 0
? Result.Ok(orders.Select(o => o.ToModel()).ToArray())
: Result.Fail<Order[]>(new Error($"No orders found for the specified date range {request.From} - {request.To}."));
}
catch (Exception ex)
{
return Result.Fail<Order[]>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,39 +0,0 @@
using LiteCharms.Features.Shop.Orders.Refunds.Commands;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Shop.Orders.Refunds.Commands.Handlers;
public class RefundCustomerCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<RefundCustomerCommand, Result<Guid>>
{
public async ValueTask<Result<Guid>> Handle(RefundCustomerCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if(!await context.Orders.AnyAsync(o => o.Id == request.OrderId, cancellationToken))
return Result.Fail<Guid>(new Error($"Order with Id: {request.OrderId} does not exist"));
if (!await context.Customers.AnyAsync(c => c.Id == request.CustomerId, cancellationToken))
return Result.Fail<Guid>(new Error($"Customer with Id: {request.CustomerId} does not exist"));
if(!await context.Orders.AnyAsync(o => o.Id == request.OrderId && o.CustomerId == request.CustomerId, cancellationToken))
return Result.Fail<Guid>(new Error($"Order with Id: {request.OrderId} does not belong to Customer with Id: {request.CustomerId}"));
var refund = context.OrderRefunds.Add(new Entities.OrderRefund
{
OrderId = request.OrderId,
Reason = request.Reason,
Amount = request.Amount
});
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(refund.Entity.Id)
: Result.Fail<Guid>(new Error($"Failed to create refund for OrderId: {request.OrderId}"));
}
catch (Exception ex)
{
return Result.Fail<Guid>(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,31 +0,0 @@
using LiteCharms.Features.Shop.Orders.Refunds.Commands;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Shop.Orders.Refunds.Commands.Handlers;
public class UpdateOrderRefundCommandHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<UpdateOrderRefundCommand, Result>
{
public async ValueTask<Result> Handle(UpdateOrderRefundCommand request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var refund = await context.OrderRefunds.FirstOrDefaultAsync(r => r.Id == request.OrderRefundId, cancellationToken);
if (refund is null)
return Result.Fail($"Order refund not found with id {request.OrderRefundId}");
refund.Reason = request.Reason;
refund.Amount = request.Amount;
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok()
: Result.Fail($"Failed to update order refund {request.OrderRefundId}");
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
}
@@ -1,38 +0,0 @@
namespace LiteCharms.Features.Shop.Orders.Refunds.Commands;
public class RefundCustomerCommand : IRequest<Result<Guid>>
{
public Guid OrderId { get; set; }
public Guid CustomerId { get; set; }
public string? Reason { get; set; }
public decimal Amount { get; set; }
private RefundCustomerCommand(Guid orderId, Guid customerId, string? reason, decimal amount)
{
OrderId = orderId;
CustomerId = customerId;
Reason = reason;
Amount = amount;
CustomerId = customerId;
}
public static RefundCustomerCommand Create(Guid orderId, Guid customerId, string? reason, decimal amount)
{
if (orderId == Guid.Empty)
throw new ArgumentException("OrderId is required", nameof(orderId));
if (customerId == Guid.Empty)
throw new ArgumentException("CustomerId is required", nameof(customerId));
if (amount <= 0)
throw new ArgumentException("Amount must be greater than zero", nameof(amount));
if (string.IsNullOrWhiteSpace(reason))
throw new ArgumentException("Reason is required", nameof(reason));
return new(orderId, customerId, reason, amount);
}
}
@@ -1,28 +0,0 @@
namespace LiteCharms.Features.Shop.Orders.Refunds.Commands;
public class UpdateOrderRefundCommand : IRequest<Result>
{
public Guid OrderRefundId { get; set; }
public string? Reason { get; set; }
public decimal Amount { get; set; }
private UpdateOrderRefundCommand(Guid orderRefundId, string? reason, decimal amount)
{
OrderRefundId = orderRefundId;
Reason = reason;
Amount = amount;
}
public static UpdateOrderRefundCommand Create(Guid orderRefundId, string? reason, decimal amount)
{
if (orderRefundId == Guid.Empty)
throw new ArgumentException("Order refund id is required.", nameof(orderRefundId));
if (string.IsNullOrWhiteSpace(reason))
throw new ArgumentException("Refund update reason is required");
return new(orderRefundId, reason, amount);
}
}
@@ -1,18 +0,0 @@
using LiteCharms.Features.Shop.Orders.Models;
namespace LiteCharms.Features.Shop.Orders.Refunds.Queries;
public class GetCustomerRefundsQuery : IRequest<Result<OrderRefund[]>>
{
public Guid CustomerId { get; set; }
private GetCustomerRefundsQuery(Guid customerId) => CustomerId = customerId;
public static GetCustomerRefundsQuery Create(Guid customerId)
{
if (customerId == Guid.Empty)
throw new ArgumentException("CustomerId is required.", nameof(customerId));
return new(customerId);
}
}
@@ -1,18 +0,0 @@
using LiteCharms.Features.Shop.Orders.Models;
namespace LiteCharms.Features.Shop.Orders.Refunds.Queries;
public class GetRefundQuery : IRequest<Result<OrderRefund>>
{
public Guid OrderRefundId { get; set; }
private GetRefundQuery(Guid orderRefundId) => OrderRefundId = orderRefundId;
public static GetRefundQuery Create(Guid orderRefundId)
{
if(orderRefundId == Guid.Empty)
throw new ArgumentException("Customer ID is required.", nameof(orderRefundId));
return new(orderRefundId);
}
}
@@ -1,32 +0,0 @@
using LiteCharms.Extensions;
using LiteCharms.Features.Shop.Orders.Models;
using LiteCharms.Features.Shop.Orders.Refunds.Queries;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Shop.Orders.Refunds.Queries.Handlers;
public class GetCustomerRefundsQueryHandler(IDbContextFactory<ShopDbContext> contextFactory) : IRequestHandler<GetCustomerRefundsQuery, Result<OrderRefund[]>>
{
public async ValueTask<Result<OrderRefund[]>> Handle(GetCustomerRefundsQuery request, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if(!await context.Customers.AnyAsync(c => c.Id == request.CustomerId, cancellationToken))
return Result.Fail<OrderRefund[]>(new Error($"Customer with Id {request.CustomerId} does not exist."));
var refunds = await context.OrderRefunds.AsNoTracking().AsSplitQuery()
.OrderByDescending(o => o.CreatedAt)
.Where(r => r.Order!.CustomerId == request.CustomerId).ToArrayAsync(cancellationToken);
return refunds?.Length > 0
? Result.Ok(refunds.Select(r => r.ToModel()).ToArray())
: Result.Fail<OrderRefund[]>(new Error($"No refunds found for customer with Id {request.CustomerId}."));
}
catch (Exception ex)
{
return Result.Fail<OrderRefund[]>(new Error(ex.Message).CausedBy(ex));
}
}
}

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