UavWalletFlowService.cs 11.5 KB
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Extend.Interfaces.UavWalletFlow;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Extend.Entitys;
using NCC.Extend.Entitys.Dto.UavWalletFlow;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.Extend.Entitys.Enums;
using Aop.Api.Domain;

namespace NCC.Extend.UavWalletFlow
{
    /// <summary>
    /// 流水记录服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "流水记录服务", Name = "UavWalletFlow", Order = 200)]
    [Route("api/Extend/[controller]")]
    public class UavWalletFlowService : IUavWalletFlowService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<UavWalletFlowEntity> _uavWalletFlowRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="UavWalletFlowService"/>类型的新实例
        /// </summary>
        public UavWalletFlowService(
            ISqlSugarRepository<UavWalletFlowEntity> uavWalletFlowRepository,
            IUserManager userManager)
        {
            _uavWalletFlowRepository = uavWalletFlowRepository;
            _db = _uavWalletFlowRepository.Context;
            _userManager = userManager;
        }
        #region 获取当前用户的收益数据
        /// <summary>
        /// 获取当前用户的收益数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetFlowByUser")]
        public async Task<dynamic> GetFlowByUser()
        {

            var now = DateTime.Now;
            //获取今日收益总金额
            var today = now.Date;
            var TodayAomunt = await _db.Queryable<UavWalletFlowEntity>().Where(x => x.CreateTime >= today && x.UserId == _userManager.UserId && x.FlowDirection == FlowDirectionEnum.收入.GetHashCode()).SumAsync(x => x.Amount);
            //获取本月收益总金额
            var monthStart = new DateTime(now.Year, now.Month, 1);
            var ThisMonthAomunt = await _db.Queryable<UavWalletFlowEntity>().Where(x => x.CreateTime >= monthStart && x.UserId == _userManager.UserId && x.FlowDirection == FlowDirectionEnum.收入.GetHashCode()).SumAsync(x => x.Amount);
            //获取总收益总金额
            var TotalAomunt = await _db.Queryable<UavWalletFlowEntity>().Where(x => x.UserId == _userManager.UserId && x.FlowDirection == FlowDirectionEnum.收入.GetHashCode()).SumAsync(x => x.Amount);
            //获取余额
            var Balance = await _db.Queryable<UavWalletFlowEntity>().Where(x => x.UserId == _userManager.UserId).SumAsync(x => x.Amount);
            return new
            {
                TodayAomunt = TodayAomunt,
                ThisMonthAomunt = ThisMonthAomunt,
                TotalAomunt = TotalAomunt,
                Balance = Balance,
            };
        }
        #endregion

        #region 获取当前用户按月的收益和提现数据
        /// <summary>
        /// 获取当前用户按月的收益和提现数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetFlowByMonth")]
        public async Task<dynamic> GetFlowByMonth()
        {
            var userId = _userManager.UserId;

            // 获取所有该用户的收入和提现记录(建议加时间范围,避免数据过多)
            var flows = await _db.Queryable<UavWalletFlowEntity>()
                .Where(x => x.UserId == userId)
                .Select(x => new
                {
                    x.CreateTime,
                    x.Amount,
                    x.FlowDirection
                })
                .ToListAsync();

            // 分组统计:按 yyyy-MM 格式分组
            var result = flows
             .GroupBy(x => x.CreateTime.GetValueOrDefault().ToString("yyyy-MM"))
             .Select(g => new
             {
                 Month = g.Key,
                 Income = g.Where(x => x.FlowDirection == FlowDirectionEnum.收入.GetHashCode()).Sum(x => x.Amount),
                 Withdraw = g.Where(x => x.FlowDirection == FlowDirectionEnum.提现.GetHashCode()).Sum(x => x.Amount)
             })
             .OrderBy(x => x.Month)
             .ToList();
            return result;
        }
        #endregion


        #region 获取流水记录
        /// <summary>
        /// 获取流水记录
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<UavWalletFlowEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<UavWalletFlowInfoOutput>();
            return output;
        }
        #endregion

        #region 获取流水记录列表
        /// <summary>
        /// 获取流水记录列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] UavWalletFlowListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            List<object> queryFlowDirection = input.flowDirection != null ? input.flowDirection.Split(',').ToObeject<List<object>>() : null;
            var startFlowDirection = input.flowDirection != null && !string.IsNullOrEmpty(queryFlowDirection.First().ToString()) ? queryFlowDirection.First() : decimal.MinValue;
            var endFlowDirection = input.flowDirection != null && !string.IsNullOrEmpty(queryFlowDirection.Last().ToString()) ? queryFlowDirection.Last() : decimal.MaxValue;
            var data = await _db.Queryable<UavWalletFlowEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.userId), p => p.UserId.Contains(input.userId))
                .WhereIF(queryFlowDirection != null, p => SqlFunc.Between(p.FlowDirection, startFlowDirection, endFlowDirection))
                .Select(it => new UavWalletFlowListOutput
                {
                    id = it.Id,
                    userId = it.UserId,
                    flowDirection = it.FlowDirection,
                    amount = it.Amount,
                    relatedId = it.RelatedId,
                    relatedType = it.RelatedType,
                    createTime = it.CreateTime
                }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<UavWalletFlowListOutput>.SqlSugarPageResult(data);
        }
        #endregion

        #region 获取当前用户的流水记录
        /// <summary>
        /// 获取当前用户的流水记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetFlowListByUser")]
        public async Task<dynamic> GetFlowListByUser([FromQuery] UavWalletFlowListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            List<object> queryFlowDirection = input.flowDirection != null ? input.flowDirection.Split(',').ToObeject<List<object>>() : null;
            var startFlowDirection = input.flowDirection != null && !string.IsNullOrEmpty(queryFlowDirection.First().ToString()) ? queryFlowDirection.First() : decimal.MinValue;
            var endFlowDirection = input.flowDirection != null && !string.IsNullOrEmpty(queryFlowDirection.Last().ToString()) ? queryFlowDirection.Last() : decimal.MaxValue;
            var data = await _db.Queryable<UavWalletFlowEntity>()
                .Where(x => x.UserId == _userManager.UserId)
                .WhereIF(queryFlowDirection != null, p => SqlFunc.Between(p.FlowDirection, startFlowDirection, endFlowDirection))
                .Select(it => new UavWalletFlowListOutput
                {
                    id = it.Id,
                    userId = it.UserId,
                    flowDirection = it.FlowDirection,
                    amount = it.Amount,
                    relatedId = it.RelatedId,
                    relatedType = it.RelatedType,
                    createTime = it.CreateTime
                }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<UavWalletFlowListOutput>.SqlSugarPageResult(data);
        }
        #endregion

        #region 新建流水记录
        /// <summary>
        /// 新建流水记录
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] UavWalletFlowCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<UavWalletFlowEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
        }

        #endregion

        #region 更新流水记录
        /// <summary>
        /// 更新流水记录
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] UavWalletFlowUpInput input)
        {
            var entity = input.Adapt<UavWalletFlowEntity>();
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
        }

        #endregion

        #region 删除流水记录
        /// <summary>
        /// 删除流水记录
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<UavWalletFlowEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<UavWalletFlowEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002);
        }
        #endregion

        #region 获取某个代理的佣金明细
        /// <summary>
        /// 获取某个代理的佣金明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetCommissionByAgent")]
        public async Task<dynamic> GetCommissionByAgent([FromQuery] UavWalletFlowListQueryInput input)
        {
            var sidx = input.sidx ?? "OrderInfo.id";

            var result = await _db.Queryable<UavWalletFlowEntity, UavOrderEntity>(
                    (WalletInfo, OrderInfo) => WalletInfo.RelatedId == OrderInfo.OrderNo)
                .Where((WalletInfo, OrderInfo) => WalletInfo.RelatedType == "分润" && OrderInfo.AgentId == input.userId && OrderInfo.Status == UavOrderStatusEnum.已完成.GetHashCode())
                .Select((WalletInfo, OrderInfo) => new
                {
                    WalletInfo,
                    OrderInfo
                })
                .MergeTable()
                // .OrderBy(sidx + " " + input.sort)
                .ToPageListAsync(input.currentPage, input.pageSize); // ✅ 用这个

            return result;
        }
        #endregion



    }
}