admin/src/Oms.Application/Shared/MarketingReferralCodeProvisioner.cs
zzh 89233bc3da feat: add customer marketing module (M1-M6 backend)
Implement referral, points, coupons, commission, member levels, and order integration with migration SQL and background jobs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-23 16:42:08 +08:00

63 lines
1.9 KiB
C#

using Fake.Application;
using Fake.DependencyInjection;
using Oms.Domain.MarketingAggregate.Entities;
using Oms.Domain.MarketingAggregate.Enums;
using Oms.Domain.MarketingAggregate.Repositories;
namespace Oms.Application.Shared;
public static class MarketingInviteCodeHelper
{
private const string Alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
public static string GenerateCode()
{
Span<char> buffer = stackalloc char[8];
for (var i = 0; i < buffer.Length; i++)
{
buffer[i] = Alphabet[Random.Shared.Next(Alphabet.Length)];
}
return new string(buffer);
}
}
public class MarketingReferralCodeProvisioner : IScopedDependency
{
private readonly ICustomerReferralCodeRepository _referralCodeRepository;
public MarketingReferralCodeProvisioner(ICustomerReferralCodeRepository referralCodeRepository)
{
_referralCodeRepository = referralCodeRepository;
}
public async Task<CustomerReferralCode> GetOrCreateAsync(int mainCustomerId, CancellationToken cancellationToken = default)
{
var existing = await _referralCodeRepository.GetByCustomerIdAsync(mainCustomerId, cancellationToken);
if (existing != null)
{
return existing;
}
for (var i = 0; i < 10; i++)
{
var code = MarketingInviteCodeHelper.GenerateCode();
if (await _referralCodeRepository.ExistsInviteCodeAsync(code, null, cancellationToken))
{
continue;
}
var entity = new CustomerReferralCode
{
CustomerId = mainCustomerId,
InviteCode = code,
Status = ReferralCodeStatus.Enabled
};
await _referralCodeRepository.InsertAsync(entity, cancellationToken);
return entity;
}
throw new BusinessException("邀请码生成失败");
}
}