using CMS.Plugin.PipeLineLems.Application.Contracts.Dtos.CallMaterialOrder;
using CMS.Plugin.PipeLineLems.Application.Contracts.Services;
using CMS.Plugin.PipeLineLems.Domain.Shared;
using CmsQueryExtensions;
using CMS.Plugin.PipeLineLems.Domain.CallMaterialOrder;
using CmsQueryExtensions.Extension;
using System.Linq.Expressions;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Data;
using Volo.Abp.ObjectExtending;
using Volo.Abp.ObjectMapping;
using CmsQueryExtensions.Entitys;
namespace CMS.Plugin.PipeLineLems.Application.Implements;
///
/// 叫料单表应用服务
///
public class CallMaterialOrderAppService : CMSPluginAppService, ICallMaterialOrderAppService
{
private readonly ICallMaterialOrderRepository _callMaterialOrderRepository;
///
/// Initializes a new instance of the class.
///
/// The task job repository.
public CallMaterialOrderAppService(ICallMaterialOrderRepository callMaterialOrderRepository)
{
_callMaterialOrderRepository = callMaterialOrderRepository;
}
///
/// 获取指定叫料单表
///
///
///
public virtual async Task GetAsync(Guid id)
{
return ObjectMapper.Map(await _callMaterialOrderRepository.GetAsync(id));
}
///
/// 分页获取叫料单表
///
///
///
public virtual async Task> GetListAsync(GetCallMaterialOrderInput input)
{
Check.NotNull(input, nameof(input));
if (input.Sorting.IsNullOrWhiteSpace())
{
input.Sorting = nameof(CallMaterialOrder.Sort);
}
#region 动态构造查询条件
//动态构造查询条件
var whereConditions = DynamicGetQueryParams(input);
#endregion
var count = await _callMaterialOrderRepository.GetCountAsync(whereConditions);
var list = await _callMaterialOrderRepository.GetListAsync(whereConditions, input.Sorting, input.MaxResultCount, input.SkipCount);
return new PagedResultDto(count, ObjectMapper.Map, List>(list));
}
///
/// 动态构造查询条件
///
/// 输入参数
///
private FunReturnResultModel>> DynamicGetQueryParams(GetCallMaterialOrderInput input)
{
//动态构造查询条件
var whereConditions = WhereConditionsExtensions.GetWhereConditions(input);
if (!whereConditions.IsSuccess)
{
throw new Exception("动态构造查询条件失败:" + whereConditions.ErrMsg);
}
//也可再次自定义构建查询条件
Expression> extendExpression = a => a.IsDeleted == false;
// 使用 System.Linq.PredicateBuilder 的 And
var pres = (System.Linq.Expressions.Expression>)(whereConditions.data);
whereConditions.data = System.Linq.PredicateBuilder.And(pres, extendExpression);
return whereConditions;
}
///
/// 新建叫料单表
///
///
///
///
public virtual async Task CreateAsync(CallMaterialOrderCreateDto input)
{
await CheckCreateOrUpdateDtoAsync(input);
var exist = await _callMaterialOrderRepository.NameExistAsync(input.DataIdentifier);
if (exist)
{
throw new UserFriendlyException(L[CMSPluginDomainErrorCodes.NameAlreadyExists, input.DataIdentifier]);
}
var maxSort = await _callMaterialOrderRepository.GetMaxSortAsync();
var sort = input.Sort ?? maxSort;
var insertObj = ObjectMapper.Map(input);
insertObj.Sort = sort;
input.MapExtraPropertiesTo(insertObj, MappingPropertyDefinitionChecks.None);
insertObj.CreatorName = input.CreatorName;//创建人
await _callMaterialOrderRepository.InsertAsync(insertObj);
//if (input.Sort.HasValue && insertObj.Sort != maxSort)
//{
// await AdjustSortAsync(insertObj.Id, insertObj.Sort);
//}
return ObjectMapper.Map(insertObj);
}
///
/// 更新叫料单表
///
///
///
///
///
public virtual async Task UpdateAsync(Guid id, CallMaterialOrderUpdateDto input)
{
await CheckCreateOrUpdateDtoAsync(input);
var updateObj = await _callMaterialOrderRepository.GetAsync(id);
var exist = await _callMaterialOrderRepository.NameExistAsync(input.DataIdentifier, updateObj.Id);
if (exist)
{
throw new UserFriendlyException(L[CMSPluginDomainErrorCodes.NameAlreadyExists, input.DataIdentifier]);
}
updateObj.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp);
input.MapExtraPropertiesTo(updateObj, MappingPropertyDefinitionChecks.None);
updateObj.DataIdentifier = input.DataIdentifier;
updateObj.MaterialMode = input.MaterialMode;
updateObj.MaterialBatch = input.MaterialBatch;
updateObj.CallMaterialStatus = input.CallMaterialStatus;
updateObj.Quantity = input.Quantity;
updateObj.WmsRetResult = input.WmsRetResult;
updateObj.WmsTaskNo = input.WmsTaskNo;
updateObj.Remark = input.Remark;
updateObj.LastModifierName = input.LastModifierName;//修改人
await _callMaterialOrderRepository.UpdateAsync(updateObj);
return ObjectMapper.Map(updateObj);
}
///
/// 克隆叫料单表
///
///
///
public async Task> CloneAsync(IEnumerable ids, MyCurrentUser myCurrentUser)
{
//var callMaterialOrders = new List();
//if (ids != null)
//{
// var sort = await _callMaterialOrderRepository.GetMaxSortAsync();
// foreach (var id in ids)
// {
// var CallMaterialOrder = await _callMaterialOrderRepository.FindAsync(id);
// if (CallMaterialOrder != null)
// {
// var name = CallMaterialOrder.Name + CallMaterialOrderConsts.CloneTag;
// var notExist = false;
// while (!notExist)
// {
// var exist = await _callMaterialOrderRepository.NameExistAsync(name);
// if (exist || callMaterialOrders.Any(x => x.Name == name))
// {
// name += CallMaterialOrderConsts.CloneTag;
// continue;
// }
// notExist = true;
// }
// //CallMaterialOrder = await _callMaterialOrderRepository.InsertAsync(CallMaterialOrder.Clone(GuidGenerator.Create(), name, sort++));
// callMaterialOrders.Add(CallMaterialOrder);
// }
// }
//}
//return ObjectMapper.Map, List>(callMaterialOrders);
return new List();
}
///
/// 删除单个叫料单表
///
///
///
public virtual Task DeleteAsync(Guid id)
{
return _callMaterialOrderRepository.DeleteAsync(id);
}
///
/// 删除多个叫料单表
///
///
///
public async Task DeleteManyAsync(IEnumerable ids, MyCurrentUser myCurrentUser)
{
foreach (var id in ids)
{
await DeleteAsync(id);
}
}
///
/// 物理删除叫料单表
///
/// 主键ID
///
///
public virtual async Task DeletePermanentlyAsync(Guid id, MyCurrentUser myCurrentUser, CancellationToken cancellationToken = default)
{
_callMaterialOrderRepository.DeletePermanentlyAsync(id);
}
///
/// 批量物理删除叫料单表(直接删除,不软删除)
///
/// 要删除的主键ID列表
///
///
public virtual async Task BatchDeletePermanentlyAsync(IEnumerable ids, MyCurrentUser myCurrentUser, CancellationToken cancellationToken = default)
{
_callMaterialOrderRepository.BatchDeletePermanentlyAsync(ids);
}
///
/// 调整排序叫料单表
///
///
///
///
public virtual async Task AdjustSortAsync(Guid id, int sort)
{
var list = await _callMaterialOrderRepository.GetListAsync(null, nameof(CallMaterialOrder.Sort));
if (list != null && list.Any())
{
var initSort = 1;
list.ForEach(x => x.AdjustSort(initSort++));
var entity = list.FirstOrDefault(x => x.Id == id);
if (entity != null)
{
if (sort == 1)
{
list.Where(x => x.Id != id).ToList()?.ForEach(x => x.AdjustSort(x.Sort + 1));
}
else if (entity.Sort > sort)
{
list.Where(x => x.Id != id && x.Sort >= sort).ToList()?.ForEach(x => x.AdjustSort(x.Sort + 1));
list.Where(x => x.Id != id && x.Sort < sort).ToList()?.ForEach(x => x.AdjustSort(x.Sort - 1));
}
else if (entity.Sort < sort)
{
list.Where(x => x.Id != id && x.Sort > sort).ToList()?.ForEach(x => x.AdjustSort(x.Sort + 1));
list.Where(x => x.Id != id && x.Sort <= sort).ToList()?.ForEach(x => x.AdjustSort(x.Sort - 1));
}
entity.AdjustSort(sort);
}
}
await _callMaterialOrderRepository.UpdateManyAsync(list);
}
///
/// 导入叫料单表
///
///
///
///
public async Task ImportAsync(CallMaterialOrdersImportModel input, MyCurrentUser myCurrentUser)
{
Check.NotNull(input, nameof(input));
var callMaterialOrderCreateDtos = new List<(int RowIndex, CallMaterialOrderCreateDto Item)>();
var callMaterialOrderUpdateDtos = new List<(int RowIndex, Guid Id, CallMaterialOrderUpdateDto Item)>();
var importItems = input.CallMaterialOrders;
if (importItems != null && importItems.Any())
{
#region 导入校验
// 判断名称是否重复,并输出第几行重复
var duplicateCallMaterialOrders = importItems.GroupBy(x => x.DataIdentifier).Where(x => x.Count() > 1).ToList();
if (duplicateCallMaterialOrders?.Any() == true)
{
var duplicateCallMaterialOrderMsgs = duplicateCallMaterialOrders.Select(x => $"第 {string.Join(",", x.Select(x => x.RowIndex))} 行:{x.Key} 名称重复");
var errorMsg = $"导入失败!配置, {string.Join(",", duplicateCallMaterialOrderMsgs)},终止导入";
throw new UserFriendlyException(errorMsg);
}
#endregion
foreach (var impItem in importItems)
{
if (impItem.DataIdentifier.IsNullOrWhiteSpace())
{
continue;
}
if (impItem.DataIdentifier.IsNullOrWhiteSpace())
{
var errorMsg = $"导入失败!配置,第{impItem.RowIndex}行:CallMaterialOrder名称不能为空";
throw new UserFriendlyException(errorMsg);
}
var oldCallMaterialOrder = await _callMaterialOrderRepository.FindByNameAsync(impItem.DataIdentifier);
if (oldCallMaterialOrder != null)
{
var callMaterialOrderUpdateDto = new CallMaterialOrderUpdateDto
{
DataIdentifier = impItem.DataIdentifier,
MaterialMode = impItem.MaterialMode,
MaterialBatch = impItem.MaterialBatch,
CallMaterialStatus = impItem.CallMaterialStatus,
Quantity = impItem.Quantity,
WmsRetResult = impItem.WmsRetResult,
WmsTaskNo = impItem.WmsTaskNo,
Remark = impItem.Remark,
};
callMaterialOrderUpdateDtos.Add((impItem.RowIndex, oldCallMaterialOrder.Id, callMaterialOrderUpdateDto));
}
else
{
var callMaterialOrderCreateDto = new CallMaterialOrderCreateDto
{
DataIdentifier = impItem.DataIdentifier,
MaterialMode = impItem.MaterialMode,
MaterialBatch = impItem.MaterialBatch,
CallMaterialStatus = impItem.CallMaterialStatus,
Quantity = impItem.Quantity,
WmsRetResult = impItem.WmsRetResult,
WmsTaskNo = impItem.WmsTaskNo,
Remark = impItem.Remark,
};
callMaterialOrderCreateDtos.Add((impItem.RowIndex, callMaterialOrderCreateDto));
}
}
}
// 新增
foreach (var callMaterialOrderDto in callMaterialOrderCreateDtos)
{
try
{
callMaterialOrderDto.Item.CreatorName = myCurrentUser.UserAccount;//创建人
await CreateAsync(callMaterialOrderDto.Item);
}
catch (Exception e)
{
var errorMsg = $"导入失败!配置,第{callMaterialOrderDto.RowIndex}行:{e.Message},终止导入";
throw new UserFriendlyException(errorMsg);
}
}
// 更新
foreach (var callMaterialOrderDto in callMaterialOrderUpdateDtos)
{
try
{
callMaterialOrderDto.Item.LastModifierName = myCurrentUser.UserAccount;//修改人
await UpdateAsync(callMaterialOrderDto.Id, callMaterialOrderDto.Item);
}
catch (Exception e)
{
var errorMsg = $"导入失败!配置,第{callMaterialOrderDto.RowIndex}行:{e.Message},终止导入";
throw new UserFriendlyException(errorMsg);
}
}
}
///
/// 导出叫料单表
///
///
///
public async Task<(Dictionary Sheets, string FileName)> ExportAsync(GetCallMaterialOrderInput input)
{
Check.NotNull(input, nameof(input));
if (input.Sorting.IsNullOrWhiteSpace())
{
input.Sorting = nameof(CallMaterialOrder.Sort);
}
#region 动态构造查询条件
//动态构造查询条件
var whereConditions = DynamicGetQueryParams(input);
#endregion
var list = await _callMaterialOrderRepository.GetListAsync(whereConditions, input.Sorting, input.MaxResultCount, input.SkipCount, includeDetails: true);
var result = ObjectMapper.Map, List>(list);
var sheets = new Dictionary
{
["配置"] = ExportHelper.ConvertListToExportData(result),
};
var fileName = "叫料单";
return (sheets, fileName);
}
///
/// 校验叫料单表,当新建或更新时
///
///
///
protected Task CheckCreateOrUpdateDtoAsync(CallMaterialOrderCreateOrUpdateDtoBase input)
{
Check.NotNull(input, nameof(input));
Check.NotNullOrWhiteSpace(input.DataIdentifier, "原料标识", 256);
Check.NotNull(input.CallMaterialStatus, "叫料状态");
Check.NotNull(input.Quantity, "叫料数量");
return Task.CompletedTask;
}
///
/// 根据条件获取叫料单表列表
///
///
///
///
public async Task> GetListByFilterAsync(Expression> whereConditions, CancellationToken cancellationToken = default)
{
return await _callMaterialOrderRepository.GetListByFilterAsync(whereConditions);
}
///
/// 根据条件获取单个叫料单表
///
///
/// 是否查询出多条就报错
///
///
///
public async Task GetSingleByFilterAsync(Expression> whereConditions, bool isMultipleThrowException = false, CancellationToken cancellationToken = default)
{
return await _callMaterialOrderRepository.GetSingleByFilterAsync(whereConditions, isMultipleThrowException);
}
}