LqBusinessUnitDashboardService.LargeAmountAudit.cs 14.2 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NCC.Common.Filter;
using NCC.Extend.Entitys.Dto.LqBusinessUnitDashboard;
using NCC.Extend.Entitys.Enum;
using NCC.Extend.Entitys.lq_card_transfer_log;
using NCC.Extend.Entitys.lq_hytk_hytk;
using NCC.Extend.Entitys.lq_kd_kdjlb;
using NCC.Extend.Entitys.lq_khxx;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Entitys.lq_xh_hyhk;
using NCC.Extend.Helpers;
using NCC.FriendlyException;
using SqlSugar;

namespace NCC.Extend
{
    public partial class LqBusinessUnitDashboardService
    {
        #region 大客卡金异常

        /// <summary>
        /// 获取大客卡金监控阈值(系统配置)
        /// </summary>
        /// <remarks>
        /// 示例请求:GET /api/Extend/LqBusinessUnitDashboard/Actions/GetLargeAmountThresholds
        /// </remarks>
        [HttpGet("Actions/GetLargeAmountThresholds")]
        public async Task<BusinessUnitLargeAmountThresholdOutput> GetLargeAmountThresholds()
        {
            var (billing, consume, refund, transfer) = await LargeAmountAuditHelper.GetThresholdsAsync(_db);
            return new BusinessUnitLargeAmountThresholdOutput
            {
                billingThreshold = billing,
                consumeThreshold = consume,
                refundThreshold = refund,
                transferThreshold = transfer
            };
        }

        /// <summary>
        /// 大客卡金异常审计列表(大额开单/耗卡/退卡/转卡)
        /// </summary>
        /// <remarks>
        /// 金额达到系统设置阈值即列入监控;门店范围与重复充值审计一致。
        ///
        /// 示例请求:
        /// ```json
        /// {
        ///   "startTime": "2026-07-01 00:00:00",
        ///   "endTime": "2026-07-31 23:59:59",
        ///   "currentPage": 1,
        ///   "pageSize": 20
        /// }
        /// ```
        /// </remarks>
        [HttpPost("GetLargeAmountAuditList")]
        public async Task<dynamic> GetLargeAmountAuditList(
            [FromBody] BusinessUnitLargeAmountAuditListInput input)
        {
            if (input == null) throw NCCException.Oh("请求参数不能为空");

            var duplicateInput = MapLargeAmountToDuplicateInput(input);
            var (startDate, endDateTime) = ResolveDuplicateAuditDateRange(duplicateInput);
            var storeIds = await ResolveDuplicateAuditStoreIdsAsync(duplicateInput, startDate);
            if (!storeIds.Any())
            {
                return EmptyLargeAmountPageResult(input);
            }

            var auditRows = await BuildLargeAmountAuditRowsAsync(storeIds, startDate, endDateTime);

            if (!string.IsNullOrWhiteSpace(input.StoreId))
                auditRows = auditRows.Where(x => x.StoreId == input.StoreId).ToList();

            if (!string.IsNullOrWhiteSpace(input.MemberName))
            {
                var memberName = input.MemberName.Trim();
                auditRows = auditRows.Where(x =>
                    !string.IsNullOrWhiteSpace(x.MemberName) &&
                    x.MemberName.Contains(memberName)).ToList();
            }

            if (!string.IsNullOrWhiteSpace(input.BizType))
            {
                var bizType = input.BizType.Trim();
                auditRows = auditRows.Where(x =>
                    x.BizType.Equals(bizType, StringComparison.OrdinalIgnoreCase)).ToList();
            }

            var keyword = string.IsNullOrWhiteSpace(input.keyword) ? null : input.keyword.Trim();
            if (keyword != null)
            {
                auditRows = auditRows.Where(x =>
                    (x.MemberName != null && x.MemberName.Contains(keyword)) ||
                    (x.StoreName != null && x.StoreName.Contains(keyword)) ||
                    (x.BizId != null && x.BizId.Contains(keyword))).ToList();
            }

            auditRows = auditRows.OrderByDescending(x => x.Amount).ThenByDescending(x => x.BizTime).ToList();
            var total = auditRows.Count;
            var pageIndex = NormalizeCapabilityPageIndex(input.currentPage);
            var pageSize = NormalizeCapabilityPageSize(input.pageSize);
            var pageList = auditRows.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return PageResult<BusinessUnitLargeAmountAuditListOutput>.SqlSugarPageResult(
                new SqlSugarPagedList<BusinessUnitLargeAmountAuditListOutput>
                {
                    list = pageList,
                    pagination = new PagedModel
                    {
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        Total = total
                    }
                });
        }

        private static dynamic EmptyLargeAmountPageResult(BusinessUnitLargeAmountAuditListInput input)
        {
            return PageResult<BusinessUnitLargeAmountAuditListOutput>.SqlSugarPageResult(
                new SqlSugarPagedList<BusinessUnitLargeAmountAuditListOutput>
                {
                    list = new List<BusinessUnitLargeAmountAuditListOutput>(),
                    pagination = new PagedModel
                    {
                        PageIndex = NormalizeCapabilityPageIndex(input.currentPage),
                        PageSize = NormalizeCapabilityPageSize(input.pageSize),
                        Total = 0
                    }
                });
        }

        private static BusinessUnitDuplicateRechargeAuditListInput MapLargeAmountToDuplicateInput(
            BusinessUnitLargeAmountAuditListInput input)
        {
            return new BusinessUnitDuplicateRechargeAuditListInput
            {
                BusinessUnitId = input.BusinessUnitId,
                StoreIds = input.StoreIds,
                StatisticsMonth = input.StatisticsMonth,
                StartTime = input.StartTime,
                EndTime = input.EndTime,
                StoreId = input.StoreId,
                MemberName = input.MemberName,
                currentPage = input.currentPage,
                pageSize = input.pageSize,
                keyword = input.keyword
            };
        }

        private async Task<List<BusinessUnitLargeAmountAuditListOutput>> BuildLargeAmountAuditRowsAsync(
            List<string> storeIds, DateTime startDate, DateTime endDateTime)
        {
            var (billingThreshold, consumeThreshold, refundThreshold, transferThreshold) =
                await LargeAmountAuditHelper.GetThresholdsAsync(_db);

            var result = new List<BusinessUnitLargeAmountAuditListOutput>();

            var billingRows = await _db.Queryable<LqKdKdjlbEntity, LqMdxxEntity, LqKhxxEntity>(
                    (bill, store, member) => new JoinQueryInfos(
                        JoinType.Left, bill.Djmd == store.Id,
                        JoinType.Left, bill.Kdhy == member.Id))
                .Where((bill, store, member) =>
                    storeIds.Contains(bill.Djmd) &&
                    bill.IsEffective == 1 &&
                    bill.Kdrq.HasValue &&
                    bill.Kdrq.Value >= startDate &&
                    bill.Kdrq.Value <= endDateTime &&
                    bill.Sfyj >= billingThreshold)
                .Select((bill, store, member) => new BusinessUnitLargeAmountAuditListOutput
                {
                    BizId = bill.Id,
                    BizType = nameof(LargeAmountBizType.Billing),
                    BizTypeName = "开单",
                    ExceptionType = "LargeAmountBilling",
                    ExceptionTypeName = "大额开单",
                    MemberId = bill.Kdhy,
                    MemberName = member.Khmc,
                    StoreId = bill.Djmd,
                    StoreName = store.Dm,
                    BizTime = bill.Kdrq.Value,
                    BizDate = bill.Kdrq.Value.Date,
                    Amount = bill.Sfyj,
                    ThresholdAmount = billingThreshold,
                    OperatorId = bill.CreateUser
                })
                .ToListAsync();
            result.AddRange(billingRows);

            var consumeRows = await _db.Queryable<LqXhHyhkEntity, LqMdxxEntity, LqKhxxEntity>(
                    (consume, store, member) => new JoinQueryInfos(
                        JoinType.Left, consume.Md == store.Id,
                        JoinType.Left, consume.Hy == member.Id))
                .Where((consume, store, member) =>
                    storeIds.Contains(consume.Md) &&
                    consume.IsEffective == 1 &&
                    consume.Hksj.HasValue &&
                    consume.Hksj.Value >= startDate &&
                    consume.Hksj.Value <= endDateTime &&
                    consume.Xfje >= consumeThreshold)
                .Select((consume, store, member) => new BusinessUnitLargeAmountAuditListOutput
                {
                    BizId = consume.Id,
                    BizType = nameof(LargeAmountBizType.Consume),
                    BizTypeName = "耗卡",
                    ExceptionType = "LargeAmountConsume",
                    ExceptionTypeName = "大额耗卡",
                    MemberId = consume.Hy,
                    MemberName = member.Khmc ?? consume.Hymc,
                    StoreId = consume.Md,
                    StoreName = store.Dm,
                    BizTime = consume.Hksj.Value,
                    BizDate = consume.Hksj.Value.Date,
                    Amount = consume.Xfje ?? 0m,
                    ThresholdAmount = consumeThreshold,
                    OperatorId = consume.Czry
                })
                .ToListAsync();
            result.AddRange(consumeRows);

            var refundEntities = await _db.Queryable<LqHytkHytkEntity, LqMdxxEntity, LqKhxxEntity>(
                    (refund, store, member) => new JoinQueryInfos(
                        JoinType.Left, refund.Md == store.Id,
                        JoinType.Left, refund.Hy == member.Id))
                .Where((refund, store, member) =>
                    storeIds.Contains(refund.Md) &&
                    refund.IsEffective == 1)
                .Select((refund, store, member) => new
                {
                    refund.Id,
                    refund.Hy,
                    MemberName = member.Khmc ?? refund.Hymc,
                    refund.Md,
                    StoreName = store.Dm ?? refund.Mdmc,
                    refund.Tksj,
                    refund.F_CreateTime,
                    Amount = refund.ActualRefundAmount ?? refund.Tkje ?? 0m,
                    OperatorId = refund.Czry ?? refund.F_CreateUser
                })
                .ToListAsync();

            var refundRows = refundEntities
                .Select(x =>
                {
                    var bizTime = x.Tksj ?? x.F_CreateTime ?? DateTime.MinValue;
                    return new { x, bizTime };
                })
                .Where(x => x.bizTime >= startDate && x.bizTime <= endDateTime && x.x.Amount >= refundThreshold)
                .Select(x => new BusinessUnitLargeAmountAuditListOutput
                {
                    BizId = x.x.Id,
                    BizType = nameof(LargeAmountBizType.RefundCard),
                    BizTypeName = "退卡",
                    ExceptionType = "LargeAmountRefundCard",
                    ExceptionTypeName = "大额退卡",
                    MemberId = x.x.Hy,
                    MemberName = x.x.MemberName,
                    StoreId = x.x.Md,
                    StoreName = x.x.StoreName,
                    BizTime = x.bizTime,
                    BizDate = x.bizTime.Date,
                    Amount = x.x.Amount,
                    ThresholdAmount = refundThreshold,
                    OperatorId = x.x.OperatorId
                })
                .ToList();
            result.AddRange(refundRows);

            var transferEntities = await _db.Queryable<LqCardTransferLogEntity, LqHytkHytkEntity, LqMdxxEntity, LqKhxxEntity, LqKhxxEntity>(
                    (transfer, refund, store, fromMember, toMember) => new JoinQueryInfos(
                        JoinType.Left, transfer.RefundCardId == refund.Id,
                        JoinType.Left, refund.Md == store.Id,
                        JoinType.Left, transfer.TransferFromMemberId == fromMember.Id,
                        JoinType.Left, transfer.TransferToMemberId == toMember.Id))
                .Where((transfer, refund, store, fromMember, toMember) =>
                    transfer.IsEffective == 1 &&
                    transfer.TransferTime >= startDate &&
                    transfer.TransferTime <= endDateTime &&
                    transfer.TransferAmount >= transferThreshold &&
                    storeIds.Contains(refund.Md))
                .Select((transfer, refund, store, fromMember, toMember) => new
                {
                    transfer.Id,
                    transfer.TransferFromMemberId,
                    transfer.TransferToMemberId,
                    transfer.TransferAmount,
                    transfer.TransferTime,
                    transfer.OperatorId,
                    transfer.RefundCardId,
                    refund.Md,
                    StoreName = store.Dm ?? refund.Mdmc,
                    FromName = fromMember.Khmc,
                    ToName = toMember.Khmc
                })
                .ToListAsync();

            var transferRows = transferEntities.Select(x => new BusinessUnitLargeAmountAuditListOutput
                {
                    BizId = x.Id,
                    BizType = nameof(LargeAmountBizType.CardTransfer),
                    BizTypeName = "转卡",
                    ExceptionType = "LargeAmountCardTransfer",
                    ExceptionTypeName = "大额转卡",
                    MemberId = x.TransferFromMemberId,
                    MemberName = $"{x.FromName ?? x.TransferFromMemberId} → {x.ToName ?? x.TransferToMemberId}",
                    StoreId = x.Md,
                    StoreName = x.StoreName,
                    BizTime = x.TransferTime,
                    BizDate = x.TransferTime.Date,
                    Amount = x.TransferAmount,
                    ThresholdAmount = transferThreshold,
                    OperatorId = x.OperatorId,
                    RefundCardId = x.RefundCardId
                })
                .ToList();
            result.AddRange(transferRows);

            return result;
        }

        #endregion
    }
}