PlanTempusApp/PlanTempus.Components/Organizations/Create/CreateOrganizationHandler.cs

45 lines
1.6 KiB
C#
Raw Normal View History

2025-03-03 00:42:20 +01:00
using Insight.Database;
2025-03-06 00:05:58 +01:00
using Microsoft.ApplicationInsights;
2025-03-10 15:56:22 +01:00
using PlanTempus.Core.Database;
2025-03-06 00:05:58 +01:00
using PlanTempus.Core.Telemetry;
2025-03-03 17:40:16 +01:00
2025-03-03 00:42:20 +01:00
namespace PlanTempus.Components.Organizations.Create
{
2025-03-06 00:05:58 +01:00
public class CreateOrganizationHandler(TelemetryClient telemetryClient, IDatabaseOperations databaseOperations)
2025-03-03 00:42:20 +01:00
{
2025-03-04 23:54:55 +01:00
public async Task<CreateOrganizationResult> Handle(CreateOrganizationCommand command)
2025-03-03 00:42:20 +01:00
{
2025-03-05 16:56:58 +01:00
using var db = databaseOperations.CreateScope(nameof(CreateOrganizationHandler));
2025-03-06 00:05:58 +01:00
using var transaction = db.Connection.BeginTransaction();
2025-03-03 00:42:20 +01:00
try
{
2025-03-06 00:05:58 +01:00
var createOrg = @"
INSERT INTO organizations (connection_string)
VALUES (@ConnectionString)
RETURNING id, created_at";
2025-03-03 00:42:20 +01:00
2025-03-06 00:05:58 +01:00
var data = await db.Connection.QuerySqlAsync<CreateOrganizationResult>(createOrg, new
2025-03-03 00:42:20 +01:00
{
2025-03-06 00:05:58 +01:00
command.ConnectionString
2025-03-03 00:42:20 +01:00
});
2025-03-06 00:05:58 +01:00
var orgResult = data.First();
await db.Connection.ExecuteAsync(@$"
INSERT INTO account_organizations (account_id, organization_id)
VALUES (@AccountId, @OrganizationId)",
new { command.AccountId, OrganizationId = orgResult.Id });
2025-03-06 00:05:58 +01:00
transaction.Commit();
telemetryClient.TrackTrace(GetType().Name, orgResult.Format());
return orgResult;
2025-03-03 00:42:20 +01:00
}
catch (Exception ex)
{
db.Error(ex);
throw;
}
}
}
}