feat: add auth and tenant operations persistence

This commit is contained in:
xiong
2026-07-26 05:29:16 +08:00
parent b2282cde8c
commit aa000c63aa
9 changed files with 10320 additions and 1 deletions

View File

@@ -6,6 +6,7 @@ namespace Tiku.Domain.Tenancy;
public sealed class TenantMembership : AuditableTenantEntity
{
public Guid UserId { get; set; }
public Guid? RoleTemplateId { get; set; }
public TenantRole Role { get; set; } = TenantRole.Student;
public MembershipStatus Status { get; set; } = MembershipStatus.Active;
public JsonElement Permissions { get; set; } = JsonDefaults.Object();

View File

@@ -0,0 +1,155 @@
using System.Text.Json;
using Tiku.Domain.Common;
namespace Tiku.Domain.Tenancy;
public sealed class TenantAuthProvider : AuditableTenantEntity
{
public string Provider { get; set; } = string.Empty;
public TenantAuthProviderStatus Status { get; set; } = TenantAuthProviderStatus.Disabled;
public string? DisplayName { get; set; }
public JsonElement ConfigPublic { get; set; } = JsonDefaults.Object();
}
public sealed class SmsVerificationCode : Entity
{
public Guid TenantId { get; set; }
public string Phone { get; set; } = string.Empty;
public SmsPurpose Purpose { get; set; } = SmsPurpose.Login;
public string CodeHash { get; set; } = string.Empty;
public string Provider { get; set; } = "mock";
public SmsVerificationStatus Status { get; set; } = SmsVerificationStatus.Pending;
public int Attempts { get; set; }
public DateTimeOffset ExpiresAt { get; set; }
public DateTimeOffset? ConsumedAt { get; set; }
public string? IpAddress { get; set; }
public string? UserAgent { get; set; }
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
}
public sealed class AuthLoginEvent : Entity
{
public Guid TenantId { get; set; }
public Guid? UserId { get; set; }
public string Provider { get; set; } = string.Empty;
public string? Identifier { get; set; }
public AuthLoginResult Result { get; set; } = AuthLoginResult.Failed;
public string? FailureCode { get; set; }
public string? IpAddress { get; set; }
public string? UserAgent { get; set; }
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
}
public sealed class AuthSession : AuditableTenantEntity
{
public Guid UserId { get; set; }
public string TokenHash { get; set; } = string.Empty;
public string Provider { get; set; } = string.Empty;
public DateTimeOffset ExpiresAt { get; set; }
public DateTimeOffset? RevokedAt { get; set; }
public string? IpAddress { get; set; }
public string? UserAgent { get; set; }
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
}
public sealed class SmsSendRateLimit
{
public Guid TenantId { get; set; }
public SmsRateLimitDimension Dimension { get; set; } = SmsRateLimitDimension.Phone;
public string ScopeHash { get; set; } = string.Empty;
public DateTimeOffset BucketStart { get; set; }
public int RequestCount { get; set; }
public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow;
}
public sealed class TenantRoleTemplate : AuditableTenantEntity
{
public string Code { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string? Description { get; set; }
public TenantRole BaseRole { get; set; } = TenantRole.TenantOperator;
public TenantRoleTemplateStatus Status { get; set; } = TenantRoleTemplateStatus.Active;
public JsonElement Permissions { get; set; } = JsonDefaults.Object();
public JsonElement MenuPermissions { get; set; } = JsonDefaults.Object();
public JsonElement ModulePermissions { get; set; } = JsonDefaults.Object();
public JsonElement FieldPermissions { get; set; } = JsonDefaults.Object();
public JsonElement DataScope { get; set; } = JsonDefaults.Object();
public bool IsSystem { get; set; }
public int SortOrder { get; set; } = 100;
public Guid? CreatedBy { get; set; }
public Guid? UpdatedBy { get; set; }
}
public sealed class TenantClass : AuditableTenantEntity
{
public Guid? RegionId { get; set; }
public string? LegacyId { get; set; }
public string? Code { get; set; }
public string Name { get; set; } = string.Empty;
public string? Description { get; set; }
public TenantRecordStatus Status { get; set; } = TenantRecordStatus.Active;
public int SortOrder { get; set; }
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
public Guid? CreatedBy { get; set; }
public Guid? UpdatedBy { get; set; }
}
public sealed class TenantClassMember : AuditableTenantEntity
{
public Guid ClassId { get; set; }
public Guid UserId { get; set; }
public TenantClassMemberType MemberType { get; set; } = TenantClassMemberType.Student;
public TenantClassMemberStatus Status { get; set; } = TenantClassMemberStatus.Active;
public DateTimeOffset JoinedAt { get; set; } = DateTimeOffset.UtcNow;
public DateTimeOffset? LeftAt { get; set; }
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
public Guid? CreatedBy { get; set; }
public Guid? UpdatedBy { get; set; }
}
public sealed class TenantStudentNote : AuditableTenantEntity
{
public Guid StudentUserId { get; set; }
public StudentNoteType NoteType { get; set; } = StudentNoteType.General;
public string Content { get; set; } = string.Empty;
public StudentNoteVisibility Visibility { get; set; } = StudentNoteVisibility.TenantStaff;
public bool IsPinned { get; set; }
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
public Guid? CreatedBy { get; set; }
public Guid? UpdatedBy { get; set; }
}
public sealed class TenantStudentFollowup : AuditableTenantEntity
{
public Guid StudentUserId { get; set; }
public Guid? AssignedToUserId { get; set; }
public Guid? ClassId { get; set; }
public string Title { get; set; } = string.Empty;
public string? Description { get; set; }
public StudentFollowupType FollowupType { get; set; } = StudentFollowupType.Learning;
public StudentFollowupPriority Priority { get; set; } = StudentFollowupPriority.Normal;
public StudentFollowupStatus Status { get; set; } = StudentFollowupStatus.Open;
public DateTimeOffset? DueAt { get; set; }
public DateTimeOffset? CompletedAt { get; set; }
public Guid? CompletedBy { get; set; }
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
public Guid? CreatedBy { get; set; }
public Guid? UpdatedBy { get; set; }
}
public enum TenantAuthProviderStatus { Active, Disabled, Testing }
public enum SmsPurpose { Login, BindPhone, ResetPassword }
public enum SmsVerificationStatus { Pending, Sent, Verified, Expired, Blocked }
public enum AuthLoginResult { Sent, Success, Failed, Blocked }
public enum SmsRateLimitDimension { Tenant, Phone, Ip, Device }
public enum TenantRoleTemplateStatus { Active, Disabled, Archived }
public enum TenantRecordStatus { Active, Disabled, Archived }
public enum TenantClassMemberType { Student, Teacher, Assistant, HeadTeacher }
public enum TenantClassMemberStatus { Active, Disabled, Removed }
public enum StudentNoteType { General, Learning, Service, Sales, Risk, FollowUp }
public enum StudentNoteVisibility { TenantStaff, ClassStaff, AuthorOnly }
public enum StudentFollowupType { Learning, Service, Sales, Renewal, Risk, Custom }
public enum StudentFollowupPriority { Low, Normal, High, Urgent }
public enum StudentFollowupStatus { Open, InProgress, Done, Cancelled }

View File

@@ -49,6 +49,11 @@ internal sealed class TenantMembershipConfiguration : IEntityTypeConfiguration<T
.WithMany()
.HasForeignKey(entity => entity.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne<TenantRoleTemplate>()
.WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.RoleTemplateId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Restrict);
}
}

View File

@@ -0,0 +1,268 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Tiku.Domain.Catalog;
using Tiku.Domain.Identity;
using Tiku.Domain.Tenancy;
namespace Tiku.Infrastructure.Persistence.Configurations;
internal sealed class TenantAuthProviderConfiguration : IEntityTypeConfiguration<TenantAuthProvider>
{
public void Configure(EntityTypeBuilder<TenantAuthProvider> builder)
{
builder.ConfigureTenantEntity("tenant_auth_providers");
builder.ConfigureTimestamps();
builder.Property(entity => entity.Provider).HasMaxLength(50);
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.DisplayName).HasMaxLength(200);
builder.Property(entity => entity.ConfigPublic).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.Provider }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.Provider, entity.Status });
}
}
internal sealed class SmsVerificationCodeConfiguration : IEntityTypeConfiguration<SmsVerificationCode>
{
public void Configure(EntityTypeBuilder<SmsVerificationCode> builder)
{
builder.ConfigureEntity("sms_verification_codes");
builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id });
builder.Property(entity => entity.Phone).HasMaxLength(32);
builder.Property(entity => entity.Purpose).HasSnakeCaseEnum();
builder.Property(entity => entity.CodeHash).HasMaxLength(256);
builder.Property(entity => entity.Provider).HasMaxLength(50);
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.IpAddress).HasMaxLength(64);
builder.Property(entity => entity.UserAgent).HasMaxLength(1000);
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.Property(entity => entity.CreatedAt).HasDefaultValueSql("now()");
builder.HasIndex(entity => new { entity.TenantId, entity.Phone, entity.Purpose, entity.ExpiresAt });
builder.HasIndex(entity => new { entity.TenantId, entity.Phone, entity.Purpose, entity.CreatedAt })
.HasFilter("consumed_at is null and status in ('pending', 'sent')");
builder.HasIndex(entity => new { entity.TenantId, entity.Phone, entity.Purpose })
.IsUnique()
.HasFilter("consumed_at is null and status in ('pending', 'sent')");
builder.ToTable(table =>
{
table.HasCheckConstraint("ck_sms_verification_codes_attempts", "attempts >= 0");
});
builder.HasOne<Tenant>().WithMany()
.HasForeignKey(entity => entity.TenantId)
.OnDelete(DeleteBehavior.Cascade);
}
}
internal sealed class AuthLoginEventConfiguration : IEntityTypeConfiguration<AuthLoginEvent>
{
public void Configure(EntityTypeBuilder<AuthLoginEvent> builder)
{
builder.ConfigureEntity("auth_login_events");
builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id });
builder.Property(entity => entity.Provider).HasMaxLength(50);
builder.Property(entity => entity.Identifier).HasMaxLength(320);
builder.Property(entity => entity.Result).HasSnakeCaseEnum();
builder.Property(entity => entity.FailureCode).HasMaxLength(100);
builder.Property(entity => entity.IpAddress).HasMaxLength(64);
builder.Property(entity => entity.UserAgent).HasMaxLength(1000);
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.Property(entity => entity.CreatedAt).HasDefaultValueSql("now()");
builder.HasIndex(entity => new { entity.TenantId, entity.UserId, entity.CreatedAt });
builder.HasOne<Tenant>().WithMany()
.HasForeignKey(entity => entity.TenantId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.UserId)
.OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class AuthSessionConfiguration : IEntityTypeConfiguration<AuthSession>
{
public void Configure(EntityTypeBuilder<AuthSession> builder)
{
builder.ConfigureTenantEntity("auth_sessions");
builder.ConfigureTimestamps();
builder.Property(entity => entity.TokenHash).HasMaxLength(256);
builder.Property(entity => entity.Provider).HasMaxLength(50);
builder.Property(entity => entity.IpAddress).HasMaxLength(64);
builder.Property(entity => entity.UserAgent).HasMaxLength(1000);
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => entity.TokenHash).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.UserId, entity.ExpiresAt })
.HasFilter("revoked_at is null");
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.UserId)
.OnDelete(DeleteBehavior.Cascade);
}
}
internal sealed class SmsSendRateLimitConfiguration : IEntityTypeConfiguration<SmsSendRateLimit>
{
public void Configure(EntityTypeBuilder<SmsSendRateLimit> builder)
{
builder.ToTable("sms_send_rate_limits");
builder.HasKey(entity => new
{
entity.TenantId,
entity.Dimension,
entity.ScopeHash,
entity.BucketStart
});
builder.Property(entity => entity.Dimension).HasSnakeCaseEnum();
builder.Property(entity => entity.ScopeHash).HasMaxLength(128);
builder.Property(entity => entity.RequestCount).HasDefaultValue(0);
builder.Property(entity => entity.UpdatedAt).HasDefaultValueSql("now()");
builder.HasIndex(entity => entity.UpdatedAt);
builder.ToTable(table =>
{
table.HasCheckConstraint("ck_sms_send_rate_limits_request_count", "request_count >= 0");
});
builder.HasOne<Tenant>().WithMany()
.HasForeignKey(entity => entity.TenantId)
.OnDelete(DeleteBehavior.Cascade);
}
}
internal sealed class TenantRoleTemplateConfiguration : IEntityTypeConfiguration<TenantRoleTemplate>
{
public void Configure(EntityTypeBuilder<TenantRoleTemplate> builder)
{
builder.ConfigureTenantEntity("tenant_role_templates");
builder.ConfigureTimestamps();
builder.Property(entity => entity.Code).HasMaxLength(100);
builder.Property(entity => entity.Name).HasMaxLength(200);
builder.Property(entity => entity.BaseRole).HasSnakeCaseEnum();
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.Permissions).IsJson("{}");
builder.Property(entity => entity.MenuPermissions).IsJson("{}");
builder.Property(entity => entity.ModulePermissions).IsJson("{}");
builder.Property(entity => entity.FieldPermissions).IsJson("{}");
builder.Property(entity => entity.DataScope).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.Code }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.SortOrder });
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.CreatedBy)
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.UpdatedBy)
.OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class TenantClassConfiguration : IEntityTypeConfiguration<TenantClass>
{
public void Configure(EntityTypeBuilder<TenantClass> builder)
{
builder.ConfigureTenantEntity("tenant_classes");
builder.ConfigureTimestamps();
builder.Property(entity => entity.LegacyId).HasMaxLength(64);
builder.Property(entity => entity.Code).HasMaxLength(100);
builder.Property(entity => entity.Name).HasMaxLength(200);
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.LegacyId }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.Code })
.IsUnique()
.HasFilter("code is not null and code <> ''");
builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.SortOrder, entity.CreatedAt });
builder.HasIndex(entity => new { entity.TenantId, entity.RegionId })
.HasFilter("region_id is not null");
builder.HasOne<Region>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.RegionId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.CreatedBy)
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.UpdatedBy)
.OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class TenantClassMemberConfiguration : IEntityTypeConfiguration<TenantClassMember>
{
public void Configure(EntityTypeBuilder<TenantClassMember> builder)
{
builder.ConfigureTenantEntity("tenant_class_members");
builder.ConfigureTimestamps();
builder.Property(entity => entity.MemberType).HasSnakeCaseEnum();
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.JoinedAt).HasDefaultValueSql("now()");
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.ClassId, entity.UserId, entity.MemberType }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.ClassId, entity.Status, entity.MemberType });
builder.HasIndex(entity => new { entity.TenantId, entity.UserId, entity.Status, entity.MemberType });
builder.HasOne<TenantClass>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.ClassId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.UserId)
.OnDelete(DeleteBehavior.Cascade);
}
}
internal sealed class TenantStudentNoteConfiguration : IEntityTypeConfiguration<TenantStudentNote>
{
public void Configure(EntityTypeBuilder<TenantStudentNote> builder)
{
builder.ConfigureTenantEntity("tenant_student_notes");
builder.ConfigureTimestamps();
builder.Property(entity => entity.NoteType).HasSnakeCaseEnum();
builder.Property(entity => entity.Visibility).HasSnakeCaseEnum();
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.StudentUserId, entity.IsPinned, entity.CreatedAt });
builder.HasIndex(entity => new { entity.TenantId, entity.CreatedBy, entity.CreatedAt })
.HasFilter("created_by is not null");
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.StudentUserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.CreatedBy)
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.UpdatedBy)
.OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class TenantStudentFollowupConfiguration : IEntityTypeConfiguration<TenantStudentFollowup>
{
public void Configure(EntityTypeBuilder<TenantStudentFollowup> builder)
{
builder.ConfigureTenantEntity("tenant_student_followups");
builder.ConfigureTimestamps();
builder.Property(entity => entity.Title).HasMaxLength(300);
builder.Property(entity => entity.FollowupType).HasSnakeCaseEnum();
builder.Property(entity => entity.Priority).HasSnakeCaseEnum();
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.StudentUserId, entity.Status, entity.DueAt, entity.CreatedAt });
builder.HasIndex(entity => new { entity.TenantId, entity.AssignedToUserId, entity.Status, entity.DueAt })
.HasFilter("assigned_to_user_id is not null");
builder.HasIndex(entity => new { entity.TenantId, entity.ClassId, entity.Status, entity.DueAt })
.HasFilter("class_id is not null");
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.StudentUserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.AssignedToUserId)
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne<TenantClass>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.ClassId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne<User>().WithMany()
.HasForeignKey(entity => entity.CompletedBy)
.OnDelete(DeleteBehavior.SetNull);
}
}

View File

@@ -0,0 +1,669 @@
using System;
using System.Text.Json;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Tiku.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class AddAuthAndTenantOperationsPersistence : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "role_template_id",
table: "tenant_memberships",
type: "uuid",
nullable: true);
migrationBuilder.CreateTable(
name: "auth_login_events",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
user_id = table.Column<Guid>(type: "uuid", nullable: true),
provider = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
identifier = table.Column<string>(type: "character varying(320)", maxLength: 320, nullable: true),
result = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
failure_code = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
ip_address = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
user_agent = table.Column<string>(type: "character varying(1000)", maxLength: 1000, nullable: true),
metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_auth_login_events", x => x.id);
table.UniqueConstraint("ak_auth_login_events_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_auth_login_events_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_auth_login_events_users_user_id",
column: x => x.user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "auth_sessions",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
user_id = table.Column<Guid>(type: "uuid", nullable: false),
token_hash = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
provider = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
expires_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
revoked_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
ip_address = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
user_agent = table.Column<string>(type: "character varying(1000)", maxLength: 1000, nullable: true),
metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_auth_sessions", x => x.id);
table.UniqueConstraint("ak_auth_sessions_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_auth_sessions_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_auth_sessions_users_user_id",
column: x => x.user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "sms_send_rate_limits",
columns: table => new
{
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
dimension = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
scope_hash = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false),
bucket_start = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
request_count = table.Column<int>(type: "integer", nullable: false, defaultValue: 0),
updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_sms_send_rate_limits", x => new { x.tenant_id, x.dimension, x.scope_hash, x.bucket_start });
table.CheckConstraint("ck_sms_send_rate_limits_request_count", "request_count >= 0");
table.ForeignKey(
name: "fk_sms_send_rate_limits_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "sms_verification_codes",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
phone = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
purpose = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
code_hash = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: false),
provider = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
attempts = table.Column<int>(type: "integer", nullable: false),
expires_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
consumed_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
ip_address = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
user_agent = table.Column<string>(type: "character varying(1000)", maxLength: 1000, nullable: true),
metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_sms_verification_codes", x => x.id);
table.UniqueConstraint("ak_sms_verification_codes_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_sms_verification_codes_attempts", "attempts >= 0");
table.ForeignKey(
name: "fk_sms_verification_codes_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "tenant_auth_providers",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
provider = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
display_name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
config_public = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_tenant_auth_providers", x => x.id);
table.UniqueConstraint("ak_tenant_auth_providers_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_tenant_auth_providers_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "tenant_classes",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
region_id = table.Column<Guid>(type: "uuid", nullable: true),
legacy_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
code = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
description = table.Column<string>(type: "text", nullable: true),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
sort_order = table.Column<int>(type: "integer", nullable: false),
metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
created_by = table.Column<Guid>(type: "uuid", nullable: true),
updated_by = table.Column<Guid>(type: "uuid", nullable: true),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_tenant_classes", x => x.id);
table.UniqueConstraint("ak_tenant_classes_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_tenant_classes_regions_tenant_id_region_id",
columns: x => new { x.tenant_id, x.region_id },
principalTable: "regions",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "fk_tenant_classes_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_classes_users_created_by",
column: x => x.created_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_tenant_classes_users_updated_by",
column: x => x.updated_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "tenant_role_templates",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
code = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
description = table.Column<string>(type: "text", nullable: true),
base_role = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
permissions = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
menu_permissions = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
module_permissions = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
field_permissions = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
data_scope = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
is_system = table.Column<bool>(type: "boolean", nullable: false),
sort_order = table.Column<int>(type: "integer", nullable: false),
created_by = table.Column<Guid>(type: "uuid", nullable: true),
updated_by = table.Column<Guid>(type: "uuid", nullable: true),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_tenant_role_templates", x => x.id);
table.UniqueConstraint("ak_tenant_role_templates_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_tenant_role_templates_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_role_templates_users_created_by",
column: x => x.created_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_tenant_role_templates_users_updated_by",
column: x => x.updated_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "tenant_student_notes",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
student_user_id = table.Column<Guid>(type: "uuid", nullable: false),
note_type = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
content = table.Column<string>(type: "text", nullable: false),
visibility = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
is_pinned = table.Column<bool>(type: "boolean", nullable: false),
metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
created_by = table.Column<Guid>(type: "uuid", nullable: true),
updated_by = table.Column<Guid>(type: "uuid", nullable: true),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_tenant_student_notes", x => x.id);
table.UniqueConstraint("ak_tenant_student_notes_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_tenant_student_notes_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_student_notes_users_created_by",
column: x => x.created_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_tenant_student_notes_users_student_user_id",
column: x => x.student_user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_student_notes_users_updated_by",
column: x => x.updated_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "tenant_class_members",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
class_id = table.Column<Guid>(type: "uuid", nullable: false),
user_id = table.Column<Guid>(type: "uuid", nullable: false),
member_type = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
joined_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
left_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
created_by = table.Column<Guid>(type: "uuid", nullable: true),
updated_by = table.Column<Guid>(type: "uuid", nullable: true),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_tenant_class_members", x => x.id);
table.UniqueConstraint("ak_tenant_class_members_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_tenant_class_members_tenant_classes_tenant_id_class_id",
columns: x => new { x.tenant_id, x.class_id },
principalTable: "tenant_classes",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_class_members_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_class_members_users_user_id",
column: x => x.user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "tenant_student_followups",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
student_user_id = table.Column<Guid>(type: "uuid", nullable: false),
assigned_to_user_id = table.Column<Guid>(type: "uuid", nullable: true),
class_id = table.Column<Guid>(type: "uuid", nullable: true),
title = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: false),
description = table.Column<string>(type: "text", nullable: true),
followup_type = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
priority = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
due_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
completed_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
completed_by = table.Column<Guid>(type: "uuid", nullable: true),
metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
created_by = table.Column<Guid>(type: "uuid", nullable: true),
updated_by = table.Column<Guid>(type: "uuid", nullable: true),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_tenant_student_followups", x => x.id);
table.UniqueConstraint("ak_tenant_student_followups_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_tenant_student_followups_tenant_classes_tenant_id_class_id",
columns: x => new { x.tenant_id, x.class_id },
principalTable: "tenant_classes",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_tenant_student_followups_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_student_followups_users_assigned_to_user_id",
column: x => x.assigned_to_user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_tenant_student_followups_users_completed_by",
column: x => x.completed_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_tenant_student_followups_users_student_user_id",
column: x => x.student_user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "ix_tenant_memberships_tenant_id_role_template_id",
table: "tenant_memberships",
columns: new[] { "tenant_id", "role_template_id" });
migrationBuilder.CreateIndex(
name: "ix_auth_login_events_tenant_id_user_id_created_at",
table: "auth_login_events",
columns: new[] { "tenant_id", "user_id", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_auth_login_events_user_id",
table: "auth_login_events",
column: "user_id");
migrationBuilder.CreateIndex(
name: "ix_auth_sessions_tenant_id_user_id_expires_at",
table: "auth_sessions",
columns: new[] { "tenant_id", "user_id", "expires_at" },
filter: "revoked_at is null");
migrationBuilder.CreateIndex(
name: "ix_auth_sessions_token_hash",
table: "auth_sessions",
column: "token_hash",
unique: true);
migrationBuilder.CreateIndex(
name: "ix_auth_sessions_user_id",
table: "auth_sessions",
column: "user_id");
migrationBuilder.CreateIndex(
name: "ix_sms_send_rate_limits_updated_at",
table: "sms_send_rate_limits",
column: "updated_at");
migrationBuilder.CreateIndex(
name: "ix_sms_verification_codes_tenant_id_phone_purpose",
table: "sms_verification_codes",
columns: new[] { "tenant_id", "phone", "purpose" },
unique: true,
filter: "consumed_at is null and status in ('pending', 'sent')");
migrationBuilder.CreateIndex(
name: "ix_sms_verification_codes_tenant_id_phone_purpose_created_at",
table: "sms_verification_codes",
columns: new[] { "tenant_id", "phone", "purpose", "created_at" },
filter: "consumed_at is null and status in ('pending', 'sent')");
migrationBuilder.CreateIndex(
name: "ix_sms_verification_codes_tenant_id_phone_purpose_expires_at",
table: "sms_verification_codes",
columns: new[] { "tenant_id", "phone", "purpose", "expires_at" });
migrationBuilder.CreateIndex(
name: "ix_tenant_auth_providers_tenant_id_provider",
table: "tenant_auth_providers",
columns: new[] { "tenant_id", "provider" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_tenant_auth_providers_tenant_id_provider_status",
table: "tenant_auth_providers",
columns: new[] { "tenant_id", "provider", "status" });
migrationBuilder.CreateIndex(
name: "ix_tenant_class_members_tenant_id_class_id_status_member_type",
table: "tenant_class_members",
columns: new[] { "tenant_id", "class_id", "status", "member_type" });
migrationBuilder.CreateIndex(
name: "ix_tenant_class_members_tenant_id_class_id_user_id_member_type",
table: "tenant_class_members",
columns: new[] { "tenant_id", "class_id", "user_id", "member_type" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_tenant_class_members_tenant_id_user_id_status_member_type",
table: "tenant_class_members",
columns: new[] { "tenant_id", "user_id", "status", "member_type" });
migrationBuilder.CreateIndex(
name: "ix_tenant_class_members_user_id",
table: "tenant_class_members",
column: "user_id");
migrationBuilder.CreateIndex(
name: "ix_tenant_classes_created_by",
table: "tenant_classes",
column: "created_by");
migrationBuilder.CreateIndex(
name: "ix_tenant_classes_tenant_id_code",
table: "tenant_classes",
columns: new[] { "tenant_id", "code" },
unique: true,
filter: "code is not null and code <> ''");
migrationBuilder.CreateIndex(
name: "ix_tenant_classes_tenant_id_legacy_id",
table: "tenant_classes",
columns: new[] { "tenant_id", "legacy_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_tenant_classes_tenant_id_region_id",
table: "tenant_classes",
columns: new[] { "tenant_id", "region_id" },
filter: "region_id is not null");
migrationBuilder.CreateIndex(
name: "ix_tenant_classes_tenant_id_status_sort_order_created_at",
table: "tenant_classes",
columns: new[] { "tenant_id", "status", "sort_order", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_tenant_classes_updated_by",
table: "tenant_classes",
column: "updated_by");
migrationBuilder.CreateIndex(
name: "ix_tenant_role_templates_created_by",
table: "tenant_role_templates",
column: "created_by");
migrationBuilder.CreateIndex(
name: "ix_tenant_role_templates_tenant_id_code",
table: "tenant_role_templates",
columns: new[] { "tenant_id", "code" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_tenant_role_templates_tenant_id_status_sort_order",
table: "tenant_role_templates",
columns: new[] { "tenant_id", "status", "sort_order" });
migrationBuilder.CreateIndex(
name: "ix_tenant_role_templates_updated_by",
table: "tenant_role_templates",
column: "updated_by");
migrationBuilder.CreateIndex(
name: "ix_tenant_student_followups_assigned_to_user_id",
table: "tenant_student_followups",
column: "assigned_to_user_id");
migrationBuilder.CreateIndex(
name: "ix_tenant_student_followups_completed_by",
table: "tenant_student_followups",
column: "completed_by");
migrationBuilder.CreateIndex(
name: "ix_tenant_student_followups_student_user_id",
table: "tenant_student_followups",
column: "student_user_id");
migrationBuilder.CreateIndex(
name: "ix_tenant_student_followups_tenant_id_assigned_to_user_id_stat~",
table: "tenant_student_followups",
columns: new[] { "tenant_id", "assigned_to_user_id", "status", "due_at" },
filter: "assigned_to_user_id is not null");
migrationBuilder.CreateIndex(
name: "ix_tenant_student_followups_tenant_id_class_id_status_due_at",
table: "tenant_student_followups",
columns: new[] { "tenant_id", "class_id", "status", "due_at" },
filter: "class_id is not null");
migrationBuilder.CreateIndex(
name: "ix_tenant_student_followups_tenant_id_student_user_id_status_d~",
table: "tenant_student_followups",
columns: new[] { "tenant_id", "student_user_id", "status", "due_at", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_tenant_student_notes_created_by",
table: "tenant_student_notes",
column: "created_by");
migrationBuilder.CreateIndex(
name: "ix_tenant_student_notes_student_user_id",
table: "tenant_student_notes",
column: "student_user_id");
migrationBuilder.CreateIndex(
name: "ix_tenant_student_notes_tenant_id_created_by_created_at",
table: "tenant_student_notes",
columns: new[] { "tenant_id", "created_by", "created_at" },
filter: "created_by is not null");
migrationBuilder.CreateIndex(
name: "ix_tenant_student_notes_tenant_id_student_user_id_is_pinned_cr~",
table: "tenant_student_notes",
columns: new[] { "tenant_id", "student_user_id", "is_pinned", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_tenant_student_notes_updated_by",
table: "tenant_student_notes",
column: "updated_by");
migrationBuilder.AddForeignKey(
name: "fk_tenant_memberships_tenant_role_templates_tenant_id_role_tem~",
table: "tenant_memberships",
columns: new[] { "tenant_id", "role_template_id" },
principalTable: "tenant_role_templates",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Restrict);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "fk_tenant_memberships_tenant_role_templates_tenant_id_role_tem~",
table: "tenant_memberships");
migrationBuilder.DropTable(
name: "auth_login_events");
migrationBuilder.DropTable(
name: "auth_sessions");
migrationBuilder.DropTable(
name: "sms_send_rate_limits");
migrationBuilder.DropTable(
name: "sms_verification_codes");
migrationBuilder.DropTable(
name: "tenant_auth_providers");
migrationBuilder.DropTable(
name: "tenant_class_members");
migrationBuilder.DropTable(
name: "tenant_role_templates");
migrationBuilder.DropTable(
name: "tenant_student_followups");
migrationBuilder.DropTable(
name: "tenant_student_notes");
migrationBuilder.DropTable(
name: "tenant_classes");
migrationBuilder.DropIndex(
name: "ix_tenant_memberships_tenant_id_role_template_id",
table: "tenant_memberships");
migrationBuilder.DropColumn(
name: "role_template_id",
table: "tenant_memberships");
}
}
}

View File

@@ -18,6 +18,16 @@ public sealed class TikuDbContext(DbContextOptions<TikuDbContext> options) : DbC
public DbSet<TenantDomain> TenantDomains => Set<TenantDomain>();
public DbSet<TenantBranding> TenantBrandings => Set<TenantBranding>();
public DbSet<TenantSettings> TenantSettings => Set<TenantSettings>();
public DbSet<TenantAuthProvider> TenantAuthProviders => Set<TenantAuthProvider>();
public DbSet<SmsVerificationCode> SmsVerificationCodes => Set<SmsVerificationCode>();
public DbSet<AuthLoginEvent> AuthLoginEvents => Set<AuthLoginEvent>();
public DbSet<AuthSession> AuthSessions => Set<AuthSession>();
public DbSet<SmsSendRateLimit> SmsSendRateLimits => Set<SmsSendRateLimit>();
public DbSet<TenantRoleTemplate> TenantRoleTemplates => Set<TenantRoleTemplate>();
public DbSet<TenantClass> TenantClasses => Set<TenantClass>();
public DbSet<TenantClassMember> TenantClassMembers => Set<TenantClassMember>();
public DbSet<TenantStudentNote> TenantStudentNotes => Set<TenantStudentNote>();
public DbSet<TenantStudentFollowup> TenantStudentFollowups => Set<TenantStudentFollowup>();
public DbSet<StudentProfile> StudentProfiles => Set<StudentProfile>();
public DbSet<Region> Regions => Set<Region>();
public DbSet<RegionModule> RegionModules => Set<RegionModule>();

View File

@@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore.Metadata;
using Tiku.Domain.Content;
using Tiku.Domain.Learning;
using Tiku.Domain.QuestionBanks;
using Tiku.Domain.Tenancy;
using Tiku.Infrastructure.Persistence;
namespace Tiku.IntegrationTests;
@@ -24,7 +25,7 @@ public sealed class PersistenceModelTests
.Select(entity => entity.GetTableName())
.ToHashSet(StringComparer.Ordinal);
Assert.Equal(55, tableNames.Count);
Assert.Equal(65, tableNames.Count);
Assert.Contains("tenants", tableNames);
Assert.Contains("tenant_settings", tableNames);
Assert.Contains("content_entries", tableNames);
@@ -58,6 +59,16 @@ public sealed class PersistenceModelTests
Assert.Contains("practice_session_report_sections", tableNames);
Assert.Contains("dashboard_daily_stats", tableNames);
Assert.Contains("revenue_daily_stats", tableNames);
Assert.Contains("tenant_auth_providers", tableNames);
Assert.Contains("sms_verification_codes", tableNames);
Assert.Contains("auth_login_events", tableNames);
Assert.Contains("auth_sessions", tableNames);
Assert.Contains("sms_send_rate_limits", tableNames);
Assert.Contains("tenant_role_templates", tableNames);
Assert.Contains("tenant_classes", tableNames);
Assert.Contains("tenant_class_members", tableNames);
Assert.Contains("tenant_student_notes", tableNames);
Assert.Contains("tenant_student_followups", tableNames);
Assert.Contains("questions", tableNames);
Assert.Contains("question_versions", tableNames);
Assert.Contains("answer_records", tableNames);
@@ -370,4 +381,57 @@ public sealed class PersistenceModelTests
Assert.Equal(6, accuracy.GetPrecision());
Assert.Equal(4, accuracy.GetScale());
}
[Theory]
[InlineData(typeof(TenantAuthProvider), nameof(TenantAuthProvider.ConfigPublic), "'{}'::jsonb")]
[InlineData(typeof(SmsVerificationCode), nameof(SmsVerificationCode.Metadata), "'{}'::jsonb")]
[InlineData(typeof(AuthLoginEvent), nameof(AuthLoginEvent.Metadata), "'{}'::jsonb")]
[InlineData(typeof(AuthSession), nameof(AuthSession.Metadata), "'{}'::jsonb")]
[InlineData(typeof(TenantRoleTemplate), nameof(TenantRoleTemplate.Permissions), "'{}'::jsonb")]
[InlineData(typeof(TenantRoleTemplate), nameof(TenantRoleTemplate.DataScope), "'{}'::jsonb")]
[InlineData(typeof(TenantClass), nameof(TenantClass.Metadata), "'{}'::jsonb")]
[InlineData(typeof(TenantClassMember), nameof(TenantClassMember.Metadata), "'{}'::jsonb")]
[InlineData(typeof(TenantStudentNote), nameof(TenantStudentNote.Metadata), "'{}'::jsonb")]
[InlineData(typeof(TenantStudentFollowup), nameof(TenantStudentFollowup.Metadata), "'{}'::jsonb")]
public void Auth_and_tenant_operations_json_properties_are_mapped_to_jsonb(
Type entityType,
string propertyName,
string expectedDefaultValueSql)
{
using var context = new TikuDbContext(Options);
var property = context.Model.FindEntityType(entityType)!
.FindProperty(propertyName)!;
Assert.Equal("jsonb", property.GetColumnType());
Assert.Equal(expectedDefaultValueSql, property.GetDefaultValueSql());
Assert.Equal(typeof(System.Text.Json.JsonElement), property.ClrType);
}
[Fact]
public void Auth_and_class_tables_have_expected_unique_indexes()
{
using var context = new TikuDbContext(Options);
AssertHasUniqueIndex<TenantAuthProvider>(
nameof(TenantAuthProvider.TenantId),
nameof(TenantAuthProvider.Provider));
AssertHasUniqueIndex<TenantClassMember>(
nameof(TenantClassMember.TenantId),
nameof(TenantClassMember.ClassId),
nameof(TenantClassMember.UserId),
nameof(TenantClassMember.MemberType));
void AssertHasUniqueIndex<TEntity>(params string[] propertyNames)
{
var indexes = context.Model.FindEntityType(typeof(TEntity))!.GetIndexes();
Assert.Contains(
indexes,
index => index.IsUnique
&& index.Properties
.Select(property => property.Name)
.SequenceEqual(propertyNames));
}
}
}