LqStudyClassService.cs 17.8 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Extend.Entitys.Dto.LqStudyClass;
using NCC.Extend.Entitys.lq_study_class;
using NCC.Extend.Entitys.lq_study_student;
using NCC.Extend.Entitys.lq_study_record;
using NCC.Extend.Interfaces.LqStudyClass;
using NCC.FriendlyException;
using NCC.System.Entitys.Permission;
using SqlSugar;
using Yitter.IdGenerator;
using NCC.Extend.Entitys.Enum;

namespace NCC.Extend
{
    /// <summary>
    /// 学习班级服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "绿纤学习班级管理", Name = "LqStudyClass", Order = 200)]
    [Route("api/Extend/LqStudyClass")]
    public class LqStudyClassService : IDynamicApiController, ITransient, ILqStudyClassService
    {
        private readonly IUserManager _userManager;
        private readonly ILogger<LqStudyClassService> _logger;
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userManager">用户管理器</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="db">数据库客户端</param>
        public LqStudyClassService(IUserManager userManager, ILogger<LqStudyClassService> logger, ISqlSugarClient db)
        {
            _userManager = userManager;
            _logger = logger;
            _db = db;
        }

        #region 创建学习班级并添加学员
        /// <summary>
        /// 创建学习班级并添加学员
        /// </summary>
        /// <param name="input">创建输入</param>
        /// <returns>创建结果</returns>
        [HttpPost("CreateClassWithStudents")]
        public async Task<dynamic> CreateClassWithStudentsAsync([FromBody] LqStudyClassCreateWithStudentsInput input)
        {
            try
            {
                _db.Ado.BeginTran();

                // 创建班级
                var classId = YitIdHelper.NextId().ToString();
                var classEntity = new LqStudyClassEntity
                {
                    Id = classId,
                    ClassName = input.ClassName,
                    TeacherId = input.TeacherId,
                    StartTime = input.StartTime,
                    EndTime = input.EndTime,
                    Remark = input.Remark,
                    CreateUser = _userManager.UserId,
                    CreateTime = DateTime.Now,
                    IsEffective = StatusEnum.有效.GetHashCode()
                };

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

                // 创建学员
                var studentEntities = new List<LqStudyStudentEntity>();
                foreach (var student in input.Students)
                {
                    var studentEntity = new LqStudyStudentEntity
                    {
                        Id = YitIdHelper.NextId().ToString(),
                        EmployeeName = student.EmployeeName,
                        EmployeePhone = student.EmployeePhone,
                        EmployeeId = student.EmployeeId,
                        AdmissionTime = student.AdmissionTime,
                        ClassId = classId,
                        ClassName = input.ClassName,
                        HrBelong = student.HrBelong,
                        CreateUser = _userManager.UserId,
                        CreateTime = DateTime.Now,
                        IsEffective = StatusEnum.有效.GetHashCode()
                    };
                    studentEntities.Add(studentEntity);
                }

                if (studentEntities.Any())
                {
                    await _db.Insertable(studentEntities).ExecuteCommandAsync();
                }

                _db.Ado.CommitTran();

                return new
                {
                    success = true,
                    data = new
                    {
                        classId = classId,
                        className = input.ClassName,
                        studentCount = studentEntities.Count,
                        message = $"成功创建班级'{input.ClassName}'并添加{studentEntities.Count}名学员"
                    },
                    message = "创建成功"
                };
            }
            catch (Exception ex)
            {
                _db.Ado.RollbackTran();
                _logger.LogError(ex, "创建学习班级并添加学员失败");
                throw NCCException.Oh($"创建失败:{ex.Message}");
            }
        }

        #endregion

        #region 向现有班级添加学员
        /// <summary>
        /// 向现有班级添加学员
        /// </summary>
        /// <param name="input">添加学员输入</param>
        /// <returns>添加结果</returns>
        [HttpPost("AddStudentsToClass")]
        public async Task<dynamic> AddStudentsToClassAsync([FromBody] LqStudyClassAddStudentsInput input)
        {
            try
            {
                // 验证班级是否存在
                var classInfo = await _db.Queryable<LqStudyClassEntity>()
                    .Where(x => x.Id == input.ClassId && x.IsEffective == StatusEnum.有效.GetHashCode())
                    .FirstAsync();

                if (classInfo == null)
                {
                    throw NCCException.Oh("班级不存在或已失效");
                }

                _db.Ado.BeginTran();

                // 创建学员
                var studentEntities = new List<LqStudyStudentEntity>();
                foreach (var student in input.Students)
                {
                    var studentEntity = new LqStudyStudentEntity
                    {
                        Id = YitIdHelper.NextId().ToString(),
                        EmployeeName = student.EmployeeName,
                        EmployeePhone = student.EmployeePhone,
                        EmployeeId = student.EmployeeId,
                        AdmissionTime = student.AdmissionTime,
                        ClassId = input.ClassId,
                        ClassName = classInfo.ClassName,
                        HrBelong = student.HrBelong,
                        CreateUser = _userManager.UserId,
                        CreateTime = DateTime.Now,
                        IsEffective = StatusEnum.有效.GetHashCode()
                    };
                    studentEntities.Add(studentEntity);
                }

                if (studentEntities.Any())
                {
                    await _db.Insertable(studentEntities).ExecuteCommandAsync();
                }

                _db.Ado.CommitTran();

                return new
                {
                    classId = input.ClassId,
                    className = classInfo.ClassName,
                    addedStudentCount = studentEntities.Count,
                    message = $"成功向班级'{classInfo.ClassName}'添加{studentEntities.Count}名学员"
                };
            }
            catch (Exception ex)
            {
                _db.Ado.RollbackTran();
                _logger.LogError(ex, "向班级添加学员失败");
                throw NCCException.Oh($"添加失败:{ex.Message}");
            }
        }
        #endregion

        #region 获取所有班级列表
        /// <summary>
        /// 获取所有班级列表
        /// </summary>
        /// <param name="input">查询输入</param>
        /// <returns>班级列表</returns>
        [HttpGet("GetClassList")]
        public async Task<dynamic> GetClassListAsync([FromQuery] LqStudyClassListQueryInput input)
        {
            try
            {
                var sidx = input.sidx == null ? "id" : input.sidx;

                // 查询班级信息
                var data = await _db.Queryable<LqStudyClassEntity>()
                    .WhereIF(!string.IsNullOrWhiteSpace(input.ClassName), x => x.ClassName.Contains(input.ClassName))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.TeacherId), x => x.TeacherId == input.TeacherId)
                    .WhereIF(input.StartTime.HasValue, x => x.StartTime >= input.StartTime.Value)
                    .WhereIF(input.EndTime.HasValue, x => x.StartTime <= input.EndTime.Value)
                    .WhereIF(input.IsEffective.HasValue, x => x.IsEffective == input.IsEffective.Value)
                    .Select(x => new LqStudyClassListOutput
                    {
                        id = x.Id,
                        className = x.ClassName,
                        teacherId = x.TeacherId,
                        teacherName = SqlFunc.Subqueryable<UserEntity>().Where(u => u.Id == x.TeacherId).Select(u => u.RealName),
                        startTime = x.StartTime,
                        endTime = x.EndTime,
                        remark = x.Remark,
                    })
                    .MergeTable()
                    .OrderBy(sidx + " " + input.sort)
                    .ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<LqStudyClassListOutput>.SqlSugarPageResult(data);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取班级列表失败");
                throw NCCException.Oh($"获取班级列表失败:{ex.Message}");
            }
        }
        #endregion

        #region 获取班级下所有学员信息
        /// <summary>
        /// 获取班级下所有学员信息(分页)
        /// </summary>
        /// <param name="input">查询输入</param>
        /// <returns>学员列表</returns>
        [HttpGet("GetStudentListByClassId")]
        public async Task<dynamic> GetStudentListByClassIdAsync([FromQuery] LqStudyStudentListQueryInput input)
        {
            try
            {
                var sidx = input.sidx == null ? "id" : input.sidx;
                // 查询学员信息
                var data = await _db.Queryable<LqStudyStudentEntity>()
                    .Where(x => x.ClassId == input.ClassId)
                    .WhereIF(!string.IsNullOrWhiteSpace(input.EmployeeName), x => x.EmployeeName.Contains(input.EmployeeName))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.EmployeePhone), x => x.EmployeePhone.Contains(input.EmployeePhone))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.EmployeeId), x => x.EmployeeId == input.EmployeeId)
                    .WhereIF(!string.IsNullOrWhiteSpace(input.HrBelong), x => x.HrBelong.Contains(input.HrBelong))
                    .WhereIF(input.IsEffective.HasValue, x => x.IsEffective == input.IsEffective.Value)
                    .Select(x => new LqStudyStudentListOutput
                    {
                        id = x.Id,
                        employeeName = SqlFunc.Subqueryable<UserEntity>().Where(u => u.Id == x.EmployeeId).Select(u => u.RealName),
                        employeePhone = SqlFunc.Subqueryable<UserEntity>().Where(u => u.Id == x.EmployeeId).Select(u => u.MobilePhone),
                        employeeId = x.EmployeeId,
                        admissionTime = x.AdmissionTime,
                        classId = x.ClassId,
                        className = x.ClassName
                    })
                    .MergeTable()
                    .OrderBy(sidx + " " + input.sort)
                    .ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<LqStudyStudentListOutput>.SqlSugarPageResult(data);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取班级学员列表失败");
                throw NCCException.Oh($"获取班级学员列表失败:{ex.Message}");
            }
        }
        #endregion

        #region 学习记录管理
        /// <summary>
        /// 添加学习记录
        /// </summary>
        /// <param name="input">学习记录输入</param>
        /// <returns>添加结果</returns>
        [HttpPost("AddStudyRecord")]
        public async Task AddStudyRecordAsync([FromBody] LqStudyRecordCreateInput input)
        {
            // 验证员工是否存在
            var employee = await _db.Queryable<UserEntity>()
                .Where(x => x.Id == input.EmployeeId && x.RealName == input.EmployeeName)
                .FirstAsync();

            if (employee == null)
            {
                throw NCCException.Oh("员工不存在,请检查员工ID和姓名是否正确");
            }

            // 如果选择下店协助,验证门店信息
            if (input.IsStoreAssist == 1)
            {
                if (string.IsNullOrWhiteSpace(input.StoreId) || string.IsNullOrWhiteSpace(input.StoreName))
                {
                    throw NCCException.Oh("选择下店协助时,门店ID和门店名称不能为空");
                }
            }
            // 创建学习记录
            var recordEntity = new LqStudyRecordEntity
            {
                Id = YitIdHelper.NextId().ToString(),
                EmployeeName = input.EmployeeName,
                EmployeeId = input.EmployeeId,
                StudyType = input.StudyType,
                TransportFee = input.TransportFee,
                StudyDate = input.StudyDate,
                DailyStatus = input.DailyStatus,
                Remark = input.Remark,
                IsStoreAssist = input.IsStoreAssist,
                StoreId = input.IsStoreAssist == 1 ? input.StoreId : null,
                StoreName = input.IsStoreAssist == 1 ? input.StoreName : null,
                CreateUser = _userManager.UserId,
                CreateTime = DateTime.Now,
                IsEffective = 1
            };
            var isOk = await _db.Insertable(recordEntity).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
        }
        #endregion

        #region 获取学习记录列表
        /// <summary>
        /// 获取学习记录列表
        /// </summary>
        /// <param name="input">查询输入</param>
        /// <returns>学习记录列表</returns>
        [HttpGet("GetStudyRecordList")]
        public async Task<dynamic> GetStudyRecordListAsync([FromQuery] LqStudyRecordListQueryInput input)
        {
            try
            {
                var sidx = input.sidx == null ? "id" : input.sidx;

                // 查询学习记录信息
                var data = await _db.Queryable<LqStudyRecordEntity>()
                    .WhereIF(!string.IsNullOrWhiteSpace(input.EmployeeName), x => x.EmployeeName.Contains(input.EmployeeName))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.EmployeeId), x => x.EmployeeId == input.EmployeeId)
                    .WhereIF(!string.IsNullOrWhiteSpace(input.StudyType), x => x.StudyType.Contains(input.StudyType))
                    .WhereIF(input.StudyDateStart.HasValue, x => x.StudyDate >= input.StudyDateStart.Value)
                    .WhereIF(input.StudyDateEnd.HasValue, x => x.StudyDate <= input.StudyDateEnd.Value)
                    .WhereIF(!string.IsNullOrWhiteSpace(input.DailyStatus), x => x.DailyStatus.Contains(input.DailyStatus))
                    .WhereIF(input.IsStoreAssist.HasValue, x => x.IsStoreAssist == input.IsStoreAssist.Value)
                    .WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), x => x.StoreId == input.StoreId)
                    .WhereIF(input.IsEffective.HasValue, x => x.IsEffective == input.IsEffective.Value)
                    .Select(x => new LqStudyRecordListOutput
                    {
                        id = x.Id,
                        employeeName = x.EmployeeName,
                        employeeId = x.EmployeeId,
                        studyType = x.StudyType,
                        transportFee = x.TransportFee,
                        studyDate = x.StudyDate,
                        dailyStatus = x.DailyStatus,
                        remark = x.Remark,
                        isStoreAssist = x.IsStoreAssist,
                        storeId = x.StoreId,
                        storeName = x.StoreName,
                        createUser = x.CreateUser,
                        createUserName = SqlFunc.Subqueryable<UserEntity>().Where(u => u.Id == x.CreateUser).Select(u => u.RealName),
                        createTime = x.CreateTime,
                        updateUser = x.UpdateUser,
                        updateUserName = SqlFunc.Subqueryable<UserEntity>().Where(u => u.Id == x.UpdateUser).Select(u => u.RealName),
                        updateTime = x.UpdateTime,
                        isEffective = x.IsEffective
                    })
                    .MergeTable()
                    .OrderBy(sidx + " " + input.sort)
                    .ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<LqStudyRecordListOutput>.SqlSugarPageResult(data);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取学习记录列表失败");
                throw NCCException.Oh($"获取学习记录列表失败:{ex.Message}");
            }
        }
        #endregion

        #region 作废学习记录
        /// <summary>
        /// 作废学习记录
        /// </summary>
        /// <param name="id">学习记录ID</param>
        /// <returns>作废结果</returns>
        [HttpPost("CancelStudyRecord")]
        public async Task CancelStudyRecordAsync([FromBody] string id)
        {
            var record = await _db.Queryable<LqStudyRecordEntity>().Where(x => x.Id == id).FirstAsync();
            if (record == null) throw NCCException.Oh("学习记录不存在");
            record.IsEffective = StatusEnum.无效.GetHashCode();
            record.UpdateTime = DateTime.Now;
            record.UpdateUser = _userManager.UserId;
            var isOk = await _db.Updateable(record).ExecuteCommandAsync();
            if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
        }
        #endregion
    }
}