admin/src/Oms.Application/Services/Channels/AutoTriggerService.cs
zzh d5d6305f9c
All checks were successful
Build and Deploy / deploy (push) Successful in 1m2s
feat: 自动触发规则支持 Excel 导入与模板下载
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 15:31:19 +08:00

301 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Linq.Expressions;
using Fake.Application;
using Microsoft.AspNetCore.Mvc;
using Oms.Application.Dtos.Channels;
using Oms.Application.Dtos.Shared;
using Oms.Application.Services.Orders.Issues;
using Oms.Application.Shared;
using Oms.Domain.ChannelsAggregate.Entities;
using Oms.Domain.ChannelsAggregate.Repositories;
namespace Oms.Application.Services.Channels;
/// <summary>
/// 自动触发规则 API 服务。
/// </summary>
[ApiExplorerSettings(GroupName = "OMS-Channel")]
public class AutoTriggerService : ApplicationService
{
private IAutoTriggerRepository AutoTriggerRepository => LazyServiceProvider.GetRequiredService<IAutoTriggerRepository>();
private OrderAutoTriggerService OrderAutoTriggerService => LazyServiceProvider.GetRequiredService<OrderAutoTriggerService>();
/// <summary>
/// 查询自动触发规则列表。
/// </summary>
[HttpGet("/channel/auto-trigger/list")]
public async Task<OmsPageResult<AutoTriggerOutput>> GetListAsync([FromQuery] AutoTriggerListInput input)
{
var predicate = BuildListPredicate(input);
var pageIndex = OmsDocHelper.NormalizePage(input.Page);
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
var entities = await AutoTriggerRepository.GetPagedListAsync(
predicate,
pageIndex,
pageSize,
new Dictionary<string, bool> { [nameof(AutoTrigger.Priority)] = true, [nameof(AutoTrigger.Id)] = true });
var total = await AutoTriggerRepository.CountAsync(predicate);
var items = entities.Select(MapOutput).ToList();
return new OmsPageResult<AutoTriggerOutput> { Items = items, Total = total };
}
/// <summary>
/// 下载自动触发规则导入模板。
/// </summary>
[HttpGet("/channel/auto-trigger/import-template")]
public async Task<FileContentResult> DownloadImportTemplateAsync()
{
var bytes = await AutoTriggerImportHelper.BuildTemplateBytesAsync();
return new FileContentResult(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = AutoTriggerImportHelper.TemplateFileName
};
}
/// <summary>
/// 导入自动触发规则(Excel)。
/// </summary>
[HttpPost("/channel/auto-trigger/import")]
public async Task<AutoTriggerImportOutput> ImportAsync([FromForm] AutoTriggerImportInput input)
{
if (input.File == null || input.File.Length == 0)
{
throw new BusinessException("请上传 Excel 文件");
}
var importMode = NormalizeImportMode(input.ImportMode);
await using var stream = input.File.OpenReadStream();
var parsedRows = await AutoTriggerImportHelper.ParseImportRowsAsync(stream);
if (parsedRows.Count == 0)
{
throw new BusinessException("Excel 中无有效数据行");
}
if (importMode == AutoTriggerImportInput.ImportModes.Full)
{
var existing = await AutoTriggerRepository.GetListAsync(_ => true);
foreach (var entity in existing)
{
await AutoTriggerRepository.DeleteAsync(entity);
}
}
var output = new AutoTriggerImportOutput();
var seenKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var (rowNumber, entity) in parsedRows)
{
try
{
AutoTriggerImportHelper.ValidateEntity(entity);
entity.TriggerTiming = AutoTriggerTimingCodes.ToCanonicalLabel(entity.TriggerTiming);
var key = BuildDuplicateKey(entity);
if (!seenKeys.Add(key))
{
output.SkipCount++;
output.Failures.Add(new AutoTriggerImportFailRow
{
RowNumber = rowNumber,
Reason = "文件内规则重复,已跳过"
});
continue;
}
if (importMode == AutoTriggerImportInput.ImportModes.Incremental)
{
var duplicated = await AutoTriggerRepository.FirstOrDefaultAsync(x =>
x.RuleName == entity.RuleName
&& x.Operation == entity.Operation
&& x.TriggerTiming == entity.TriggerTiming
&& x.TriggerCondition == entity.TriggerCondition);
if (duplicated != null)
{
output.SkipCount++;
output.Failures.Add(new AutoTriggerImportFailRow
{
RowNumber = rowNumber,
Reason = "与已有规则重复,已跳过"
});
continue;
}
}
await AutoTriggerRepository.InsertAsync(entity);
output.SuccessCount++;
}
catch (Exception ex)
{
output.FailCount++;
output.Failures.Add(new AutoTriggerImportFailRow
{
RowNumber = rowNumber,
Reason = ex.Message
});
}
}
return output;
}
private static string NormalizeImportMode(string? mode)
{
if (string.Equals(mode, AutoTriggerImportInput.ImportModes.Full, StringComparison.OrdinalIgnoreCase)
|| string.Equals(mode, "全量", StringComparison.OrdinalIgnoreCase)
|| string.Equals(mode, "replace", StringComparison.OrdinalIgnoreCase))
{
return AutoTriggerImportInput.ImportModes.Full;
}
return AutoTriggerImportInput.ImportModes.Incremental;
}
private static string BuildDuplicateKey(AutoTrigger entity) =>
$"{entity.RuleName}|{entity.Operation}|{entity.TriggerTiming}|{entity.TriggerCondition}";
/// <summary>
/// 获取公式字段元数据。
/// </summary>
[HttpGet("/channel/auto-trigger/meta")]
public Task<AutoTriggerMetaOutput> GetMetaAsync() =>
Task.FromResult(AutoTriggerFormulaMeta.BuildMetaOutput());
/// <summary>
/// 测试公式是否命中。
/// </summary>
[HttpPost("/channel/auto-trigger/test")]
public Task<AutoTriggerTestOutput> TestFormulaAsync(AutoTriggerTestInput input) =>
OrderAutoTriggerService.TestFormulaAsync(input);
/// <summary>
/// 新增自动触发规则。
/// </summary>
[HttpPost("/channel/auto-trigger/create")]
public async Task CreateAsync(AutoTriggerSaveInput input)
{
var entity = new AutoTrigger
{
Status = input.Status,
RuleName = NormalizeRuleName(input),
Priority = NormalizePriority(input),
Operation = input.Operation,
TriggerTiming = AutoTriggerTimingCodes.ToCanonicalLabel(input.TriggerTiming),
TriggerCondition = input.TriggerCondition,
PromptMessage = input.PromptMessage,
Notifier = input.Notifier
};
await AutoTriggerRepository.InsertAsync(entity);
}
/// <summary>
/// 更新自动触发规则。
/// </summary>
[HttpPost("/channel/auto-trigger/update")]
public async Task UpdateAsync(AutoTriggerSaveInput input)
{
var entity = await GetEntityOrThrowAsync(input.Id);
entity.Status = input.Status;
entity.RuleName = NormalizeRuleName(input);
entity.Priority = NormalizePriority(input);
entity.Operation = input.Operation;
entity.TriggerTiming = AutoTriggerTimingCodes.ToCanonicalLabel(input.TriggerTiming);
entity.TriggerCondition = input.TriggerCondition;
entity.PromptMessage = input.PromptMessage;
entity.Notifier = input.Notifier;
await AutoTriggerRepository.UpdateAsync(entity);
}
/// <summary>
/// 删除自动触发规则。
/// </summary>
[HttpPost("/channel/auto-trigger/delete")]
public async Task DeleteAsync(IdInput input)
{
var entity = await GetEntityOrThrowAsync(input.Id);
await AutoTriggerRepository.DeleteAsync(entity);
}
/// <summary>
/// 切换自动触发规则状态。
/// </summary>
[HttpPost("/channel/auto-trigger/toggleStatus")]
public async Task ToggleStatusAsync(ToggleStatusInput input)
{
var entity = await GetEntityOrThrowAsync(input.Id);
entity.Status = input.Status;
await AutoTriggerRepository.UpdateAsync(entity);
}
private static Expression<Func<AutoTrigger, bool>> BuildListPredicate(AutoTriggerListInput input)
{
var operation = input.Operation?.Trim();
var triggerTiming = AutoTriggerTimingCodes.ToCanonicalLabel(input.TriggerTiming);
// 预报已并入下单:筛「下单」时同时命中历史「预报」落库值
if (triggerTiming == AutoTriggerTimingCodes.LabelOrderCreate)
{
return entity =>
(string.IsNullOrWhiteSpace(operation) || entity.Operation == operation) &&
(entity.TriggerTiming == AutoTriggerTimingCodes.LabelOrderCreate
|| entity.TriggerTiming == "预报"
|| entity.TriggerTiming == "forecast"
|| entity.TriggerTiming == AutoTriggerTimingCodes.OrderCreate);
}
return entity =>
(string.IsNullOrWhiteSpace(operation) || entity.Operation == operation) &&
(string.IsNullOrWhiteSpace(triggerTiming) || entity.TriggerTiming == triggerTiming);
}
private async Task<AutoTrigger> GetEntityOrThrowAsync(int? id)
{
if (!id.HasValue || id.Value <= 0)
{
throw new BusinessException("自动触发不存在");
}
var entity = await AutoTriggerRepository.FirstOrDefaultAsync(x => x.Id == id.Value);
if (entity == null)
{
throw new BusinessException("自动触发不存在");
}
return entity;
}
private static string? NormalizeRuleName(AutoTriggerSaveInput input)
{
if (!string.IsNullOrWhiteSpace(input.RuleName))
{
return input.RuleName.Trim();
}
return AutoTriggerConditionParser.Parse(input.TriggerCondition).RuleName;
}
private static int NormalizePriority(AutoTriggerSaveInput input)
{
if (input.Priority > 0)
{
return input.Priority;
}
var parsed = AutoTriggerConditionParser.Parse(input.TriggerCondition);
return parsed.Priority > 0 ? parsed.Priority : 100;
}
private static AutoTriggerOutput MapOutput(AutoTrigger entity)
{
return new AutoTriggerOutput
{
Id = entity.Id,
Status = (byte)entity.Status,
RuleName = AutoTriggerRuleResolver.GetRuleName(entity),
Priority = AutoTriggerRuleResolver.GetPriority(entity),
Operation = entity.Operation,
TriggerTiming = AutoTriggerTimingCodes.ToCanonicalLabel(entity.TriggerTiming),
TriggerCondition = entity.TriggerCondition,
PromptMessage = entity.PromptMessage,
Notifier = entity.Notifier,
CreateTime = entity.CreateTime,
UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime)
};
}
}