admin/src/Oms.Application/Services/Kb/KbArticleService.cs
zzh 7e442180cd fix: avoid SqlSugar invalid SQL from null/HasValue KB filters
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 16:53:09 +08:00

395 lines
14 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 Fake.Domain.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Oms.Application.Dtos.Kb;
using Oms.Application.Dtos.Shared;
using Oms.Application.Shared;
using Oms.Domain.KbAggregate.Entities;
using Oms.Domain.KbAggregate.Repositories;
namespace Oms.Application.Services.Kb;
/// <summary>
/// 知识库文章:管理端 + 客户门户。
/// </summary>
[ApiExplorerSettings(GroupName = "OMS-Kb")]
public class KbArticleService : ApplicationService
{
private IKbArticleRepository ArticleRepository =>
LazyServiceProvider.GetRequiredService<IKbArticleRepository>();
private IKbCategoryRepository CategoryRepository =>
LazyServiceProvider.GetRequiredService<IKbCategoryRepository>();
[HttpPost("/kb/admin/article/page")]
public async Task<OmsPageResult<KbArticleOutput>> AdminPageAsync(KbArticleListInput input)
{
var predicate = BuildAdminPredicate(input);
var pageIndex = OmsDocHelper.NormalizePage(input.Page);
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
var entities = await ArticleRepository.GetPagedListAsync(
predicate,
pageIndex,
pageSize,
new Dictionary<string, bool>
{
[nameof(KbArticle.IsPinned)] = false,
[nameof(KbArticle.SortOrder)] = true,
[nameof(KbArticle.Id)] = false
});
var total = await ArticleRepository.CountAsync(predicate);
var categoryMap = await LoadCategoryNameMapAsync(entities.Select(x => x.CategoryId).Distinct());
return new OmsPageResult<KbArticleOutput>
{
Total = total,
Items = entities.Select(x => Map(x, categoryMap, input.IncludeContent)).ToList()
};
}
[HttpGet("/kb/admin/article/{id:int}")]
public async Task<KbArticleOutput> AdminGetAsync(int id)
{
var entity = await GetArticleOrThrowAsync(id);
var categoryMap = await LoadCategoryNameMapAsync([entity.CategoryId]);
return Map(entity, categoryMap, includeContent: true);
}
[HttpPost("/kb/admin/article/save")]
public async Task<KbArticleOutput> SaveAsync(KbArticleSaveInput input)
{
ValidateSave(input);
await EnsureCategoryExistsAsync(input.CategoryId);
KbArticle? entity = null;
if (input.Id is > 0)
{
entity = await GetArticleOrThrowAsync(input.Id.Value);
}
entity ??= new KbArticle();
ApplySave(input, entity);
if (string.Equals(entity.Status, KbArticleStatusCodes.Published, StringComparison.OrdinalIgnoreCase)
&& entity.PublishTime == null)
{
entity.PublishTime = DateTime.Now;
}
if (entity.Id > 0)
{
await ArticleRepository.UpdateAsync(entity);
}
else
{
await ArticleRepository.InsertAsync(entity);
}
var categoryMap = await LoadCategoryNameMapAsync([entity.CategoryId]);
return Map(entity, categoryMap, includeContent: true);
}
[HttpPost("/kb/admin/article/publish")]
public async Task PublishAsync(KbArticleIdInput input)
{
var entity = await GetArticleOrThrowAsync(input.Id);
entity.Status = KbArticleStatusCodes.Published;
entity.PublishTime ??= DateTime.Now;
await ArticleRepository.UpdateAsync(entity);
}
[HttpPost("/kb/admin/article/offline")]
public async Task OfflineAsync(KbArticleIdInput input)
{
var entity = await GetArticleOrThrowAsync(input.Id);
entity.Status = KbArticleStatusCodes.Offline;
await ArticleRepository.UpdateAsync(entity);
}
[HttpPost("/kb/admin/article/pin")]
public async Task PinAsync(KbArticlePinInput input)
{
var entity = await GetArticleOrThrowAsync(input.Id);
entity.IsPinned = input.IsPinned;
await ArticleRepository.UpdateAsync(entity);
}
[HttpPost("/kb/admin/article/delete")]
public async Task DeleteAsync(KbArticleIdInput input)
{
var entity = await GetArticleOrThrowAsync(input.Id);
await ArticleRepository.DeleteAsync(entity);
}
/// <summary>门户:启用分类列表(需客户登录)。</summary>
[HttpGet("/kb/portal/category/list")]
public async Task<OmsItemsResult<KbCategoryOutput>> PortalCategoryListAsync()
{
MarketingPortalSessionHelper.EnsureCustomerLogin(CurrentUser);
var items = await CategoryRepository.GetListAsync(x => x.Enabled);
var ordered = items.OrderBy(x => x.SortOrder).ThenBy(x => x.Id).ToList();
return new OmsItemsResult<KbCategoryOutput>
{
Items = ordered.Select(x => new KbCategoryOutput
{
Id = x.Id,
Code = x.Code,
Name = x.Name,
SortOrder = x.SortOrder,
Enabled = x.Enabled
}).ToList()
};
}
/// <summary>门户:文章分页(需客户登录)。</summary>
[HttpPost("/kb/portal/article/page")]
public async Task<OmsPageResult<KbArticleOutput>> PortalPageAsync(KbPortalArticleListInput input)
{
MarketingPortalSessionHelper.EnsureCustomerLogin(CurrentUser);
var predicate = BuildPortalPredicate(input.Keyword, input.CategoryId);
var pageIndex = OmsDocHelper.NormalizePage(input.Page);
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
var entities = await ArticleRepository.GetPagedListAsync(
predicate,
pageIndex,
pageSize,
new Dictionary<string, bool>
{
[nameof(KbArticle.IsPinned)] = false,
[nameof(KbArticle.SortOrder)] = true,
[nameof(KbArticle.PublishTime)] = false,
[nameof(KbArticle.Id)] = false
});
var total = await ArticleRepository.CountAsync(predicate);
var categoryMap = await LoadCategoryNameMapAsync(entities.Select(x => x.CategoryId).Distinct());
return new OmsPageResult<KbArticleOutput>
{
Total = total,
Items = entities.Select(x => Map(x, categoryMap, includeContent: false)).ToList()
};
}
/// <summary>门户:热门(需客户登录)。</summary>
[HttpGet("/kb/portal/article/hot")]
public async Task<OmsItemsResult<KbArticleOutput>> PortalHotAsync([FromQuery] int top = 10)
{
MarketingPortalSessionHelper.EnsureCustomerLogin(CurrentUser);
top = Math.Clamp(top <= 0 ? 10 : top, 1, 50);
var now = DateTime.Now;
var all = await ArticleRepository.GetListAsync(x =>
x.Status == KbArticleStatusCodes.Published
&& x.Audience == KbAudienceCodes.Customer
&& (x.ExpireTime == null || x.ExpireTime > now));
var ordered = all
.OrderByDescending(x => x.IsPinned)
.ThenByDescending(x => x.ViewCount)
.ThenByDescending(x => x.PublishTime)
.ThenByDescending(x => x.Id)
.Take(top)
.ToList();
var categoryMap = await LoadCategoryNameMapAsync(ordered.Select(x => x.CategoryId).Distinct());
return new OmsItemsResult<KbArticleOutput>
{
Items = ordered.Select(x => Map(x, categoryMap, includeContent: false)).ToList()
};
}
/// <summary>门户:详情(需客户登录;浏览量 +1)。</summary>
[HttpGet("/kb/portal/article/{id:int}")]
public async Task<KbArticleOutput> PortalGetAsync(int id)
{
MarketingPortalSessionHelper.EnsureCustomerLogin(CurrentUser);
var entity = await GetArticleOrThrowAsync(id);
EnsurePortalVisible(entity);
entity.ViewCount += 1;
await ArticleRepository.UpdateAsync(entity);
var categoryMap = await LoadCategoryNameMapAsync([entity.CategoryId]);
return Map(entity, categoryMap, includeContent: true);
}
private static Expression<Func<KbArticle, bool>> BuildAdminPredicate(KbArticleListInput input)
{
var keyword = NormalizeOptional(input.Keyword);
var status = NormalizeOptional(input.Status);
var audience = NormalizeOptional(input.Audience);
var predicate = ExpressionPredicate.True<KbArticle>();
if (input.CategoryId is int categoryId)
{
predicate = ExpressionPredicate.AndAlso(predicate, x => x.CategoryId == categoryId);
}
if (status != null)
{
predicate = ExpressionPredicate.AndAlso(predicate, x => x.Status == status);
}
if (audience != null)
{
predicate = ExpressionPredicate.AndAlso(predicate, x => x.Audience == audience);
}
if (input.IsPinned is bool isPinned)
{
predicate = ExpressionPredicate.AndAlso(predicate, x => x.IsPinned == isPinned);
}
if (keyword != null)
{
predicate = ExpressionPredicate.AndAlso(
predicate,
x => x.Title.Contains(keyword)
|| (x.Summary != null && x.Summary.Contains(keyword))
|| (x.Tags != null && x.Tags.Contains(keyword)));
}
return predicate;
}
private static Expression<Func<KbArticle, bool>> BuildPortalPredicate(string? keyword, int? categoryId)
{
var kw = NormalizeOptional(keyword);
var now = DateTime.Now;
var predicate = ExpressionPredicate.AndAlso(
ExpressionPredicate.True<KbArticle>(),
x => x.Status == KbArticleStatusCodes.Published
&& x.Audience == KbAudienceCodes.Customer
&& (x.ExpireTime == null || x.ExpireTime > now));
if (categoryId is int cid)
{
predicate = ExpressionPredicate.AndAlso(predicate, x => x.CategoryId == cid);
}
if (kw != null)
{
predicate = ExpressionPredicate.AndAlso(
predicate,
x => x.Title.Contains(kw)
|| (x.Summary != null && x.Summary.Contains(kw))
|| (x.Tags != null && x.Tags.Contains(kw)));
}
return predicate;
}
private static void EnsurePortalVisible(KbArticle entity)
{
if (!string.Equals(entity.Audience, KbAudienceCodes.Customer, StringComparison.OrdinalIgnoreCase)
|| !string.Equals(entity.Status, KbArticleStatusCodes.Published, StringComparison.OrdinalIgnoreCase)
|| (entity.ExpireTime != null && entity.ExpireTime <= DateTime.Now))
{
throw new BusinessException("文章不存在或未发布");
}
}
private async Task EnsureCategoryExistsAsync(int categoryId)
{
var exists = await CategoryRepository.AnyAsync(x => x.Id == categoryId && x.Enabled);
if (!exists)
{
throw new BusinessException("分类不存在或已停用");
}
}
private async Task<KbArticle> GetArticleOrThrowAsync(int id)
{
var entity = await ArticleRepository.FirstOrDefaultAsync(x => x.Id == id);
if (entity == null)
{
throw new BusinessException("文章不存在");
}
return entity;
}
private async Task<Dictionary<int, string>> LoadCategoryNameMapAsync(IEnumerable<int> ids)
{
var idList = ids.Where(x => x > 0).Distinct().ToList();
if (idList.Count == 0)
{
return new Dictionary<int, string>();
}
var categories = await CategoryRepository.GetListAsync(x => idList.Contains(x.Id));
return categories.ToDictionary(x => x.Id, x => x.Name);
}
private static void ValidateSave(KbArticleSaveInput input)
{
if (input.CategoryId <= 0)
{
throw new BusinessException("请选择分类");
}
if (string.IsNullOrWhiteSpace(input.Title))
{
throw new BusinessException("标题不能为空");
}
if (string.IsNullOrWhiteSpace(input.Content))
{
throw new BusinessException("正文不能为空");
}
var audience = (input.Audience ?? string.Empty).Trim().ToLowerInvariant();
if (audience is not (KbAudienceCodes.Customer or KbAudienceCodes.Internal))
{
throw new BusinessException("受众仅支持 customer / internal");
}
var status = (input.Status ?? string.Empty).Trim().ToLowerInvariant();
if (status is not (KbArticleStatusCodes.Draft or KbArticleStatusCodes.Published or KbArticleStatusCodes.Offline))
{
throw new BusinessException("状态仅支持 draft / published / offline");
}
}
private static void ApplySave(KbArticleSaveInput input, KbArticle entity)
{
entity.CategoryId = input.CategoryId;
entity.Title = input.Title.Trim();
entity.Summary = NormalizeOptional(input.Summary);
entity.Content = input.Content ?? string.Empty;
entity.Audience = input.Audience.Trim().ToLowerInvariant();
entity.Status = input.Status.Trim().ToLowerInvariant();
entity.Tags = NormalizeOptional(input.Tags);
entity.RelatedPath = NormalizeOptional(input.RelatedPath);
entity.RelatedLabel = NormalizeOptional(input.RelatedLabel);
entity.IsPinned = input.IsPinned;
entity.SortOrder = input.SortOrder;
entity.ExpireTime = input.ExpireTime;
}
private static KbArticleOutput Map(
KbArticle x,
IReadOnlyDictionary<int, string> categoryMap,
bool includeContent) =>
new()
{
Id = x.Id,
CategoryId = x.CategoryId,
CategoryName = categoryMap.TryGetValue(x.CategoryId, out var name) ? name : null,
Title = x.Title,
Summary = x.Summary,
Content = includeContent ? x.Content : null,
Audience = x.Audience,
Status = x.Status,
Tags = x.Tags,
RelatedPath = x.RelatedPath,
RelatedLabel = x.RelatedLabel,
IsPinned = x.IsPinned,
SortOrder = x.SortOrder,
PublishTime = x.PublishTime,
ExpireTime = x.ExpireTime,
ViewCount = x.ViewCount,
UpdateTime = x.UpdateTime
};
private static string? NormalizeOptional(string? value)
{
var trimmed = value?.Trim();
return string.IsNullOrWhiteSpace(trimmed) ? null : trimmed;
}
}