LqYaoyjlService.cs 20.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
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.LqYaoyjl;
using NCC.Extend.Interfaces.BusinessOperationLog;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Extend.Entitys.lq_yaoyjl;
using NCC.Extend.Entitys.Dto.LqYaoyjl;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.Common.Model.NPOI;
using NCC.Common.Configuration;
using NCC.DataEncryption;
using NCC.ClayObject;
using NCC.System.Entitys.Permission;
using NCC.Extend.Entitys.lq_mdxx;
using NCC.Extend.Entitys.lq_khxx;
using NCC.Extend.Entitys.lq_todo;
using NCC.Extend.Entitys.Enum;

namespace NCC.Extend.LqYaoyjl
{
    /// <summary>
    /// 沟通记录服务(原邀约记录)
    /// </summary>
    [ApiDescriptionSettings(Tag = "绿纤沟通记录服务", Name = "LqYaoyjl", Order = 200)]
    [Route("api/Extend/[controller]")]
    public class LqYaoyjlService : ILqYaoyjlService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<LqYaoyjlEntity> _lqYaoyjlRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly IBusinessOperationLogService _businessOperationLogService;
        private readonly ILogger<LqYaoyjlService> _logger;

        private const string BizLogModuleContact = "沟通记录";

        /// <summary>
        /// 初始化一个<see cref="LqYaoyjlService"/>类型的新实例
        /// </summary>
        public LqYaoyjlService(
            ISqlSugarRepository<LqYaoyjlEntity> lqYaoyjlRepository,
            IUserManager userManager,
            IBusinessOperationLogService businessOperationLogService,
            ILogger<LqYaoyjlService> logger)
        {
            _lqYaoyjlRepository = lqYaoyjlRepository;
            _db = _lqYaoyjlRepository.Context;
            _userManager = userManager;
            _businessOperationLogService = businessOperationLogService;
            _logger = logger;
        }

        #region 沟通记录
        /// <summary>
        /// 获取沟通记录
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<LqYaoyjlEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<LqYaoyjlInfoOutput>();
            output.lxjl_voice = entity.LxjlVoice;
            output.storeName = _db.Queryable<LqMdxxEntity>().Where(u => u.Id == entity.StoreId).Select(u => u.Dm).First();
            return output;
        }
        #endregion

        #region 沟通记录列表
        /// <summary>
		/// 获取沟通记录列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] LqYaoyjlListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            List<string> queryYysj = input.yysj != null ? input.yysj.Split(',').ToObeject<List<string>>() : null;
            DateTime? startYysj = queryYysj != null ? Ext.GetDateTime(queryYysj.First()) : null;
            DateTime? endYysj = queryYysj != null ? Ext.GetDateTime(queryYysj.Last()) : null;
            List<string> queryLxsj = input.lxsj != null ? input.lxsj.Split(',').ToObeject<List<string>>() : null;
            DateTime? startLxsj = queryLxsj != null ? Ext.GetDateTime(queryLxsj.First()) : null;
            DateTime? endLxsj = queryLxsj != null ? Ext.GetDateTime(queryLxsj.Last()) : null;
            var data = await _db.Queryable<LqYaoyjlEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.id), p => p.Id.Contains(input.id))
                .WhereIF(!string.IsNullOrEmpty(input.yyr), p => p.Yyr.Equals(input.yyr))
                .WhereIF(queryYysj != null, p => p.Yysj >= new DateTime(startYysj.ToDate().Year, startYysj.ToDate().Month, startYysj.ToDate().Day, 0, 0, 0))
                .WhereIF(queryYysj != null, p => p.Yysj <= new DateTime(endYysj.ToDate().Year, endYysj.ToDate().Month, endYysj.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.yykh), p => p.Yykh.Equals(input.yykh))
                .WhereIF(!string.IsNullOrEmpty(input.yykhxm), p => p.Yykhxm.Contains(input.yykhxm))
                .WhereIF(!string.IsNullOrEmpty(input.dhsfyx), p => p.Dhsfyx.Equals(input.dhsfyx))
                .WhereIF(queryLxsj != null, p => p.Lxsj >= new DateTime(startLxsj.ToDate().Year, startLxsj.ToDate().Month, startLxsj.ToDate().Day, 0, 0, 0))
                .WhereIF(queryLxsj != null, p => p.Lxsj <= new DateTime(endLxsj.ToDate().Year, endLxsj.ToDate().Month, endLxsj.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.lxjl), p => p.Lxjl.Contains(input.lxjl))
                .WhereIF(!string.IsNullOrEmpty(input.storeId), p => p.StoreId.Equals(input.storeId))
                .WhereIF(!string.IsNullOrEmpty(input.gtfs), p => p.Gtfs.Equals(input.gtfs))
                .WhereIF(!string.IsNullOrEmpty(input.sfjt), p => p.Sfjt.Equals(input.sfjt))
                .Select(it => new LqYaoyjlListOutput
                {
                    id = it.Id,
                    yyr = it.Yyr,
                    yysj = it.Yysj,
                    yykh = it.Yykh,
                    yykhxm = it.Yykhxm,
                    dhsfyx = it.Dhsfyx,
                    lxsj = it.Lxsj,
                    lxjl = it.Lxjl,
                    lxjl_voice = it.LxjlVoice,
                    storeId = it.StoreId,
                    storeName = SqlFunc.Subqueryable<LqMdxxEntity>().Where(u => u.Id == it.StoreId).Select(u => u.Dm),
                    createTime = it.CreateTime,
                    yyrName = SqlFunc.Subqueryable<UserEntity>().Where(u => u.Id == it.Yyr).Select(u => u.RealName),
                    tkbh = it.Tkbh,
                    gtfs = it.Gtfs,
                    sfjt = it.Sfjt,
                    xcLxsj = it.XcLxsj,
                }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<LqYaoyjlListOutput>.SqlSugarPageResult(data);
        }
        #endregion

        #region 新建沟通记录
        /// <summary>
        /// 新建沟通记录
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] LqYaoyjlCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var ownerId = !string.IsNullOrEmpty(input.yyr) ? input.yyr : userInfo.userId;
            var entity = input.Adapt<LqYaoyjlEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.Yyr = ownerId;
            entity.CreateTime = DateTime.Now;
            entity.StoreId = _db.Queryable<UserEntity>().Where(u => u.Id == ownerId).Select(u => u.Mdid).First();
            entity.LxjlVoice = string.IsNullOrWhiteSpace(input.lxjl_voice) ? null : input.lxjl_voice.Trim();
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);

            await TryWriteBizLogAsync(
                "新增沟通记录",
                "lq_yaoyjl",
                entity.Id,
                $"新增沟通记录 {entity.Id}({entity.Yykhxm})",
                new { after = BuildYaoyjlSnapshot(entity) }.Serialize());

            if (input.xcLxsj.HasValue)
            {
                var customerPhone = await _db.Queryable<LqKhxxEntity>()
                    .Where(k => k.Id == input.yykh)
                    .Select(k => k.Sjh)
                    .FirstAsync() ?? "";
                var todoEntity = new LqTodoEntity
                {
                    Id = YitIdHelper.NextId().ToString(),
                    UserId = ownerId,
                    StoreId = entity.StoreId,
                    Source = TodoSourceEnum.follow_up.ToString(),
                    RefId = entity.Id,
                    Title = $"跟进客户:{input.yykhxm ?? "未知"}",
                    Desc = $"上次沟通:{((input.lxjl ?? "").Length > 30 ? input.lxjl.Substring(0, 30) + "..." : input.lxjl ?? "")}",
                    Tag = "客户跟进",
                    Urgency = TodoUrgencyEnum.normal.ToString(),
                    DueTime = input.xcLxsj,
                    HandlePath = "contactDialog",
                    HandleType = TodoHandleTypeEnum.dialog.ToString(),
                    HandleParam = $"{{\"customerId\":\"{input.yykh}\",\"customerName\":\"{input.yykhxm}\",\"customerPhone\":\"{customerPhone}\"}}",
                    Status = (int)TodoStatusEnum.Pending,
                    CreateTime = DateTime.Now
                };
                await _db.Insertable(todoEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }
        }
        #endregion

        #region 沟通记录无分页列表
        /// <summary>
		/// 获取沟通记录无分页列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] LqYaoyjlListQueryInput input)
        {
            var sidx = input.sidx == null ? "id" : input.sidx;
            List<string> queryYysj = input.yysj != null ? input.yysj.Split(',').ToObeject<List<string>>() : null;
            DateTime? startYysj = queryYysj != null ? Ext.GetDateTime(queryYysj.First()) : null;
            DateTime? endYysj = queryYysj != null ? Ext.GetDateTime(queryYysj.Last()) : null;
            List<string> queryLxsj = input.lxsj != null ? input.lxsj.Split(',').ToObeject<List<string>>() : null;
            DateTime? startLxsj = queryLxsj != null ? Ext.GetDateTime(queryLxsj.First()) : null;
            DateTime? endLxsj = queryLxsj != null ? Ext.GetDateTime(queryLxsj.Last()) : null;
            var data = await _db.Queryable<LqYaoyjlEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.id), p => p.Id.Contains(input.id))
                .WhereIF(!string.IsNullOrEmpty(input.yyr), p => p.Yyr.Equals(input.yyr))
                .WhereIF(queryYysj != null, p => p.Yysj >= new DateTime(startYysj.ToDate().Year, startYysj.ToDate().Month, startYysj.ToDate().Day, 0, 0, 0))
                .WhereIF(queryYysj != null, p => p.Yysj <= new DateTime(endYysj.ToDate().Year, endYysj.ToDate().Month, endYysj.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.yykh), p => p.Yykh.Equals(input.yykh))
                .WhereIF(!string.IsNullOrEmpty(input.yykhxm), p => p.Yykhxm.Contains(input.yykhxm))
                .WhereIF(!string.IsNullOrEmpty(input.dhsfyx), p => p.Dhsfyx.Equals(input.dhsfyx))
                .WhereIF(queryLxsj != null, p => p.Lxsj >= new DateTime(startLxsj.ToDate().Year, startLxsj.ToDate().Month, startLxsj.ToDate().Day, 0, 0, 0))
                .WhereIF(queryLxsj != null, p => p.Lxsj <= new DateTime(endLxsj.ToDate().Year, endLxsj.ToDate().Month, endLxsj.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.lxjl), p => p.Lxjl.Contains(input.lxjl))
                .WhereIF(!string.IsNullOrEmpty(input.storeId), p => p.StoreId.Equals(input.storeId))
                .WhereIF(!string.IsNullOrEmpty(input.gtfs), p => p.Gtfs.Equals(input.gtfs))
                .WhereIF(!string.IsNullOrEmpty(input.sfjt), p => p.Sfjt.Equals(input.sfjt))
                .Select(it => new LqYaoyjlListOutput
                {
                    id = it.Id,
                    yyr = it.Yyr,
                    yysj = it.Yysj,
                    yykh = it.Yykh,
                    yykhxm = it.Yykhxm,
                    dhsfyx = it.Dhsfyx,
                    lxsj = it.Lxsj,
                    lxjl = it.Lxjl,
                    lxjl_voice = it.LxjlVoice,
                    yyrName = SqlFunc.Subqueryable<UserEntity>().Where(u => u.MobilePhone == it.Yyr).Select(u => u.RealName),
                    tkbh = it.Tkbh,
                    gtfs = it.Gtfs,
                    sfjt = it.Sfjt,
                    xcLxsj = it.XcLxsj,
                }).MergeTable().OrderBy(sidx + " " + input.sort).ToListAsync();
            return data;
        }
        #endregion

        #region 导出沟通记录
        /// <summary>
		/// 导出沟通记录
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] LqYaoyjlListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<LqYaoyjlListOutput>();
            if (input.dataType == 0)
            {
                var data = Clay.Object(await this.GetList(input));
                exportData = data.Solidify<PageResult<LqYaoyjlListOutput>>().list;
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }
            List<ParamsModel> paramList = "[{\"value\":\"沟通编号\",\"field\":\"id\"},{\"value\":\"沟通人\",\"field\":\"yyr\"},{\"value\":\"沟通时间\",\"field\":\"yysj\"},{\"value\":\"沟通客户\",\"field\":\"yykh\"},{\"value\":\"沟通客户姓名\",\"field\":\"yykhxm\"},{\"value\":\"电话是否有效\",\"field\":\"dhsfyx\"},{\"value\":\"联系时间\",\"field\":\"lxsj\"},{\"value\":\"联系记录\",\"field\":\"lxjl\"},{\"value\":\"联系记录语音\",\"field\":\"lxjl_voice\"},{\"value\":\"沟通方式\",\"field\":\"gtfs\"},{\"value\":\"是否接听\",\"field\":\"sfjt\"},{\"value\":\"下次联系时间\",\"field\":\"xcLxsj\"},]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "沟通记录.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<LqYaoyjlListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";

            await TryWriteBizLogAsync(
                "导出沟通记录",
                "lq_yaoyjl",
                null,
                $"导出沟通记录,共 {exportData.Count} 条",
                new
                {
                    filters = new { input.yyr, input.yykh, input.yysj, input.lxsj, input.dataType },
                    rowCount = exportData.Count,
                    fileName = excelconfig.FileName
                }.Serialize());

            var output = new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
            };
            return output;
        }
        #endregion

        #region 批量删除沟通记录
        /// <summary>
        /// 批量删除沟通记录
        /// </summary>
        /// <param name="ids">主键数组</param>
        /// <returns></returns>
        [HttpPost("batchRemove")]
        public async Task BatchRemove([FromBody] List<string> ids)
        {
            var entitys = await _db.Queryable<LqYaoyjlEntity>().In(it => it.Id, ids).ToListAsync();
            if (entitys.Count > 0)
            {
                try
                {
                    //开启事务
                    _db.BeginTran();
                    //批量删除沟通记录
                    await _db.Deleteable<LqYaoyjlEntity>().In(d => d.Id, ids).ExecuteCommandAsync();
                    //关闭事务
                    _db.CommitTran();
                }
                catch (Exception)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw NCCException.Oh(ErrorCode.COM1002);
                }

                foreach (var entity in entitys)
                {
                    await TryWriteBizLogAsync(
                        "批量删除沟通记录",
                        "lq_yaoyjl",
                        entity.Id,
                        $"批量删除沟通记录 {entity.Id}({entity.Yykhxm})",
                        new { before = BuildYaoyjlSnapshot(entity) }.Serialize());
                }
            }
        }
        #endregion

        #region 更新沟通记录
        /// <summary>
        /// 更新沟通记录
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] LqYaoyjlUpInput input)
        {
            var beforeEntity = await _db.Queryable<LqYaoyjlEntity>().FirstAsync(p => p.Id == id);
            _ = beforeEntity ?? throw NCCException.Oh(ErrorCode.COM1005);

            var entity = input.Adapt<LqYaoyjlEntity>();
            entity.StoreId = _db.Queryable<UserEntity>().Where(u => u.Id == input.yyr).Select(u => u.Mdid).First();
            entity.LxjlVoice = string.IsNullOrWhiteSpace(input.lxjl_voice) ? null : input.lxjl_voice.Trim();
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);

            var afterEntity = await _db.Queryable<LqYaoyjlEntity>().FirstAsync(p => p.Id == id);
            await TryWriteBizLogAsync(
                "修改沟通记录",
                "lq_yaoyjl",
                id,
                $"修改沟通记录 {id}({afterEntity?.Yykhxm})",
                new
                {
                    before = BuildYaoyjlSnapshot(beforeEntity),
                    after = BuildYaoyjlSnapshot(afterEntity)
                }.Serialize());
        }
        #endregion

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

            await TryWriteBizLogAsync(
                "删除沟通记录",
                "lq_yaoyjl",
                id,
                $"删除沟通记录 {id}({entity.Yykhxm})",
                new { before = beforeSnapshot }.Serialize());
        }
        #endregion

        private static object BuildYaoyjlSnapshot(LqYaoyjlEntity entity)
        {
            if (entity == null)
                return null;

            return new
            {
                id = entity.Id,
                yyr = entity.Yyr,
                yykh = entity.Yykh,
                yykhxm = entity.Yykhxm,
                yysj = entity.Yysj,
                lxsj = entity.Lxsj,
                gtfs = entity.Gtfs,
                storeId = entity.StoreId
            };
        }

        private async Task TryWriteBizLogAsync(
            string actionCode,
            string bizType,
            string bizId,
            string summary,
            string detailJson)
        {
            try
            {
                await _businessOperationLogService.WriteAsync(
                    BizLogModuleContact,
                    actionCode,
                    bizType,
                    bizId,
                    summary,
                    detailJson);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "写入沟通记录业务操作日志失败 action={Action}", actionCode);
            }
        }
    }
}