feat: add platform billing dunning and audit persistence

This commit is contained in:
xiong
2026-07-26 06:02:58 +08:00
parent 9fd8708fa5
commit a2b10fb05b
7 changed files with 17472 additions and 1 deletions

View File

@@ -0,0 +1,248 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Tiku.Domain.Identity;
using Tiku.Domain.Operations;
using Tiku.Domain.Platform;
using Tiku.Domain.Tenancy;
namespace Tiku.Infrastructure.Persistence.Configurations;
internal sealed class PlatformSaasPlanConfiguration : IEntityTypeConfiguration<PlatformSaasPlan>
{
public void Configure(EntityTypeBuilder<PlatformSaasPlan> builder)
{
builder.ConfigureEntity("platform_saas_plans");
builder.ConfigureTimestamps();
builder.Property(entity => entity.Code).HasMaxLength(100);
builder.Property(entity => entity.Name).HasMaxLength(200);
builder.Property(entity => entity.BillingCycle).HasSnakeCaseEnum();
builder.Property(entity => entity.Currency).HasMaxLength(10);
builder.Property(entity => entity.IncludedQuotas).IsJson("{}");
builder.Property(entity => entity.OveragePrices).IsJson("{}");
builder.Property(entity => entity.FeatureFlags).IsJson("{}");
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.HasIndex(entity => entity.Code).IsUnique();
builder.HasIndex(entity => new { entity.Status, entity.SortOrder });
builder.ToTable(table => table.HasCheckConstraint("ck_platform_saas_plans_amount", "base_amount_cents >= 0"));
}
}
internal sealed class TenantBillingProfileConfiguration : IEntityTypeConfiguration<TenantBillingProfile>
{
public void Configure(EntityTypeBuilder<TenantBillingProfile> builder)
{
builder.ToTable("tenant_billing_profiles");
builder.HasKey(entity => entity.TenantId);
builder.ConfigureTimestamps();
builder.Property(entity => entity.BillingName).HasMaxLength(300);
builder.Property(entity => entity.TaxId).HasMaxLength(100);
builder.Property(entity => entity.ContactName).HasMaxLength(100);
builder.Property(entity => entity.ContactPhone).HasMaxLength(50);
builder.Property(entity => entity.ContactEmail).HasColumnType("citext").HasMaxLength(300);
builder.Property(entity => entity.InvoiceTitle).HasMaxLength(300);
builder.Property(entity => entity.InvoiceType).HasNullableSnakeCaseEnum();
builder.Property(entity => entity.BankName).HasMaxLength(200);
builder.Property(entity => entity.BankAccountMasked).HasMaxLength(100);
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasOne<Tenant>().WithOne().HasForeignKey<TenantBillingProfile>(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
}
}
internal sealed class TenantInvoiceConfiguration : IEntityTypeConfiguration<TenantInvoice>
{
public void Configure(EntityTypeBuilder<TenantInvoice> builder)
{
builder.ConfigureTenantEntity("tenant_invoices");
builder.ConfigureTimestamps();
builder.Property(entity => entity.InvoiceNo).HasMaxLength(100);
builder.Property(entity => entity.InvoiceType).HasSnakeCaseEnum();
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.Currency).HasMaxLength(10);
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => entity.InvoiceNo).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.DueDate });
builder.HasIndex(entity => new { entity.TenantId, entity.BillingPeriodStart, entity.BillingPeriodEnd })
.IsUnique()
.HasFilter("invoice_type = 'usage_overage' and status <> 'void' and metadata->>'source' = 'usage_overage_auto'");
builder.ToTable(table =>
{
table.HasCheckConstraint("ck_tenant_invoices_amounts", "subtotal_cents >= 0 and discount_cents >= 0 and tax_cents >= 0 and total_cents >= 0 and paid_cents >= 0 and balance_cents >= 0");
table.HasCheckConstraint("ck_tenant_invoices_period", "billing_period_end is null or billing_period_start is null or billing_period_end >= billing_period_start");
});
builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.CreatedBy).OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class TenantInvoiceItemConfiguration : IEntityTypeConfiguration<TenantInvoiceItem>
{
public void Configure(EntityTypeBuilder<TenantInvoiceItem> builder)
{
builder.ConfigureEntity("tenant_invoice_items");
builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id });
builder.Property(entity => entity.ItemType).HasMaxLength(100);
builder.Property(entity => entity.Description).HasMaxLength(500);
builder.Property(entity => entity.Quantity).HasPrecision(12, 2);
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.Property(entity => entity.CreatedAt).HasDefaultValueSql("now()");
builder.HasIndex(entity => entity.InvoiceId);
builder.ToTable(table =>
{
table.HasCheckConstraint("ck_tenant_invoice_items_quantity", "quantity > 0");
table.HasCheckConstraint("ck_tenant_invoice_items_amounts", "unit_amount_cents >= 0 and amount_cents >= 0");
});
builder.HasOne<Tenant>().WithMany().HasForeignKey(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<TenantInvoice>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.InvoiceId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Cascade);
}
}
internal sealed class TenantInvoicePaymentConfiguration : IEntityTypeConfiguration<TenantInvoicePayment>
{
public void Configure(EntityTypeBuilder<TenantInvoicePayment> builder)
{
builder.ConfigureTenantEntity("tenant_invoice_payments");
builder.ConfigureTimestamps();
builder.Property(entity => entity.PaymentNo).HasMaxLength(100);
builder.Property(entity => entity.Provider).HasMaxLength(50);
builder.Property(entity => entity.Method).HasMaxLength(50);
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.ProviderTradeNo).HasMaxLength(200);
builder.Property(entity => entity.RawPayload).IsJson("{}");
builder.HasIndex(entity => entity.PaymentNo).IsUnique();
builder.HasIndex(entity => new { entity.InvoiceId, entity.Status });
builder.ToTable(table => table.HasCheckConstraint("ck_tenant_invoice_payments_amount", "amount_cents >= 0"));
builder.HasOne<TenantInvoice>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.InvoiceId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.ReceivedBy).OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class TenantInvoiceReminderConfiguration : IEntityTypeConfiguration<TenantInvoiceReminder>
{
public void Configure(EntityTypeBuilder<TenantInvoiceReminder> builder)
{
builder.ConfigureTenantEntity("tenant_invoice_reminders");
builder.ConfigureTimestamps();
builder.Property(entity => entity.ReminderType).HasSnakeCaseEnum();
builder.Property(entity => entity.Channel).HasSnakeCaseEnum();
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.InvoiceId, entity.ReminderType, entity.Channel, entity.ReminderDate }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.ReminderDate });
builder.HasIndex(entity => new { entity.InvoiceId, entity.ReminderDate });
builder.ToTable(table =>
{
table.HasCheckConstraint("ck_tenant_invoice_reminders_level", "reminder_level between 1 and 20");
table.HasCheckConstraint("ck_tenant_invoice_reminders_balance", "balance_cents_snapshot >= 0");
});
builder.HasOne<TenantInvoice>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.InvoiceId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.CreatedBy).OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class PlatformAuditAlertRuleConfiguration : IEntityTypeConfiguration<PlatformAuditAlertRule>
{
public void Configure(EntityTypeBuilder<PlatformAuditAlertRule> builder)
{
builder.ConfigureEntity("platform_audit_alert_rules");
builder.ConfigureTimestamps();
builder.Property(entity => entity.Code).HasMaxLength(100);
builder.Property(entity => entity.Name).HasMaxLength(200);
builder.Property(entity => entity.Severity).HasSnakeCaseEnum();
builder.Property(entity => entity.ActionPatterns).HasColumnType("text[]").HasDefaultValueSql("'{}'::text[]");
builder.Property(entity => entity.TargetTypes).HasColumnType("text[]").HasDefaultValueSql("'{}'::text[]");
builder.Property(entity => entity.Conditions).IsJson("{}");
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => entity.Code).IsUnique();
builder.HasIndex(entity => new { entity.Enabled, entity.Severity, entity.Code });
builder.HasOne<Tenant>().WithMany().HasForeignKey(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
}
}
internal sealed class PlatformAuditAlertConfiguration : IEntityTypeConfiguration<PlatformAuditAlert>
{
public void Configure(EntityTypeBuilder<PlatformAuditAlert> builder)
{
builder.ConfigureEntity("platform_audit_alerts");
builder.ConfigureTimestamps();
builder.Property(entity => entity.Severity).HasSnakeCaseEnum();
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.Action).HasMaxLength(200);
builder.Property(entity => entity.TargetType).HasMaxLength(200);
builder.Property(entity => entity.TargetId).HasMaxLength(200);
builder.Property(entity => entity.Title).HasMaxLength(300);
builder.Property(entity => entity.Details).IsJson("{}");
builder.Property(entity => entity.FirstSeenAt).HasDefaultValueSql("now()");
builder.Property(entity => entity.LastSeenAt).HasDefaultValueSql("now()");
builder.HasIndex(entity => new { entity.RuleId, entity.AuditLogId }).IsUnique();
builder.HasIndex(entity => new { entity.Status, entity.Severity, entity.CreatedAt });
builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.CreatedAt });
builder.HasIndex(entity => entity.AuditLogId);
builder.HasOne<PlatformAuditAlertRule>().WithMany().HasForeignKey(entity => entity.RuleId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<AuditLog>().WithMany().HasForeignKey(entity => entity.AuditLogId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<Tenant>().WithMany().HasForeignKey(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.AcknowledgedBy).OnDelete(DeleteBehavior.SetNull);
builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.ResolvedBy).OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class PlatformDunningNotificationChannelConfiguration : IEntityTypeConfiguration<PlatformDunningNotificationChannel>
{
public void Configure(EntityTypeBuilder<PlatformDunningNotificationChannel> builder)
{
builder.ConfigureEntity("platform_dunning_notification_channels");
builder.ConfigureTimestamps();
builder.Property(entity => entity.ChannelCode).HasMaxLength(100);
builder.Property(entity => entity.Name).HasMaxLength(200);
builder.Property(entity => entity.Provider).HasSnakeCaseEnum();
builder.Property(entity => entity.WebhookUrl).HasMaxLength(2048);
builder.Property(entity => entity.SecretRef).HasMaxLength(300);
builder.Property(entity => entity.ReminderTypes).HasColumnType("text[]").HasDefaultValueSql("array['overdue', 'final_notice']::text[]");
builder.Property(entity => entity.ReminderChannels).HasColumnType("text[]").HasDefaultValueSql("array['internal']::text[]");
builder.Property(entity => entity.TenantIds).HasColumnType("uuid[]").HasDefaultValueSql("'{}'::uuid[]");
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => entity.ChannelCode).IsUnique();
builder.HasIndex(entity => new { entity.Enabled, entity.MinReminderLevel, entity.ChannelCode });
builder.ToTable(table =>
{
table.HasCheckConstraint("ck_platform_dunning_channels_level", "min_reminder_level between 1 and 20");
table.HasCheckConstraint("ck_platform_dunning_channels_timeout", "timeout_seconds between 1 and 60");
});
}
}
internal sealed class PlatformDunningNotificationEventConfiguration : IEntityTypeConfiguration<PlatformDunningNotificationEvent>
{
public void Configure(EntityTypeBuilder<PlatformDunningNotificationEvent> builder)
{
builder.ConfigureTenantEntity("platform_dunning_notification_events");
builder.ConfigureTimestamps();
builder.Property(entity => entity.Provider).HasSnakeCaseEnum();
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.RequestPayload).IsJson("{}");
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.Property(entity => entity.ScheduledAt).HasDefaultValueSql("now()");
builder.HasIndex(entity => new { entity.ChannelId, entity.ReminderId }).IsUnique();
builder.HasIndex(entity => new { entity.Status, entity.NextAttemptAt, entity.ScheduledAt, entity.CreatedAt });
builder.HasIndex(entity => new { entity.ReminderId, entity.Status, entity.CreatedAt });
builder.HasIndex(entity => new { entity.InvoiceId, entity.Status, entity.CreatedAt });
builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.CreatedAt });
builder.ToTable(table => table.HasCheckConstraint("ck_platform_dunning_events_attempts", "attempts >= 0"));
builder.HasOne<PlatformDunningNotificationChannel>().WithMany().HasForeignKey(entity => entity.ChannelId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<TenantInvoiceReminder>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.ReminderId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne<TenantInvoice>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.InvoiceId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Cascade);
}
}

View File

@@ -0,0 +1,633 @@
using System;
using System.Text.Json;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Tiku.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class AddPlatformBillingDunningAndAuditPersistence : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "platform_audit_alert_rules",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
tenant_id = table.Column<Guid>(type: "uuid", nullable: true),
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),
enabled = table.Column<bool>(type: "boolean", nullable: false),
severity = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
action_patterns = table.Column<string[]>(type: "text[]", nullable: false, defaultValueSql: "'{}'::text[]"),
target_types = table.Column<string[]>(type: "text[]", nullable: false, defaultValueSql: "'{}'::text[]"),
conditions = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
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_platform_audit_alert_rules", x => x.id);
table.ForeignKey(
name: "fk_platform_audit_alert_rules_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "platform_dunning_notification_channels",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
channel_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),
enabled = table.Column<bool>(type: "boolean", nullable: false),
provider = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
webhook_url = table.Column<string>(type: "character varying(2048)", maxLength: 2048, nullable: false),
secret_ref = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: true),
reminder_types = table.Column<string[]>(type: "text[]", nullable: false, defaultValueSql: "array['overdue', 'final_notice']::text[]"),
reminder_channels = table.Column<string[]>(type: "text[]", nullable: false, defaultValueSql: "array['internal']::text[]"),
min_reminder_level = table.Column<int>(type: "integer", nullable: false),
tenant_ids = table.Column<Guid[]>(type: "uuid[]", nullable: false, defaultValueSql: "'{}'::uuid[]"),
timeout_seconds = table.Column<int>(type: "integer", nullable: false),
metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
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_platform_dunning_notification_channels", x => x.id);
table.CheckConstraint("ck_platform_dunning_channels_level", "min_reminder_level between 1 and 20");
table.CheckConstraint("ck_platform_dunning_channels_timeout", "timeout_seconds between 1 and 60");
});
migrationBuilder.CreateTable(
name: "platform_saas_plans",
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),
billing_cycle = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
base_amount_cents = table.Column<int>(type: "integer", nullable: false),
currency = table.Column<string>(type: "character varying(10)", maxLength: 10, nullable: false),
included_quotas = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
overage_prices = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
feature_flags = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
sort_order = table.Column<int>(type: "integer", 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_platform_saas_plans", x => x.id);
table.CheckConstraint("ck_platform_saas_plans_amount", "base_amount_cents >= 0");
});
migrationBuilder.CreateTable(
name: "tenant_billing_profiles",
columns: table => new
{
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
billing_name = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: true),
tax_id = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
contact_name = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
contact_phone = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
contact_email = table.Column<string>(type: "citext", maxLength: 300, nullable: true),
billing_address = table.Column<string>(type: "text", nullable: true),
invoice_title = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: true),
invoice_type = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: true),
bank_name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
bank_account_masked = table.Column<string>(type: "character varying(100)", maxLength: 100, 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()"),
updated_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_tenant_billing_profiles", x => x.tenant_id);
table.ForeignKey(
name: "fk_tenant_billing_profiles_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "tenant_invoices",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
created_by = table.Column<Guid>(type: "uuid", nullable: true),
invoice_no = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
invoice_type = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
currency = table.Column<string>(type: "character varying(10)", maxLength: 10, nullable: false),
subtotal_cents = table.Column<int>(type: "integer", nullable: false),
discount_cents = table.Column<int>(type: "integer", nullable: false),
tax_cents = table.Column<int>(type: "integer", nullable: false),
total_cents = table.Column<int>(type: "integer", nullable: false),
paid_cents = table.Column<int>(type: "integer", nullable: false),
balance_cents = table.Column<int>(type: "integer", nullable: false),
billing_period_start = table.Column<DateOnly>(type: "date", nullable: true),
billing_period_end = table.Column<DateOnly>(type: "date", nullable: true),
due_date = table.Column<DateOnly>(type: "date", nullable: true),
issued_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
paid_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
note = table.Column<string>(type: "text", 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_tenant_invoices", x => x.id);
table.UniqueConstraint("ak_tenant_invoices_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_tenant_invoices_amounts", "subtotal_cents >= 0 and discount_cents >= 0 and tax_cents >= 0 and total_cents >= 0 and paid_cents >= 0 and balance_cents >= 0");
table.CheckConstraint("ck_tenant_invoices_period", "billing_period_end is null or billing_period_start is null or billing_period_end >= billing_period_start");
table.ForeignKey(
name: "fk_tenant_invoices_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_invoices_users_created_by",
column: x => x.created_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "platform_audit_alerts",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
rule_id = table.Column<Guid>(type: "uuid", nullable: false),
audit_log_id = table.Column<Guid>(type: "uuid", nullable: false),
tenant_id = table.Column<Guid>(type: "uuid", nullable: true),
acknowledged_by = table.Column<Guid>(type: "uuid", nullable: true),
resolved_by = table.Column<Guid>(type: "uuid", nullable: true),
severity = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
action = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
target_type = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
target_id = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
title = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: false),
summary = table.Column<string>(type: "text", nullable: true),
details = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
first_seen_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
last_seen_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
acknowledged_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
resolved_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
resolution_note = table.Column<string>(type: "text", nullable: true),
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_platform_audit_alerts", x => x.id);
table.ForeignKey(
name: "fk_platform_audit_alerts_audit_logs_audit_log_id",
column: x => x.audit_log_id,
principalTable: "audit_logs",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_platform_audit_alerts_platform_audit_alert_rules_rule_id",
column: x => x.rule_id,
principalTable: "platform_audit_alert_rules",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_platform_audit_alerts_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_platform_audit_alerts_users_acknowledged_by",
column: x => x.acknowledged_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_platform_audit_alerts_users_resolved_by",
column: x => x.resolved_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "tenant_invoice_items",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
invoice_id = table.Column<Guid>(type: "uuid", nullable: false),
item_type = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
item_ref_id = table.Column<Guid>(type: "uuid", nullable: true),
description = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: false),
quantity = table.Column<decimal>(type: "numeric(12,2)", precision: 12, scale: 2, nullable: false),
unit_amount_cents = table.Column<int>(type: "integer", nullable: false),
amount_cents = table.Column<int>(type: "integer", nullable: false),
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_tenant_invoice_items", x => x.id);
table.UniqueConstraint("ak_tenant_invoice_items_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_tenant_invoice_items_amounts", "unit_amount_cents >= 0 and amount_cents >= 0");
table.CheckConstraint("ck_tenant_invoice_items_quantity", "quantity > 0");
table.ForeignKey(
name: "fk_tenant_invoice_items_tenant_invoices_tenant_id_invoice_id",
columns: x => new { x.tenant_id, x.invoice_id },
principalTable: "tenant_invoices",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_invoice_items_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "tenant_invoice_payments",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
invoice_id = table.Column<Guid>(type: "uuid", nullable: false),
received_by = table.Column<Guid>(type: "uuid", nullable: true),
payment_no = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
provider = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
method = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
amount_cents = table.Column<int>(type: "integer", nullable: false),
paid_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
provider_trade_no = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
raw_payload = 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_invoice_payments", x => x.id);
table.UniqueConstraint("ak_tenant_invoice_payments_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_tenant_invoice_payments_amount", "amount_cents >= 0");
table.ForeignKey(
name: "fk_tenant_invoice_payments_tenant_invoices_tenant_id_invoice_id",
columns: x => new { x.tenant_id, x.invoice_id },
principalTable: "tenant_invoices",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_invoice_payments_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_invoice_payments_users_received_by",
column: x => x.received_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "tenant_invoice_reminders",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
invoice_id = table.Column<Guid>(type: "uuid", nullable: false),
created_by = table.Column<Guid>(type: "uuid", nullable: true),
reminder_type = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
channel = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
reminder_date = table.Column<DateOnly>(type: "date", nullable: false),
reminder_level = table.Column<int>(type: "integer", nullable: false),
due_date = table.Column<DateOnly>(type: "date", nullable: true),
balance_cents_snapshot = table.Column<int>(type: "integer", nullable: false),
message = table.Column<string>(type: "text", nullable: true),
metadata = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
sent_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
acknowledged_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", 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_invoice_reminders", x => x.id);
table.UniqueConstraint("ak_tenant_invoice_reminders_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_tenant_invoice_reminders_balance", "balance_cents_snapshot >= 0");
table.CheckConstraint("ck_tenant_invoice_reminders_level", "reminder_level between 1 and 20");
table.ForeignKey(
name: "fk_tenant_invoice_reminders_tenant_invoices_tenant_id_invoice_~",
columns: x => new { x.tenant_id, x.invoice_id },
principalTable: "tenant_invoices",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_invoice_reminders_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_tenant_invoice_reminders_users_created_by",
column: x => x.created_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "platform_dunning_notification_events",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
channel_id = table.Column<Guid>(type: "uuid", nullable: false),
reminder_id = table.Column<Guid>(type: "uuid", nullable: false),
invoice_id = table.Column<Guid>(type: "uuid", nullable: false),
provider = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
attempts = table.Column<int>(type: "integer", nullable: false),
scheduled_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
next_attempt_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
last_attempt_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
sent_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
last_error = table.Column<string>(type: "text", nullable: true),
last_http_code = table.Column<int>(type: "integer", nullable: true),
last_response_summary = table.Column<string>(type: "text", nullable: true),
request_payload = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
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_platform_dunning_notification_events", x => x.id);
table.UniqueConstraint("ak_platform_dunning_notification_events_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_platform_dunning_events_attempts", "attempts >= 0");
table.ForeignKey(
name: "fk_platform_dunning_notification_events_platform_dunning_notif~",
column: x => x.channel_id,
principalTable: "platform_dunning_notification_channels",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_platform_dunning_notification_events_tenant_invoice_reminde~",
columns: x => new { x.tenant_id, x.reminder_id },
principalTable: "tenant_invoice_reminders",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_platform_dunning_notification_events_tenant_invoices_tenant~",
columns: x => new { x.tenant_id, x.invoice_id },
principalTable: "tenant_invoices",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_platform_dunning_notification_events_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "ix_platform_audit_alert_rules_code",
table: "platform_audit_alert_rules",
column: "code",
unique: true);
migrationBuilder.CreateIndex(
name: "ix_platform_audit_alert_rules_enabled_severity_code",
table: "platform_audit_alert_rules",
columns: new[] { "enabled", "severity", "code" });
migrationBuilder.CreateIndex(
name: "ix_platform_audit_alert_rules_tenant_id",
table: "platform_audit_alert_rules",
column: "tenant_id");
migrationBuilder.CreateIndex(
name: "ix_platform_audit_alerts_acknowledged_by",
table: "platform_audit_alerts",
column: "acknowledged_by");
migrationBuilder.CreateIndex(
name: "ix_platform_audit_alerts_audit_log_id",
table: "platform_audit_alerts",
column: "audit_log_id");
migrationBuilder.CreateIndex(
name: "ix_platform_audit_alerts_resolved_by",
table: "platform_audit_alerts",
column: "resolved_by");
migrationBuilder.CreateIndex(
name: "ix_platform_audit_alerts_rule_id_audit_log_id",
table: "platform_audit_alerts",
columns: new[] { "rule_id", "audit_log_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_platform_audit_alerts_status_severity_created_at",
table: "platform_audit_alerts",
columns: new[] { "status", "severity", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_platform_audit_alerts_tenant_id_status_created_at",
table: "platform_audit_alerts",
columns: new[] { "tenant_id", "status", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_platform_dunning_notification_channels_channel_code",
table: "platform_dunning_notification_channels",
column: "channel_code",
unique: true);
migrationBuilder.CreateIndex(
name: "ix_platform_dunning_notification_channels_enabled_min_reminder~",
table: "platform_dunning_notification_channels",
columns: new[] { "enabled", "min_reminder_level", "channel_code" });
migrationBuilder.CreateIndex(
name: "ix_platform_dunning_notification_events_channel_id_reminder_id",
table: "platform_dunning_notification_events",
columns: new[] { "channel_id", "reminder_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_platform_dunning_notification_events_invoice_id_status_crea~",
table: "platform_dunning_notification_events",
columns: new[] { "invoice_id", "status", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_platform_dunning_notification_events_reminder_id_status_cre~",
table: "platform_dunning_notification_events",
columns: new[] { "reminder_id", "status", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_platform_dunning_notification_events_status_next_attempt_at~",
table: "platform_dunning_notification_events",
columns: new[] { "status", "next_attempt_at", "scheduled_at", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_platform_dunning_notification_events_tenant_id_invoice_id",
table: "platform_dunning_notification_events",
columns: new[] { "tenant_id", "invoice_id" });
migrationBuilder.CreateIndex(
name: "ix_platform_dunning_notification_events_tenant_id_reminder_id",
table: "platform_dunning_notification_events",
columns: new[] { "tenant_id", "reminder_id" });
migrationBuilder.CreateIndex(
name: "ix_platform_dunning_notification_events_tenant_id_status_creat~",
table: "platform_dunning_notification_events",
columns: new[] { "tenant_id", "status", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_platform_saas_plans_code",
table: "platform_saas_plans",
column: "code",
unique: true);
migrationBuilder.CreateIndex(
name: "ix_platform_saas_plans_status_sort_order",
table: "platform_saas_plans",
columns: new[] { "status", "sort_order" });
migrationBuilder.CreateIndex(
name: "ix_tenant_invoice_items_invoice_id",
table: "tenant_invoice_items",
column: "invoice_id");
migrationBuilder.CreateIndex(
name: "ix_tenant_invoice_items_tenant_id_invoice_id",
table: "tenant_invoice_items",
columns: new[] { "tenant_id", "invoice_id" });
migrationBuilder.CreateIndex(
name: "ix_tenant_invoice_payments_invoice_id_status",
table: "tenant_invoice_payments",
columns: new[] { "invoice_id", "status" });
migrationBuilder.CreateIndex(
name: "ix_tenant_invoice_payments_payment_no",
table: "tenant_invoice_payments",
column: "payment_no",
unique: true);
migrationBuilder.CreateIndex(
name: "ix_tenant_invoice_payments_received_by",
table: "tenant_invoice_payments",
column: "received_by");
migrationBuilder.CreateIndex(
name: "ix_tenant_invoice_payments_tenant_id_invoice_id",
table: "tenant_invoice_payments",
columns: new[] { "tenant_id", "invoice_id" });
migrationBuilder.CreateIndex(
name: "ix_tenant_invoice_reminders_created_by",
table: "tenant_invoice_reminders",
column: "created_by");
migrationBuilder.CreateIndex(
name: "ix_tenant_invoice_reminders_invoice_id_reminder_date",
table: "tenant_invoice_reminders",
columns: new[] { "invoice_id", "reminder_date" });
migrationBuilder.CreateIndex(
name: "ix_tenant_invoice_reminders_tenant_id_invoice_id_reminder_type~",
table: "tenant_invoice_reminders",
columns: new[] { "tenant_id", "invoice_id", "reminder_type", "channel", "reminder_date" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_tenant_invoice_reminders_tenant_id_status_reminder_date",
table: "tenant_invoice_reminders",
columns: new[] { "tenant_id", "status", "reminder_date" });
migrationBuilder.CreateIndex(
name: "ix_tenant_invoices_created_by",
table: "tenant_invoices",
column: "created_by");
migrationBuilder.CreateIndex(
name: "ix_tenant_invoices_invoice_no",
table: "tenant_invoices",
column: "invoice_no",
unique: true);
migrationBuilder.CreateIndex(
name: "ix_tenant_invoices_tenant_id_billing_period_start_billing_peri~",
table: "tenant_invoices",
columns: new[] { "tenant_id", "billing_period_start", "billing_period_end" },
unique: true,
filter: "invoice_type = 'usage_overage' and status <> 'void' and metadata->>'source' = 'usage_overage_auto'");
migrationBuilder.CreateIndex(
name: "ix_tenant_invoices_tenant_id_status_due_date",
table: "tenant_invoices",
columns: new[] { "tenant_id", "status", "due_date" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "platform_audit_alerts");
migrationBuilder.DropTable(
name: "platform_dunning_notification_events");
migrationBuilder.DropTable(
name: "platform_saas_plans");
migrationBuilder.DropTable(
name: "tenant_billing_profiles");
migrationBuilder.DropTable(
name: "tenant_invoice_items");
migrationBuilder.DropTable(
name: "tenant_invoice_payments");
migrationBuilder.DropTable(
name: "platform_audit_alert_rules");
migrationBuilder.DropTable(
name: "platform_dunning_notification_channels");
migrationBuilder.DropTable(
name: "tenant_invoice_reminders");
migrationBuilder.DropTable(
name: "tenant_invoices");
}
}
}

View File

@@ -7,6 +7,7 @@ using Tiku.Domain.Growth;
using Tiku.Domain.Identity;
using Tiku.Domain.Learning;
using Tiku.Domain.Operations;
using Tiku.Domain.Platform;
using Tiku.Domain.QuestionBanks;
using Tiku.Domain.Tenancy;
@@ -125,6 +126,16 @@ public sealed class TikuDbContext(DbContextOptions<TikuDbContext> options) : DbC
public DbSet<TenantContentNotification> TenantContentNotifications => Set<TenantContentNotification>();
public DbSet<TenantThemeTemplate> TenantThemeTemplates => Set<TenantThemeTemplate>();
public DbSet<TenantThemeConfig> TenantThemeConfigs => Set<TenantThemeConfig>();
public DbSet<PlatformSaasPlan> PlatformSaasPlans => Set<PlatformSaasPlan>();
public DbSet<TenantBillingProfile> TenantBillingProfiles => Set<TenantBillingProfile>();
public DbSet<TenantInvoice> TenantInvoices => Set<TenantInvoice>();
public DbSet<TenantInvoiceItem> TenantInvoiceItems => Set<TenantInvoiceItem>();
public DbSet<TenantInvoicePayment> TenantInvoicePayments => Set<TenantInvoicePayment>();
public DbSet<TenantInvoiceReminder> TenantInvoiceReminders => Set<TenantInvoiceReminder>();
public DbSet<PlatformAuditAlertRule> PlatformAuditAlertRules => Set<PlatformAuditAlertRule>();
public DbSet<PlatformAuditAlert> PlatformAuditAlerts => Set<PlatformAuditAlert>();
public DbSet<PlatformDunningNotificationChannel> PlatformDunningNotificationChannels => Set<PlatformDunningNotificationChannel>();
public DbSet<PlatformDunningNotificationEvent> PlatformDunningNotificationEvents => Set<PlatformDunningNotificationEvent>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{