using Fake.Application;
using Fake.DependencyInjection;
using Oms.Domain.ChannelsAggregate.Consts;
using Oms.Domain.ChannelsAggregate.Repositories;
using Oms.Domain.OperationsAggregate.Repositories;
using Oms.Domain.OrdersAggregate.Repositories;
namespace Oms.Application.Shared.DocNumbers;
///
/// 单号生成:匹配规则 → 渲染公式 → 唯一性重试;无规则走内置。
///
public class DocNumberGenerator(
IDocNumberRuleRepository ruleRepository,
IDocNumberSeqRepository seqRepository,
IOrderRepository orderRepository,
IPickupOrderRepository pickupOrderRepository,
IShipBagRepository bagRepository,
IShipMasterRepository masterRepository) : IDocNumberGenerator, IScopedDependency
{
private const int MaxAttempts = 8;
public async Task GenerateAsync(
string docType,
DocNumberGenerateContext context,
CancellationToken cancellationToken = default)
{
var normalizedType = NormalizeDocType(docType);
var now = context.Now ?? DateTime.Now;
var effectiveContext = CloneWithNow(context, now);
var rule = await ResolveRuleAsync(normalizedType, effectiveContext, cancellationToken);
for (var attempt = 0; attempt < MaxAttempts; attempt++)
{
string generated;
if (rule == null)
{
generated = BuildBuiltin(normalizedType, now);
}
else
{
Func? nextSeq = null;
if (DocNumberFormulaRenderer.ContainsSeq(rule.Formula))
{
var scopeKey = now.ToString("yyyyMMdd");
int seqValue;
try
{
seqValue = await seqRepository.NextValueAsync(rule.Id, scopeKey, cancellationToken);
}
catch (InvalidOperationException ex)
{
throw new BusinessException(ex.Message);
}
nextSeq = _ => seqValue;
}
generated = DocNumberFormulaRenderer.Render(
rule.Formula,
effectiveContext,
nextSeq: nextSeq,
nowOverride: now);
}
EnsureLength(normalizedType, generated);
if (await IsAvailableAsync(normalizedType, generated, effectiveContext, cancellationToken))
{
return generated;
}
// 内置/RAND 冲突可直接重试;仅 SEQ 的纯序号冲突也会再取下一号
now = DateTime.Now;
effectiveContext = CloneWithNow(context, now);
}
throw new BusinessException(FailureMessage(normalizedType));
}
public async Task PreviewAsync(
string docType,
string? formula,
DocNumberGenerateContext context,
CancellationToken cancellationToken = default)
{
var normalizedType = NormalizeDocType(docType);
var now = context.Now ?? DateTime.Now;
var effectiveContext = CloneWithNow(context, now);
string usedFormula;
int? ruleId = null;
var usedRule = false;
if (!string.IsNullOrWhiteSpace(formula))
{
usedFormula = formula.Trim();
}
else
{
var rule = await ResolveRuleAsync(normalizedType, effectiveContext, cancellationToken);
if (rule != null)
{
usedFormula = rule.Formula;
ruleId = rule.Id;
usedRule = true;
}
else
{
usedFormula = BuiltinFormula(normalizedType);
}
}
var sample = DocNumberFormulaRenderer.Render(
usedFormula,
effectiveContext,
nextSeq: width => 1,
nowOverride: now);
// 内置默认并非公式串时,直接用 BuildBuiltin 对齐现网
if (!usedRule && string.IsNullOrWhiteSpace(formula))
{
sample = BuildBuiltin(normalizedType, now);
usedFormula = BuiltinFormula(normalizedType);
}
EnsureLength(normalizedType, sample);
return new DocNumberPreviewResult
{
Sample = sample,
UsedRule = usedRule || !string.IsNullOrWhiteSpace(formula),
RuleId = ruleId,
Formula = usedFormula
};
}
private async Task ResolveRuleAsync(
string docType,
DocNumberGenerateContext context,
CancellationToken cancellationToken)
{
var rules = await ruleRepository.ListEnabledByDocTypeAsync(docType, cancellationToken);
return DocNumberRuleMatcher.PickBest(rules, context);
}
private async Task IsAvailableAsync(
string docType,
string value,
DocNumberGenerateContext context,
CancellationToken cancellationToken)
{
return docType switch
{
DocNumberTypeCodes.ServiceNo =>
!await orderRepository.HasServiceNoAsync(value, cancellationToken),
DocNumberTypeCodes.ClientNo =>
await IsClientNoAvailableAsync(value, context, cancellationToken),
DocNumberTypeCodes.PickupNo =>
await pickupOrderRepository.GetByPickupNoAsync(value, cancellationToken) == null,
DocNumberTypeCodes.BagNo =>
await bagRepository.GetByBagNoAsync(value, cancellationToken) == null,
DocNumberTypeCodes.MasterNo =>
await masterRepository.GetByMasterNoAsync(value, cancellationToken) == null,
_ => true
};
}
private async Task IsClientNoAvailableAsync(
string value,
DocNumberGenerateContext context,
CancellationToken cancellationToken)
{
if (context.CustomerId is not > 0)
{
return true;
}
var existed = await orderRepository.GetByCustomerAndClientNoAsync(
context.CustomerId.Value,
value,
cancellationToken);
return existed == null;
}
internal static string BuildBuiltin(string docType, DateTime now) =>
docType switch
{
DocNumberTypeCodes.ServiceNo =>
$"BCD{now:yyMMddHHmmss}{Random.Shared.Next(1000, 9999)}",
DocNumberTypeCodes.ClientNo =>
$"C{now:yyyyMMdd}{Random.Shared.Next(100000, 999999)}",
DocNumberTypeCodes.PickupNo =>
$"PK{now:yyyyMMddHHmmss}{Random.Shared.Next(1000, 9999)}",
DocNumberTypeCodes.BagNo =>
$"BAG{now:yyMMddHHmmss}{Random.Shared.Next(1000, 9999)}",
DocNumberTypeCodes.MasterNo =>
$"MBL{now:yyMMddHHmmss}{Random.Shared.Next(1000, 9999)}",
_ => throw new BusinessException($"不支持的单号类型:{docType}")
};
internal static string BuiltinFormula(string docType) =>
docType switch
{
DocNumberTypeCodes.ServiceNo => "BCD{yyMMddHHmmss}{RAND:4}",
DocNumberTypeCodes.ClientNo => "C{yyyyMMdd}{RAND:6}",
DocNumberTypeCodes.PickupNo => "PK{yyyyMMddHHmmss}{RAND:4}",
DocNumberTypeCodes.BagNo => "BAG{yyMMddHHmmss}{RAND:4}",
DocNumberTypeCodes.MasterNo => "MBL{yyMMddHHmmss}{RAND:4}",
_ => string.Empty
};
private static string NormalizeDocType(string docType)
{
if (!DocNumberTypeCodes.IsGenerateType(docType))
{
throw new BusinessException($"不支持的单号类型:{docType}");
}
return DocNumberTypeCodes.Normalize(docType);
}
private static void EnsureLength(string docType, string value)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new BusinessException("生成的单号为空,请检查公式");
}
var max = DocNumberTypeCodes.MaxLength(docType);
if (value.Length > max)
{
throw new BusinessException($"生成的单号长度 {value.Length} 超过上限 {max},请缩短公式");
}
}
private static string FailureMessage(string docType) =>
docType switch
{
DocNumberTypeCodes.ServiceNo => "运单号生成失败",
DocNumberTypeCodes.ClientNo => "客户单号生成失败",
DocNumberTypeCodes.PickupNo => "揽收单号生成失败",
DocNumberTypeCodes.BagNo => "生成大包号失败,请重试",
DocNumberTypeCodes.MasterNo => "生成主单号失败,请重试",
_ => "单号生成失败"
};
private static DocNumberGenerateContext CloneWithNow(DocNumberGenerateContext context, DateTime now) =>
new()
{
ProductCode = context.ProductCode,
ChannelCode = context.ChannelCode,
CountryCode = context.CountryCode,
CustomerId = context.CustomerId,
Now = now
};
}