ChangelogService.cs 10.5 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NCC.Common.Core.Manager;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.Changelog;
using NCC.Extend.Entitys.lq_changelog;
using NCC.Extend.Helpers;
using NCC.Extend.Interfaces.BusinessOperationLog;
using SqlSugar;
using Yitter.IdGenerator;

namespace NCC.Extend
{
    /// <summary>
    /// 系统更新日志服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Common", Name = "Changelog", Order = 170)]
    [Route("api/Extend/[controller]")]
    public class ChangelogService : IDynamicApiController, ITransient
    {
        private const string BizLogModule = "系统更新";

        private readonly ISqlSugarClient _db;
        private readonly IUserManager _userManager;
        private readonly IBusinessOperationLogService _businessOperationLogService;
        private readonly ILogger<ChangelogService> _logger;

        public ChangelogService(
            ISqlSugarClient db,
            IUserManager userManager,
            IBusinessOperationLogService businessOperationLogService,
            ILogger<ChangelogService> logger)
        {
            _db = db;
            _userManager = userManager;
            _businessOperationLogService = businessOperationLogService;
            _logger = logger;
            _db.CodeFirst.InitTables(typeof(LqChangelogEntity));
        }

        /// <summary>
        /// 获取更新日志列表(分页)
        /// </summary>
        [HttpGet("GetList")]
        public async Task<dynamic> GetList([FromQuery] ChangelogListQueryInput input)
        {
            var data = await _db.Queryable<LqChangelogEntity>()
                .WhereIF(input.isPublished.HasValue, x => x.IsPublished == input.isPublished.Value)
                .WhereIF(input.type.HasValue, x => x.Type == input.type.Value)
                .WhereIF(!string.IsNullOrWhiteSpace(input.keyword),
                    x => x.Title.Contains(input.keyword) || x.Version.Contains(input.keyword))
                .OrderBy(x => x.PublishedTime, OrderByType.Desc)
                .OrderBy(x => x.CreateTime, OrderByType.Desc)
                .Select(x => new ChangelogListOutput
                {
                    id = x.Id,
                    version = x.Version,
                    title = x.Title,
                    content = x.Content,
                    type = x.Type,
                    isPublished = x.IsPublished,
                    publishedTime = x.PublishedTime,
                    createTime = x.CreateTime,
                    modifyTime = x.ModifyTime
                })
                .ToPagedListAsync(input.currentPage, input.pageSize);

            return PageResult<ChangelogListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 获取已发布的更新日志列表(前端用)
        /// </summary>
        [HttpGet("GetPublishedList")]
        public async Task<dynamic> GetPublishedList([FromQuery] int currentPage = 1, int pageSize = 20)
        {
            var data = await _db.Queryable<LqChangelogEntity>()
                .Where(x => x.IsPublished)
                .OrderBy(x => x.PublishedTime, OrderByType.Desc)
                .Select(x => new ChangelogListOutput
                {
                    id = x.Id,
                    version = x.Version,
                    title = x.Title,
                    content = x.Content,
                    type = x.Type,
                    isPublished = x.IsPublished,
                    publishedTime = x.PublishedTime,
                    createTime = x.CreateTime,
                    modifyTime = x.ModifyTime
                })
                .ToPagedListAsync(currentPage, pageSize);

            return PageResult<ChangelogListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 获取最新一条已发布更新日志(右上角红点提示用)
        /// </summary>
        [HttpGet("GetLatest")]
        public async Task<dynamic> GetLatest()
        {
            var latest = await _db.Queryable<LqChangelogEntity>()
                .Where(x => x.IsPublished)
                .OrderBy(x => x.PublishedTime, OrderByType.Desc)
                .FirstAsync();

            return latest;
        }

        /// <summary>
        /// 获取更新日志详情
        /// </summary>
        [HttpGet("GetDetail/{id}")]
        public async Task<dynamic> GetDetail(string id)
        {
            var entity = await _db.Queryable<LqChangelogEntity>()
                .Where(x => x.Id == id)
                .FirstAsync();

            if (entity == null)
                throw new Exception("更新日志不存在");

            return entity;
        }

        /// <summary>
        /// 添加更新日志
        /// </summary>
        [HttpPost("Add")]
        public async Task<dynamic> Add([FromBody] ChangelogAddInput input)
        {
            var entity = new LqChangelogEntity
            {
                Id = YitIdHelper.NextId().ToString(),
                Version = input.Version,
                Title = input.Title,
                Content = input.Content,
                Type = input.Type,
                IsPublished = input.IsPublished,
                PublishedTime = input.IsPublished ? DateTime.Now : null,
                CreateUserId = _userManager?.UserId,
                CreateTime = DateTime.Now
            };

            await _db.Insertable(entity).ExecuteCommandAsync();

            var snapshot = BuildSnapshot(entity);
            await BusinessOperationLogHelper.SafeWriteAsync(
                _businessOperationLogService,
                _logger,
                BizLogModule,
                "新增更新日志",
                "lq_changelog",
                entity.Id,
                $"新增更新日志 {entity.Version}:{entity.Title}",
                JsonConvert.SerializeObject(new { after = snapshot }));

            return new { success = true, id = entity.Id };
        }

        /// <summary>
        /// 修改更新日志
        /// </summary>
        [HttpPost("Update")]
        public async Task<dynamic> Update([FromBody] ChangelogUpdateInput input)
        {
            var entity = await _db.Queryable<LqChangelogEntity>()
                .Where(x => x.Id == input.Id)
                .FirstAsync();

            if (entity == null)
                throw new Exception("更新日志不存在");

            var beforeSnapshot = BuildSnapshot(entity);
            entity.Version = input.Version ?? entity.Version;
            entity.Title = input.Title ?? entity.Title;
            entity.Content = input.Content ?? entity.Content;
            entity.Type = input.Type;
            entity.ModifyTime = DateTime.Now;

            if (input.IsPublished && !entity.IsPublished)
            {
                entity.IsPublished = true;
                entity.PublishedTime = DateTime.Now;
            }
            else if (!input.IsPublished)
            {
                entity.IsPublished = false;
                entity.PublishedTime = null;
            }

            await _db.Updateable(entity).ExecuteCommandAsync();

            await BusinessOperationLogHelper.SafeWriteAsync(
                _businessOperationLogService,
                _logger,
                BizLogModule,
                "修改更新日志",
                "lq_changelog",
                entity.Id,
                $"修改更新日志 {entity.Version}:{entity.Title}",
                JsonConvert.SerializeObject(new { before = beforeSnapshot, after = BuildSnapshot(entity) }));

            return new { success = true };
        }

        /// <summary>
        /// 删除更新日志
        /// </summary>
        [HttpPost("Delete/{id}")]
        public async Task<dynamic> Delete(string id)
        {
            var entity = await _db.Queryable<LqChangelogEntity>()
                .Where(x => x.Id == id)
                .FirstAsync();
            if (entity == null)
            {
                throw new Exception("更新日志不存在");
            }

            var beforeSnapshot = BuildSnapshot(entity);
            await _db.Deleteable<LqChangelogEntity>(id).ExecuteCommandAsync();

            await BusinessOperationLogHelper.SafeWriteAsync(
                _businessOperationLogService,
                _logger,
                BizLogModule,
                "删除更新日志",
                "lq_changelog",
                id,
                $"删除更新日志 {entity.Version}:{entity.Title}",
                JsonConvert.SerializeObject(new { before = beforeSnapshot }));

            return new { success = true };
        }

        /// <summary>
        /// 切换发布状态
        /// </summary>
        [HttpPost("TogglePublish/{id}")]
        public async Task<dynamic> TogglePublish(string id)
        {
            var entity = await _db.Queryable<LqChangelogEntity>()
                .Where(x => x.Id == id)
                .FirstAsync();

            if (entity == null)
                throw new Exception("更新日志不存在");

            var beforePublished = entity.IsPublished;
            entity.IsPublished = !entity.IsPublished;
            entity.PublishedTime = entity.IsPublished ? DateTime.Now : null;
            entity.ModifyTime = DateTime.Now;

            await _db.Updateable(entity)
                .UpdateColumns(x => new { x.IsPublished, x.PublishedTime, x.ModifyTime })
                .ExecuteCommandAsync();

            var action = entity.IsPublished ? "发布更新日志" : "取消发布更新日志";
            await BusinessOperationLogHelper.SafeWriteAsync(
                _businessOperationLogService,
                _logger,
                BizLogModule,
                action,
                "lq_changelog",
                entity.Id,
                $"{action} {entity.Version}:{entity.Title}",
                JsonConvert.SerializeObject(new
                {
                    before = new { isPublished = beforePublished },
                    after = new { isPublished = entity.IsPublished }
                }));

            return new { success = true, isPublished = entity.IsPublished };
        }

        private static object BuildSnapshot(LqChangelogEntity entity) => new
        {
            version = entity.Version,
            title = entity.Title,
            type = entity.Type,
            isPublished = entity.IsPublished,
            publishedTime = entity.PublishedTime
        };
    }
}