You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

211 lines
8.2 KiB

2 years ago
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NUglify.Helpers;
using Volo.Abp.Caching;
using Win_in.Sfs.Basedata.Application.Contracts;
using Win_in.Sfs.Basedata.Domain;
using Win_in.Sfs.Basedata.Domain.Shared;
namespace Win_in.Sfs.Basedata.Application;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
2 years ago
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Office2010.ExcelAc;
2 years ago
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Volo.Abp;
using Volo.Abp.Domain.Entities;
2 years ago
using Volo.Abp.Domain.Repositories;
using Win_in.Sfs.Shared;
using Win_in.Sfs.Shared.Application.Contracts;
using Win_in.Sfs.Shared.Domain;
2 years ago
[Authorize]
[Route($"{BasedataConsts.RootPath}dict")]
public class DictAppService : SfsBaseDataWithCodeAppServiceBase<Dict, DictDTO, SfsBaseDataRequestInputBase, DictEditInput, DictImportInput>, IDictAppService
{
private readonly IDictManager _dictManager;
private new readonly IDictRepository _repository;
public DictAppService(IDictRepository repository, IDistributedCache<DictDTO> cache, IDictManager dictManager) : base(repository, cache)
{
_repository = repository;
this._dictManager = dictManager;
// base.CreatePolicyName = DictPermissions.Create;
// base.UpdatePolicyName = DictPermissions.Update;
// base.DeletePolicyName = DictPermissions.Delete;
}
[HttpPost]
[Route("")]
public override async Task<DictDTO> CreateAsync(DictEditInput input)
{
var entity = ObjectMapper.Map<DictEditInput, Dict>(input);
entity.SetId(Guid.NewGuid());
entity.Items.ForEach(item =>
{
item.MasterId = entity.Id;
});
entity = await _repository.InsertAsync(entity).ConfigureAwait(false);
return ObjectMapper.Map<Dict, DictDTO>(entity);
}
[HttpPut]
[Route("{id}")]
public override async Task<DictDTO> UpdateAsync(Guid id, DictEditInput input)
2 years ago
{
//return await base.UpdateAsync(id, input).ConfigureAwait(false); //lyf at 0621, 更新报错所以注释
var entity = await _repository.GetAsync(id).ConfigureAwait(false);
if (entity == null)
{
throw new UserFriendlyException($"根据Id取字典表为空:{id}");
}
ObjectMapper.Map<DictEditInput, Dict>(input, entity);
await _repository.UpdateAsync(entity, true).ConfigureAwait(false);
return ObjectMapper.Map<Dict, DictDTO>(entity);
2 years ago
}
[HttpPost("update")]
public virtual async Task UpdateAsync(DictEditInput input)
{
var entity = ObjectMapper.Map<DictEditInput, Dict>(input);
//var dic=await _repository.GetAsync(r => r.Code == entity.Code);
// if (dic != null)
// {
// await _repository.DeleteAsync(dic);
// }
// await _repository.InsertAsync(entity);
await _repository.UpdateAsync(entity).ConfigureAwait(false);
}
protected override async Task<DictDTO> GetFromRepositoryAsync(string code)
{
var displayName = typeof(DictDTO).GetNameOfDisplay();
var query = await _repository.WithDetailsAsync().ConfigureAwait(false);
var entity = await query.Where(p => p.Code == code).FirstOrDefaultAsync().ConfigureAwait(false);
return ObjectMapper.Map<Dict, DictDTO>(entity);
}
/// <summary>
/// 导入数据具体实现,可重写
/// </summary>
protected override async Task<SfsImportResult> ImportInternalAsync(SfsImportRequestInput requestInput, byte[] inputFileBytes)
{
IList<DictImportInput> modelList = null;
var modelDict = new Dictionary<DictImportInput, List<ValidationResult>>();
var entityDict = new Dictionary<Dict, EntityState>();
try
{
var hasDetails = typeof(Dict).GetInterfaces().Any(o => o.IsGenericType && o.GetGenericTypeDefinition() == typeof(IMasterEntity<>));
modelDict = ExportImportService.ImportHaveValidationResult<DictImportInput>(inputFileBytes);
foreach (var modelDictItem in modelDict)
{
// DataAnnotations 静态验证
var validationRresults = modelDictItem.Value;
var model = modelDictItem.Key;
Validator.TryValidateObject(model, new ValidationContext(model, null, null), validationRresults);
}
modelList = modelDict.Keys.ToList();
// 如果没有验证错误或允许部分导入
if (!modelDict.SelectMany(o => o.Value).Any() || requestInput.IsAllowPartImport)
{
var dictCodes = modelList.Select(p => p.Code).Distinct().ToList();
foreach (var detail in dictCodes)
{
var dictDetail = modelList.FirstOrDefault(p => p.Code == detail);
Dict dictItem = new Dict();
dictItem.SetId(GuidGenerator.Create());
dictItem.Code = dictDetail.Code;
dictItem.Name = dictDetail.Name;
dictItem.Description = dictDetail.Description;
foreach (var item in modelList.Where(p=>p.Code==detail))
{
DictItem dictItemDetail = new DictItem();
dictItemDetail.SetId(GuidGenerator.Create());
dictItemDetail.Code = item.Item_Code;
dictItemDetail.Name = item.Item_Name;
dictItemDetail.Value = item.Item_Value;
dictItemDetail.Description = item.Item_Description;
dictItemDetail.Enabled = true;
dictItemDetail.MasterId = dictItem.Id;
dictItem.Items.Add(dictItemDetail);
}
await _repository.InsertAsync(dictItem).ConfigureAwait(false);
}
}
// 创建导入报告
var reportFile = ExportImportService.GetImportReport(inputFileBytes, modelDict);
// 创建返回值
return new SfsImportResult
{
TotalNum = modelList.Count,
ErrorNum = modelDict.Count(o => o.Value.Any()),
FileName = reportFile.FileDownloadName,
FileContents = reportFile.FileContents
};
}
catch (Exception ex)
{
Console.WriteLine("---------------------------------");
Console.WriteLine($"####导入验证错误:");
Console.WriteLine($"{ex.Message}");
Console.WriteLine("---------------------------------");
Logger.LogException(ex);
if (modelList != null)
{
try
{
foreach (var item in modelDict)
{
var model = item.Key;
var validationRresults = item.Value;
validationRresults.Add(new ValidationResult($"无法添加,{ex.Message}", new string[] { "异常" }));
}
// 创建导入报告
var reportFile = ExportImportService.GetImportReport(inputFileBytes, modelDict);
return new SfsImportResult
{
TotalNum = modelList.Count,
ErrorNum = modelDict.Count(o => o.Value.Any()),
FileName = reportFile.FileDownloadName,
FileContents = reportFile.FileContents
};
}
catch (Exception)
{
return new SfsImportResult()
{
ExceptionMessage = ex.Message,
FileContents = Encoding.Default.GetBytes(ex.Message)
};
}
}
else
{
return new SfsImportResult()
{
ExceptionMessage = ex.Message,
FileContents = Encoding.Default.GetBytes(ex.Message)
};
}
}
}
2 years ago
}