using ATS.NonCustodial.Application.Base;
using ATS.NonCustodial.Application.Contracts.Interfaces.Admins.AppDictionaries;
using ATS.NonCustodial.Application.Contracts.Interfaces.Admins.Role;
using ATS.NonCustodial.Application.Contracts.Interfaces.Admins.User;
using ATS.NonCustodial.Application.Contracts.Interfaces.Admins.User.Input;
using ATS.NonCustodial.Application.Contracts.Interfaces.Business.AppCaseManagements.AppCaseManagement;
using ATS.NonCustodial.Application.Contracts.Interfaces.Business.AppCaseManagements.AppCaseManagement.Input;
using ATS.NonCustodial.Application.Contracts.Interfaces.Business.AppCaseManagements.AppCaseManagement.Output;
using ATS.NonCustodial.Application.Contracts.Interfaces.Business.AppCaseManagements.AppSupervisedPersons.Output;
using ATS.NonCustodial.Domain.Entities.Admins;
using ATS.NonCustodial.Domain.Entities.Business;
using ATS.NonCustodial.Domain.Entities.Business.CaseManagements;
using ATS.NonCustodial.Domain.Shared.AggRootEntities.Dtos;
using ATS.NonCustodial.Domain.Shared.Common.Dtos;
using ATS.NonCustodial.Domain.Shared.Enums;
using ATS.NonCustodial.Domain.Shared.OrmRepositories.Basic.EfCore;
using ATS.NonCustodial.DynamicApi;
using ATS.NonCustodial.DynamicApi.Attributes;
using ATS.NonCustodial.Shared.Common.Auth;
using ATS.NonCustodial.Shared.Common.Dtos;
using ATS.NonCustodial.Shared.Common.Enums;
using ATS.NonCustodial.Shared.Common.UnifiedResults;
using ATS.NonCustodial.Shared.Configurations.Options;
using ATS.NonCustodial.Shared.Extensions;
using ATS.NonCustodial.Shared.Extensions.AdvancedQuery;
using ATS.NonCustodial.Shared.Extensions.Collection;
using ATS.NonCustodial.Shared.Helpers;
using AutoMapper.QueryableExtensions;
using Castle.Components.DictionaryAdapter;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SixLabors.ImageSharp;
using Yitter.IdGenerator;
namespace ATS.NonCustodial.Application.Impl.Business.CaseManagements
{
///
/// 案件管理服务
///
/// Author:mxg
/// CreatedTimed:2022-06-06 10:41 AM
///
/// 案件进度:
/// 1、待执行:案件创建后的案件进度为待执行
/// 2、执行中:案件中被监管人有一个在app上的绑定申请通过了,案件进度变为执行中
/// 3、已结束:手动结束案件后的进度为已结束
///
[DynamicApi(Area = "admin")]
public class AppCaseManagementService : AdminCommonService, IAppCaseManagementService, IDynamicApi
{
#region Identity
private readonly IEfRepository _appCaseNotesRepository;
private readonly IEfRepository _appBusinessApplicationRepository;
private readonly IRoleService _roleService;
private readonly IEfRepository _appCommonFenceRepository;
private readonly IEfRepository _appUserRepository;
private readonly IEfRepository _appDeviceManagementRepository;
private readonly IEfRepository _appuserRepository;
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
public AppCaseManagementService(
IEfRepository appCaseManagementRepository,
IEfRepository appCaseSupervisorRepository,
IEfRepository appCaseNotesRepository,
IEfRepository appSupervisedPersonRepository,
IEfRepository appBusinessApplicationRepository,
IUserService userService,
IRoleService roleService,
IEfRepository appuserRepository,
IAppDictionaryService appDictionaryService,
IEfRepository appCommonFenceRepository,
IEfRepository appUserRepository,
IEfRepository appSupervisedPersonRealTimeLocationRepository,
IEfRepository appDeviceManagementRepository)
: base(
appCaseManagementRepository,
appCaseSupervisorRepository,
appSupervisedPersonRepository,
userService,
appDictionaryService,
appSupervisedPersonRealTimeLocationRepository)
{
_appCaseNotesRepository = appCaseNotesRepository;
_appBusinessApplicationRepository = appBusinessApplicationRepository;
_roleService = roleService;
_appCommonFenceRepository = appCommonFenceRepository;
_appUserRepository = appUserRepository;
_appDeviceManagementRepository = appDeviceManagementRepository;
_appuserRepository = appuserRepository;
}
#endregion Identity
///
/// 查询
///
///
///
public async Task Get(long id)
{
var caseDto = await base.GetWithDataAsync(_appCaseManagementRepository, id);
//监管人员(管理员)
caseDto.SupervisorIds = await _appCaseSupervisorRepository
.AsQueryable(false, true)
.Where(w => w.CaseId == id)
.Select(w => w.SupervisorId).ToListAsync();
//案子-被监管人员
caseDto.SupervisedPersonGetDtos = await _appSupervisedPersonRepository.AsQueryable(false, true)
.Where(w => w.CaseId == id)
.OrderBy(W => W.Id)
.ProjectTo(Mapper.ConfigurationProvider).ToListAsync();
//返回结果
return ResultOutput.Ok(caseDto);
}
///
/// 分页查询
///
///
///
[HttpPost]
public async Task GetPageAsync(AppCaseManagementGetPageInput input)
{
var limits = User.limits;
var selectLimits = await _appCaseSupervisorRepository.AsQueryable(false, true)
.Where(w => limits.Contains(w.UnitId.ToString()))
.ToListAsync();
input.CaseIds = selectLimits.Select(w => w.CaseId).Distinct().ToList();
var express = await GetExpression(input, _appCaseManagementRepository.AsQueryable(false, true));
var rtn = await base.GetPageAsync(input, express);
foreach (var listDto in rtn.Data)
{
listDto.Supervisor = selectLimits.Where(w => w.CaseId == listDto.Id).Select(w => w.SupervisorName).JoinAsString(",");
}
return ResultOutput.Ok(rtn);
}
//[HttpPost]
//public async Task GetPageAsync(AppCaseManagementGetPageInput input)
//{
// var express = await GetExpression(input, _appCaseManagementRepository.AsQueryable(false, true));
// var rtn = await base.GetPageAsync(input, express);
// var caseIds = rtn.Data.Select(w => w.Id).ToList();
// var caseSupervisor = await _appCaseSupervisorRepository.AsQueryable(false, true)
// .Where(w => caseIds.Contains(w.CaseId))
// .ToListAsync();
// foreach (var listDto in rtn.Data)
// {
// listDto.Supervisor = caseSupervisor.Where(w => w.CaseId == listDto.Id).Select(w => w.SupervisorName).JoinAsString(",");
// }
// return ResultOutput.Ok(rtn);
//}
///
/// 案件统计
///
///
///
[HttpPost]
public async Task GetAjtjAsync(AppCaseManagementGetPageInput input)
{
var Caselist = await _appCaseManagementRepository.AsQueryable(false, true).WhereIf(input.TimeSearch.BeginTime != null && input.TimeSearch.EndTime != null, q => q.CreatedTime >= input.TimeSearch.BeginTime && q.CreatedTime <= $"{input.TimeSearch.EndTime.Value.ToString("yyyy-MM-dd")} 23:59:59".ToDateTime()).Where(q => q.IsDeleted == false).ToListAsync();
var count = Caselist.Count();
var datalist = Caselist.Where(q => q.CreatedTime != null).GroupBy(q => $"{q.CreatedTime.Value.ToString("MM月dd日")}").Select(q => new { name = q.Key, value = q.Count() }).ToList();
return ResultOutput.Ok(new { count = count, data = datalist });
}
///
/// 涉案人员统计
///
///
///
[HttpPost]
public async Task GetSaryAsync(AppCaseManagementGetPageInput input)
{
var caseIds = await _appCaseManagementRepository.AsQueryable(false, true).Where(q => q.IsDeleted == false).Select(q => q.Id).ToListAsync();
var list = await _appSupervisedPersonRepository.AsQueryable(false, true).WhereIf(input.TimeSearch.BeginTime != null && input.TimeSearch.EndTime != null, q => q.CreatedTime >= input.TimeSearch.BeginTime && q.CreatedTime <= $"{input.TimeSearch.EndTime.Value.ToString("yyyy-MM-dd")} 23:59:59".ToDateTime()).Where(q => q.IsDeleted == false && caseIds.Contains(q.CaseId)).ToListAsync();
var dalist = list.Distinct((a, b) => a.SupervisedPersonId == b.SupervisedPersonId);
var count = dalist.Count();
var datalist = dalist.Where(q => q.CreatedTime != null).GroupBy(q => $"{q.CreatedTime.Value.ToString("MM月dd日")}").Select(q => new { name = q.Key, value = q.Count() });
return ResultOutput.Ok(new { count = count, data = datalist, list = dalist });
}
///
/// 涉案人员统计分页查询
///
///
///
[HttpPost]
public async Task SupervisedPersonAsync(GetSupervisedPersonPage input)
{
var caselist = await _appCaseManagementRepository.AsQueryable(false, true).WhereIf(input.TimeSearch.BeginTime != null && input.TimeSearch.EndTime != null, q => q.CreatedTime >= input.TimeSearch.BeginTime && q.CreatedTime <= $"{input.TimeSearch.EndTime.Value.ToString("yyyy-MM-dd")} 23:59:59".ToDateTime()).Where(q => q.IsDeleted == false).ToListAsync();
var caseIds = caselist.Select(q => q.Id).ToList();
var data = await _appSupervisedPersonRepository
.Where(q => caseIds.Contains(q.CaseId))
.OrderByDescending(r => r.CreatedTime)
.ProjectTo(Mapper.ConfigurationProvider)
.PagedAsync(input)
.ConfigureAwait(false);
return ResultOutput.Ok(new { data, caselist });
}
///
/// 案件信息数据统计
///
///
///
[HttpPost]
public async Task caseStatistics()
{
//获取案件信息
var express = await base.GetCurrentUserCaseListAsync();
//案件信息Id
var caseIds = await express.Select(w => w.AppCaseManagement.Id).ToListAsync();
//监管人数
var caseSupervisor = await _appCaseSupervisorRepository.AsQueryable(false, true)
.Where(w => caseIds.Contains(w.CaseId))
.ToListAsync();
//被监管人数
var caseSupervisorperson = await _appSupervisedPersonRepository.AsQueryable(false, true)
.Where(w => caseIds.Contains(w.CaseId))
.ToListAsync();
var total = express.GroupBy(q => q.AppCaseManagement.Id).Count();//案件总数
var typenotused = express.GroupBy(q => q.AppCaseManagement.CaseTypeId).Count();//案件类型总数
var superviseNumber = caseSupervisor.GroupBy(q => q.SupervisorId).Count();//监管人数
var Supervisedpersonnumber = caseSupervisorperson.Count();//被监管人数
return ResultOutput.Ok(new { total, typenotused, superviseNumber, Supervisedpersonnumber });
}
///
/// 案件类型统计
///
///
///
[HttpPost]
public async Task casetypeStatistics()
{
var diclist = new List();
//获取当前用户能看到的数据Id
var caseIds = await (await base.GetCurrentUserCaseListAsync()).Select(w => w.AppCaseManagement.Id).ToListAsync();
//获取案件信息
var express = await _appCaseManagementRepository.AsQueryable(false, true).Where(q => caseIds.Contains(q.Id)).ToListAsync();
var otherexpress = express;
//var total = express.Count();//获取案件总数
//案件类型分组获取数量最多前10个 其余得为其他分组
var expresstype = express.GroupBy(q => q.CaseTypeId).OrderByDescending(q => q.Count()).Take(5).ToList();
foreach (var item in expresstype)
{
//计算百分比
//double number = (Convert.ToDouble(item.ToList().Count()) / Convert.ToDouble(total)) * 100;
double number = item.ToList().Count();
//通过id获取字典信息
var dataDict = await _appDictionaryService.GetDicByDicId(item.Key);
diclist.Add(new { name = dataDict?.Name, value = Convert.ToInt32(number) });
otherexpress = otherexpress.Where(q => q.CaseTypeId != item.Key).ToList();
}
//类型大于10
if (expresstype.Count() > 5)
diclist.Add(new { name = "其他", value = otherexpress.Count() });
//diclist.Add(new { name = "其他", value = Convert.ToInt32(Convert.ToDouble((otherexpress.Count() / total) * 100)) });
return ResultOutput.Ok(diclist);
}
///
/// 非羁押人员流向统计
///
///
///
[HttpPost]
public async Task flowtoStatistics()
{
//定义当前年开始时间结束时间
var st = $"{DateTime.Now.ToString("yyyy-MM")}-01".ToDateTime().AddMonths(-5);
var et = $"{DateTime.Now.ToString("yyyy-MM")}-{DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)}".ToDateTime();
//获取当前用户能看到的数据
var caseIds = await (await base.GetCurrentUserCaseListAsync()).Select(w => w.AppCaseManagement.Id).ToListAsync();
//获取当前年案件信息及案件被监管人----已通过审核的被监管人
var datalist = await (from a in _appCaseManagementRepository.AsQueryable(false, true).Where(q => q.CreatedTime >= st && q.CreatedTime <= et && caseIds.Contains(q.Id))
join b in _appSupervisedPersonRepository.AsQueryable(false, true)
.Where(w => w.ApprovalStatus == ApprovalStatusEnum.PassReview) on a.Id equals b.CaseId
select new { ajid = a.Id, a.CreatedTime, a.CaseProgress, b.Id }).ToListAsync();
//获取每月非羁押人员数及释放人员数
var list = datalist.GroupBy(q => $"{q.CreatedTime}".ToDateTime().ToString("MM")).Select(q => new
{
timestr = q.Key,
fjynumber = q.ToList().Where(q => q.CaseProgress == CaseProgressEnum.Closed).Count(),
sfnumber = q.ToList().Where(q => q.CaseProgress != CaseProgressEnum.Pending && q.CaseProgress != CaseProgressEnum.Closed).Count(),
}).ToList();
string YearMonth = "", fjynumber = "", sfnumber = "";
for (int i = 0; i < 6; i++)
{
var time = st.AddMonths(i);
var data = list.Where(q => q.timestr == $"{time.ToString("MM")}").FirstOrDefault();
YearMonth += $"{time.Year}/{time.Month},";
if (data != null)
{
fjynumber += $"{data.fjynumber},";
sfnumber += $"{data.sfnumber},";
}
else
{
fjynumber += $"0,";
sfnumber += $"0,";
}
}
return ResultOutput.Ok(new { YearMonth = YearMonth.Trim(',').Split(","), fjynumber = fjynumber.Trim(',').Split(","), sfnumber = sfnumber.Trim(',').Split(",") });
}
///
/// 根据案件Id查询被监管人员信息
///
///
///
[HttpPost]
public async Task GetSupervisedPersonPageAsync(GetSupervisedPersonPage input)
{
var data = await _appSupervisedPersonRepository.AsQueryable(false, true)
.Where(w => w.CaseId == input.Id)
.OrderBy(r => r.Id)
.ProjectTo(Mapper.ConfigurationProvider)
.PagedAsync(input)
.ConfigureAwait(false);
return ResultOutput.Ok(data);
}
///
/// 根据案件Id查询监管人员信息
///
///
///
[HttpPost]
public async Task> GetSupervisedPageAsync(GetSuperviseorPage input)
{
var data = await _appCaseSupervisorRepository.AsQueryable(false, true)
.Where(w => input.Ids.Contains(w.CaseId))
.ProjectTo(Mapper.ConfigurationProvider)
.ToListAsync()
.ConfigureAwait(false);
return data;
}
///
/// 获取案件批注内容列表
///
///
///
public async Task GetCaseNotes(long id) => await base.GetListAsync(_appCaseNotesRepository, w => w.CaseId == id);
///
/// 添加案件重要节点批注
///
///
///
public async Task AddCaseNotes(AddCaseNotesInput input)
{
if (input.CaseId == default || !input.Notes.NotNull()) return ResultOutput.Ok("参数错误!");
await _appCaseNotesRepository.InsertAsync(new AppCaseNotes(YitIdHelper.NextId())
{
CaseId = input.CaseId,
Notes = input.Notes
});
return ResultOutput.Ok();
}
///
/// 批量处理案子进度
///
///
///
public async Task BatchHandleCaseProgress(BatchHandleCaseProgressInput input)
{
if (!input.Ids.Any()) return ResultOutput.NotOk("参数错误!");
var dataList = await _appCaseManagementRepository.Where(w => input.Ids.Contains(w.Id))
.ToListAsync();
if (!dataList.Any()) return ResultOutput.NotOk("数据为空!");
//没有开始的案件不能执行结束
if (input.CaseProgress == CaseProgressEnum.Closed && dataList.Exists(w => w.CaseProgress == CaseProgressEnum.Pending)) return ResultOutput.NotOk("待执行的案件不能结束");
dataList.ForEach(item =>
{
item.CaseProgress = input.CaseProgress;
//案子结束时间
item.CaseClosedTime = input.CaseProgress == CaseProgressEnum.Closed ? DateTime.Now : null;
});
await _appCaseManagementRepository.UpdateAsync(dataList);
return ResultOutput.Ok();
}
///
/// 创建或者添加 案子
///
///
///
///
/// ###### 入参示例
/// {
/// "id": 0,
/// "name": "moshang4",
/// "caseTypeId": 297606176055365,
/// "judgmentStatusId": 297606175068229,
/// "proximityLevel": 11,
/// "restBeginTime": "16:07",
/// "restEndTime": "02:07",
/// "checkInFrequency": 2,
/// "supervisorIds": [
/// {
/// "supervisedId": 303362251345989,
/// "supervisedName": "moshang2"
/// }
/// ],
/// "supervisedPersonGetDtos": [
/// {
/// "id": 0,
/// "supervisedPersonId": 297606179328069,
/// "supervisedPersonName": "moshang",
/// "caseId": 0,
/// "approvalStatus": 0,
/// "isBound": true,
/// "name": "moshang",
/// "warningGradeId": 0,
/// "idCard": "511502198912311256",
/// "phone": "18980975824",
/// "electricFenceId": 303366664052805,
/// "electricFenceName": "常用围栏1",
/// "privacyLevel": 11,
/// "enterFace": "",
/// "imei": ""
/// }
/// ]
/// }
///
public async Task CreateOrModify(AppCaseManagementCreateOrModifyInput input)
{
/*
1、案件添加和编辑被监管人不做用户表数据重复验证,包括身份证和手机号
2、添加和修改时候,只通过身份证去查询用户表数据 如果存在,则获取被监管人id,如果不存在则新增后返回id,
3、如果身份证存在用户表,直接强行修改用户姓名和手机号
4、案件执行和待执行的校验值通过身份证进行判断,如果该身份证存在待执行或执行中的 提示 xxxxxx身份证存在待执行或执行中的案件,注意已删除的不需要判断
*/
if (input.SupervisedPersonGetDtos == null || !input.SupervisedPersonGetDtos.Any()) return ResultOutput.Ok("每个案件至少需要一个被监管人!");
//if (input.RestBeginTime == input.RestEndTime) return ResultOutput.NotOk("休息结束时间必须大于开算时间");
#region Valid
//校验案子
var caseValid = await base.Valid(input, _appCaseManagementRepository, w =>
{
w = w.AndNotNull(w => w.Bmsah == input.Bmsah, input.Bmsah.IsNotNullOrEmpty());
return (w, $"当前部门受案号:{input.Bmsah}已存在");
});
if (!caseValid.Success) return caseValid;
//校验案件被监管人
var validSpCase = await ValidSupervisedPerson(input);
if (!validSpCase.Success) return validSpCase;
#endregion Valid
var caseId = input.Id;
Uow.BeginTransaction();
//修改
if (input.Id > 0)
{
var data = _appCaseManagementRepository.AsQueryable().Where(q => q.Id == input.Id).FirstOrDefault();
input.CaseProgress = data?.CaseProgress;
await base.UpdateAsync(input, _appCaseManagementRepository);
}
else
{
var entity = Mapper.Map(input);
caseId = (await _appCaseManagementRepository.InsertAsync(entity)).Id;
}
//案子监管管理人员(Bug:当我修改监管人后,已审核过的被监管人需要重新申请,被切换的监管人没有对应数据)
if (input.SupervisorIds!.Any())
{
var sList = input.SupervisorIds!.Select(csp => new AppCaseSupervisor(YitIdHelper.NextId())
{
CaseId = caseId.Value,
SupervisorId = csp.SupervisedId,
SupervisorName = csp.SupervisedName
});
var dels = new List();
var list = await _appCaseSupervisorRepository.AsQueryable(false, true).Where(w => w.CaseId == caseId).ToListAsync();
foreach (var item in sList)
{
if (list.Count > 0)
{
var data = list.First(q => q.SupervisorId == item.SupervisorId);
if (data != null)
{
//排除不需要删除的被监管人
list = list.Where(q => q.SupervisorId != item.SupervisorId).ToList();
//排除已存在的监管人
sList = sList.Where(q => q.SupervisorId != item.SupervisorId);
}
}
}
//需要删除的监管人
var SupervisorIds = list.Select(q => q.SupervisorId);
//删除的监管人
await _appCaseSupervisorRepository.DeleteAsync(w => w.CaseId == caseId && SupervisorIds.Contains(w.SupervisorId));
//新增监管人
await _appCaseSupervisorRepository.InsertAsync(sList);
}
//案子-被监管人员
if (input.SupervisedPersonGetDtos!.Any())
{
//不存在的被监管人
var roles = (await _roleService.GetRoleByKeyword("supervisedPerson")).FirstOrDefault();
//被监管人职位字典
var supervisedPersonPosition = await base.GetDictionariesOutput("job_position", "supervisedperson");
//被监管人员
var supervisedPersonList = Mapper.Map, List>(input.SupervisedPersonGetDtos);
supervisedPersonList.ForEach(item =>
{
if (item.Id == null)
item.Id = YitIdHelper.NextId();
item.CaseId = caseId!.Value;
});
#region [1]如果用户不存在就添加到用户表中(根据身份证来判断)
List addUsers = new();
List updateAppUsers = new();
foreach (var item in supervisedPersonList)
{
var tempUser = await _appUserRepository.FindAsync(w => w.IdCard == item.IdCard);
//存在就修改名字和手机号
if (tempUser != null)
{
tempUser.UserName = tempUser.Name = item.SupervisedPersonName;
tempUser.Phone = item.Phone;
updateAppUsers.Add(new SupervisedPersonUpdateInput()
{
UserName = item.SupervisedPersonName,
Name = item.SupervisedPersonName,
Phone = tempUser.Phone,
IdCard = item.IdCard,
Id = tempUser.Id
});
}
else
{
addUsers.Add(new SupervisedPersonAddInput()
{
UserName = item.SupervisedPersonName,
Name = item.SupervisedPersonName,
Password = "Mr@123456",
Phone = item.Phone,
RoleIds = new[] { roles!.Id },
DataStatus = DataStatusEnum.Normal,
PositionId = supervisedPersonPosition?.Id,
PositionName = supervisedPersonPosition?.Name,
RoleName = roles.Name,
IdCard = item.IdCard,
Id = YitIdHelper.NextId()
});
}
}
if (addUsers.Any()) await _userService.BatchAddAsync(addUsers);
if (updateAppUsers.Any()) await _userService.BatchUpdateAsync(updateAppUsers);
var userIds = addUsers.Select(w => w.Id).Union(updateAppUsers.Select(w => w.Id)).Distinct();
//所有用户
var allUsers = await _appUserRepository.Where(w => userIds.Contains(w.Id)).ToListAsync();
foreach (var person in supervisedPersonList)
{
//根据身份证号来确定唯一
var tempUser = allUsers.FirstOrDefault(w => w.IdCard == person.IdCard);
if (tempUser == null)
tempUser = await _appUserRepository.FindAsync(w => w.IdCard == person.IdCard);
if (tempUser == null) continue;
person.SupervisedPersonId = tempUser.Id;
person.SupervisedPersonName = tempUser.UserName;
person.Phone = tempUser.Phone;
}
#endregion [1]如果用户不存在就添加到用户表中(根据身份证来判断)
#region 被监管人电子围栏
{
var spIds = supervisedPersonList
.Where(w => w.ElectricFenceId == 0)
.Select(w => w.SupervisedPersonId)
.ToList();
//只有是设置得才添加
if (spIds.Any())
{
//先删除
await _appCommonFenceRepository.DeleteAsync(w =>
w.CaseId == caseId && w.CommonFenceType == CommonFenceTypeEnum.SupervisedPerson &&
spIds.Contains(w.SupervisedPersonId.Value));
var adCfList = input.SupervisedPersonGetDtos
.Select(w => new AppCommonFence(YitIdHelper.NextId())
{
CaseId = caseId,
SupervisedPersonId = w.SupervisedPersonId,
SupervisedPersonName = w.SupervisedPersonName,
CommonFenceType = CommonFenceTypeEnum.SupervisedPerson,
Name = w.CommonFenceAddInput?.Name,
Path = w.CommonFenceAddInput?.Path
});
if (adCfList.Any())
{
var addedCfList = await _appCommonFenceRepository.InsertAsync(adCfList);
foreach (var item in supervisedPersonList)
{
var tempCommonFence = addedCfList.FirstOrDefault(w =>
w.CaseId == caseId &&
w.CommonFenceType == CommonFenceTypeEnum.SupervisedPerson &&
w.SupervisedPersonId == item.SupervisedPersonId);
//说明是常用围栏
if (tempCommonFence == null) continue;
item.ElectricFenceId = tempCommonFence?.Id;
item.ElectricFenceName = tempCommonFence?.Name;
}
}
}
}
#endregion 被监管人电子围栏
//案子被监管人中间表
var sprIds = supervisedPersonList.Select(w => w.SupervisedPersonId).ToList();
//当前案件所有已经存在的被监管人
var sprList = await _appSupervisedPersonRepository.AsQueryable(false, true)
.Where(w => w.CaseId == caseId && sprIds.Contains(w.SupervisedPersonId)).ToListAsync();
//await _appSupervisedPersonRepository.DeleteAsync(w => w.CaseId == caseId);
var addsupervisedPerson = new List();
var UpdatesupervisedPerson = new List();
//防止漏网之鱼
foreach (var person in supervisedPersonList)
{
if (person.SupervisedPersonId == default)
{
var temUser = allUsers.FirstOrDefault(w => w.IdCard == person.IdCard);
if (temUser == null) continue;
person.SupervisedPersonId = temUser!.Id;
person.SupervisedPersonName = temUser.UserName;
}
else
{
var tempSp = sprList.FirstOrDefault(w => w.IdCard == person.IdCard);
if (tempSp == null)
{
addsupervisedPerson.Add(person);
continue;
}
//把已经存在的数据全部赋值上(案件只能修改名字、身份证、手机号)
person.ApprovalStatus = tempSp!.ApprovalStatus;
person.IsBound = tempSp.IsBound;
person.WarningGradeId = tempSp.WarningGradeId;
person.EnterFace = tempSp.EnterFace;
person.IMEI = tempSp.IMEI;
UpdatesupervisedPerson.Add(person);
}
}
await _appSupervisedPersonRepository.UpdateAsync(UpdatesupervisedPerson);
await _appSupervisedPersonRepository.InsertAsync(addsupervisedPerson);
}
#region 打卡消息推送手机通知栏
if (input.Id == 0)
{
var cidslist = new List();
//通过新案件id获取监管人
var CaseSupervisorlist = await _appCaseSupervisorRepository.AsQueryable(false, true).Where(q => q.CaseId == caseId).ToListAsync();
//监管人ids
var SupervisedIds = new List();
CaseSupervisorlist.ForEach(q =>
{
SupervisedIds.Add(q.SupervisorId);
});
//获取监管人手机唯一id
var supervisecids = _appuserRepository.AsQueryable(false, true).ToList().Where(q => SupervisedIds.Contains(q.Id) && !string.IsNullOrEmpty(q.CId));
supervisecids.Where(q => !string.IsNullOrEmpty(q.CId)).ForEach(q =>
{
cidslist.Add($"{q.CId}");
});
//所有管理员
var adminList = await _userService.GetAllAdminUserIds();
adminList.Where(q => !string.IsNullOrEmpty(q.CId)).ForEach(q =>
{
cidslist.Add($"{q.CId}");
});
if (cidslist.Count() > 0)
{
try
{
//获取个推配置
var TweetConfig = LazyGetRequiredService();
//查询判断token是否存在 存在直接获取 不存在通过接口重新获取token
var token = Cache.Exists("token");
if (!token)
base.GettoekenQuery();
var tokenstr = Cache.Get("token");
var msg_list = new List();
foreach (var item in cidslist.Distinct())
{
//随机生成数
var request_id = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 32).ToString();
msg_list.Add(new
{
request_id = request_id,
settings = new { ttl = 7200000 },
audience = new { cid = item.ToString().Split(",") },
push_message = new
{
notification = new
{
title = "非羁押",
body = $"有新案件录入!",
click_type = "none",
}
}
});
}
var data = new
{
is_async = true,
msg_list = msg_list
};
//打卡消息推送被监管人手机通知栏
var re = base.GetpostQuery($"{TweetConfig.BaseUrl.Replace("$appId", TweetConfig.AppID)}{TweetConfig.cidurl}", data, tokenstr);
}
catch (Exception)
{
}
}
}
#endregion
await Uow.CommitAsync();
//返回结果
return ResultOutput.Ok();
}
///
/// 新增案子监管人
///
///
///
public async Task addCreateOrModify(AppCaseManagementCreateOrModifyInput input)
{
var caseId = input.Id;
var data = await _appCaseManagementRepository.AsQueryable(false, true).FirstAsync(q => q.Id == caseId);
if (data != null)
{
Uow.BeginTransaction();
//当案件移交后添加监管人和修改案件状态
if (input.SupervisorIds!.Any())
{
var sList = input.SupervisorIds!.Select(csp => new AppCaseSupervisor(YitIdHelper.NextId())
{
CaseId = caseId.Value,
SupervisorId = csp.SupervisedId,
SupervisorName = csp.SupervisedName
});
var Supervisordata = await _appCaseSupervisorRepository.FindAsync(q => q.CaseId == caseId && sList.Select(q => q.SupervisorId).Contains(q.SupervisorId));
//if (Supervisordata != null)
//{
// return ResultOutput.NotOk("已是监管人,请选择其他监管人");
//}
if (Supervisordata == null)
await _appCaseSupervisorRepository.InsertAsync(sList);
}
data.CaseProgress = (CaseProgressEnum)input.CaseProgress;
await _appCaseManagementRepository.UpdateAsync(data, UpdatingProps(x => x.CaseProgress)!);
await Uow.CommitAsync();
}
//返回结果
return ResultOutput.Ok();
}
///
/// 批量删除案子
///
///
///
[HttpDelete]
public async Task BatchDelete(BatchIdsInput input)
{
Uow.BeginTransaction();
{
//删除案子主表
await _appCaseManagementRepository.DeleteAsync(w => input.Ids.Contains(w.Id));
//删除案子监管人员表数据
await _appCaseSupervisorRepository.DeleteAsync(w => input.Ids.Contains(w.CaseId));
//删除案子被监管人员
await _appSupervisedPersonRepository.DeleteAsync(w => input.Ids.Contains(w.CaseId));
//删除案子的评论
await _appCaseNotesRepository.DeleteAsync(w => input.Ids.Contains(w.CaseId));
}
await Uow.CommitAsync();
return ResultOutput.Ok();
}
///
/// 删除案子中被监管人员
///
///
///
[HttpDelete]
public async Task DeleteAsync(DeleteCaseSupervisedPersonInput input)
{
if (await _appSupervisedPersonRepository.CountAsync(w => w.CaseId == input.CaseId) <= 1)
return ResultOutput.NotOk("每一个案件至少存在一个被监管人!");
await _appSupervisedPersonRepository.DeleteAsync(w =>
w.CaseId == input.CaseId &&
w.SupervisedPersonId == input.SupervisedPersonId);
return ResultOutput.Ok();
}
///
/// 办案时长统计(办案时长允许0.5天的这样形式当前 显示为0天)
///
///
///
public async Task CaseStatisticsHandlingTime(CaseStatisticsHandlingTimePageInput input)
{
var query = _appCaseManagementRepository
.AsQueryable(false, true)
.Where(w => w.CaseProgress == CaseProgressEnum.Closed)
.WhereIf(input.KeyWord.NotNull(), a => a.Name.Contains(input.KeyWord))
.WhereIf(input.TimeSearch.BeginTime.Length == 2, w => w.CaseBeginTime > input.TimeSearch.BeginTime[0] && w.CaseBeginTime < input.TimeSearch.BeginTime[1].AddDays(1))
.WhereIf(input.TimeSearch.EndTime.Length == 2, w => w.CaseClosedTime > input.TimeSearch.EndTime[0] && w.CaseClosedTime <= input.TimeSearch.EndTime[1].AddDays(1));
var pageData = await
query.ProjectTo(Mapper.ConfigurationProvider)
.PagedAsync(input)
.ConfigureAwait(false);
var caseIds = pageData.Data.Select(w => w.Id);
//涉事人员(被监管人员)
var personInvolvedList = await _appSupervisedPersonRepository
.AsQueryable(false, true)
.Where(w => caseIds.Contains(w.CaseId))
.ToListAsync();
//处理时长和涉事人员
foreach (var person in pageData.Data)
{
person.PersonInvolved = personInvolvedList
.Where(w => w.CaseId == person.Id)
.Select(w => w.SupervisedPersonName)!
.JoinAsString(",");
if (person.CaseBeginTime.HasValue) person.CaseHandlingTime = new TimeSpan(person.CaseClosedTime!.Value.Ticks - person.CaseBeginTime.Value.Ticks).TotalDays.ToString("F1");
}
//返回结果
return ResultOutput.Ok(pageData);
}
///
/// 案件类型统计
///
///
public async Task CaseTypeStatistics(CaseTypeStatisticsGetPageInput input)
{
//获取当前用户权限下的案件ids
var limits = User.limits;
var selectLimits = await _appCaseSupervisorRepository.AsQueryable(false, true)
.Where(w => limits.Contains(w.UnitId.ToString()))
.ToListAsync();
var caseIds = selectLimits.Select(w => w.CaseId).Distinct().ToList();
var data = await _appCaseManagementRepository.AsQueryable(false, true)
.WhereIf(input.KeyWord.NotNull(), a => a.Name.Contains(input.KeyWord))
.WhereIf(input.TimeSearch.BeginTime.Length == 2, w => w.CreatedTime > input.TimeSearch.BeginTime[0] && w.CreatedTime < input.TimeSearch.BeginTime[1].AddDays(1))
.WhereIf(input.TimeSearch.EndTime.Length == 2, w => w.CaseClosedTime > input.TimeSearch.EndTime[0] && w.CaseClosedTime < input.TimeSearch.EndTime[1].AddDays(1))
.WhereIf(input.ajtype.NotNull(), w => w.CaseTypeId == input.ajtype.ToLong()).Where(w=> caseIds.Contains(w.Id))
.ToListAsync();
var dataGroup = data.GroupBy(w => w.CaseTypeId);
var pageData = dataGroup
.OrderBy(w => w.Key)
.Skip((input.PageIndex - 1) * input.PageSize)
.Take(input.PageSize);
//案件类型Id
var caseTypeIds = pageData
.Select(w => w.Key)
.ToList();
var allCaseTypeDics = await _appDictionaryService.GetDicByDicIds(new BatchIdsInput
{
Ids = caseTypeIds
});
//处理配型
var dataList = pageData.Select(data => new CaseTypeStatisticsListDto()
{
CaseTypeId = data.Key,
CaseTypeName = allCaseTypeDics.FirstOrDefault(w => w.Id == data.Key)?.Name,
TotalCaseCount = data.Count()
}).ToList();
var rtn = new PageOutput()
{
Total = dataGroup.Count(),
List = dataList
};
//返回结果
return ResultOutput.Ok(rtn);
}
///
/// 办案频次统计(办案次数是指被监管人申请业务的次数【当前监管人】)
///
///
///
public async Task CaseHandlingFrequencyStatistics(CaseHandlingFrequencyStatisticsGetPageInput input)
{
//获取当前用户权限下的案件ids
var limits = User.limits;
var selectLimits = await _appCaseSupervisorRepository.AsQueryable(false, true)
.Where(w => limits.Contains(w.UnitId.ToString()))
.ToListAsync();
var caseIds = selectLimits.Select(w => w.CaseId).Distinct().ToList();
//query
var query = await (await base.GetCurrentUserCaseListAsync())
//.Where(w => w.AppCaseSupervisedPerson != null && w.AppCaseManagement.CaseProgress != CaseProgressEnum.Closed)
.Where(w => w.AppCaseSupervisedPerson != null)
.WhereIf(input.SupervisedPersonName.IsNotNullOrWhiteSpace(), w => w.AppCaseSupervisedPerson.SupervisedPersonName.Contains(input.SupervisedPersonName))
.Select(w => new CaseHandlingFrequencyStatisticsListDto()
{
CaseId = w.AppCaseManagement.Id,
Name = w.AppCaseManagement.Name,
SupervisedPersonId = w.AppCaseSupervisedPerson.SupervisedPersonId,
SupervisedPersonName = w.AppCaseSupervisedPerson.SupervisedPersonName
}).ToListAsync();
var dataGroup = query.Where(w=> caseIds.Contains(w.CaseId)).GroupBy(w => new
{
w.CaseId,
w.SupervisedPersonId,
w.Name,
w.SupervisedPersonName
});
//pageData
var pageData = dataGroup
.Skip((input.PageIndex - 1) * input.PageSize)
.Take(input.PageSize)
.ToList();
//业务申请
var dataList = new List();
//处理身份证字段
var userList = await _userService.GetAllByConditionAsync(new BatchIdsInput()
{
Ids = pageData.Select(w => w.Key.SupervisedPersonId).ToList()
});
foreach (var data in pageData)
{
var chFCount = await _appBusinessApplicationRepository
.AsQueryable(false, true)
.CountAsync(w => w.SupervisedPersonId == data.Key.SupervisedPersonId && w.CaseId == data.Key.CaseId);
dataList.Add(new CaseHandlingFrequencyStatisticsListDto()
{
CaseId = data.Key.CaseId,
Name = data.Key.Name,
SupervisedPersonId = data.Key.SupervisedPersonId,
SupervisedPersonName = data.Key.SupervisedPersonName,
HandleCaseCount = chFCount,
IdCard = userList.FirstOrDefault(w => w.Id == data.Key.SupervisedPersonId)?.IdCard
});
}
//分页输出
var rtn = new PageOutput()
{
Total = dataGroup.Count(),
List = dataList
};
return ResultOutput.Ok(rtn);
}
///
/// 即时通讯管理(当前案件下所有被监管人分组)
///
///
///
public async Task ImManagement(ImManagementInput input)
{
var imManagementList = await (from cm in _appCaseManagementRepository.AsQueryable(false, true).Where(w => w.CaseProgress != CaseProgressEnum.Closed)
join csp in _appSupervisedPersonRepository.AsQueryable(false, true)
.WhereIf(input.SupervisedPersonName.NotNull(), w => w.SupervisedPersonName.Contains(input.SupervisedPersonName))
on cm.Id equals csp.CaseId
select new ImManagementListDto()
{
CaseId = cm.Id,
CaseName = cm.Name,
SupervisedPersonId = csp.SupervisedPersonId,
SupervisedPersonName = csp.SupervisedPersonName
}).ToListAsync();
var spIdList = imManagementList.Select(w => w.SupervisedPersonId).ToList();
var spList = await _appSupervisedPersonRepository.AsQueryable(false, true)
.Where(w => spIdList.Contains(w.Id))
.ToListAsync();
foreach (var imManagementListDto in imManagementList)
{
imManagementListDto.Gender =
spList.FirstOrDefault(w => w.Id == imManagementListDto.SupervisedPersonId)!.Gender;
}
//分组
var rtn = imManagementList.GroupBy(w => new { w.CaseId, w.CaseName })
.Select(w => new ImManagementGroupListDto()
{
Key = w.Key.CaseName + "-" + w.Key.CaseId,
ImList = w.ToList()
}).ToList();
//返回
return ResultOutput.Ok(rtn);
}
///
/// 业务工作台===>即时通讯(取最新5条作为展示)
///
///
public async Task ImBusinessWorkbench()
{
var caseIds = await (await base.GetCurrentUserCaseListAsync()).Select(w => w.AppCaseManagement.Id).ToListAsync();
var imManagementList = await (from cm in _appCaseManagementRepository.AsQueryable(false, true)
.Where(w => w.CaseProgress != CaseProgressEnum.Closed && caseIds.Contains(w.Id))
join csp in _appSupervisedPersonRepository.AsQueryable(false, true)
on cm.Id equals csp.CaseId
select new ImManagementListDto()
{
CaseId = cm.Id,
CaseName = cm.Name,
SupervisedPersonId = csp.SupervisedPersonId,
SupervisedPersonName = csp.SupervisedPersonName,
CreatedTime = cm.CreatedTime
}).OrderByDescending(w => w.CreatedTime)
.Skip(0)
.Take(5)
.ToListAsync();
return ResultOutput.Ok(imManagementList);
}
///
/// 业务工作台===>查看案件(取最新5条作为展示)
///
///
public async Task CaseBusinessWorkbench()
{
var dataDict = await _appDictionaryService.GetListNoApiAsync(null);
var caseList = (await (await base.GetCurrentUserCaseListAsync()).ToListAsync())
.Where(w => w.AppCaseManagement.CaseProgress != CaseProgressEnum.Closed)
.OrderByDescending(w => w.AppCaseSupervisedPerson?.CreatedTime)
.Where(w => w.AppCaseSupervisedPerson != null)
.Skip(0)
.Take(5)
.Select(caseAgg =>
{
return new ImManagementListDto()
{
CaseId = caseAgg.AppCaseManagement!.Id,
CaseName = caseAgg.AppCaseManagement.Name,
CreatedTime = caseAgg.AppCaseManagement.CreatedTime,
JudgmentStatusId = caseAgg.AppCaseManagement.JudgmentStatusId,
JudgmentStatusName = dataDict
.FirstOrDefault(w => w.Code == "judgment")!
.Dictionaries!
.FirstOrDefault(w => w.Id == caseAgg.AppCaseManagement.JudgmentStatusId)!
.Name,
SupervisedPersonId = caseAgg.AppCaseSupervisedPerson!.SupervisedPersonId,
SupervisedPersonName = caseAgg.AppCaseSupervisedPerson.SupervisedPersonName,
Avatar = caseAgg.AppCaseSupervisedPerson?.EnterFace ?? "/avatar/default.png"
};
})
.Distinct((x, y) => x.CaseId == y.CaseId)
.ToList();
return ResultOutput.Ok(caseList);
}
///
/// 获取监管人员手里的案子列表
///
///
///
public async Task GetSupervisorCaseList(GetSupervisorCaseListInput input)
{
var dataaggList = await (await base.GetCurrentUserCaseListAsync())
.Where(w => w.AppCaseManagement.CaseProgress == input.CaseProgress)
.Select(w => new GetSupervisorCaseListDto()
{
Id = w.AppCaseManagement.Id,
CaseProgress = w.AppCaseManagement.CaseProgress,
Name = w.AppCaseManagement.Name,
//SupervisorId = w.cspr.SupervisorId,
SupervisorName = w.AppCaseSupervisor.SupervisorName,
//UserId = w.csR.UserId,
SupervisedPersonName = w.AppCaseSupervisedPerson.SupervisedPersonName,
SupervisedPersonfile = w.AppCaseSupervisedPerson.EnterFace,
CreatedTime = w.AppCaseManagement.CreatedTime,
CreatedUserId = w.AppCaseManagement.CreatedUserId,
CreatedUserName = w.AppCaseManagement.CreatedUserName
})
.ToListAsync();
var dataGroup = dataaggList.GroupBy(w => new { w.Id });
var totalCount = dataGroup.Count();
dataGroup = dataGroup
.Skip((input.PageIndex - 1) * input.PageSize)
.Take(input.PageSize)
.ToList();
var rtn = (from data in dataGroup
let dataList = data.ToList()
let first = data.FirstOrDefault()
select new GetSupervisorCaseListDto()
{
Id = first.Id,
CaseProgress = first.CaseProgress,
Name = first.Name,
SupervisorName = dataList.GroupBy(q => q.SupervisorName).Select(w => w.Key).JoinAsString(","),
SupervisedPersonName = dataList.GroupBy(q => q.SupervisedPersonName).Select(w => w.Key)!.JoinAsString(","),
SupervisedPersonfile = dataList.GroupBy(q => q.SupervisedPersonfile).Select(w => w.Key)!.JoinAsString(","),
CreatedTime = first.CreatedTime,
CreatedUserId = first.CreatedUserId,
CreatedUserName = first.CreatedUserName
}).ToList();
//返回结果
return ResultOutput.Ok(new PagedList()
{
TotalCount = totalCount,
Data = rtn
});
}
///
/// 获取当前监管人手里的案件(带数据权限)
///
///
public async Task> GetCaseSuperviseList()
{
var data = await (await GetCurrentUserCaseListAsync())
.Where(w => w.AppCaseManagement.CaseProgress != CaseProgressEnum.Closed)
.ToListAsync();
var dataGroup = data.GroupBy(w => new
{
w.AppCaseManagement!.Id,
w.AppCaseManagement.Name
}).Select(data =>
{
var tempData = data.ToList();
//监管人
var superviseDetailDtos = tempData.Select(w => new CaseSuperviseDetailDto()
{
SupervisedId = w.AppCaseSupervisor.SupervisorId,
SupervisedName = w.AppCaseSupervisor?.SupervisorName,
}).Distinct((x, y) => x.SupervisedId == y.SupervisedId).ToList();
//被监管人
var supervisedPersonDetailDtps = tempData.Where(w => w.AppCaseSupervisedPerson != null).Select(w => new CaseSupervisedPersonDetailDto
{
SupervisedPersonId = w.AppCaseSupervisedPerson.SupervisedPersonId,
SupervisedPersonName = w.AppCaseSupervisedPerson?.SupervisedPersonName,
}).Distinct((x, y) => x.SupervisedPersonId == y.SupervisedPersonId).ToList();
return new CaseSuperviseListDto()
{
CaseId = data.Key.Id,
CaseName = data.Key.Name,
SuperviseDetailDtos = superviseDetailDtos,
SupervisedPersonDetailDtps = supervisedPersonDetailDtps
};
}).ToList();
return dataGroup;
}
///
/// 根据被监管人Id获取相关信息(案件、监管人信息)
///
///
///
public async Task GetSupervisedPersonInfoById(long id)
{
var rtn = new SupervisedPersonInfoDto();
var data = await (await GetCurrentUserCaseListAsync())
.Where(w => w.AppCaseManagement.CaseProgress != CaseProgressEnum.Closed)
.ToListAsync();
var dataGroup = data.Where(w => w.AppCaseSupervisedPerson != null).GroupBy(w => new
{
w.AppCaseSupervisedPerson.SupervisedPersonId,
w.AppCaseSupervisedPerson.SupervisedPersonName
}).ToList();
rtn.SupervisedPersonId = User.Id;
rtn.SupervisedPersonName = User.Name;
rtn.Phone = User.Phone;
rtn.Avatar = User.Avatar;
rtn.NickName = User.NickName;
//所有监管人信息
var spList = await _userService.GetAllByConditionAsync(new BatchIdsInput()
{
Ids = data.Select(w => w.AppCaseSupervisor.SupervisorId).ToList()
});
//循环处理
dataGroup.ForEach(item =>
{
var tempData = item.ToList();
//案件信息
rtn.SpCaseListDtos.AddRange(tempData.Select(w => new SpCaseListDto()
{
CaseId = w.AppCaseManagement.Id,
CaseName = w.AppCaseManagement.Name
}).ToList());
//监管人信息
rtn.SpCaseSpListDtos.AddRange(tempData.Select(w => new SpCaseSpListDto()
{
SupervisedId = w.AppCaseSupervisor.SupervisorId,
SupervisedName = w.AppCaseSupervisor.SupervisorName,
Avatar = spList.FirstOrDefault(s => s.Id == w.AppCaseSupervisor.SupervisorId)?.Avatar,
NickName = spList.FirstOrDefault(s => s.Id == w.AppCaseSupervisor.SupervisorId)?.NickName,
Phone = spList.FirstOrDefault(s => s.Id == w.AppCaseSupervisor.SupervisorId)?.Phone,
}).ToList());
});
//返回结果
return rtn;
}
///
/// 根据当前用户Id(被监管人)获取【监管人】列表
///
///
///
public async Task> GetSuperviseListByUserId(long userId) => await base.GetSuperviseListByUserId(new EditableList()
{
userId
});
///
/// 根据当前登录的用户获取【被监管人】列表 (监控大屏被监管人列表)只查询有经纬度且案件没有结束的人且没有被删除的人
///
///
public async Task GetSupervisedPersonListByCurrentUser()
{
var superviseList = await (await base.GetCurrentUserCaseListAsync())
.Where(w => w.AppCaseManagement.CaseProgress != CaseProgressEnum.Closed)
.Select(w => new SupervisedPersonByUserOutput()
{
SupervisedPersonId = w.AppCaseSupervisedPerson!.SupervisedPersonId,
SupervisedPersonName = w.AppCaseSupervisedPerson.SupervisedPersonName,
CaseId = w.AppCaseManagement!.Id,
CaseName = w.AppCaseManagement.Name,
Gender = w.AppCaseSupervisedPerson.Gender
}).ToListAsync();
//返回列表
return ResultOutput.Ok(superviseList);
}
///
/// 获取所有案件没有结束的被监管人列表()
///
///
///
/// 1、被监管人输入身份证 绑定当前案件 (待执行或执行中)的被监管人数据
/// 2、同一个被监管人 只能绑定同一个设备的1次
///
public async Task GetSupervisedPersonList()
{
var rtn = await (from c in _appCaseManagementRepository.AsQueryable(false, true)
join spr in _appSupervisedPersonRepository.AsQueryable(false, true) on c.Id equals spr.CaseId
//join device in _appDeviceManagementRepository.AsQueryable(false, true) on spr.SupervisedPersonId equals device.SupervisedPersonId into td
//from d in td.DefaultIfEmpty()
//where c.CaseProgress != CaseProgressEnum.Closed && spr.IdCard != null && d == null
where c.CaseProgress != CaseProgressEnum.Closed && spr.IdCard != null
select new SupervisedPersonDto()
{
SupervisedPersonId = spr.SupervisedPersonId,
SupervisedPersonName = spr.SupervisedPersonName,
CaseId = c.Id,
IdCard = spr.IdCard
}).ToListAsync();
//去重
rtn = rtn.Distinct((x, y) => x.SupervisedPersonId == y.SupervisedPersonId).ToList();
return ResultOutput.Ok(rtn);
}
///
/// 根据当前登录的被监管人员获取其正在进行的案件信息
///
///
public async Task GetCaseInfoBySupervisedPersonId(long? userId = null) => await base.GetCaseInfoBySupervisedPersonId(userId);
///
/// 查看当前案件是否还存在待提交或待审核的被监管人员
///
/// 案件Id
///
public async Task> IsExistSupervisedPersonCase(long caseId)
{
var caseDetail = GetCaseSupervisedPersonQuery()
.Where(w =>
w.AppCaseManagement.Id == caseId &&
w.AppCaseSupervisedPerson.ApprovalStatus != ApprovalStatusEnum.PassReview);
return (IResultOutput)ResultOutput.Ok(await caseDetail.AnyAsync());
}
///
/// 一个被监管人待审核状态的列表 用于前端直接点击查看
///
///
///
[HttpPost]
public async Task>> GetSupervisedPersonApprovalStatus(GetSupervisedPersonApprovalStatusPageInput input)
{
var queryable = (await GetCurrentUserCaseListAsync())
.WhereIf(input.SupervisedPersonId > 0, w => w.AppCaseSupervisedPerson.SupervisedPersonId == input.SupervisedPersonId)
.WhereIf(input.ApprovalStatus.HasValue, w => w.AppCaseSupervisedPerson.ApprovalStatus == input.ApprovalStatus)
.WhereIf(input.name.NotNull(), w => w.AppCaseSupervisedPerson.SupervisedPersonName.Contains(input.name));
var caseSpQueryable = await queryable.Where(q => q.AppCaseSupervisedPerson != null).Select(w => Mapper.Map(w.AppCaseSupervisedPerson)).ToListAsync();
if ((await base.IsAdmin()).IsAdmin) caseSpQueryable = caseSpQueryable.Distinct((x, y) => x.CaseId == y.CaseId && x.SupervisedPersonId == y.SupervisedPersonId).ToList();
var totalCount = caseSpQueryable.Count();
var dataList = caseSpQueryable.Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();
dataList.ForEach(item =>
{
item.CaseName = queryable.FirstOrDefault(w => w.AppCaseManagement.Id == item.CaseId)?.AppCaseManagement?.Name;
});
return (IResultOutput>)ResultOutput.Ok(new PagedList()
{
TotalCount = totalCount,
Data = dataList.OrderByDescending(q => q.CreatedTime).ToList()
});
}
///
/// 根据当前登录人获取能看到的Id(监管人、管理员)
///
///
public async Task> GetUserIdListByCurrentUser()
{
var data = await (await base.GetCurrentUserCaseListAsync()).ToListAsync();
var userList = new List();
userList = data.Where(q => q.AppCaseSupervisedPerson != null).Select(w => w.AppCaseSupervisedPerson.SupervisedPersonId)
.Union(data.Select(w => w.AppCaseSupervisor.SupervisorId))
.Union(new List() { User.Id })
.Distinct()
.ToList();
return userList;
}
#region Private
///
/// 查询条件
///
///
///
///
private async Task> GetExpression(AppCaseManagementGetPageInput pageInput, IQueryable query)
{
var caseIds = await (await base.GetCurrentUserCaseListAsync()).Select(w => w.AppCaseManagement.Id).ToListAsync();
query = query
.WhereIf(pageInput.CaseIds.IsNotNullOrEmpty(), w => pageInput.CaseIds.Contains(w.Id))
.WhereIf(pageInput.CaseName.NotNull(), a => a.Name.Contains(pageInput.CaseName))
.WhereIf(pageInput.CaseTypeId != null, a => a.CaseTypeId == pageInput.CaseTypeId)
.WhereIf(pageInput.JudgmentStatusIds.IsNotNullOrEmpty(), w => pageInput.JudgmentStatusIds.Contains(w.JudgmentStatusId))
.WhereIf(pageInput.CaseProgresses.IsNotNullOrEmpty(), w => pageInput.CaseProgresses.Contains(w.CaseProgress))
.WhereIf(pageInput.TimeSearch != null && pageInput.TimeSearch.BeginTime != null && pageInput.TimeSearch.EndTime != null, q => q.CreatedTime >= pageInput.TimeSearch.BeginTime && q.CreatedTime <= $"{pageInput.TimeSearch.EndTime.Value.ToString("yyyy-MM-dd")} 23:59:59".ToDateTime());
var express = base.GetWithOutStatusExpression(pageInput, query);
return express;
}
///
/// 校验被监管人信息 ,通过身份证号 和手机号
///
///
///
private async Task ValidSupervisedPerson(AppCaseManagementCreateOrModifyInput input)
{
var validMsg = string.Empty;
if (input.SupervisedPersonGetDtos!.Any(w => w.Name.IsNull() || w.Phone.IsNull() || w.IdCard.IsNull())) validMsg = "被监管人姓名,手机号或者身份证不能为空!";
if (validMsg.NotNull()) return ResultOutput.NotOk(validMsg);
//校验身份证、手机号不能重复
if (input.SupervisedPersonGetDtos!.GroupBy(w => w.IdCard).Any(w => w.Count() > 1)) validMsg = "身份证重复";
if (input.SupervisedPersonGetDtos!.GroupBy(w => w.Phone).Any(w => w.Count() > 1)) validMsg = "手机号重复";
var spList = (from ca in _appCaseManagementRepository.AsQueryable(false, true)
join sp in _appSupervisedPersonRepository.AsQueryable(false, true) on ca.Id equals sp.CaseId
select new
{
ca,
sp
});
//一个人只能存在一个正在进行中的案件 (根据身份证)
foreach (var personGetDto in input.SupervisedPersonGetDtos!)
{
if (spList.Any(w => w.sp.Id != personGetDto.Id && w.sp.IdCard == personGetDto.IdCard && w.ca.CaseProgress != CaseProgressEnum.Closed))
{
validMsg = $"{personGetDto.SupervisedPersonName}的身份证{personGetDto.IdCard}存在一个没结束的案件";
break;
}
}
return validMsg.NotNull() ? ResultOutput.NotOk(validMsg) : ResultOutput.Ok();
}
///
/// 校验被监管人电子围栏名称
///
///
///
private async Task ValidSpCommonFence(AppCaseManagementCreateOrModifyInput input)
{
var validMsg = string.Empty;
var commName = input.SupervisedPersonGetDtos.Where(w => w.CommonFenceAddInput != null).Select(w => w.CommonFenceAddInput.Name).ToList();
var commFenceList = await _appCommonFenceRepository.AsQueryable(false, true)
.Where(w => commName.Contains(w.Name))
.ToListAsync();
foreach (var fence in commFenceList)
{
validMsg = $"电子围栏名称为:{fence.Name}已存在!";
break;
}
return validMsg.NotNull()
? ResultOutput.NotOk(validMsg)
: ResultOutput.Ok();
}
#endregion Private
#region 新增涉嫌人员接口
///
/// 查询被监管人员信息---列表
///
///
///
[HttpPost]
public async Task GetSupervisedPersonAsync(GetSupervisedPersonPage input)
{
var limits = User.limits;
var selectLimits = await _appCaseSupervisorRepository.AsQueryable(false, true)
.Where(w => limits.Contains(w.UnitId.ToString()))
.ToListAsync();
var caseIds = selectLimits.Select(w => w.CaseId).Distinct().ToList();
//var caseIds = await (await base.GetCurrentUserCaseListAsync()).Select(w => w.AppCaseManagement.Id).ToListAsync();
var caselist = await (await base.GetCurrentUserCaseListAsync()).Select(w => new { w.AppCaseManagement.Id, w.AppCaseManagement.Name }).ToListAsync();
//查询待执行,执行种案件涉嫌人员 去除状态筛选,与导出接口一致
//var appSupervisedlist = from a in base._appCaseManagementRepository.AsQueryable(false, true).Where(q => q.CaseProgress != CaseProgressEnum.Closed)
// join b in _appSupervisedPersonRepository.AsQueryable(false, true) on a.Id equals b.CaseId
// select b;
var appSupervisedlist = from a in base._appCaseManagementRepository.AsQueryable(false, true)
join b in _appSupervisedPersonRepository.AsQueryable(false, true) on a.Id equals b.CaseId
select b;
var data = await appSupervisedlist
.Where(q => caseIds.Contains(q.CaseId))
.WhereIf(input.TimeSearch?.BeginTime != null && input.TimeSearch?.EndTime != null, q => q.CreatedTime >= input.TimeSearch.BeginTime && q.CreatedTime <= $"{input.TimeSearch.EndTime.Value.ToString("yyyy-MM-dd")} 23:59:59".ToDateTime())
.WhereIf(input.name.NotNull(), q => q.SupervisedPersonName.Contains(input.name))
.OrderByDescending(r => r.CreatedTime)
.ProjectTo(Mapper.ConfigurationProvider)
.PagedAsync(input)
.ConfigureAwait(false);
return ResultOutput.Ok(new { data, caselist });
}
///
/// 添加修改被监管人
///
///
///
public async Task AddSupervisedPersonAsync(AppCaseManagementCreateOrModifyInput input)
{
//校验案件被监管人
var validSpCase = await ValidSupervisedPerson(input);
if (!validSpCase.Success) return validSpCase;
//案件Id
var caseId = input.Id;
Uow.BeginTransaction();
//不存在的被监管人
var roles = (await _roleService.GetRoleByKeyword("supervisedPerson")).FirstOrDefault();
//被监管人职位字典
var supervisedPersonPosition = await base.GetDictionariesOutput("job_position", "supervisedperson");
//被监管人员
var supervisedPersonList = Mapper.Map, List>(input.SupervisedPersonGetDtos);
supervisedPersonList.ForEach(item =>
{
item.Id = YitIdHelper.NextId();
item.CaseId = caseId!.Value;
});
#region [1]如果用户不存在就添加到用户表中(根据身份证来判断)
List addUsers = new();
List updateAppUsers = new();
foreach (var item in supervisedPersonList)
{
var tempUser = await _appUserRepository.FindAsync(w => w.IdCard == item.IdCard);
//存在就修改名字和手机号
if (tempUser != null)
{
tempUser.UserName = tempUser.Name = item.SupervisedPersonName;
tempUser.Phone = item.Phone;
}
else
{
addUsers.Add(new SupervisedPersonAddInput()
{
UserName = item.SupervisedPersonName,
Name = item.SupervisedPersonName,
Password = "Mr@123456",
Phone = item.Phone,
RoleIds = new[] { roles!.Id },
DataStatus = DataStatusEnum.Normal,
PositionId = supervisedPersonPosition?.Id,
PositionName = supervisedPersonPosition?.Name,
RoleName = roles.Name,
IdCard = item.IdCard,
Id = YitIdHelper.NextId()
});
}
}
if (addUsers.Any()) await _userService.BatchAddAsync(addUsers);
if (updateAppUsers.Any()) await _userService.BatchUpdateAsync(updateAppUsers);
var userIds = addUsers.Select(w => w.Id).Union(updateAppUsers.Select(w => w.Id)).Distinct();
//所有用户
var allUsers = await _appUserRepository.Where(w => userIds.Contains(w.Id)).ToListAsync();
foreach (var person in supervisedPersonList)
{
//根据身份证号来确定唯一
var tempUser = allUsers.FirstOrDefault(w => w.IdCard == person.IdCard);
if (tempUser == null)
tempUser = await _appUserRepository.FindAsync(w => w.IdCard == person.IdCard);
if (tempUser == null) continue;
person.SupervisedPersonId = tempUser.Id;
person.SupervisedPersonName = tempUser.UserName;
person.Phone = tempUser.Phone;
}
#endregion [1]如果用户不存在就添加到用户表中(根据身份证来判断)
#region 被监管人电子围栏
{
var spIds = supervisedPersonList
.Where(w => w.ElectricFenceId == 0)
.Select(w => w.SupervisedPersonId)
.ToList();
//只有是设置得才添加
if (spIds.Any())
{
//先删除
await _appCommonFenceRepository.DeleteAsync(w =>
w.CaseId == caseId && w.CommonFenceType == CommonFenceTypeEnum.SupervisedPerson &&
spIds.Contains(w.SupervisedPersonId.Value));
var adCfList = input.SupervisedPersonGetDtos
.Select(w => new AppCommonFence(YitIdHelper.NextId())
{
CaseId = caseId,
SupervisedPersonId = w.SupervisedPersonId,
SupervisedPersonName = w.SupervisedPersonName,
CommonFenceType = CommonFenceTypeEnum.SupervisedPerson,
Name = w.CommonFenceAddInput?.Name,
Path = w.CommonFenceAddInput?.Path
});
if (adCfList.Any())
{
var addedCfList = await _appCommonFenceRepository.InsertAsync(adCfList);
foreach (var item in supervisedPersonList)
{
var tempCommonFence = addedCfList.FirstOrDefault(w =>
w.CaseId == caseId &&
w.CommonFenceType == CommonFenceTypeEnum.SupervisedPerson &&
w.SupervisedPersonId == item.SupervisedPersonId);
//说明是常用围栏
if (tempCommonFence == null) continue;
item.ElectricFenceId = tempCommonFence?.Id;
item.ElectricFenceName = tempCommonFence?.Name;
}
}
}
}
#endregion 被监管人电子围栏
//案子被监管人中间表
var sprIds = supervisedPersonList.Select(w => w.SupervisedPersonId).ToList();
//当前案件所有已经存在的被监管人
var sprList = await _appSupervisedPersonRepository.AsQueryable(false, true)
.Where(w => w.CaseId == caseId && sprIds.Contains(w.SupervisedPersonId)).ToListAsync();
//删除当前
await _appSupervisedPersonRepository.DeleteAsync(w => sprIds.Contains(w.SupervisedPersonId));
//防止漏网之鱼
foreach (var person in supervisedPersonList)
{
if (person.SupervisedPersonId == default)
{
var temUser = allUsers.FirstOrDefault(w => w.IdCard == person.IdCard);
if (temUser == null) continue;
person.SupervisedPersonId = temUser!.Id;
person.SupervisedPersonName = temUser.UserName;
}
else
{
var tempSp = sprList.FirstOrDefault(w => w.IdCard == person.IdCard);
if (tempSp == null) continue;
//把已经存在的数据全部赋值上(案件只能修改名字、身份证、手机号)
person.ApprovalStatus = tempSp!.ApprovalStatus;
person.IsBound = tempSp.IsBound;
person.WarningGradeId = tempSp.WarningGradeId;
person.EnterFace = tempSp.EnterFace;
person.IMEI = tempSp.IMEI;
}
}
//添加被监管人
await _appSupervisedPersonRepository.InsertAsync(supervisedPersonList);
await Uow.CommitAsync();
//返回结果
return ResultOutput.Ok();
}
///
/// 查询被监管人----id
///
///
///
public async Task GetSupervised(long id)
{
var caseDto = await _appSupervisedPersonRepository.AsQueryable(false, true)
.Where(w => w.SupervisedPersonId == id)
.OrderBy(W => W.Id)
.ProjectTo(Mapper.ConfigurationProvider).ToListAsync();
//返回结果
return ResultOutput.Ok(caseDto);
}
#endregion
#region 新增案件导入接口
///
/// 案件导入预览
///
///
///
[HttpPut]
public async Task BatchHandlefile([FromForm] IFormFile file)
{
var datalist = ExcelHelper.GetList(file, 0);
//返回结果
return ResultOutput.Ok(datalist);
}
///
/// 案件导入保存
///
///
///
public async Task Getfilesava(List inputlist)
{
var mag = "";//已存在数据库的案件部门受案号提示
var datalist = new List();//案件信息集合
var Supervisorlist = new List();//案件监管人信息集合
var list = Mapper.Map, List>(inputlist);
foreach (var item in list)
{
//校验案子
var caseValid = await base.Valid(item, _appCaseManagementRepository, w =>
{
w = w.AndNotNull(w => w.Bmsah == item.Bmsah, item.Bmsah.IsNotNullOrEmpty());
return (w, $"{item.Bmsah}");
});
if (!caseValid.Success)
{
mag += $"{caseValid.Msg},";
continue;
}
else
{
item.Id = YitIdHelper.NextId();
}
//案子监管管理人员(Bug:当我修改监管人后,已审核过的被监管人需要重新申请,被切换的监管人没有对应数据)
if (item.SupervisorIds!.Any())
{
var sList = item.SupervisorIds!.Select(csp => new AppCaseSupervisor(YitIdHelper.NextId())
{
CaseId = (long)item.Id,
SupervisorId = csp.SupervisedId,
SupervisorName = csp.SupervisedName
});
await _appCaseSupervisorRepository.DeleteAsync(w => w.CaseId == item.Id);
Supervisorlist.AddRange(sList);
}
datalist.AddRange(item);
}
Uow.BeginTransaction();
if (datalist.Any())
{
var entity = Mapper.Map>(datalist);
await _appCaseManagementRepository.InsertAsync(entity);
await _appCaseSupervisorRepository.InsertAsync(Supervisorlist);
}
await Uow.CommitAsync();
//返回结果
if (string.IsNullOrEmpty(mag))
return ResultOutput.Ok("", "保存成功");
else return datalist.Count == 0
? ResultOutput.Ok("", $"案件已存在,重复案件的部门受案号为:{mag.Trim(',')}")
: ResultOutput.Ok("", $"保存成功,重复案件的部门受案号为:{mag.Trim(',')}");
}
///
/// 案件导出
///
///
///
public async Task Getexport(AppCaseManagementGetPageInput input)
{
input.PageIndex = 1;
input.PageSize = 999999;
var limits = User.limits;
var selectLimits = await _appCaseSupervisorRepository.AsQueryable(false, true)
.Where(w => limits.Contains(w.UnitId.ToString()))
.ToListAsync();
input.CaseIds = selectLimits.Select(w => w.CaseId).Distinct().ToList();
var express = await GetExpression(input, _appCaseManagementRepository.AsQueryable(false, true));
var rtn = await base.GetPageAsync(input, express);
//var caseIds = rtn.Data.Select(w => w.Id).ToList();
var caseSupervisor = await _appCaseSupervisorRepository.AsQueryable(false, true)
.Where(w => input.CaseIds.Contains(w.CaseId))
.ToListAsync();
foreach (var listDto in rtn.Data)
{
var judgmentlist = await base.GetDictionariesOutput1("judgment", "");
var type_caselist = await base.GetDictionariesOutput1("type_case", "");
listDto.CaseTypename = type_caselist.Where(w => w.Id == listDto.CaseTypeId).Select(w => w.Name).JoinAsString(",");
listDto.JudgmentStatusname = judgmentlist.Where(w => w.Id == listDto.JudgmentStatusId).Select(w => w.Name).JoinAsString(",");
listDto.Supervisor = caseSupervisor.Where(w => w.CaseId == listDto.Id).Select(w => w.SupervisorName).JoinAsString(",");
}
var list = new List();
list.AddRange(rtn.Data);
var memorySystem = ExcelHelper.ToExcel(list);
return new Controller().File(memorySystem.ToArray(), "application/ms-excel", $"{DateTime.Now.ToString("f")}.xlsx");
}
///
/// 案件涉案人员导出
///
///
///
public async Task Getuserexport(GetSupervisedPersonPage input)
{
input.PageIndex = 1;
input.PageSize = 999999;
var limits = User.limits;
var selectLimits = await _appCaseSupervisorRepository.AsQueryable(false, true)
.Where(w => limits.Contains(w.UnitId.ToString()))
.ToListAsync();
var caseIds = selectLimits.Select(w => w.CaseId).Distinct().ToList();
//var caseIds = await (await base.GetCurrentUserCaseListAsync()).Select(w => w.AppCaseManagement.Id).ToListAsync();
var caselist = await (await base.GetCurrentUserCaseListAsync()).Select(w => new { w.AppCaseManagement.Id, w.AppCaseManagement.Name }).ToListAsync();
var data = await _appSupervisedPersonRepository.AsQueryable(false, true)
.Where(q => caseIds.Contains(q.CaseId))
.WhereIf(input.name.NotNull(), q => q.SupervisedPersonName.Contains(input.name))
.OrderByDescending(r => r.CreatedTime)
.ProjectTo(Mapper.ConfigurationProvider)
.PagedAsync(input)
.ConfigureAwait(false);
foreach (var listDto in data.Data)
{
//var judgmentlist = await base.GetDictionariesOutput1("judgment", "");
//var type_caselist = await base.GetDictionariesOutput1("type_case", "");
listDto.Casename = caselist.Where(q => q.Id == listDto.CaseId).Select(q => q.Name).JoinAsString(",");
//listDto.CaseTypename = type_caselist.Where(w => w.Id == listDto.CaseTypeId).Select(w => w.Name).JoinAsString(",");
//listDto.JudgmentStatusname = judgmentlist.Where(w => w.Id == listDto.JudgmentStatusId).Select(w => w.Name).JoinAsString(",");
//listDto.Supervisor = caseSupervisor.Where(w => w.CaseId == listDto.Id).Select(w => w.SupervisorName).JoinAsString(",");
}
var list = new List();
list.AddRange(data.Data);
var memorySystem = ExcelHelper.ToExcel(list);
return new Controller().File(memorySystem.ToArray(), "application/ms-excel", $"{DateTime.Now.ToString("f")}.xlsx");
}
#endregion
}
public class Controller : ControllerBase
{
}
}