feat: add commerce persistence

This commit is contained in:
xiong
2026-07-26 05:36:03 +08:00
parent aa000c63aa
commit fc8e04ebd6
7 changed files with 12766 additions and 1 deletions

View File

@@ -0,0 +1,230 @@
using System.Text.Json;
using Tiku.Domain.Common;
namespace Tiku.Domain.Commerce;
public sealed class Product : AuditableTenantEntity
{
public Guid? RegionId { get; set; }
public string? LegacyId { get; set; }
public string Title { get; set; } = string.Empty;
public string? LegacyPriceText { get; set; }
public string? Link { get; set; }
public ProductType Type { get; set; } = ProductType.Material;
public JsonElement Tags { get; set; } = JsonDefaults.Array();
public int SortOrder { get; set; }
public string? Cover { get; set; }
public string? PreviewIframe { get; set; }
public JsonElement DetailImages { get; set; } = JsonDefaults.Array();
}
public sealed class SvipPlan : AuditableTenantEntity
{
public Guid? RegionId { get; set; }
public string? LegacyId { get; set; }
public string Name { get; set; } = string.Empty;
public int PriceCents { get; set; }
public int? OriginalPriceCents { get; set; }
public int Days { get; set; }
public string? Description { get; set; }
public string? PerDayLabel { get; set; }
public string? Badge { get; set; }
public bool Recommended { get; set; }
public bool CouponOnly { get; set; }
public string? VpProductId { get; set; }
public bool VpEnabled { get; set; }
public int SortOrder { get; set; }
public bool IsActive { get; set; } = true;
}
public sealed class Order : AuditableTenantEntity
{
public Guid? UserId { get; set; }
public Guid? PlanId { get; set; }
public Guid? RegionId { get; set; }
public string? LegacyId { get; set; }
public string? LegacyUserId { get; set; }
public string? LegacyPlanId { get; set; }
public string? LegacyRegionId { get; set; }
public string OrderNo { get; set; } = string.Empty;
public OrderStatus Status { get; set; } = OrderStatus.Pending;
public string? ProductType { get; set; }
public string? ProductName { get; set; }
public int AmountCents { get; set; }
public string? PayMethod { get; set; }
public string? PayProvider { get; set; }
public string? TradeNo { get; set; }
public int? Days { get; set; }
public DateTimeOffset? PaidAt { get; set; }
public JsonElement RawPayload { get; set; } = JsonDefaults.Object();
}
public sealed class OrderItem : AuditableTenantEntity
{
public Guid OrderId { get; set; }
public string? LegacyId { get; set; }
public string ItemType { get; set; } = string.Empty;
public Guid? ItemId { get; set; }
public string Name { get; set; } = string.Empty;
public int Quantity { get; set; } = 1;
public int UnitAmountCents { get; set; }
public int TotalAmountCents { get; set; }
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
}
public sealed class Payment : AuditableTenantEntity
{
public Guid OrderId { get; set; }
public string? LegacyId { get; set; }
public string? LegacyOrderId { get; set; }
public string Provider { get; set; } = string.Empty;
public string? Method { get; set; }
public PaymentStatus Status { get; set; } = PaymentStatus.Pending;
public int AmountCents { get; set; }
public string? ProviderTradeNo { get; set; }
public DateTimeOffset? PaidAt { get; set; }
public JsonElement RawPayload { get; set; } = JsonDefaults.Object();
}
public sealed class PaymentEvent : Entity
{
public Guid TenantId { get; set; }
public Guid? PaymentId { get; set; }
public string Provider { get; set; } = string.Empty;
public string EventType { get; set; } = string.Empty;
public string? EventId { get; set; }
public bool? SignatureValid { get; set; }
public JsonElement Payload { get; set; } = JsonDefaults.Object();
public DateTimeOffset? ProcessedAt { get; set; }
public string? Error { get; set; }
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
}
public sealed class Entitlement : Entity
{
public Guid TenantId { get; set; }
public Guid UserId { get; set; }
public string EntitlementType { get; set; } = "svip";
public EntitlementScopeType ScopeType { get; set; } = EntitlementScopeType.Tenant;
public Guid? ScopeId { get; set; }
public string SourceType { get; set; } = "migration";
public Guid? SourceId { get; set; }
public string? LegacySourceId { get; set; }
public DateTimeOffset StartsAt { get; set; } = DateTimeOffset.UtcNow;
public DateTimeOffset? ExpiresAt { get; set; }
public EntitlementStatus Status { get; set; } = EntitlementStatus.Active;
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
}
public sealed class CodeBatch : AuditableTenantEntity
{
public Guid? RegionId { get; set; }
public Guid? CreatedBy { get; set; }
public string? LegacyId { get; set; }
public string Name { get; set; } = string.Empty;
public string? SaleType { get; set; }
public string? Channel { get; set; }
public string? CampaignName { get; set; }
public int DefaultUnitPriceCents { get; set; }
public int CostPriceCents { get; set; }
public int TotalCount { get; set; }
public int? Days { get; set; }
public string? LegacyRegionId { get; set; }
public DateTimeOffset? IssuedAt { get; set; }
public string? Remark { get; set; }
public decimal? CommissionRate { get; set; }
}
public sealed class ActivationCode : AuditableTenantEntity
{
public Guid? UsedBy { get; set; }
public Guid? AgentUserId { get; set; }
public Guid? BatchId { get; set; }
public Guid? UsedRegionId { get; set; }
public Guid? CouponRedemptionId { get; set; }
public string? LegacyId { get; set; }
public string Code { get; set; } = string.Empty;
public int Days { get; set; }
public bool IsUsed { get; set; }
public DateTimeOffset? UsedAt { get; set; }
public string? SaleType { get; set; }
public int? UnitPriceCents { get; set; }
public string? SoldTo { get; set; }
public string? CouponCode { get; set; }
public string? Remark { get; set; }
}
public sealed class Coupon : AuditableTenantEntity
{
public Guid? PlanId { get; set; }
public string? LegacyId { get; set; }
public string Code { get; set; } = string.Empty;
public DiscountType? DiscountType { get; set; }
public decimal? DiscountValue { get; set; }
public DateTimeOffset? ValidFrom { get; set; }
public DateTimeOffset? ValidTo { get; set; }
public int? MaxUses { get; set; }
public int UsedCount { get; set; }
public string? Source { get; set; }
public string? Remark { get; set; }
}
public sealed class CouponRedemption : AuditableTenantEntity
{
public Guid? CouponId { get; set; }
public Guid? UserId { get; set; }
public Guid? PlanId { get; set; }
public Guid? OrderId { get; set; }
public Guid? RegionId { get; set; }
public string? LegacyId { get; set; }
public string? CouponCode { get; set; }
public CouponRedemptionStatus Status { get; set; } = CouponRedemptionStatus.Claimed;
public int? DiscountAppliedCents { get; set; }
public string? Source { get; set; }
public string? Remark { get; set; }
public DateTimeOffset? ClaimedAt { get; set; }
public DateTimeOffset? UsedAt { get; set; }
}
public sealed class TenantPaymentAccount : AuditableTenantEntity
{
public string Provider { get; set; } = string.Empty;
public TenantPaymentMode Mode { get; set; } = TenantPaymentMode.PlatformCollect;
public string? DisplayName { get; set; }
public TenantPaymentAccountStatus Status { get; set; } = TenantPaymentAccountStatus.Disabled;
public JsonElement ConfigPublic { get; set; } = JsonDefaults.Object();
}
public sealed class TenantSubscription : AuditableTenantEntity
{
public string PlanCode { get; set; } = string.Empty;
public TenantSubscriptionStatus Status { get; set; } = TenantSubscriptionStatus.Trial;
public DateTimeOffset? StartsAt { get; set; }
public DateTimeOffset? ExpiresAt { get; set; }
public string? BillingCycle { get; set; } = "yearly";
public int AmountCents { get; set; }
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
}
public sealed class TenantUsageRecord : Entity
{
public Guid TenantId { get; set; }
public string MetricKey { get; set; } = string.Empty;
public decimal MetricValue { get; set; }
public DateOnly PeriodStart { get; set; }
public DateOnly PeriodEnd { get; set; }
public JsonElement Metadata { get; set; } = JsonDefaults.Object();
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
}
public enum ProductType { Material, Course, Service, Link, Other }
public enum OrderStatus { Pending, Paid, Failed, Closed, Refunded }
public enum PaymentStatus { Pending, Paid, Failed, Cancelled, Refunded }
public enum EntitlementScopeType { Tenant, Region, Module, Subject, QuestionBank }
public enum EntitlementStatus { Active, Revoked, Expired }
public enum DiscountType { Percent, Fixed }
public enum CouponRedemptionStatus { Claimed, Used, Expired, Cancelled }
public enum TenantPaymentMode { PlatformCollect, TenantCollect, ServiceProvider }
public enum TenantPaymentAccountStatus { Active, Disabled, Pending }
public enum TenantSubscriptionStatus { Trial, Active, PastDue, Cancelled }

View File

@@ -0,0 +1,333 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Tiku.Domain.Catalog;
using Tiku.Domain.Commerce;
using Tiku.Domain.Identity;
using Tiku.Domain.Tenancy;
namespace Tiku.Infrastructure.Persistence.Configurations;
internal sealed class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.ConfigureTenantEntity("products");
builder.ConfigureTimestamps();
builder.Property(entity => entity.LegacyId).HasMaxLength(64);
builder.Property(entity => entity.Title).HasMaxLength(300);
builder.Property(entity => entity.LegacyPriceText).HasMaxLength(100);
builder.Property(entity => entity.Link).HasMaxLength(2048);
builder.Property(entity => entity.Type).HasSnakeCaseEnum();
builder.Property(entity => entity.Tags).IsJson("[]");
builder.Property(entity => entity.Cover).HasMaxLength(2048);
builder.Property(entity => entity.PreviewIframe).HasMaxLength(2048);
builder.Property(entity => entity.DetailImages).IsJson("[]");
builder.HasIndex(entity => new { entity.TenantId, entity.LegacyId }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.RegionId, entity.Type, entity.SortOrder });
builder.HasOne<Region>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.RegionId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Restrict);
}
}
internal sealed class SvipPlanConfiguration : IEntityTypeConfiguration<SvipPlan>
{
public void Configure(EntityTypeBuilder<SvipPlan> builder)
{
builder.ConfigureTenantEntity("svip_plans");
builder.ConfigureTimestamps();
builder.Property(entity => entity.LegacyId).HasMaxLength(64);
builder.Property(entity => entity.Name).HasMaxLength(200);
builder.Property(entity => entity.PerDayLabel).HasMaxLength(100);
builder.Property(entity => entity.Badge).HasMaxLength(100);
builder.Property(entity => entity.VpProductId).HasMaxLength(100);
builder.HasIndex(entity => new { entity.TenantId, entity.LegacyId }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.RegionId, entity.IsActive, entity.SortOrder });
builder.ToTable(table =>
{
table.HasCheckConstraint("ck_svip_plans_price", "price_cents >= 0 and (original_price_cents is null or original_price_cents >= 0)");
table.HasCheckConstraint("ck_svip_plans_days", "days >= 0");
});
builder.HasOne<Region>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.RegionId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Restrict);
}
}
internal sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.ConfigureTenantEntity("orders");
builder.ConfigureTimestamps();
builder.Property(entity => entity.LegacyId).HasMaxLength(64);
builder.Property(entity => entity.LegacyUserId).HasMaxLength(64);
builder.Property(entity => entity.LegacyPlanId).HasMaxLength(64);
builder.Property(entity => entity.LegacyRegionId).HasMaxLength(64);
builder.Property(entity => entity.OrderNo).HasMaxLength(100);
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.ProductType).HasMaxLength(100);
builder.Property(entity => entity.ProductName).HasMaxLength(300);
builder.Property(entity => entity.PayMethod).HasMaxLength(50);
builder.Property(entity => entity.PayProvider).HasMaxLength(50);
builder.Property(entity => entity.TradeNo).HasMaxLength(200);
builder.Property(entity => entity.RawPayload).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.OrderNo }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.LegacyId }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.UserId, entity.CreatedAt });
builder.ToTable(table => table.HasCheckConstraint("ck_orders_amount", "amount_cents >= 0"));
builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.UserId).OnDelete(DeleteBehavior.SetNull);
builder.HasOne<SvipPlan>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.PlanId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne<Region>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.RegionId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Restrict);
}
}
internal sealed class OrderItemConfiguration : IEntityTypeConfiguration<OrderItem>
{
public void Configure(EntityTypeBuilder<OrderItem> builder)
{
builder.ConfigureTenantEntity("order_items");
builder.ConfigureTimestamps();
builder.Property(entity => entity.LegacyId).HasMaxLength(64);
builder.Property(entity => entity.ItemType).HasMaxLength(100);
builder.Property(entity => entity.Name).HasMaxLength(300);
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.LegacyId }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.OrderId });
builder.ToTable(table =>
{
table.HasCheckConstraint("ck_order_items_quantity", "quantity > 0");
table.HasCheckConstraint("ck_order_items_amounts", "unit_amount_cents >= 0 and total_amount_cents >= 0");
});
builder.HasOne<Order>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.OrderId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Cascade);
}
}
internal sealed class PaymentConfiguration : IEntityTypeConfiguration<Payment>
{
public void Configure(EntityTypeBuilder<Payment> builder)
{
builder.ConfigureTenantEntity("payments");
builder.ConfigureTimestamps();
builder.Property(entity => entity.LegacyId).HasMaxLength(64);
builder.Property(entity => entity.LegacyOrderId).HasMaxLength(64);
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 => new { entity.TenantId, entity.LegacyId }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.OrderId, entity.UpdatedAt });
builder.HasIndex(entity => new { entity.Provider, entity.ProviderTradeNo })
.IsUnique()
.HasFilter("provider_trade_no is not null");
builder.ToTable(table => table.HasCheckConstraint("ck_payments_amount", "amount_cents >= 0"));
builder.HasOne<Order>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.OrderId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Cascade);
}
}
internal sealed class PaymentEventConfiguration : IEntityTypeConfiguration<PaymentEvent>
{
public void Configure(EntityTypeBuilder<PaymentEvent> builder)
{
builder.ConfigureEntity("payment_events");
builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id });
builder.Property(entity => entity.Provider).HasMaxLength(50);
builder.Property(entity => entity.EventType).HasMaxLength(100);
builder.Property(entity => entity.EventId).HasMaxLength(200);
builder.Property(entity => entity.Payload).IsJson("{}");
builder.Property(entity => entity.CreatedAt).HasDefaultValueSql("now()");
builder.HasIndex(entity => new { entity.Provider, entity.EventId }).IsUnique();
builder.HasOne<Tenant>().WithMany().HasForeignKey(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<Payment>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.PaymentId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class EntitlementConfiguration : IEntityTypeConfiguration<Entitlement>
{
public void Configure(EntityTypeBuilder<Entitlement> builder)
{
builder.ConfigureEntity("entitlements");
builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id });
builder.Property(entity => entity.EntitlementType).HasMaxLength(50);
builder.Property(entity => entity.ScopeType).HasSnakeCaseEnum();
builder.Property(entity => entity.SourceType).HasMaxLength(100);
builder.Property(entity => entity.LegacySourceId).HasMaxLength(64);
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.Property(entity => entity.StartsAt).HasDefaultValueSql("now()");
builder.Property(entity => entity.CreatedAt).HasDefaultValueSql("now()");
builder.HasIndex(entity => new { entity.TenantId, entity.UserId, entity.Status, entity.ExpiresAt });
builder.HasOne<Tenant>().WithMany().HasForeignKey(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.UserId).OnDelete(DeleteBehavior.Cascade);
}
}
internal sealed class CodeBatchConfiguration : IEntityTypeConfiguration<CodeBatch>
{
public void Configure(EntityTypeBuilder<CodeBatch> builder)
{
builder.ConfigureTenantEntity("code_batches");
builder.ConfigureTimestamps();
builder.Property(entity => entity.LegacyId).HasMaxLength(64);
builder.Property(entity => entity.Name).HasMaxLength(200);
builder.Property(entity => entity.SaleType).HasMaxLength(50);
builder.Property(entity => entity.Channel).HasMaxLength(100);
builder.Property(entity => entity.CampaignName).HasMaxLength(200);
builder.Property(entity => entity.LegacyRegionId).HasMaxLength(64);
builder.Property(entity => entity.CommissionRate).HasPrecision(6, 4);
builder.HasIndex(entity => new { entity.TenantId, entity.LegacyId }).IsUnique();
builder.ToTable(table =>
{
table.HasCheckConstraint("ck_code_batches_counts", "total_count >= 0");
table.HasCheckConstraint("ck_code_batches_amounts", "default_unit_price_cents >= 0 and cost_price_cents >= 0");
});
}
}
internal sealed class ActivationCodeConfiguration : IEntityTypeConfiguration<ActivationCode>
{
public void Configure(EntityTypeBuilder<ActivationCode> builder)
{
builder.ConfigureTenantEntity("activation_codes");
builder.ConfigureTimestamps();
builder.Property(entity => entity.LegacyId).HasMaxLength(64);
builder.Property(entity => entity.Code).HasColumnType("citext").HasMaxLength(100);
builder.Property(entity => entity.SaleType).HasMaxLength(50);
builder.Property(entity => entity.SoldTo).HasMaxLength(200);
builder.Property(entity => entity.CouponCode).HasMaxLength(100);
builder.HasIndex(entity => new { entity.TenantId, entity.Code }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.LegacyId }).IsUnique();
builder.HasOne<CodeBatch>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.BatchId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.UsedBy).OnDelete(DeleteBehavior.SetNull);
builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.AgentUserId).OnDelete(DeleteBehavior.SetNull);
builder.HasOne<Region>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.UsedRegionId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne<CouponRedemption>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.CouponRedemptionId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class CouponConfiguration : IEntityTypeConfiguration<Coupon>
{
public void Configure(EntityTypeBuilder<Coupon> builder)
{
builder.ConfigureTenantEntity("coupons");
builder.ConfigureTimestamps();
builder.Property(entity => entity.LegacyId).HasMaxLength(64);
builder.Property(entity => entity.Code).HasColumnType("citext").HasMaxLength(100);
builder.Property(entity => entity.DiscountType).HasNullableSnakeCaseEnum();
builder.Property(entity => entity.DiscountValue).HasPrecision(10, 2);
builder.Property(entity => entity.Source).HasMaxLength(50);
builder.HasIndex(entity => new { entity.TenantId, entity.Code }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.LegacyId }).IsUnique();
builder.HasOne<SvipPlan>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.PlanId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.Restrict);
}
}
internal sealed class CouponRedemptionConfiguration : IEntityTypeConfiguration<CouponRedemption>
{
public void Configure(EntityTypeBuilder<CouponRedemption> builder)
{
builder.ConfigureTenantEntity("coupon_redemptions");
builder.ConfigureTimestamps();
builder.Property(entity => entity.LegacyId).HasMaxLength(64);
builder.Property(entity => entity.CouponCode).HasMaxLength(100);
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.Source).HasMaxLength(50);
builder.HasIndex(entity => new { entity.TenantId, entity.LegacyId }).IsUnique();
builder.HasIndex(entity => new { entity.TenantId, entity.UserId, entity.CouponId })
.IsUnique()
.HasFilter("coupon_id is not null");
builder.HasIndex(entity => new { entity.TenantId, entity.OrderId, entity.UserId })
.HasFilter("order_id is not null");
builder.HasOne<Coupon>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.CouponId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne<User>().WithMany().HasForeignKey(entity => entity.UserId).OnDelete(DeleteBehavior.SetNull);
builder.HasOne<SvipPlan>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.PlanId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne<Order>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.OrderId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.SetNull);
builder.HasOne<Region>().WithMany()
.HasForeignKey(entity => new { entity.TenantId, entity.RegionId })
.HasPrincipalKey(entity => new { entity.TenantId, entity.Id })
.OnDelete(DeleteBehavior.SetNull);
}
}
internal sealed class TenantPaymentAccountConfiguration : IEntityTypeConfiguration<TenantPaymentAccount>
{
public void Configure(EntityTypeBuilder<TenantPaymentAccount> builder)
{
builder.ConfigureTenantEntity("tenant_payment_accounts");
builder.ConfigureTimestamps();
builder.Property(entity => entity.Provider).HasMaxLength(50);
builder.Property(entity => entity.Mode).HasSnakeCaseEnum();
builder.Property(entity => entity.DisplayName).HasMaxLength(200);
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.ConfigPublic).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.Provider }).IsUnique();
}
}
internal sealed class TenantSubscriptionConfiguration : IEntityTypeConfiguration<TenantSubscription>
{
public void Configure(EntityTypeBuilder<TenantSubscription> builder)
{
builder.ConfigureTenantEntity("tenant_subscriptions");
builder.ConfigureTimestamps();
builder.Property(entity => entity.PlanCode).HasMaxLength(100);
builder.Property(entity => entity.Status).HasSnakeCaseEnum();
builder.Property(entity => entity.BillingCycle).HasMaxLength(50);
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.HasIndex(entity => new { entity.TenantId, entity.Status, entity.ExpiresAt });
}
}
internal sealed class TenantUsageRecordConfiguration : IEntityTypeConfiguration<TenantUsageRecord>
{
public void Configure(EntityTypeBuilder<TenantUsageRecord> builder)
{
builder.ConfigureEntity("tenant_usage_records");
builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id });
builder.Property(entity => entity.MetricKey).HasMaxLength(100);
builder.Property(entity => entity.MetricValue).HasPrecision(18, 4);
builder.Property(entity => entity.Metadata).IsJson("{}");
builder.Property(entity => entity.CreatedAt).HasDefaultValueSql("now()");
builder.HasIndex(entity => new { entity.TenantId, entity.MetricKey, entity.PeriodStart, entity.PeriodEnd });
builder.HasOne<Tenant>().WithMany().HasForeignKey(entity => entity.TenantId).OnDelete(DeleteBehavior.Cascade);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,853 @@
using System;
using System.Text.Json;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Tiku.Infrastructure.Persistence.Migrations
{
/// <inheritdoc />
public partial class AddCommercePersistence : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "code_batches",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
region_id = table.Column<Guid>(type: "uuid", nullable: true),
created_by = table.Column<Guid>(type: "uuid", nullable: true),
legacy_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
sale_type = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
channel = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
campaign_name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
default_unit_price_cents = table.Column<int>(type: "integer", nullable: false),
cost_price_cents = table.Column<int>(type: "integer", nullable: false),
total_count = table.Column<int>(type: "integer", nullable: false),
days = table.Column<int>(type: "integer", nullable: true),
legacy_region_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
issued_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
remark = table.Column<string>(type: "text", nullable: true),
commission_rate = table.Column<decimal>(type: "numeric(6,4)", precision: 6, scale: 4, 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_code_batches", x => x.id);
table.UniqueConstraint("ak_code_batches_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_code_batches_amounts", "default_unit_price_cents >= 0 and cost_price_cents >= 0");
table.CheckConstraint("ck_code_batches_counts", "total_count >= 0");
table.ForeignKey(
name: "fk_code_batches_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "entitlements",
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: false),
entitlement_type = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
scope_type = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
scope_id = table.Column<Guid>(type: "uuid", nullable: true),
source_type = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
source_id = table.Column<Guid>(type: "uuid", nullable: true),
legacy_source_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
starts_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
expires_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, 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_entitlements", x => x.id);
table.UniqueConstraint("ak_entitlements_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_entitlements_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_entitlements_users_user_id",
column: x => x.user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "products",
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),
title = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: false),
legacy_price_text = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
link = table.Column<string>(type: "character varying(2048)", maxLength: 2048, nullable: true),
type = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
tags = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'[]'::jsonb"),
sort_order = table.Column<int>(type: "integer", nullable: false),
cover = table.Column<string>(type: "character varying(2048)", maxLength: 2048, nullable: true),
preview_iframe = table.Column<string>(type: "character varying(2048)", maxLength: 2048, nullable: true),
detail_images = 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_products", x => x.id);
table.UniqueConstraint("ak_products_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_products_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_products_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "svip_plans",
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),
name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
price_cents = table.Column<int>(type: "integer", nullable: false),
original_price_cents = table.Column<int>(type: "integer", nullable: true),
days = table.Column<int>(type: "integer", nullable: false),
description = table.Column<string>(type: "text", nullable: true),
per_day_label = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
badge = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
recommended = table.Column<bool>(type: "boolean", nullable: false),
coupon_only = table.Column<bool>(type: "boolean", nullable: false),
vp_product_id = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
vp_enabled = table.Column<bool>(type: "boolean", nullable: false),
sort_order = table.Column<int>(type: "integer", nullable: false),
is_active = table.Column<bool>(type: "boolean", nullable: false),
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_svip_plans", x => x.id);
table.UniqueConstraint("ak_svip_plans_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_svip_plans_days", "days >= 0");
table.CheckConstraint("ck_svip_plans_price", "price_cents >= 0 and (original_price_cents is null or original_price_cents >= 0)");
table.ForeignKey(
name: "fk_svip_plans_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_svip_plans_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "tenant_payment_accounts",
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),
mode = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
display_name = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
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_payment_accounts", x => x.id);
table.UniqueConstraint("ak_tenant_payment_accounts_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_tenant_payment_accounts_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "tenant_subscriptions",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
plan_code = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
starts_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
expires_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
billing_cycle = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
amount_cents = table.Column<int>(type: "integer", nullable: false),
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_subscriptions", x => x.id);
table.UniqueConstraint("ak_tenant_subscriptions_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_tenant_subscriptions_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "tenant_usage_records",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
metric_key = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
metric_value = table.Column<decimal>(type: "numeric(18,4)", precision: 18, scale: 4, nullable: false),
period_start = table.Column<DateOnly>(type: "date", nullable: false),
period_end = table.Column<DateOnly>(type: "date", 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_usage_records", x => x.id);
table.UniqueConstraint("ak_tenant_usage_records_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_tenant_usage_records_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "coupons",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
plan_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: "citext", maxLength: 100, nullable: false),
discount_type = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: true),
discount_value = table.Column<decimal>(type: "numeric(10,2)", precision: 10, scale: 2, nullable: true),
valid_from = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
valid_to = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
max_uses = table.Column<int>(type: "integer", nullable: true),
used_count = table.Column<int>(type: "integer", nullable: false),
source = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
remark = table.Column<string>(type: "text", 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_coupons", x => x.id);
table.UniqueConstraint("ak_coupons_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_coupons_svip_plans_tenant_id_plan_id",
columns: x => new { x.tenant_id, x.plan_id },
principalTable: "svip_plans",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "fk_coupons_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "orders",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
user_id = table.Column<Guid>(type: "uuid", nullable: true),
plan_id = table.Column<Guid>(type: "uuid", nullable: true),
region_id = table.Column<Guid>(type: "uuid", nullable: true),
legacy_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
legacy_user_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
legacy_plan_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
legacy_region_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
order_no = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
product_type = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
product_name = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: true),
amount_cents = table.Column<int>(type: "integer", nullable: false),
pay_method = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
pay_provider = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
trade_no = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
days = table.Column<int>(type: "integer", nullable: true),
paid_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", 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_orders", x => x.id);
table.UniqueConstraint("ak_orders_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_orders_amount", "amount_cents >= 0");
table.ForeignKey(
name: "fk_orders_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_orders_svip_plans_tenant_id_plan_id",
columns: x => new { x.tenant_id, x.plan_id },
principalTable: "svip_plans",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "fk_orders_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_orders_users_user_id",
column: x => x.user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "coupon_redemptions",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
coupon_id = table.Column<Guid>(type: "uuid", nullable: true),
user_id = table.Column<Guid>(type: "uuid", nullable: true),
plan_id = table.Column<Guid>(type: "uuid", nullable: true),
order_id = table.Column<Guid>(type: "uuid", nullable: true),
region_id = table.Column<Guid>(type: "uuid", nullable: true),
legacy_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
coupon_code = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
status = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
discount_applied_cents = table.Column<int>(type: "integer", nullable: true),
source = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
remark = table.Column<string>(type: "text", nullable: true),
claimed_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
used_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_coupon_redemptions", x => x.id);
table.UniqueConstraint("ak_coupon_redemptions_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_coupon_redemptions_coupons_tenant_id_coupon_id",
columns: x => new { x.tenant_id, x.coupon_id },
principalTable: "coupons",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_coupon_redemptions_orders_tenant_id_order_id",
columns: x => new { x.tenant_id, x.order_id },
principalTable: "orders",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_coupon_redemptions_regions_tenant_id_region_id",
columns: x => new { x.tenant_id, x.region_id },
principalTable: "regions",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_coupon_redemptions_svip_plans_tenant_id_plan_id",
columns: x => new { x.tenant_id, x.plan_id },
principalTable: "svip_plans",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_coupon_redemptions_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_coupon_redemptions_users_user_id",
column: x => x.user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "order_items",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
order_id = table.Column<Guid>(type: "uuid", nullable: false),
legacy_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
item_type = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
item_id = table.Column<Guid>(type: "uuid", nullable: true),
name = table.Column<string>(type: "character varying(300)", maxLength: 300, nullable: false),
quantity = table.Column<int>(type: "integer", nullable: false),
unit_amount_cents = table.Column<int>(type: "integer", nullable: false),
total_amount_cents = table.Column<int>(type: "integer", nullable: false),
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_order_items", x => x.id);
table.UniqueConstraint("ak_order_items_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_order_items_amounts", "unit_amount_cents >= 0 and total_amount_cents >= 0");
table.CheckConstraint("ck_order_items_quantity", "quantity > 0");
table.ForeignKey(
name: "fk_order_items_orders_tenant_id_order_id",
columns: x => new { x.tenant_id, x.order_id },
principalTable: "orders",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_order_items_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "payments",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
order_id = table.Column<Guid>(type: "uuid", nullable: false),
legacy_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
legacy_order_id = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
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),
provider_trade_no = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
paid_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", 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_payments", x => x.id);
table.UniqueConstraint("ak_payments_tenant_id_id", x => new { x.tenant_id, x.id });
table.CheckConstraint("ck_payments_amount", "amount_cents >= 0");
table.ForeignKey(
name: "fk_payments_orders_tenant_id_order_id",
columns: x => new { x.tenant_id, x.order_id },
principalTable: "orders",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_payments_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "activation_codes",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
used_by = table.Column<Guid>(type: "uuid", nullable: true),
agent_user_id = table.Column<Guid>(type: "uuid", nullable: true),
batch_id = table.Column<Guid>(type: "uuid", nullable: true),
used_region_id = table.Column<Guid>(type: "uuid", nullable: true),
coupon_redemption_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: "citext", maxLength: 100, nullable: false),
days = table.Column<int>(type: "integer", nullable: false),
is_used = table.Column<bool>(type: "boolean", nullable: false),
used_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
sale_type = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
unit_price_cents = table.Column<int>(type: "integer", nullable: true),
sold_to = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
coupon_code = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: true),
remark = table.Column<string>(type: "text", 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_activation_codes", x => x.id);
table.UniqueConstraint("ak_activation_codes_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_activation_codes_code_batches_tenant_id_batch_id",
columns: x => new { x.tenant_id, x.batch_id },
principalTable: "code_batches",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_activation_codes_coupon_redemptions_tenant_id_coupon_redemp~",
columns: x => new { x.tenant_id, x.coupon_redemption_id },
principalTable: "coupon_redemptions",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_activation_codes_regions_tenant_id_used_region_id",
columns: x => new { x.tenant_id, x.used_region_id },
principalTable: "regions",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_activation_codes_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_activation_codes_users_agent_user_id",
column: x => x.agent_user_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_activation_codes_users_used_by",
column: x => x.used_by,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.SetNull);
});
migrationBuilder.CreateTable(
name: "payment_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),
payment_id = table.Column<Guid>(type: "uuid", nullable: true),
provider = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
event_type = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
event_id = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: true),
signature_valid = table.Column<bool>(type: "boolean", nullable: true),
payload = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
processed_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
error = table.Column<string>(type: "text", nullable: true),
created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()")
},
constraints: table =>
{
table.PrimaryKey("pk_payment_events", x => x.id);
table.UniqueConstraint("ak_payment_events_tenant_id_id", x => new { x.tenant_id, x.id });
table.ForeignKey(
name: "fk_payment_events_payments_tenant_id_payment_id",
columns: x => new { x.tenant_id, x.payment_id },
principalTable: "payments",
principalColumns: new[] { "tenant_id", "id" },
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "fk_payment_events_tenants_tenant_id",
column: x => x.tenant_id,
principalTable: "tenants",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "ix_activation_codes_agent_user_id",
table: "activation_codes",
column: "agent_user_id");
migrationBuilder.CreateIndex(
name: "ix_activation_codes_tenant_id_batch_id",
table: "activation_codes",
columns: new[] { "tenant_id", "batch_id" });
migrationBuilder.CreateIndex(
name: "ix_activation_codes_tenant_id_code",
table: "activation_codes",
columns: new[] { "tenant_id", "code" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_activation_codes_tenant_id_coupon_redemption_id",
table: "activation_codes",
columns: new[] { "tenant_id", "coupon_redemption_id" });
migrationBuilder.CreateIndex(
name: "ix_activation_codes_tenant_id_legacy_id",
table: "activation_codes",
columns: new[] { "tenant_id", "legacy_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_activation_codes_tenant_id_used_region_id",
table: "activation_codes",
columns: new[] { "tenant_id", "used_region_id" });
migrationBuilder.CreateIndex(
name: "ix_activation_codes_used_by",
table: "activation_codes",
column: "used_by");
migrationBuilder.CreateIndex(
name: "ix_code_batches_tenant_id_legacy_id",
table: "code_batches",
columns: new[] { "tenant_id", "legacy_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_coupon_redemptions_tenant_id_coupon_id",
table: "coupon_redemptions",
columns: new[] { "tenant_id", "coupon_id" });
migrationBuilder.CreateIndex(
name: "ix_coupon_redemptions_tenant_id_legacy_id",
table: "coupon_redemptions",
columns: new[] { "tenant_id", "legacy_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_coupon_redemptions_tenant_id_order_id_user_id",
table: "coupon_redemptions",
columns: new[] { "tenant_id", "order_id", "user_id" },
filter: "order_id is not null");
migrationBuilder.CreateIndex(
name: "ix_coupon_redemptions_tenant_id_plan_id",
table: "coupon_redemptions",
columns: new[] { "tenant_id", "plan_id" });
migrationBuilder.CreateIndex(
name: "ix_coupon_redemptions_tenant_id_region_id",
table: "coupon_redemptions",
columns: new[] { "tenant_id", "region_id" });
migrationBuilder.CreateIndex(
name: "ix_coupon_redemptions_tenant_id_user_id_coupon_id",
table: "coupon_redemptions",
columns: new[] { "tenant_id", "user_id", "coupon_id" },
unique: true,
filter: "coupon_id is not null");
migrationBuilder.CreateIndex(
name: "ix_coupon_redemptions_user_id",
table: "coupon_redemptions",
column: "user_id");
migrationBuilder.CreateIndex(
name: "ix_coupons_tenant_id_code",
table: "coupons",
columns: new[] { "tenant_id", "code" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_coupons_tenant_id_legacy_id",
table: "coupons",
columns: new[] { "tenant_id", "legacy_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_coupons_tenant_id_plan_id",
table: "coupons",
columns: new[] { "tenant_id", "plan_id" });
migrationBuilder.CreateIndex(
name: "ix_entitlements_tenant_id_user_id_status_expires_at",
table: "entitlements",
columns: new[] { "tenant_id", "user_id", "status", "expires_at" });
migrationBuilder.CreateIndex(
name: "ix_entitlements_user_id",
table: "entitlements",
column: "user_id");
migrationBuilder.CreateIndex(
name: "ix_order_items_tenant_id_legacy_id",
table: "order_items",
columns: new[] { "tenant_id", "legacy_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_order_items_tenant_id_order_id",
table: "order_items",
columns: new[] { "tenant_id", "order_id" });
migrationBuilder.CreateIndex(
name: "ix_orders_tenant_id_legacy_id",
table: "orders",
columns: new[] { "tenant_id", "legacy_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_orders_tenant_id_order_no",
table: "orders",
columns: new[] { "tenant_id", "order_no" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_orders_tenant_id_plan_id",
table: "orders",
columns: new[] { "tenant_id", "plan_id" });
migrationBuilder.CreateIndex(
name: "ix_orders_tenant_id_region_id",
table: "orders",
columns: new[] { "tenant_id", "region_id" });
migrationBuilder.CreateIndex(
name: "ix_orders_tenant_id_user_id_created_at",
table: "orders",
columns: new[] { "tenant_id", "user_id", "created_at" });
migrationBuilder.CreateIndex(
name: "ix_orders_user_id",
table: "orders",
column: "user_id");
migrationBuilder.CreateIndex(
name: "ix_payment_events_provider_event_id",
table: "payment_events",
columns: new[] { "provider", "event_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_payment_events_tenant_id_payment_id",
table: "payment_events",
columns: new[] { "tenant_id", "payment_id" });
migrationBuilder.CreateIndex(
name: "ix_payments_provider_provider_trade_no",
table: "payments",
columns: new[] { "provider", "provider_trade_no" },
unique: true,
filter: "provider_trade_no is not null");
migrationBuilder.CreateIndex(
name: "ix_payments_tenant_id_legacy_id",
table: "payments",
columns: new[] { "tenant_id", "legacy_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_payments_tenant_id_order_id_updated_at",
table: "payments",
columns: new[] { "tenant_id", "order_id", "updated_at" });
migrationBuilder.CreateIndex(
name: "ix_products_tenant_id_legacy_id",
table: "products",
columns: new[] { "tenant_id", "legacy_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_products_tenant_id_region_id_type_sort_order",
table: "products",
columns: new[] { "tenant_id", "region_id", "type", "sort_order" });
migrationBuilder.CreateIndex(
name: "ix_svip_plans_tenant_id_legacy_id",
table: "svip_plans",
columns: new[] { "tenant_id", "legacy_id" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_svip_plans_tenant_id_region_id_is_active_sort_order",
table: "svip_plans",
columns: new[] { "tenant_id", "region_id", "is_active", "sort_order" });
migrationBuilder.CreateIndex(
name: "ix_tenant_payment_accounts_tenant_id_provider",
table: "tenant_payment_accounts",
columns: new[] { "tenant_id", "provider" },
unique: true);
migrationBuilder.CreateIndex(
name: "ix_tenant_subscriptions_tenant_id_status_expires_at",
table: "tenant_subscriptions",
columns: new[] { "tenant_id", "status", "expires_at" });
migrationBuilder.CreateIndex(
name: "ix_tenant_usage_records_tenant_id_metric_key_period_start_peri~",
table: "tenant_usage_records",
columns: new[] { "tenant_id", "metric_key", "period_start", "period_end" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "activation_codes");
migrationBuilder.DropTable(
name: "entitlements");
migrationBuilder.DropTable(
name: "order_items");
migrationBuilder.DropTable(
name: "payment_events");
migrationBuilder.DropTable(
name: "products");
migrationBuilder.DropTable(
name: "tenant_payment_accounts");
migrationBuilder.DropTable(
name: "tenant_subscriptions");
migrationBuilder.DropTable(
name: "tenant_usage_records");
migrationBuilder.DropTable(
name: "code_batches");
migrationBuilder.DropTable(
name: "coupon_redemptions");
migrationBuilder.DropTable(
name: "payments");
migrationBuilder.DropTable(
name: "coupons");
migrationBuilder.DropTable(
name: "orders");
migrationBuilder.DropTable(
name: "svip_plans");
}
}
}

View File

@@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Tiku.Domain.Catalog;
using Tiku.Domain.Commerce;
using Tiku.Domain.Common;
using Tiku.Domain.Content;
using Tiku.Domain.Identity;
@@ -76,6 +77,20 @@ public sealed class TikuDbContext(DbContextOptions<TikuDbContext> options) : DbC
public DbSet<PracticeSessionReportSection> PracticeSessionReportSections => Set<PracticeSessionReportSection>();
public DbSet<DashboardDailyStat> DashboardDailyStats => Set<DashboardDailyStat>();
public DbSet<RevenueDailyStat> RevenueDailyStats => Set<RevenueDailyStat>();
public DbSet<Product> Products => Set<Product>();
public DbSet<SvipPlan> SvipPlans => Set<SvipPlan>();
public DbSet<Order> Orders => Set<Order>();
public DbSet<OrderItem> OrderItems => Set<OrderItem>();
public DbSet<Payment> Payments => Set<Payment>();
public DbSet<PaymentEvent> PaymentEvents => Set<PaymentEvent>();
public DbSet<Entitlement> Entitlements => Set<Entitlement>();
public DbSet<CodeBatch> CodeBatches => Set<CodeBatch>();
public DbSet<ActivationCode> ActivationCodes => Set<ActivationCode>();
public DbSet<Coupon> Coupons => Set<Coupon>();
public DbSet<CouponRedemption> CouponRedemptions => Set<CouponRedemption>();
public DbSet<TenantPaymentAccount> TenantPaymentAccounts => Set<TenantPaymentAccount>();
public DbSet<TenantSubscription> TenantSubscriptions => Set<TenantSubscription>();
public DbSet<TenantUsageRecord> TenantUsageRecords => Set<TenantUsageRecord>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{

View File

@@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Tiku.Domain.Commerce;
using Tiku.Domain.Content;
using Tiku.Domain.Learning;
using Tiku.Domain.QuestionBanks;
@@ -25,7 +26,7 @@ public sealed class PersistenceModelTests
.Select(entity => entity.GetTableName())
.ToHashSet(StringComparer.Ordinal);
Assert.Equal(65, tableNames.Count);
Assert.Equal(79, tableNames.Count);
Assert.Contains("tenants", tableNames);
Assert.Contains("tenant_settings", tableNames);
Assert.Contains("content_entries", tableNames);
@@ -69,6 +70,20 @@ public sealed class PersistenceModelTests
Assert.Contains("tenant_class_members", tableNames);
Assert.Contains("tenant_student_notes", tableNames);
Assert.Contains("tenant_student_followups", tableNames);
Assert.Contains("products", tableNames);
Assert.Contains("svip_plans", tableNames);
Assert.Contains("orders", tableNames);
Assert.Contains("order_items", tableNames);
Assert.Contains("payments", tableNames);
Assert.Contains("payment_events", tableNames);
Assert.Contains("entitlements", tableNames);
Assert.Contains("code_batches", tableNames);
Assert.Contains("activation_codes", tableNames);
Assert.Contains("coupons", tableNames);
Assert.Contains("coupon_redemptions", tableNames);
Assert.Contains("tenant_payment_accounts", tableNames);
Assert.Contains("tenant_subscriptions", tableNames);
Assert.Contains("tenant_usage_records", tableNames);
Assert.Contains("questions", tableNames);
Assert.Contains("question_versions", tableNames);
Assert.Contains("answer_records", tableNames);
@@ -434,4 +449,58 @@ public sealed class PersistenceModelTests
.SequenceEqual(propertyNames));
}
}
[Theory]
[InlineData(typeof(Product), nameof(Product.Tags), "'[]'::jsonb")]
[InlineData(typeof(Product), nameof(Product.DetailImages), "'[]'::jsonb")]
[InlineData(typeof(Order), nameof(Order.RawPayload), "'{}'::jsonb")]
[InlineData(typeof(OrderItem), nameof(OrderItem.Metadata), "'{}'::jsonb")]
[InlineData(typeof(Payment), nameof(Payment.RawPayload), "'{}'::jsonb")]
[InlineData(typeof(PaymentEvent), nameof(PaymentEvent.Payload), "'{}'::jsonb")]
[InlineData(typeof(Entitlement), nameof(Entitlement.Metadata), "'{}'::jsonb")]
[InlineData(typeof(TenantPaymentAccount), nameof(TenantPaymentAccount.ConfigPublic), "'{}'::jsonb")]
[InlineData(typeof(TenantSubscription), nameof(TenantSubscription.Metadata), "'{}'::jsonb")]
[InlineData(typeof(TenantUsageRecord), nameof(TenantUsageRecord.Metadata), "'{}'::jsonb")]
public void Commerce_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 Commerce_tables_have_expected_unique_indexes_and_money_types()
{
using var context = new TikuDbContext(Options);
AssertHasUniqueIndex<Order>(nameof(Order.TenantId), nameof(Order.OrderNo));
AssertHasUniqueIndex<ActivationCode>(nameof(ActivationCode.TenantId), nameof(ActivationCode.Code));
AssertHasUniqueIndex<TenantPaymentAccount>(
nameof(TenantPaymentAccount.TenantId),
nameof(TenantPaymentAccount.Provider));
var amount = context.Model.FindEntityType(typeof(Order))!
.FindProperty(nameof(Order.AmountCents))!;
Assert.Equal(typeof(int), amount.ClrType);
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));
}
}
}