forked from gongxuegit/tiku-backend.net
feat: add tenant commerce operations
This commit is contained in:
222
Tiku.IntegrationTests/Api/TenantCommerceEndpointTests.cs
Normal file
222
Tiku.IntegrationTests/Api/TenantCommerceEndpointTests.cs
Normal file
@@ -0,0 +1,222 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Tiku.Api.Contracts;
|
||||
using Tiku.Application.Auth;
|
||||
using Tiku.Application.Commerce;
|
||||
using Tiku.Domain.Commerce;
|
||||
using Tiku.Domain.Identity;
|
||||
using Tiku.Domain.Tenancy;
|
||||
using Tiku.Infrastructure.Auth;
|
||||
using Tiku.Infrastructure.Persistence;
|
||||
|
||||
namespace Tiku.IntegrationTests.Api;
|
||||
|
||||
public sealed class TenantCommerceEndpointTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Non_admin_cannot_access_tenant_commerce_operations()
|
||||
{
|
||||
await using var factory = new ApiTestFactory(paymentProviderGateway: new FakePaymentGateway());
|
||||
var seed = await SeedLoginUserAsync(factory, TenantRole.Student);
|
||||
using var client = factory.CreateClient();
|
||||
await LoginAsync(client, seed);
|
||||
|
||||
var response = await client.GetAsync("/api/tenant-commerce/orders");
|
||||
|
||||
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Payment_account_public_config_rejects_secrets()
|
||||
{
|
||||
await using var factory = new ApiTestFactory(paymentProviderGateway: new FakePaymentGateway());
|
||||
var seed = await SeedLoginUserAsync(factory, TenantRole.TenantAdmin);
|
||||
using var client = factory.CreateClient();
|
||||
await LoginAsync(client, seed);
|
||||
|
||||
var response = await client.PutAsJsonAsync(
|
||||
"/api/tenant-commerce/payment-accounts",
|
||||
new UpsertPaymentAccountDto
|
||||
{
|
||||
Provider = "wechat_pay",
|
||||
Status = TenantPaymentAccountStatus.Active,
|
||||
ConfigPublic = JsonSerializer.SerializeToElement(new
|
||||
{
|
||||
merchantId = "mch",
|
||||
apiV3Key = "must-not-be-public"
|
||||
})
|
||||
});
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_can_configure_payment_account_and_secret()
|
||||
{
|
||||
await using var factory = new ApiTestFactory(paymentProviderGateway: new FakePaymentGateway());
|
||||
var seed = await SeedLoginUserAsync(factory, TenantRole.TenantAdmin);
|
||||
using var client = factory.CreateClient();
|
||||
await LoginAsync(client, seed);
|
||||
|
||||
var secretResponse = await client.PutAsJsonAsync(
|
||||
"/api/tenant-commerce/secrets",
|
||||
new UpsertTenantSecretDto
|
||||
{
|
||||
Purpose = "payment",
|
||||
Provider = "wechat_pay",
|
||||
SecretKey = "default",
|
||||
SecretRef = "tenant_secrets:payment:wechat_pay:default",
|
||||
SecretPayload = JsonSerializer.SerializeToElement(new
|
||||
{
|
||||
privateKey = "pem",
|
||||
apiV3Key = "v3"
|
||||
})
|
||||
});
|
||||
var accountResponse = await client.PutAsJsonAsync(
|
||||
"/api/tenant-commerce/payment-accounts",
|
||||
new UpsertPaymentAccountDto
|
||||
{
|
||||
Provider = "wechat_pay",
|
||||
Status = TenantPaymentAccountStatus.Active,
|
||||
ConfigPublic = JsonSerializer.SerializeToElement(new
|
||||
{
|
||||
merchantId = "mch",
|
||||
secretRef = "tenant_secrets:payment:wechat_pay:default"
|
||||
})
|
||||
});
|
||||
var accountsResponse = await client.GetAsync("/api/tenant-commerce/payment-accounts?provider=wechat_pay");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, secretResponse.StatusCode);
|
||||
Assert.DoesNotContain("privateKey", await secretResponse.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Equal(HttpStatusCode.OK, accountResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, accountsResponse.StatusCode);
|
||||
Assert.Contains("wechat_pay", await accountsResponse.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_can_create_and_redeem_activation_code_batch()
|
||||
{
|
||||
await using var factory = new ApiTestFactory(paymentProviderGateway: new FakePaymentGateway());
|
||||
var seed = await SeedLoginUserAsync(factory, TenantRole.TenantAdmin);
|
||||
using var client = factory.CreateClient();
|
||||
await LoginAsync(client, seed);
|
||||
|
||||
var batchResponse = await client.PostAsJsonAsync(
|
||||
"/api/tenant-commerce/code-batches",
|
||||
new CreateCodeBatchDto
|
||||
{
|
||||
Name = "测试批次",
|
||||
TotalCount = 2,
|
||||
Days = 30
|
||||
});
|
||||
var codesResponse = await client.GetAsync("/api/tenant-commerce/activation-codes?status=unused&limit=5");
|
||||
var codes = await codesResponse.Content.ReadFromJsonAsync<ActivationCodeList>();
|
||||
var code = codes!.Items.First().Code;
|
||||
var redeemResponse = await client.PostAsJsonAsync(
|
||||
"/api/tenant-commerce/activation-codes/redeem",
|
||||
new RedeemActivationCodeDto
|
||||
{
|
||||
Code = code,
|
||||
UserId = seed.UserId
|
||||
});
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, batchResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, codesResponse.StatusCode);
|
||||
Assert.Equal(2, codes.Items.Count);
|
||||
Assert.Equal(HttpStatusCode.OK, redeemResponse.StatusCode);
|
||||
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var dbContext = scope.ServiceProvider.GetRequiredService<TikuDbContext>();
|
||||
Assert.Contains(dbContext.Entitlements, item =>
|
||||
item.TenantId == seed.TenantId &&
|
||||
item.UserId == seed.UserId &&
|
||||
item.SourceType == "activation_code");
|
||||
}
|
||||
|
||||
private static async Task<LoginSeed> SeedLoginUserAsync(ApiTestFactory factory, TenantRole role)
|
||||
{
|
||||
var tenantId = Guid.NewGuid();
|
||||
var userId = Guid.NewGuid();
|
||||
var phone = "13800000000";
|
||||
var passwordHash = new PasswordHasher().Hash("passw0rd!");
|
||||
await factory.SeedAsync(
|
||||
new Tenant
|
||||
{
|
||||
Id = tenantId,
|
||||
Slug = tenantId.ToString("N"),
|
||||
Name = "Tenant Commerce"
|
||||
},
|
||||
new User
|
||||
{
|
||||
Id = userId,
|
||||
Phone = phone,
|
||||
Name = "Tenant Commerce User"
|
||||
},
|
||||
new TenantMembership
|
||||
{
|
||||
TenantId = tenantId,
|
||||
UserId = userId,
|
||||
Role = role,
|
||||
Status = MembershipStatus.Active
|
||||
},
|
||||
new UserIdentity
|
||||
{
|
||||
UserId = userId,
|
||||
Provider = "password",
|
||||
ProviderSubject = phone,
|
||||
Phone = phone,
|
||||
SecretPayload = CreateSecretPayload(passwordHash)
|
||||
});
|
||||
|
||||
return new LoginSeed(tenantId, userId, phone);
|
||||
}
|
||||
|
||||
private static async Task LoginAsync(HttpClient client, LoginSeed seed)
|
||||
{
|
||||
var loginResponse = await client.PostAsJsonAsync(
|
||||
"/api/auth/login/password",
|
||||
new PasswordLoginDto
|
||||
{
|
||||
TenantId = seed.TenantId,
|
||||
Phone = seed.Phone,
|
||||
Password = "passw0rd!"
|
||||
});
|
||||
loginResponse.EnsureSuccessStatusCode();
|
||||
using var loginJson = await JsonDocument.ParseAsync(await loginResponse.Content.ReadAsStreamAsync());
|
||||
var accessToken = loginJson.RootElement
|
||||
.GetProperty("tokens")
|
||||
.GetProperty("accessToken")
|
||||
.GetString();
|
||||
client.DefaultRequestHeaders.Authorization = new("Bearer", accessToken);
|
||||
}
|
||||
|
||||
private static JsonElement CreateSecretPayload(string passwordHash)
|
||||
{
|
||||
using var document = JsonDocument.Parse(
|
||||
$$"""{"passwordHash":{{JsonSerializer.Serialize(passwordHash)}}}""");
|
||||
return document.RootElement.Clone();
|
||||
}
|
||||
|
||||
private sealed record LoginSeed(Guid TenantId, Guid UserId, string Phone);
|
||||
|
||||
private sealed class FakePaymentGateway : IPaymentProviderGateway
|
||||
{
|
||||
public Task<CreatePaymentProviderResult> CreatePaymentAsync(
|
||||
string provider,
|
||||
CreatePaymentProviderRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public Task<PaymentNotificationResult> ParsePaymentNotificationAsync(
|
||||
string provider,
|
||||
PaymentNotificationRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user