feat: 单号规则可配置生成(运单/客户单号/揽收/大包/主单)
All checks were successful
Build and Deploy / deploy (push) Successful in 1m18s
All checks were successful
Build and Deploy / deploy (push) Successful in 1m18s
支持按产品、渠道、国家匹配占位符公式,未命中沿用内置规则。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
f8d2d563dc
commit
0e68f7a87e
41
db.sql
41
db.sql
@ -78,6 +78,8 @@ DROP TABLE IF EXISTS `t_inbound_record`;
|
||||
DROP TABLE IF EXISTS `t_label_template`;
|
||||
DROP TABLE IF EXISTS `t_issue_template`;
|
||||
DROP TABLE IF EXISTS `t_auto_trigger`;
|
||||
DROP TABLE IF EXISTS `t_doc_number_seq`;
|
||||
DROP TABLE IF EXISTS `t_doc_number_rule`;
|
||||
DROP TABLE IF EXISTS `t_weight_rounding_info`;
|
||||
DROP TABLE IF EXISTS `t_weight_rounding`;
|
||||
DROP TABLE IF EXISTS `t_weight_rule_info`;
|
||||
@ -917,6 +919,45 @@ CREATE TABLE `t_auto_trigger` (
|
||||
KEY `idx_at_operation` (`Operation`)
|
||||
) COMMENT='自动触发表';
|
||||
|
||||
CREATE TABLE `t_doc_number_rule` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
|
||||
`DocType` VARCHAR(32) NOT NULL COMMENT '单据类型:ServiceNo/ClientNo/PickupNo/BagNo/MasterNo',
|
||||
`RuleName` VARCHAR(128) NOT NULL COMMENT '规则名称',
|
||||
`Formula` VARCHAR(256) NOT NULL COMMENT '占位符公式',
|
||||
`ProductCode` VARCHAR(64) NULL COMMENT '销售产品编码,空=通配',
|
||||
`ChannelCode` VARCHAR(64) NULL COMMENT '渠道编码,空=通配',
|
||||
`CountryCode` VARCHAR(8) NULL COMMENT '国家二字码,空=通配',
|
||||
`Priority` INT NOT NULL DEFAULT 100 COMMENT '优先级,数值越小越优先(同分时)',
|
||||
`Status` TINYINT NOT NULL DEFAULT 2 COMMENT '启用状态:1禁用 2启用',
|
||||
`Remark` VARCHAR(512) NULL COMMENT '备注',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`UpdateUserId` INT NULL COMMENT '更新人',
|
||||
`UpdateTime` DATETIME NULL COMMENT '更新时间',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_doc_number_rule_type_status` (`DocType`, `Status`),
|
||||
KEY `ix_doc_number_rule_product` (`ProductCode`),
|
||||
KEY `ix_doc_number_rule_channel` (`ChannelCode`),
|
||||
KEY `ix_doc_number_rule_country` (`CountryCode`)
|
||||
) COMMENT='单号生成规则';
|
||||
|
||||
CREATE TABLE `t_doc_number_seq` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
|
||||
`RuleId` INT NOT NULL COMMENT '规则Id',
|
||||
`ScopeKey` VARCHAR(32) NOT NULL COMMENT '分桶键,如 yyyyMMdd',
|
||||
`CurrentValue` INT NOT NULL DEFAULT 0 COMMENT '当前序号',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`UpdateUserId` INT NULL COMMENT '更新人',
|
||||
`UpdateTime` DATETIME NULL COMMENT '更新时间',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_doc_number_seq_rule_scope` (`RuleId`, `ScopeKey`)
|
||||
) COMMENT='单号规则日序号';
|
||||
|
||||
CREATE TABLE `t_issue_template` (
|
||||
`Id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`OrganizationId` CHAR(36) NULL COMMENT '归属组织 GUID;NULL=平台通用',
|
||||
|
||||
72
sql/migrate_doc_number_rule_20261114.sql
Normal file
72
sql/migrate_doc_number_rule_20261114.sql
Normal file
@ -0,0 +1,72 @@
|
||||
-- =============================================================================
|
||||
-- migrate_doc_number_rule_20261114.sql
|
||||
-- 单号规则:运单号 / 客户单号 / 揽收单号 / 大包号 / 主单号 可配置生成公式
|
||||
-- 审计字段对齐 t_outbound_record(定死):
|
||||
-- IsDeleted TINYINT NOT NULL DEFAULT 0
|
||||
-- ConcurrencyStamp CHAR(36) NOT NULL DEFAULT (UUID())
|
||||
-- CreateUserId INT NOT NULL DEFAULT 0
|
||||
-- CreateTime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
-- UpdateUserId INT NULL
|
||||
-- UpdateTime DATETIME NULL
|
||||
-- 禁止 UNIQUE KEY;唯一性业务侧校验。可重复执行。
|
||||
-- =============================================================================
|
||||
SET @db := DATABASE();
|
||||
|
||||
-- ---------- t_doc_number_rule ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_doc_number_rule'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_doc_number_rule` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`DocType` VARCHAR(32) NOT NULL COMMENT ''单据类型:ServiceNo/ClientNo/PickupNo/BagNo/MasterNo'',
|
||||
`RuleName` VARCHAR(128) NOT NULL COMMENT ''规则名称'',
|
||||
`Formula` VARCHAR(256) NOT NULL COMMENT ''占位符公式'',
|
||||
`ProductCode` VARCHAR(64) NULL COMMENT ''销售产品编码,空=通配'',
|
||||
`ChannelCode` VARCHAR(64) NULL COMMENT ''渠道编码,空=通配'',
|
||||
`CountryCode` VARCHAR(8) NULL COMMENT ''国家二字码,空=通配'',
|
||||
`Priority` INT NOT NULL DEFAULT 100 COMMENT ''优先级,数值越小越优先(同分时)'',
|
||||
`Status` TINYINT NOT NULL DEFAULT 2 COMMENT ''启用状态:1禁用 2启用'',
|
||||
`Remark` VARCHAR(512) NULL COMMENT ''备注'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_doc_number_rule_type_status` (`DocType`, `Status`),
|
||||
KEY `ix_doc_number_rule_product` (`ProductCode`),
|
||||
KEY `ix_doc_number_rule_channel` (`ChannelCode`),
|
||||
KEY `ix_doc_number_rule_country` (`CountryCode`)
|
||||
) COMMENT=''单号生成规则''',
|
||||
'SELECT ''t_doc_number_rule already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_doc_number_seq ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_doc_number_seq'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_doc_number_seq` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`RuleId` INT NOT NULL COMMENT ''规则Id'',
|
||||
`ScopeKey` VARCHAR(32) NOT NULL COMMENT ''分桶键,如 yyyyMMdd'',
|
||||
`CurrentValue` INT NOT NULL DEFAULT 0 COMMENT ''当前序号'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_doc_number_seq_rule_scope` (`RuleId`, `ScopeKey`)
|
||||
) COMMENT=''单号规则日序号''',
|
||||
'SELECT ''t_doc_number_seq already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
49
src/Oms.Application/Dtos/Channels/DocNumberMetaOutput.cs
Normal file
49
src/Oms.Application/Dtos/Channels/DocNumberMetaOutput.cs
Normal file
@ -0,0 +1,49 @@
|
||||
namespace Oms.Application.Dtos.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// 单号规则元数据(单据类型、占位符说明)。
|
||||
/// </summary>
|
||||
public class DocNumberMetaOutput
|
||||
{
|
||||
/// <summary>单据类型选项。</summary>
|
||||
public List<DocNumberOptionItem> DocTypes { get; set; } = [];
|
||||
|
||||
/// <summary>可插入的占位符。</summary>
|
||||
public List<DocNumberTokenItem> Tokens { get; set; } = [];
|
||||
|
||||
/// <summary>各类型内置默认公式说明。</summary>
|
||||
public List<DocNumberBuiltinItem> Builtins { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>下拉选项。</summary>
|
||||
public class DocNumberOptionItem
|
||||
{
|
||||
/// <summary>编码。</summary>
|
||||
public string Value { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>显示名。</summary>
|
||||
public string Label { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>占位符说明。</summary>
|
||||
public class DocNumberTokenItem
|
||||
{
|
||||
/// <summary>插入文本,如 {PRODUCT}。</summary>
|
||||
public string Token { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>说明。</summary>
|
||||
public string Label { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>内置默认。</summary>
|
||||
public class DocNumberBuiltinItem
|
||||
{
|
||||
/// <summary>单据类型。</summary>
|
||||
public string DocType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>显示名。</summary>
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>等价公式说明。</summary>
|
||||
public string Formula { get; set; } = string.Empty;
|
||||
}
|
||||
22
src/Oms.Application/Dtos/Channels/DocNumberPreviewInput.cs
Normal file
22
src/Oms.Application/Dtos/Channels/DocNumberPreviewInput.cs
Normal file
@ -0,0 +1,22 @@
|
||||
namespace Oms.Application.Dtos.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// 单号试算入参。
|
||||
/// </summary>
|
||||
public class DocNumberPreviewInput
|
||||
{
|
||||
/// <summary>单据类型。</summary>
|
||||
public string DocType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>公式;空则按匹配规则或内置。</summary>
|
||||
public string? Formula { get; set; }
|
||||
|
||||
/// <summary>销售产品编码。</summary>
|
||||
public string? ProductCode { get; set; }
|
||||
|
||||
/// <summary>渠道编码。</summary>
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
/// <summary>国家二字码。</summary>
|
||||
public string? CountryCode { get; set; }
|
||||
}
|
||||
19
src/Oms.Application/Dtos/Channels/DocNumberPreviewOutput.cs
Normal file
19
src/Oms.Application/Dtos/Channels/DocNumberPreviewOutput.cs
Normal file
@ -0,0 +1,19 @@
|
||||
namespace Oms.Application.Dtos.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// 单号试算出参。
|
||||
/// </summary>
|
||||
public class DocNumberPreviewOutput
|
||||
{
|
||||
/// <summary>示例单号。</summary>
|
||||
public string Sample { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>是否使用配置规则 / 入参公式。</summary>
|
||||
public bool UsedRule { get; set; }
|
||||
|
||||
/// <summary>命中规则 Id。</summary>
|
||||
public int? RuleId { get; set; }
|
||||
|
||||
/// <summary>实际公式。</summary>
|
||||
public string Formula { get; set; } = string.Empty;
|
||||
}
|
||||
22
src/Oms.Application/Dtos/Channels/DocNumberRuleListInput.cs
Normal file
22
src/Oms.Application/Dtos/Channels/DocNumberRuleListInput.cs
Normal file
@ -0,0 +1,22 @@
|
||||
namespace Oms.Application.Dtos.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// 单号规则列表查询。
|
||||
/// </summary>
|
||||
public class DocNumberRuleListInput
|
||||
{
|
||||
/// <summary>页码。</summary>
|
||||
public int Page { get; set; } = 1;
|
||||
|
||||
/// <summary>每页条数。</summary>
|
||||
public int PageSize { get; set; } = 50;
|
||||
|
||||
/// <summary>单据类型筛选。</summary>
|
||||
public string? DocType { get; set; }
|
||||
|
||||
/// <summary>规则名称关键词。</summary>
|
||||
public string? Keyword { get; set; }
|
||||
|
||||
/// <summary>状态:1 禁用 / 2 启用。</summary>
|
||||
public byte? Status { get; set; }
|
||||
}
|
||||
46
src/Oms.Application/Dtos/Channels/DocNumberRuleOutput.cs
Normal file
46
src/Oms.Application/Dtos/Channels/DocNumberRuleOutput.cs
Normal file
@ -0,0 +1,46 @@
|
||||
namespace Oms.Application.Dtos.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// 单号规则出参。
|
||||
/// </summary>
|
||||
public class DocNumberRuleOutput
|
||||
{
|
||||
/// <summary>主键。</summary>
|
||||
public int Id { get; set; }
|
||||
|
||||
/// <summary>单据类型。</summary>
|
||||
public string DocType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>单据类型显示名。</summary>
|
||||
public string DocTypeName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>规则名称。</summary>
|
||||
public string RuleName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>公式。</summary>
|
||||
public string Formula { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>销售产品编码。</summary>
|
||||
public string? ProductCode { get; set; }
|
||||
|
||||
/// <summary>渠道编码。</summary>
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
/// <summary>国家二字码。</summary>
|
||||
public string? CountryCode { get; set; }
|
||||
|
||||
/// <summary>优先级。</summary>
|
||||
public int Priority { get; set; }
|
||||
|
||||
/// <summary>状态。</summary>
|
||||
public byte Status { get; set; }
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
public string? Remark { get; set; }
|
||||
|
||||
/// <summary>创建时间。</summary>
|
||||
public DateTime CreateTime { get; set; }
|
||||
|
||||
/// <summary>更新时间。</summary>
|
||||
public DateTime? UpdateTime { get; set; }
|
||||
}
|
||||
39
src/Oms.Application/Dtos/Channels/DocNumberRuleSaveInput.cs
Normal file
39
src/Oms.Application/Dtos/Channels/DocNumberRuleSaveInput.cs
Normal file
@ -0,0 +1,39 @@
|
||||
using Oms.Domain.Shared.Enums;
|
||||
|
||||
namespace Oms.Application.Dtos.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// 单号规则保存入参。
|
||||
/// </summary>
|
||||
public class DocNumberRuleSaveInput
|
||||
{
|
||||
/// <summary>主键;更新必填。</summary>
|
||||
public int? Id { get; set; }
|
||||
|
||||
/// <summary>单据类型:ServiceNo / ClientNo / PickupNo / BagNo / MasterNo。</summary>
|
||||
public string DocType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>规则名称。</summary>
|
||||
public string RuleName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>占位符公式。</summary>
|
||||
public string Formula { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>销售产品编码;空=通配。</summary>
|
||||
public string? ProductCode { get; set; }
|
||||
|
||||
/// <summary>渠道编码;空=通配。</summary>
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
/// <summary>国家二字码;空=通配。</summary>
|
||||
public string? CountryCode { get; set; }
|
||||
|
||||
/// <summary>优先级,数值越小越优先。</summary>
|
||||
public int Priority { get; set; } = 100;
|
||||
|
||||
/// <summary>启用状态。</summary>
|
||||
public EnableStatus Status { get; set; } = EnableStatus.Enabled;
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
279
src/Oms.Application/Services/Channels/DocNumberRuleService.cs
Normal file
279
src/Oms.Application/Services/Channels/DocNumberRuleService.cs
Normal file
@ -0,0 +1,279 @@
|
||||
using System.Linq.Expressions;
|
||||
using Fake.Application;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Channels;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Shared.DocNumbers;
|
||||
using Oms.Domain.ChannelsAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
using Oms.Domain.ChannelsAggregate.Repositories;
|
||||
using Oms.Domain.Shared.Enums;
|
||||
|
||||
namespace Oms.Application.Services.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// 单号规则 API:运单号 / 客户单号 / 揽收单号 / 大包号 / 主单号。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-Channel")]
|
||||
public class DocNumberRuleService : ApplicationService
|
||||
{
|
||||
private IDocNumberRuleRepository DocNumberRuleRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IDocNumberRuleRepository>();
|
||||
|
||||
private IDocNumberGenerator DocNumberGenerator =>
|
||||
LazyServiceProvider.GetRequiredService<IDocNumberGenerator>();
|
||||
|
||||
/// <summary>
|
||||
/// 单号规则元数据(单据类型、占位符、内置默认)。
|
||||
/// </summary>
|
||||
[HttpGet("/channel/number-rule/meta")]
|
||||
public Task<DocNumberMetaOutput> GetMetaAsync() =>
|
||||
Task.FromResult(BuildMeta());
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询单号规则。
|
||||
/// </summary>
|
||||
[HttpGet("/channel/number-rule/list")]
|
||||
public async Task<OmsPageResult<DocNumberRuleOutput>> GetListAsync([FromQuery] DocNumberRuleListInput input)
|
||||
{
|
||||
var predicate = BuildListPredicate(input);
|
||||
var pageIndex = OmsDocHelper.NormalizePage(input.Page);
|
||||
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
|
||||
var entities = await DocNumberRuleRepository.GetPagedListAsync(
|
||||
predicate,
|
||||
pageIndex,
|
||||
pageSize,
|
||||
new Dictionary<string, bool>
|
||||
{
|
||||
[nameof(DocNumberRule.Priority)] = true,
|
||||
[nameof(DocNumberRule.Id)] = true
|
||||
});
|
||||
var total = await DocNumberRuleRepository.CountAsync(predicate);
|
||||
return new OmsPageResult<DocNumberRuleOutput>
|
||||
{
|
||||
Items = entities.Select(MapOutput).ToList(),
|
||||
Total = total
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增单号规则。
|
||||
/// </summary>
|
||||
[HttpPost("/channel/number-rule/create")]
|
||||
public async Task CreateAsync(DocNumberRuleSaveInput input)
|
||||
{
|
||||
var entity = MapToEntity(input, existing: null);
|
||||
ValidateEntity(entity);
|
||||
await DocNumberRuleRepository.InsertAsync(entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新单号规则。
|
||||
/// </summary>
|
||||
[HttpPost("/channel/number-rule/update")]
|
||||
public async Task UpdateAsync(DocNumberRuleSaveInput input)
|
||||
{
|
||||
var entity = await GetEntityOrThrowAsync(input.Id);
|
||||
MapToEntity(input, entity);
|
||||
ValidateEntity(entity);
|
||||
await DocNumberRuleRepository.UpdateAsync(entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除单号规则。
|
||||
/// </summary>
|
||||
[HttpPost("/channel/number-rule/delete")]
|
||||
public async Task DeleteAsync(IdInput input)
|
||||
{
|
||||
var entity = await GetEntityOrThrowAsync(input.Id);
|
||||
await DocNumberRuleRepository.DeleteAsync(entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 切换单号规则启用状态。
|
||||
/// </summary>
|
||||
[HttpPost("/channel/number-rule/toggleStatus")]
|
||||
public async Task ToggleStatusAsync(ToggleStatusInput input)
|
||||
{
|
||||
var entity = await GetEntityOrThrowAsync(input.Id);
|
||||
entity.Status = input.Status;
|
||||
await DocNumberRuleRepository.UpdateAsync(entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 试算单号(不落库、不占用真实序号;SEQ 以 1 填充)。
|
||||
/// </summary>
|
||||
[HttpPost("/channel/number-rule/preview")]
|
||||
public async Task<DocNumberPreviewOutput> PreviewAsync(DocNumberPreviewInput input)
|
||||
{
|
||||
var result = await DocNumberGenerator.PreviewAsync(
|
||||
input.DocType,
|
||||
input.Formula,
|
||||
new DocNumberGenerateContext
|
||||
{
|
||||
ProductCode = NormalizeOptional(input.ProductCode),
|
||||
ChannelCode = NormalizeOptional(input.ChannelCode),
|
||||
CountryCode = NormalizeCountry(input.CountryCode)
|
||||
});
|
||||
|
||||
return new DocNumberPreviewOutput
|
||||
{
|
||||
Sample = result.Sample,
|
||||
UsedRule = result.UsedRule,
|
||||
RuleId = result.RuleId,
|
||||
Formula = result.Formula
|
||||
};
|
||||
}
|
||||
|
||||
private static Expression<Func<DocNumberRule, bool>> BuildListPredicate(DocNumberRuleListInput input)
|
||||
{
|
||||
var docType = string.IsNullOrWhiteSpace(input.DocType)
|
||||
? null
|
||||
: DocNumberTypeCodes.Normalize(input.DocType);
|
||||
var keyword = input.Keyword?.Trim();
|
||||
var status = input.Status;
|
||||
|
||||
return entity =>
|
||||
(docType == null || entity.DocType == docType)
|
||||
&& (status == null || (byte)entity.Status == status.Value)
|
||||
&& (string.IsNullOrWhiteSpace(keyword)
|
||||
|| (entity.RuleName != null && entity.RuleName.Contains(keyword))
|
||||
|| (entity.Formula != null && entity.Formula.Contains(keyword))
|
||||
|| (entity.ProductCode != null && entity.ProductCode.Contains(keyword))
|
||||
|| (entity.ChannelCode != null && entity.ChannelCode.Contains(keyword))
|
||||
|| (entity.CountryCode != null && entity.CountryCode.Contains(keyword)));
|
||||
}
|
||||
|
||||
private async Task<DocNumberRule> GetEntityOrThrowAsync(int? id)
|
||||
{
|
||||
if (!id.HasValue || id.Value <= 0)
|
||||
{
|
||||
throw new BusinessException("单号规则不存在");
|
||||
}
|
||||
|
||||
var entity = await DocNumberRuleRepository.FirstOrDefaultAsync(x => x.Id == id.Value);
|
||||
if (entity == null)
|
||||
{
|
||||
throw new BusinessException("单号规则不存在");
|
||||
}
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
private static DocNumberRule MapToEntity(DocNumberRuleSaveInput input, DocNumberRule? existing)
|
||||
{
|
||||
var entity = existing ?? new DocNumberRule();
|
||||
entity.DocType = DocNumberTypeCodes.Normalize(Require(input.DocType, "单据类型不能为空"));
|
||||
if (!DocNumberTypeCodes.IsKnown(entity.DocType))
|
||||
{
|
||||
throw new BusinessException("单据类型无效");
|
||||
}
|
||||
|
||||
entity.RuleName = Require(input.RuleName, "规则名称不能为空");
|
||||
entity.Formula = Require(input.Formula, "公式不能为空");
|
||||
entity.ProductCode = NormalizeOptional(input.ProductCode);
|
||||
entity.ChannelCode = NormalizeOptional(input.ChannelCode);
|
||||
entity.CountryCode = NormalizeCountry(input.CountryCode);
|
||||
entity.Priority = input.Priority > 0 ? input.Priority : 100;
|
||||
entity.Status = input.Status == EnableStatus.None ? EnableStatus.Enabled : input.Status;
|
||||
entity.Remark = NormalizeOptional(input.Remark);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private static void ValidateEntity(DocNumberRule entity)
|
||||
{
|
||||
// 试渲染:SEQ 用 1,校验公式可解析且长度不超限
|
||||
var sample = DocNumberFormulaRenderer.Render(
|
||||
entity.Formula,
|
||||
new DocNumberGenerateContext
|
||||
{
|
||||
ProductCode = entity.ProductCode ?? "PRODUCT",
|
||||
ChannelCode = entity.ChannelCode ?? "CHANNEL",
|
||||
CountryCode = entity.CountryCode ?? "US"
|
||||
},
|
||||
nextSeq: _ => 1);
|
||||
|
||||
var max = DocNumberTypeCodes.MaxLength(entity.DocType);
|
||||
if (sample.Length > max)
|
||||
{
|
||||
throw new BusinessException($"公式生成长度 {sample.Length} 超过该单号上限 {max}");
|
||||
}
|
||||
}
|
||||
|
||||
private static DocNumberRuleOutput MapOutput(DocNumberRule entity) =>
|
||||
new()
|
||||
{
|
||||
Id = entity.Id,
|
||||
DocType = entity.DocType,
|
||||
DocTypeName = DocTypeLabel(entity.DocType),
|
||||
RuleName = entity.RuleName,
|
||||
Formula = entity.Formula,
|
||||
ProductCode = entity.ProductCode,
|
||||
ChannelCode = entity.ChannelCode,
|
||||
CountryCode = entity.CountryCode,
|
||||
Priority = entity.Priority,
|
||||
Status = (byte)entity.Status,
|
||||
Remark = entity.Remark,
|
||||
CreateTime = entity.CreateTime,
|
||||
UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime)
|
||||
};
|
||||
|
||||
private static DocNumberMetaOutput BuildMeta() =>
|
||||
new()
|
||||
{
|
||||
DocTypes = DocNumberTypeCodes.All
|
||||
.Select(x => new DocNumberOptionItem { Value = x, Label = DocTypeLabel(x) })
|
||||
.ToList(),
|
||||
Tokens =
|
||||
[
|
||||
new DocNumberTokenItem { Token = "{PRODUCT}", Label = "销售产品编码" },
|
||||
new DocNumberTokenItem { Token = "{CHANNEL}", Label = "渠道编码" },
|
||||
new DocNumberTokenItem { Token = "{COUNTRY}", Label = "国家二字码" },
|
||||
new DocNumberTokenItem { Token = "{yyMMdd}", Label = "日期 yyMMdd" },
|
||||
new DocNumberTokenItem { Token = "{yyyyMMdd}", Label = "日期 yyyyMMdd" },
|
||||
new DocNumberTokenItem { Token = "{yyMMddHHmmss}", Label = "时间 yyMMddHHmmss" },
|
||||
new DocNumberTokenItem { Token = "{yyyyMMddHHmmss}", Label = "时间 yyyyMMddHHmmss" },
|
||||
new DocNumberTokenItem { Token = "{RAND:4}", Label = "4 位随机数" },
|
||||
new DocNumberTokenItem { Token = "{SEQ:6}", Label = "6 位日序号" }
|
||||
],
|
||||
Builtins = DocNumberTypeCodes.All
|
||||
.Select(x => new DocNumberBuiltinItem
|
||||
{
|
||||
DocType = x,
|
||||
Label = DocTypeLabel(x),
|
||||
Formula = Shared.DocNumbers.DocNumberGenerator.BuiltinFormula(x)
|
||||
})
|
||||
.ToList()
|
||||
};
|
||||
|
||||
private static string DocTypeLabel(string docType) =>
|
||||
DocNumberTypeCodes.Normalize(docType) switch
|
||||
{
|
||||
DocNumberTypeCodes.ServiceNo => "运单号",
|
||||
DocNumberTypeCodes.ClientNo => "客户单号",
|
||||
DocNumberTypeCodes.PickupNo => "揽收单号",
|
||||
DocNumberTypeCodes.BagNo => "大包号",
|
||||
DocNumberTypeCodes.MasterNo => "主单号",
|
||||
_ => docType
|
||||
};
|
||||
|
||||
private static string Require(string? value, string message)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
throw new BusinessException(message);
|
||||
}
|
||||
|
||||
return value.Trim();
|
||||
}
|
||||
|
||||
private static string? NormalizeOptional(string? value) =>
|
||||
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
|
||||
private static string? NormalizeCountry(string? value)
|
||||
{
|
||||
var trimmed = NormalizeOptional(value);
|
||||
return trimmed?.ToUpperInvariant();
|
||||
}
|
||||
}
|
||||
@ -9,6 +9,7 @@ using Oms.Application.Labeling;
|
||||
using Oms.Application.Services.Orders;
|
||||
using Oms.Application.Services.Orders.Issues;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Shared.DocNumbers;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Domain.ChannelsAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
@ -45,6 +46,9 @@ public class ShipBagService : ApplicationService
|
||||
private IWarehouseAddressRepository WarehouseAddressRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IWarehouseAddressRepository>();
|
||||
|
||||
private IDocNumberGenerator DocNumberGenerator =>
|
||||
LazyServiceProvider.GetRequiredService<IDocNumberGenerator>();
|
||||
|
||||
/// <summary>
|
||||
/// 创建空大包(装袋中)。
|
||||
/// </summary>
|
||||
@ -60,19 +64,28 @@ public class ShipBagService : ApplicationService
|
||||
throw new BusinessException("袋型仅支持 sack(麻袋)或 box(箱子)");
|
||||
}
|
||||
|
||||
var destinationCountry = string.IsNullOrWhiteSpace(input.DestinationCountry)
|
||||
? null
|
||||
: input.DestinationCountry.Trim().ToUpperInvariant();
|
||||
var channelCode = string.IsNullOrWhiteSpace(input.ChannelCode) ? null : input.ChannelCode.Trim();
|
||||
|
||||
var entity = new ShipBag
|
||||
{
|
||||
BagNo = await NextBagNoAsync(),
|
||||
BagNo = await DocNumberGenerator.GenerateAsync(
|
||||
DocNumberTypeCodes.BagNo,
|
||||
new DocNumberGenerateContext
|
||||
{
|
||||
CountryCode = destinationCountry,
|
||||
ChannelCode = channelCode
|
||||
}),
|
||||
BagType = bagType,
|
||||
Status = ShipBagStatusCodes.Open,
|
||||
WarehouseId = input.WarehouseId,
|
||||
DestinationCountry = string.IsNullOrWhiteSpace(input.DestinationCountry)
|
||||
? null
|
||||
: input.DestinationCountry.Trim().ToUpperInvariant(),
|
||||
DestinationCountry = destinationCountry,
|
||||
DestinationPort = string.IsNullOrWhiteSpace(input.DestinationPort)
|
||||
? null
|
||||
: input.DestinationPort.Trim(),
|
||||
ChannelCode = string.IsNullOrWhiteSpace(input.ChannelCode) ? null : input.ChannelCode.Trim(),
|
||||
ChannelCode = channelCode,
|
||||
Length = input.Length,
|
||||
Width = input.Width,
|
||||
Height = input.Height,
|
||||
@ -597,20 +610,6 @@ public class ShipBagService : ApplicationService
|
||||
return order;
|
||||
}
|
||||
|
||||
private async Task<string> NextBagNoAsync()
|
||||
{
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var no = $"BAG{DateTime.Now:yyMMddHHmmss}{Random.Shared.Next(1000, 9999)}";
|
||||
if (await BagRepository.GetByBagNoAsync(no) == null)
|
||||
{
|
||||
return no;
|
||||
}
|
||||
}
|
||||
|
||||
throw new BusinessException("生成大包号失败,请重试");
|
||||
}
|
||||
|
||||
private static ShipBagOutput MapBag(ShipBag bag) =>
|
||||
new()
|
||||
{
|
||||
|
||||
@ -7,6 +7,7 @@ using Oms.Application.Dtos.Operations;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Labeling;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Shared.DocNumbers;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Domain.ChannelsAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
@ -41,6 +42,9 @@ public class ShipMasterService : ApplicationService
|
||||
private IWarehouseAddressRepository WarehouseAddressRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IWarehouseAddressRepository>();
|
||||
|
||||
private IDocNumberGenerator DocNumberGenerator =>
|
||||
LazyServiceProvider.GetRequiredService<IDocNumberGenerator>();
|
||||
|
||||
/// <summary>
|
||||
/// 创建内部主单(打板中)。
|
||||
/// </summary>
|
||||
@ -48,14 +52,21 @@ public class ShipMasterService : ApplicationService
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipMasterOutput> CreateAsync(CreateShipMasterInput input)
|
||||
{
|
||||
var destinationCountry = string.IsNullOrWhiteSpace(input.DestinationCountry)
|
||||
? null
|
||||
: input.DestinationCountry.Trim().ToUpperInvariant();
|
||||
|
||||
var entity = new ShipMaster
|
||||
{
|
||||
MasterNo = await NextMasterNoAsync(),
|
||||
MasterNo = await DocNumberGenerator.GenerateAsync(
|
||||
DocNumberTypeCodes.MasterNo,
|
||||
new DocNumberGenerateContext
|
||||
{
|
||||
CountryCode = destinationCountry
|
||||
}),
|
||||
Status = ShipMasterStatusCodes.Open,
|
||||
WarehouseId = input.WarehouseId,
|
||||
DestinationCountry = string.IsNullOrWhiteSpace(input.DestinationCountry)
|
||||
? null
|
||||
: input.DestinationCountry.Trim().ToUpperInvariant(),
|
||||
DestinationCountry = destinationCountry,
|
||||
DestinationPort = string.IsNullOrWhiteSpace(input.DestinationPort)
|
||||
? null
|
||||
: input.DestinationPort.Trim(),
|
||||
@ -578,20 +589,6 @@ public class ShipMasterService : ApplicationService
|
||||
return master;
|
||||
}
|
||||
|
||||
private async Task<string> NextMasterNoAsync()
|
||||
{
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var no = $"MBL{DateTime.Now:yyMMddHHmmss}{Random.Shared.Next(1000, 9999)}";
|
||||
if (await MasterRepository.GetByMasterNoAsync(no) == null)
|
||||
{
|
||||
return no;
|
||||
}
|
||||
}
|
||||
|
||||
throw new BusinessException("生成主单号失败,请重试");
|
||||
}
|
||||
|
||||
private static ShipMasterOutput MapMaster(ShipMaster m) =>
|
||||
new()
|
||||
{
|
||||
|
||||
@ -15,6 +15,7 @@ using Oms.Application.Messaging;
|
||||
using Oms.Application.Messaging.OrderSideEffects;
|
||||
using Oms.Application.Messaging.ParcelCreate;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Shared.DocNumbers;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Application.Services.Orders.Batch;
|
||||
using Oms.Application.Services.Orders.Issues;
|
||||
@ -143,9 +144,17 @@ public partial class OrderService
|
||||
sessionCustomer);
|
||||
var orderAgentId = mainCustomerForAgent.AgentId;
|
||||
|
||||
await ValidateParcelCreateInputAsync(input);
|
||||
if (string.IsNullOrWhiteSpace(input.ProductCode))
|
||||
{
|
||||
throw new BusinessException("产品代码不能为空");
|
||||
}
|
||||
|
||||
var product = await SalesProductRepository.GetByProductCodeAsync(input.ProductCode!.Trim());
|
||||
if (input.Receiver == null || string.IsNullOrWhiteSpace(input.Receiver.CountryCode))
|
||||
{
|
||||
throw new BusinessException("收件国家不能为空");
|
||||
}
|
||||
|
||||
var product = await SalesProductRepository.GetByProductCodeAsync(input.ProductCode.Trim());
|
||||
if (product == null || product.IsActive != EnableStatus.Enabled)
|
||||
{
|
||||
throw new BusinessException("销售产品不存在或未启用");
|
||||
@ -154,7 +163,28 @@ public partial class OrderService
|
||||
EnsureAdditionalServicesAllowed(product, input.AdditionalServices);
|
||||
|
||||
var snapshotBinding = await ResolveSnapshotBindingAsync(product, bindTime);
|
||||
var country = await GetCountryOrThrowAsync(input.Receiver!.CountryCode);
|
||||
var country = await GetCountryOrThrowAsync(input.Receiver.CountryCode);
|
||||
|
||||
var channelCode = string.IsNullOrWhiteSpace(input.ChannelCode)
|
||||
? product.ProductCode
|
||||
: input.ChannelCode.Trim();
|
||||
var numberContext = new DocNumberGenerateContext
|
||||
{
|
||||
ProductCode = product.ProductCode,
|
||||
ChannelCode = channelCode,
|
||||
CountryCode = country.CountryCode,
|
||||
CustomerId = sessionCustomer.Id
|
||||
};
|
||||
|
||||
// 客户单号为空时按规则/内置生成,再做必填与唯一校验。
|
||||
if (string.IsNullOrWhiteSpace(input.ClientNo))
|
||||
{
|
||||
input.ClientNo = await DocNumberGenerator.GenerateAsync(
|
||||
DocNumberTypeCodes.ClientNo,
|
||||
numberContext);
|
||||
}
|
||||
|
||||
await ValidateParcelCreateInputAsync(input);
|
||||
|
||||
if (await IsBlacklistHitAsync(
|
||||
product,
|
||||
@ -174,7 +204,9 @@ public partial class OrderService
|
||||
country.ChineseName);
|
||||
|
||||
// 3. 落库订单、件重尺和收发件等子表。此后才有 OrderId,才能写 Outbox。
|
||||
var serviceNo = await ResolveServiceNoAsync();
|
||||
var serviceNo = await DocNumberGenerator.GenerateAsync(
|
||||
DocNumberTypeCodes.ServiceNo,
|
||||
numberContext);
|
||||
var operatorId = operatorUserId ?? (CurrentUser.IsAuthenticated ? CurrentUser.GetId<int>() : 0);
|
||||
var order = BuildDraftOrderEntity(
|
||||
input,
|
||||
@ -402,14 +434,6 @@ public partial class OrderService
|
||||
return ex;
|
||||
}
|
||||
|
||||
private const string ParcelServiceNoPrefix = "BCD";
|
||||
|
||||
/// <summary>
|
||||
/// 自动生成运单号:BCD + yyMMddHHmmss + 4 位随机数(如 BCD2607221859123456)。
|
||||
/// </summary>
|
||||
private static string BuildParcelServiceNo(DateTime now, int randomSuffix) =>
|
||||
$"{ParcelServiceNoPrefix}{now:yyMMddHHmmss}{randomSuffix}";
|
||||
|
||||
private static void NormalizeParcelCreateInput(OrderParcelCreateInput input)
|
||||
{
|
||||
input.TrackNo = null;
|
||||
@ -2394,20 +2418,6 @@ public partial class OrderService
|
||||
await OrderRepository.UpdateAsync(order);
|
||||
}
|
||||
|
||||
private async Task<string> ResolveServiceNoAsync()
|
||||
{
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
var generated = BuildParcelServiceNo(DateTime.Now, Random.Shared.Next(1000, 9999));
|
||||
if (!await OrderRepository.HasServiceNoAsync(generated))
|
||||
{
|
||||
return generated;
|
||||
}
|
||||
}
|
||||
|
||||
throw new BusinessException("运单号生成失败");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 草稿重新预报:同步做黑名单等硬校验,计重/应收/排货投递 ForecastBilling MQ。
|
||||
/// </summary>
|
||||
|
||||
@ -13,6 +13,7 @@ using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.DataPerm;
|
||||
using Oms.Application.Labeling;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Shared.DocNumbers;
|
||||
using Oms.Application.Storage;
|
||||
using Newtonsoft.Json;
|
||||
using Oms.Application.Messaging;
|
||||
@ -48,6 +49,9 @@ public partial class OrderService : ApplicationService
|
||||
private OmsRbacUserDisplayNameResolver UserDisplayNameResolver =>
|
||||
LazyServiceProvider.GetRequiredService<OmsRbacUserDisplayNameResolver>();
|
||||
|
||||
private IDocNumberGenerator DocNumberGenerator =>
|
||||
LazyServiceProvider.GetRequiredService<IDocNumberGenerator>();
|
||||
|
||||
private EffectiveScopeBuilder DataScopeBuilder =>
|
||||
LazyServiceProvider.GetRequiredService<EffectiveScopeBuilder>();
|
||||
|
||||
|
||||
@ -19,9 +19,8 @@ public static class PickupOrderParcelBuilder
|
||||
{
|
||||
var cargoName = input.CargoName.Trim();
|
||||
var weight = input.ActualWeight;
|
||||
var clientNo = string.IsNullOrWhiteSpace(input.ClientNo)
|
||||
? $"PK{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(1000, 9999)}"
|
||||
: input.ClientNo.Trim();
|
||||
// 客户单号为空时留给 CreateParcelCore 按单号规则生成(含内置默认)
|
||||
var clientNo = string.IsNullOrWhiteSpace(input.ClientNo) ? null : input.ClientNo.Trim();
|
||||
|
||||
var warehouseContact = string.IsNullOrWhiteSpace(warehouse.Recipient)
|
||||
? warehouse.WarehouseName
|
||||
|
||||
@ -5,6 +5,8 @@ using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Integrations.Itfx;
|
||||
using Oms.Application.Integrations.SmallBagTrack;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Shared.DocNumbers;
|
||||
using Oms.Domain.ChannelsAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Repositories;
|
||||
using Oms.Domain.CustomersAggregate.Repositories;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
@ -48,6 +50,9 @@ public class PickupOrderService : ApplicationService
|
||||
private IWarehouseAddressRepository WarehouseAddressRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IWarehouseAddressRepository>();
|
||||
|
||||
private IDocNumberGenerator DocNumberGenerator =>
|
||||
LazyServiceProvider.GetRequiredService<IDocNumberGenerator>();
|
||||
|
||||
private ICountryRepository CountryRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ICountryRepository>();
|
||||
|
||||
@ -218,7 +223,15 @@ public class PickupOrderService : ApplicationService
|
||||
|
||||
var entity = new PickupOrder
|
||||
{
|
||||
PickupNo = await GeneratePickupNoAsync(),
|
||||
PickupNo = await DocNumberGenerator.GenerateAsync(
|
||||
DocNumberTypeCodes.PickupNo,
|
||||
new DocNumberGenerateContext
|
||||
{
|
||||
CountryCode = senderCountryCode,
|
||||
CustomerId = customerId,
|
||||
ProductCode = accepted.Select(x => x.ProductCode).FirstOrDefault(x => !string.IsNullOrWhiteSpace(x)),
|
||||
ChannelCode = accepted.Select(x => x.ChannelCode).FirstOrDefault(x => !string.IsNullOrWhiteSpace(x))
|
||||
}),
|
||||
RequestId = NormalizeOptional(input.RequestId),
|
||||
CustomerId = customerId,
|
||||
OrganizationId = orgId,
|
||||
@ -1328,21 +1341,6 @@ public class PickupOrderService : ApplicationService
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<string> GeneratePickupNoAsync()
|
||||
{
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var no = $"PK{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(1000, 9999)}";
|
||||
var existed = await PickupOrderRepository.GetByPickupNoAsync(no);
|
||||
if (existed == null)
|
||||
{
|
||||
return no;
|
||||
}
|
||||
}
|
||||
|
||||
throw new BusinessException("揽收单号生成失败");
|
||||
}
|
||||
|
||||
private async Task<PickupOrderOutput> MapOutputAsync(PickupOrder entity, bool includeOrders)
|
||||
{
|
||||
string? warehouseName = null;
|
||||
|
||||
@ -0,0 +1,142 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Fake.Application;
|
||||
|
||||
namespace Oms.Application.Shared.DocNumbers;
|
||||
|
||||
/// <summary>
|
||||
/// 占位符公式渲染:{PRODUCT}/{CHANNEL}/{COUNTRY}/日期/{RAND:n}/{SEQ:n}。
|
||||
/// </summary>
|
||||
public static partial class DocNumberFormulaRenderer
|
||||
{
|
||||
private static readonly Regex TokenRegex = MyTokenRegex();
|
||||
|
||||
/// <summary>公式是否包含 {SEQ:n}。</summary>
|
||||
public static bool ContainsSeq(string? formula) =>
|
||||
!string.IsNullOrWhiteSpace(formula)
|
||||
&& formula.Contains("{SEQ:", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public static string Render(
|
||||
string formula,
|
||||
DocNumberGenerateContext context,
|
||||
Func<int, int>? nextSeq = null,
|
||||
Func<int, string>? nextRand = null,
|
||||
DateTime? nowOverride = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(formula))
|
||||
{
|
||||
throw new BusinessException("单号公式不能为空");
|
||||
}
|
||||
|
||||
var now = nowOverride ?? context.Now ?? DateTime.Now;
|
||||
var sb = new StringBuilder();
|
||||
var lastIndex = 0;
|
||||
foreach (Match match in TokenRegex.Matches(formula))
|
||||
{
|
||||
sb.Append(formula, lastIndex, match.Index - lastIndex);
|
||||
sb.Append(ResolveToken(match.Groups[1].Value, context, now, nextSeq, nextRand));
|
||||
lastIndex = match.Index + match.Length;
|
||||
}
|
||||
|
||||
sb.Append(formula, lastIndex, formula.Length - lastIndex);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string ResolveToken(
|
||||
string token,
|
||||
DocNumberGenerateContext context,
|
||||
DateTime now,
|
||||
Func<int, int>? nextSeq,
|
||||
Func<int, string>? nextRand)
|
||||
{
|
||||
if (string.Equals(token, "PRODUCT", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(token, "PRODUCT_CODE", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return context.ProductCode?.Trim() ?? string.Empty;
|
||||
}
|
||||
|
||||
if (string.Equals(token, "CHANNEL", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(token, "CHANNEL_CODE", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return context.ChannelCode?.Trim() ?? string.Empty;
|
||||
}
|
||||
|
||||
if (string.Equals(token, "COUNTRY", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(token, "COUNTRY_CODE", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return context.CountryCode?.Trim().ToUpperInvariant() ?? string.Empty;
|
||||
}
|
||||
|
||||
if (string.Equals(token, "yyMMdd", StringComparison.Ordinal))
|
||||
{
|
||||
return now.ToString("yyMMdd");
|
||||
}
|
||||
|
||||
if (string.Equals(token, "yyyyMMdd", StringComparison.Ordinal))
|
||||
{
|
||||
return now.ToString("yyyyMMdd");
|
||||
}
|
||||
|
||||
if (string.Equals(token, "yyMMddHHmmss", StringComparison.Ordinal))
|
||||
{
|
||||
return now.ToString("yyMMddHHmmss");
|
||||
}
|
||||
|
||||
if (string.Equals(token, "yyyyMMddHHmmss", StringComparison.Ordinal))
|
||||
{
|
||||
return now.ToString("yyyyMMddHHmmss");
|
||||
}
|
||||
|
||||
if (token.StartsWith("RAND:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var width = ParseWidth(token[5..], "RAND");
|
||||
return nextRand?.Invoke(width) ?? DefaultRand(width);
|
||||
}
|
||||
|
||||
if (token.StartsWith("SEQ:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var width = ParseWidth(token[4..], "SEQ");
|
||||
if (nextSeq == null)
|
||||
{
|
||||
throw new BusinessException("当前公式含 {SEQ:n},但未提供序号源");
|
||||
}
|
||||
|
||||
var value = nextSeq(width);
|
||||
if (value < 0)
|
||||
{
|
||||
throw new BusinessException("序号不能为负数");
|
||||
}
|
||||
|
||||
var text = value.ToString();
|
||||
if (text.Length > width)
|
||||
{
|
||||
throw new BusinessException($"序号位数已超过 {width},请调整公式或分桶");
|
||||
}
|
||||
|
||||
return text.PadLeft(width, '0');
|
||||
}
|
||||
|
||||
// 未知占位符:原样保留,避免静默吞掉配置错误
|
||||
return "{" + token + "}";
|
||||
}
|
||||
|
||||
private static int ParseWidth(string raw, string kind)
|
||||
{
|
||||
if (!int.TryParse(raw.Trim(), out var width) || width is < 1 or > 12)
|
||||
{
|
||||
throw new BusinessException($"{kind} 位数须为 1~12 的整数");
|
||||
}
|
||||
|
||||
return width;
|
||||
}
|
||||
|
||||
private static string DefaultRand(int width)
|
||||
{
|
||||
var maxExclusive = (int)Math.Pow(10, width);
|
||||
var value = Random.Shared.Next(0, maxExclusive);
|
||||
return value.ToString().PadLeft(width, '0');
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\{([^{}]+)\}", RegexOptions.Compiled)]
|
||||
private static partial Regex MyTokenRegex();
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
namespace Oms.Application.Shared.DocNumbers;
|
||||
|
||||
/// <summary>
|
||||
/// 单号生成上下文(匹配维度 + 占位符取值)。
|
||||
/// </summary>
|
||||
public sealed class DocNumberGenerateContext
|
||||
{
|
||||
/// <summary>销售产品编码。</summary>
|
||||
public string? ProductCode { get; init; }
|
||||
|
||||
/// <summary>渠道编码。</summary>
|
||||
public string? ChannelCode { get; init; }
|
||||
|
||||
/// <summary>国家二字码。</summary>
|
||||
public string? CountryCode { get; init; }
|
||||
|
||||
/// <summary>客户 Id(客户单号唯一性校验)。</summary>
|
||||
public int? CustomerId { get; init; }
|
||||
|
||||
/// <summary>生成时刻;默认 DateTime.Now。</summary>
|
||||
public DateTime? Now { get; init; }
|
||||
}
|
||||
256
src/Oms.Application/Shared/DocNumbers/DocNumberGenerator.cs
Normal file
256
src/Oms.Application/Shared/DocNumbers/DocNumberGenerator.cs
Normal file
@ -0,0 +1,256 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 单号生成:匹配规则 → 渲染公式 → 唯一性重试;无规则走内置。
|
||||
/// </summary>
|
||||
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<string> 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<int, int>? 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<DocNumberPreviewResult> 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<Domain.ChannelsAggregate.Entities.DocNumberRule?> ResolveRuleAsync(
|
||||
string docType,
|
||||
DocNumberGenerateContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var rules = await ruleRepository.ListEnabledByDocTypeAsync(docType, cancellationToken);
|
||||
return DocNumberRuleMatcher.PickBest(rules, context);
|
||||
}
|
||||
|
||||
private async Task<bool> 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<bool> 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.IsKnown(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
|
||||
};
|
||||
}
|
||||
105
src/Oms.Application/Shared/DocNumbers/DocNumberRuleMatcher.cs
Normal file
105
src/Oms.Application/Shared/DocNumbers/DocNumberRuleMatcher.cs
Normal file
@ -0,0 +1,105 @@
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
|
||||
namespace Oms.Application.Shared.DocNumbers;
|
||||
|
||||
/// <summary>
|
||||
/// 按产品 / 渠道 / 国家打分选最优规则。
|
||||
/// </summary>
|
||||
public static class DocNumberRuleMatcher
|
||||
{
|
||||
public const int ProductScore = 100;
|
||||
public const int ChannelScore = 50;
|
||||
public const int CountryScore = 20;
|
||||
|
||||
public static DocNumberRule? PickBest(
|
||||
IEnumerable<DocNumberRule> rules,
|
||||
DocNumberGenerateContext context)
|
||||
{
|
||||
DocNumberRule? best = null;
|
||||
var bestScore = int.MinValue;
|
||||
var bestPriority = int.MaxValue;
|
||||
var bestId = int.MaxValue;
|
||||
|
||||
foreach (var rule in rules)
|
||||
{
|
||||
if (!TryScore(rule, context, out var score))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var priority = rule.Priority <= 0 ? 100 : rule.Priority;
|
||||
if (score > bestScore
|
||||
|| (score == bestScore && priority < bestPriority)
|
||||
|| (score == bestScore && priority == bestPriority && rule.Id < bestId))
|
||||
{
|
||||
best = rule;
|
||||
bestScore = score;
|
||||
bestPriority = priority;
|
||||
bestId = rule.Id;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
public static bool TryScore(DocNumberRule rule, DocNumberGenerateContext context, out int score)
|
||||
{
|
||||
score = 0;
|
||||
if (!MatchesDimension(rule.ProductCode, context.ProductCode, out var productHit))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!MatchesDimension(rule.ChannelCode, context.ChannelCode, out var channelHit))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!MatchesDimension(rule.CountryCode, context.CountryCode, out var countryHit))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (productHit)
|
||||
{
|
||||
score += ProductScore;
|
||||
}
|
||||
|
||||
if (channelHit)
|
||||
{
|
||||
score += ChannelScore;
|
||||
}
|
||||
|
||||
if (countryHit)
|
||||
{
|
||||
score += CountryScore;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 规则维度为空=通配;有值则必须与上下文忽略大小写相等才命中。
|
||||
/// </summary>
|
||||
private static bool MatchesDimension(string? ruleValue, string? contextValue, out bool exactHit)
|
||||
{
|
||||
exactHit = false;
|
||||
if (string.IsNullOrWhiteSpace(ruleValue))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(contextValue))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!string.Equals(ruleValue.Trim(), contextValue.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
exactHit = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
42
src/Oms.Application/Shared/DocNumbers/IDocNumberGenerator.cs
Normal file
42
src/Oms.Application/Shared/DocNumbers/IDocNumberGenerator.cs
Normal file
@ -0,0 +1,42 @@
|
||||
namespace Oms.Application.Shared.DocNumbers;
|
||||
|
||||
/// <summary>
|
||||
/// 按规则(或内置默认)生成单据号。
|
||||
/// </summary>
|
||||
public interface IDocNumberGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// 生成单据号;未命中启用规则时走内置默认。
|
||||
/// </summary>
|
||||
Task<string> GenerateAsync(
|
||||
string docType,
|
||||
DocNumberGenerateContext context,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 试算预览(不落库、不占序号;含 SEQ 时用 1 填充)。
|
||||
/// </summary>
|
||||
Task<DocNumberPreviewResult> PreviewAsync(
|
||||
string docType,
|
||||
string? formula,
|
||||
DocNumberGenerateContext context,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 试算结果。
|
||||
/// </summary>
|
||||
public sealed class DocNumberPreviewResult
|
||||
{
|
||||
/// <summary>预览单号。</summary>
|
||||
public string Sample { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>是否命中配置规则(否则为内置)。</summary>
|
||||
public bool UsedRule { get; init; }
|
||||
|
||||
/// <summary>命中规则 Id。</summary>
|
||||
public int? RuleId { get; init; }
|
||||
|
||||
/// <summary>实际使用的公式。</summary>
|
||||
public string Formula { get; init; } = string.Empty;
|
||||
}
|
||||
@ -0,0 +1,57 @@
|
||||
namespace Oms.Domain.ChannelsAggregate.Consts;
|
||||
|
||||
/// <summary>
|
||||
/// 可配置生成的单据号类型。
|
||||
/// </summary>
|
||||
public static class DocNumberTypeCodes
|
||||
{
|
||||
/// <summary>运单号(t_order.ServiceNo)。</summary>
|
||||
public const string ServiceNo = "ServiceNo";
|
||||
|
||||
/// <summary>客户单号(t_order.ClientNo)。</summary>
|
||||
public const string ClientNo = "ClientNo";
|
||||
|
||||
/// <summary>揽收单号(t_pickup_order.PickupNo)。</summary>
|
||||
public const string PickupNo = "PickupNo";
|
||||
|
||||
/// <summary>大包号(t_ship_bag.BagNo)。</summary>
|
||||
public const string BagNo = "BagNo";
|
||||
|
||||
/// <summary>主单号(t_ship_master.MasterNo)。</summary>
|
||||
public const string MasterNo = "MasterNo";
|
||||
|
||||
public static readonly string[] All =
|
||||
[
|
||||
ServiceNo,
|
||||
ClientNo,
|
||||
PickupNo,
|
||||
BagNo,
|
||||
MasterNo
|
||||
];
|
||||
|
||||
public static bool IsKnown(string? docType) =>
|
||||
!string.IsNullOrWhiteSpace(docType)
|
||||
&& All.Any(x => string.Equals(x, docType.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public static string Normalize(string docType)
|
||||
{
|
||||
var trimmed = docType.Trim();
|
||||
foreach (var code in All)
|
||||
{
|
||||
if (string.Equals(code, trimmed, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/// <summary>字段长度上限(对齐库表 VARCHAR)。</summary>
|
||||
public static int MaxLength(string docType) =>
|
||||
Normalize(docType) switch
|
||||
{
|
||||
ServiceNo or ClientNo => 64,
|
||||
_ => 32
|
||||
};
|
||||
}
|
||||
46
src/Oms.Domain/ChannelsAggregate/Entities/DocNumberRule.cs
Normal file
46
src/Oms.Domain/ChannelsAggregate/Entities/DocNumberRule.cs
Normal file
@ -0,0 +1,46 @@
|
||||
using Oms.Domain.Shared;
|
||||
using Oms.Domain.Shared.Enums;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.ChannelsAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 单号生成规则(产品 / 渠道 / 国家可通配)。
|
||||
/// </summary>
|
||||
[SugarTable("t_doc_number_rule")]
|
||||
public class DocNumberRule : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>单据类型:ServiceNo / ClientNo / PickupNo / BagNo / MasterNo。</summary>
|
||||
[SugarColumn(Length = 32)]
|
||||
public string DocType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>规则名称。</summary>
|
||||
[SugarColumn(Length = 128)]
|
||||
public string RuleName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>占位符公式,如 {PRODUCT}{COUNTRY}{yyMMdd}{SEQ:6}。</summary>
|
||||
[SugarColumn(Length = 256)]
|
||||
public string Formula { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>销售产品编码;空=通配。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? ProductCode { get; set; }
|
||||
|
||||
/// <summary>渠道编码;空=通配。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
/// <summary>国家二字码;空=通配。</summary>
|
||||
[SugarColumn(Length = 8, IsNullable = true)]
|
||||
public string? CountryCode { get; set; }
|
||||
|
||||
/// <summary>优先级,数值越小越优先(同分时)。</summary>
|
||||
public int Priority { get; set; } = 100;
|
||||
|
||||
/// <summary>启用状态。</summary>
|
||||
public EnableStatus Status { get; set; } = EnableStatus.Enabled;
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
[SugarColumn(Length = 512, IsNullable = true)]
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
21
src/Oms.Domain/ChannelsAggregate/Entities/DocNumberSeq.cs
Normal file
21
src/Oms.Domain/ChannelsAggregate/Entities/DocNumberSeq.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.ChannelsAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 单号规则日序号({SEQ:n} 使用)。
|
||||
/// </summary>
|
||||
[SugarTable("t_doc_number_seq")]
|
||||
public class DocNumberSeq : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>规则 Id。</summary>
|
||||
public int RuleId { get; set; }
|
||||
|
||||
/// <summary>分桶键,如 yyyyMMdd。</summary>
|
||||
[SugarColumn(Length = 32)]
|
||||
public string ScopeKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>当前序号。</summary>
|
||||
public int CurrentValue { get; set; }
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.ChannelsAggregate.Repositories;
|
||||
|
||||
public interface IDocNumberRuleRepository : IRepository<DocNumberRule>
|
||||
{
|
||||
/// <summary>
|
||||
/// 查询某单据类型下全部启用规则。
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<DocNumberRule>> ListEnabledByDocTypeAsync(
|
||||
string docType,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.ChannelsAggregate.Repositories;
|
||||
|
||||
public interface IDocNumberSeqRepository : IRepository<DocNumberSeq>
|
||||
{
|
||||
/// <summary>
|
||||
/// 按规则 + 分桶取序号行。
|
||||
/// </summary>
|
||||
Task<DocNumberSeq?> GetByRuleAndScopeAsync(
|
||||
int ruleId,
|
||||
string scopeKey,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 原子递增并返回新值;不存在则插入从 1 开始。
|
||||
/// </summary>
|
||||
Task<int> NextValueAsync(
|
||||
int ruleId,
|
||||
string scopeKey,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
20
src/Oms.SqlSugarCore/Channels/DocNumberRuleRepository.cs
Normal file
20
src/Oms.SqlSugarCore/Channels/DocNumberRuleRepository.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
using Oms.Domain.ChannelsAggregate.Repositories;
|
||||
using Oms.Domain.Shared.Enums;
|
||||
using Oms.SqlSugarCore.Repositories;
|
||||
|
||||
namespace Oms.SqlSugarCore.Channels;
|
||||
|
||||
public class DocNumberRuleRepository : OmsSqlSugarRepository<DocNumberRule>, IDocNumberRuleRepository, IScopedDependency
|
||||
{
|
||||
public async Task<IReadOnlyList<DocNumberRule>> ListEnabledByDocTypeAsync(
|
||||
string docType,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var list = await GetListAsync(
|
||||
x => x.DocType == docType && x.Status == EnableStatus.Enabled,
|
||||
cancellationToken: cancellationToken);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
65
src/Oms.SqlSugarCore/Channels/DocNumberSeqRepository.cs
Normal file
65
src/Oms.SqlSugarCore/Channels/DocNumberSeqRepository.cs
Normal file
@ -0,0 +1,65 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
using Oms.Domain.ChannelsAggregate.Repositories;
|
||||
using Oms.SqlSugarCore.Repositories;
|
||||
|
||||
namespace Oms.SqlSugarCore.Channels;
|
||||
|
||||
public class DocNumberSeqRepository : OmsSqlSugarRepository<DocNumberSeq>, IDocNumberSeqRepository, IScopedDependency
|
||||
{
|
||||
private const int MaxRetries = 8;
|
||||
|
||||
public Task<DocNumberSeq?> GetByRuleAndScopeAsync(
|
||||
int ruleId,
|
||||
string scopeKey,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
FirstOrDefaultAsync(x => x.RuleId == ruleId && x.ScopeKey == scopeKey, cancellationToken);
|
||||
|
||||
public async Task<int> NextValueAsync(
|
||||
int ruleId,
|
||||
string scopeKey,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
for (var attempt = 0; attempt < MaxRetries; attempt++)
|
||||
{
|
||||
var existing = await GetByRuleAndScopeAsync(ruleId, scopeKey, cancellationToken);
|
||||
if (existing == null)
|
||||
{
|
||||
var created = new DocNumberSeq
|
||||
{
|
||||
RuleId = ruleId,
|
||||
ScopeKey = scopeKey,
|
||||
CurrentValue = 1
|
||||
};
|
||||
try
|
||||
{
|
||||
await InsertAsync(created, cancellationToken: cancellationToken);
|
||||
return 1;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 并发插入冲突时重试读改写
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
var expected = existing.CurrentValue;
|
||||
var next = expected + 1;
|
||||
var db = await GetDbContextAsync(cancellationToken);
|
||||
var affected = await db.Updateable<DocNumberSeq>()
|
||||
.SetColumns(x => new DocNumberSeq
|
||||
{
|
||||
CurrentValue = next,
|
||||
UpdateTime = DateTime.Now
|
||||
})
|
||||
.Where(x => x.Id == existing.Id && x.CurrentValue == expected)
|
||||
.ExecuteCommandAsync(cancellationToken);
|
||||
if (affected > 0)
|
||||
{
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("单号序号分配失败,请重试");
|
||||
}
|
||||
}
|
||||
83
src/Oms.Tests/DocNumberFormulaRendererTests.cs
Normal file
83
src/Oms.Tests/DocNumberFormulaRendererTests.cs
Normal file
@ -0,0 +1,83 @@
|
||||
using FluentAssertions;
|
||||
using Oms.Application.Shared.DocNumbers;
|
||||
using Oms.Domain.ChannelsAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
|
||||
namespace Oms.Tests;
|
||||
|
||||
public class DocNumberFormulaRendererTests
|
||||
{
|
||||
[Fact]
|
||||
public void Render_ShouldExpandKnownTokens()
|
||||
{
|
||||
var now = new DateTime(2026, 11, 14, 15, 30, 45);
|
||||
var result = DocNumberFormulaRenderer.Render(
|
||||
"{PRODUCT}-{COUNTRY}-{yyMMdd}-{SEQ:4}-{RAND:3}",
|
||||
new DocNumberGenerateContext
|
||||
{
|
||||
ProductCode = "EX_DHL",
|
||||
CountryCode = "us",
|
||||
ChannelCode = "CH1"
|
||||
},
|
||||
nextSeq: _ => 12,
|
||||
nextRand: _ => "007",
|
||||
nowOverride: now);
|
||||
|
||||
result.Should().Be("EX_DHL-US-261114-0012-007");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Render_MissingContext_ShouldUseEmptyString()
|
||||
{
|
||||
var result = DocNumberFormulaRenderer.Render(
|
||||
"X{PRODUCT}{CHANNEL}Y",
|
||||
new DocNumberGenerateContext(),
|
||||
nowOverride: new DateTime(2026, 1, 1));
|
||||
|
||||
result.Should().Be("XY");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Builtin_ServiceNo_ShouldMatchLegacyShape()
|
||||
{
|
||||
var now = new DateTime(2026, 7, 22, 18, 59, 12);
|
||||
var sample = DocNumberGenerator.BuildBuiltin(DocNumberTypeCodes.ServiceNo, now);
|
||||
sample.Should().StartWith("BCD260722185912");
|
||||
sample.Length.Should().Be(19);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Matcher_ShouldPreferMoreSpecificRule()
|
||||
{
|
||||
var rules = new List<DocNumberRule>
|
||||
{
|
||||
new() { Id = 1, Priority = 100, Formula = "A", ProductCode = null, ChannelCode = null, CountryCode = null },
|
||||
new() { Id = 2, Priority = 100, Formula = "B", ProductCode = "P1", ChannelCode = null, CountryCode = "US" },
|
||||
new() { Id = 3, Priority = 1, Formula = "C", ProductCode = "P1", ChannelCode = null, CountryCode = null },
|
||||
};
|
||||
|
||||
var best = DocNumberRuleMatcher.PickBest(
|
||||
rules,
|
||||
new DocNumberGenerateContext { ProductCode = "P1", CountryCode = "US" });
|
||||
|
||||
best!.Id.Should().Be(2);
|
||||
best.Formula.Should().Be("B");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Matcher_EqualScore_ShouldPreferHigherPriorityThenLowerId()
|
||||
{
|
||||
var rules = new List<DocNumberRule>
|
||||
{
|
||||
new() { Id = 5, Priority = 50, Formula = "A", CountryCode = "US" },
|
||||
new() { Id = 3, Priority = 50, Formula = "B", CountryCode = "US" },
|
||||
new() { Id = 9, Priority = 10, Formula = "C", CountryCode = "US" },
|
||||
};
|
||||
|
||||
var best = DocNumberRuleMatcher.PickBest(
|
||||
rules,
|
||||
new DocNumberGenerateContext { CountryCode = "US" });
|
||||
|
||||
best!.Formula.Should().Be("C");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user