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; /// /// 知识库文章:管理端 + 客户门户。 /// [ApiExplorerSettings(GroupName = "OMS-Kb")] public class KbArticleService : ApplicationService { private IKbArticleRepository ArticleRepository => LazyServiceProvider.GetRequiredService(); private IKbCategoryRepository CategoryRepository => LazyServiceProvider.GetRequiredService(); [HttpPost("/kb/admin/article/page")] public async Task> 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 { [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 { Total = total, Items = entities.Select(x => Map(x, categoryMap, input.IncludeContent)).ToList() }; } [HttpGet("/kb/admin/article/{id:int}")] public async Task 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 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); } /// 门户:启用分类列表(需客户登录)。 [HttpGet("/kb/portal/category/list")] public async Task> 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 { Items = ordered.Select(x => new KbCategoryOutput { Id = x.Id, Code = x.Code, Name = x.Name, SortOrder = x.SortOrder, Enabled = x.Enabled }).ToList() }; } /// 门户:文章分页(需客户登录)。 [HttpPost("/kb/portal/article/page")] public async Task> 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 { [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 { Total = total, Items = entities.Select(x => Map(x, categoryMap, includeContent: false)).ToList() }; } /// 门户:热门(需客户登录)。 [HttpGet("/kb/portal/article/hot")] public async Task> 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 { Items = ordered.Select(x => Map(x, categoryMap, includeContent: false)).ToList() }; } /// 门户:详情(需客户登录;浏览量 +1)。 [HttpGet("/kb/portal/article/{id:int}")] public async Task 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> BuildAdminPredicate(KbArticleListInput input) { var keyword = NormalizeOptional(input.Keyword); var status = NormalizeOptional(input.Status); var audience = NormalizeOptional(input.Audience); var predicate = ExpressionPredicate.True(); 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> BuildPortalPredicate(string? keyword, int? categoryId) { var kw = NormalizeOptional(keyword); var now = DateTime.Now; var predicate = ExpressionPredicate.AndAlso( ExpressionPredicate.True(), 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 GetArticleOrThrowAsync(int id) { var entity = await ArticleRepository.FirstOrDefaultAsync(x => x.Id == id); if (entity == null) { throw new BusinessException("文章不存在"); } return entity; } private async Task> LoadCategoryNameMapAsync(IEnumerable ids) { var idList = ids.Where(x => x > 0).Distinct().ToList(); if (idList.Count == 0) { return new Dictionary(); } 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 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; } }