Skip to content

Commit

Permalink
Remove seeds from the initializer and add to a script instead
Browse files Browse the repository at this point in the history
  • Loading branch information
carlsixsmith-moj committed May 31, 2024
1 parent 8179b4d commit 239fae4
Show file tree
Hide file tree
Showing 7 changed files with 246 additions and 426 deletions.
236 changes: 236 additions & 0 deletions db/seed/001_development_seed.sql

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions db/seed/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Database Seed Scripts

This directory contains SQL scripts to seed the database with initial data.

## How to Use

1. Ensure your database is created and migrated using EF Core.
2. Run the seed scripts in the alphabetical order
145 changes: 2 additions & 143 deletions src/Infrastructure/Persistence/ApplicationDbContextInitializer.cs
Original file line number Diff line number Diff line change
@@ -1,35 +1,7 @@
using System.Text.Json;
using Cfo.Cats.Domain.Common.Enums;
using Cfo.Cats.Domain.Entities.Administration;
using Cfo.Cats.Domain.Identity;
using Cfo.Cats.Infrastructure.Constants.ClaimTypes;
using Cfo.Cats.Infrastructure.Constants.Role;
using Cfo.Cats.Infrastructure.PermissionSet;
using Cfo.Cats.Infrastructure.Persistence.Initializers;
using DocumentFormat.OpenXml.Office2010.Excel;
namespace Cfo.Cats.Infrastructure.Persistence;

namespace Cfo.Cats.Infrastructure.Persistence;

public class ApplicationDbContextInitializer
public class ApplicationDbContextInitializer(ILogger<ApplicationDbContextInitializer> logger, ApplicationDbContext context)
{
private readonly ApplicationDbContext context;
private readonly ILogger<ApplicationDbContextInitializer> logger;
private readonly RoleManager<ApplicationRole> roleManager;
private readonly UserManager<ApplicationUser> userManager;

public ApplicationDbContextInitializer(
ILogger<ApplicationDbContextInitializer> logger,
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager
)
{
this.logger = logger;
this.context = context;
this.userManager = userManager;
this.roleManager = roleManager;
}

public async Task InitialiseAsync()
{
try
Expand All @@ -48,117 +20,4 @@ public async Task InitialiseAsync()
throw;
}
}

public async Task SeedAsync()
{
try
{
await TrySeedAsync();
context.ChangeTracker.Clear();
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred while seeding the database");
throw;
}
}

private async Task TrySeedAsync()
{
await SeedTenants();
await SeedContracts();
await SeedLocations();
await SeedDictionaries();

// Default roles
var administratorRole = new ApplicationRole(RoleName.Admin) { Description = "Admin Group" };
var basicRole = new ApplicationRole(RoleName.Basic) { Description = "Basic User Group" };

var permissions = Permissions.GetRegisteredPermissions();

if (roleManager.Roles.All(r => r.Name != administratorRole.Name))
{
await roleManager.CreateAsync(administratorRole);

foreach (var permission in permissions)
{
await roleManager.AddClaimAsync(
administratorRole,
new Claim(ApplicationClaimTypes.Permission, permission)
);
}
}

if (roleManager.Roles.All(r => r.Name != basicRole.Name))
{
await roleManager.CreateAsync(basicRole);
foreach (var permission in permissions.Where(p => p.EndsWith(".View")))
{
await roleManager.AddClaimAsync(basicRole, new Claim(ApplicationClaimTypes.Permission, permission));
}
}

var defaultUser = new ApplicationUser()
{
UserName = "[email protected]",
Provider = "Local",
IsActive = true,
TenantId = context.Tenants.First().Id,
TenantName = context.Tenants.First().Name,
DisplayName = "Support Worker",
Email = "[email protected]",
EmailConfirmed = true,
ProfilePictureDataUrl =
"https://avatars.githubusercontent.com/u/9332472?s=400&u=73c208bf07ba967d5407aae9068580539cfc80a2&v=4",
TwoFactorEnabled = false
};

if (userManager.Users.All(u => u.UserName != "[email protected]"))
{
await userManager.CreateAsync(defaultUser, "Password123!");
await userManager.AddToRolesAsync(defaultUser, new[] { administratorRole.Name! });
}
}
private async Task SeedDictionaries()
{
if (await context.KeyValues.AnyAsync() == false)
{
var kvps = SeedingData.GetDictionaries();
context.KeyValues.AddRange(kvps);
await context.SaveChangesAsync();
}
}

private async Task SeedLocations()
{
if (await context.Locations.AnyAsync() == false)
{
var locations = SeedingData.GetLocations();
context.Locations.AddRange(locations);
await context.SaveChangesAsync();

}
}

private async Task SeedTenants()
{
if (await context.Tenants.OrderBy(r => r.Id).Select(e => e.Id).FirstOrDefaultAsync() == null)
{
var tenants = SeedingData.GetTenants();
context.Tenants.AddRange(tenants);
await context.SaveChangesAsync();
}
}

private async Task SeedContracts()
{
if (await context.Contracts.OrderBy(r => r.Id).Select(e => e.Id).FirstOrDefaultAsync() is null)
{
var contracts = SeedingData.GetContracts();
context.Contracts.AddRange(contracts);
await context.SaveChangesAsync();
}
}


}

This file was deleted.

30 changes: 0 additions & 30 deletions src/Infrastructure/Persistence/DataSeeds/Development/Users.json

This file was deleted.

Loading

0 comments on commit 239fae4

Please sign in to comment.