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

398 lines
15 KiB
C#

using System.Text;
using DS.Module.Core;
using DS.Module.Core.Enums;
using DS.Module.Core.Extensions;
using DS.WMS.Core.Application.Entity;
using DS.WMS.Core.Application.Interface;
using DS.WMS.Core.Fee.Entity;
using DS.WMS.Core.Fee.Method;
using DS.WMS.Core.Settlement.Dtos;
using DS.WMS.Core.Settlement.Entity;
using DS.WMS.Core.Sys.Interface;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
namespace DS.WMS.Core.Settlement.Method
{
/// <summary>
/// 结算基础实现
/// </summary>
/// <typeparam name="TEntity">实体的类型声明</typeparam>
public class SettlementService<TEntity> : FeeServiceBase, ISettlementService<TEntity>
where TEntity : SettlementBase, new()
{
protected readonly Lazy<ICommonService> CommonService;
/// <summary>
/// 初始化
/// </summary>
/// <param name="serviceProvider">DI容器</param>
public SettlementService(IServiceProvider serviceProvider) : base(serviceProvider)
{
CommonService = new Lazy<ICommonService>(serviceProvider.GetRequiredService<ICommonService>());
}
#region 保存
/// <summary>
/// 提交结算单
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<DataResult<TEntity>> SaveAsync(SettlementRequest<TEntity> request)
{
var settlement = request.Settlement;
if (settlement.SettlementDate == default)
settlement.SettlementDate = DateTime.Now;
settlement.Mode = SettlementMode.Payment;
settlement.BillType = SettlementBillType.Payment;
TEntity? dbValue = default;
if (request.Settlement.Id > 0)
{
dbValue = await TenantDb.Queryable<TEntity>().Select(x => new TEntity
{
Id = x.Id,
IsLocked = x.IsLocked,
Mode = x.Mode
}).FirstAsync(x => x.Id == request.Settlement.Id);
if (dbValue.IsLocked)
return DataResult<TEntity>.FailedWithDesc(nameof(MultiLanguageConst.SettlementIsLocked));
}
var result = EnsureSettlement(request.Settlement, dbValue);
if (!result.Succeeded)
return DataResult<TEntity>.Failed(result.Message, result.MultiCode);
if (request.Details?.Count > 0)
{
if (settlement.Id == 0)
{
var first = request.Details[0];
settlement.CustomerId = first.CustomerId.GetValueOrDefault();
settlement.CustomerName = first.CustomerName;
}
settlement.Details = request.Details.Select(x => new ApplicationDetail
{
ApplicationId = x.ApplicationId,
DetailId = x.Id,
RecordId = x.RecordId,
BusinessId = x.BusinessId,
BusinessType = x.BusinessType,
CustomerName = x.CustomerName ?? settlement.CustomerName,
FeeId = x.FeeId,
FeeName = x.FeeName,
FeeType = x.FeeType,
Category = FeeCategory.PaidApplicationSettlement,
ApplyAmount = x.Amount,
Currency = x.Currency,
ExchangeRate = x.ExchangeRate,
OriginalAmount = x.OriginalAmount,
OriginalCurrency = x.OriginalCurrency ?? (settlement.Currency.IsNullOrEmpty() ? x.Currency : settlement.Currency),
}).ToList();
//金额禁止为0
if (settlement.Details.Any(x => x.ApplyAmount == 0 || x.OriginalAmount == 0))
return DataResult<TEntity>.FailedWithDesc(nameof(MultiLanguageConst.AmountCannotBeZero));
if (settlement.Details.Any(x => x.OriginalCurrency.IsNullOrEmpty()))
return DataResult<TEntity>.FailedWithDesc(nameof(MultiLanguageConst.OriginalCurrencyCanNotNull));
result = await PreSaveAsync(settlement);
if (!result.Succeeded)
return DataResult<TEntity>.Failed(result.Message, result.MultiCode);
settlement.Amount = settlement.Details.Sum(x => x.ApplyAmount);
}
await TenantDb.Ado.BeginTranAsync();
try
{
//关联导航属性插入
if (settlement.Id == 0)
{
//创建时需要生成申请单编号
var sequence = CommonService.Value.GetSequenceNext<TEntity>();
if (!sequence.Succeeded)
{
return DataResult<TEntity>.Failed(sequence.Message, MultiLanguageConst.SequenceSetNotExist);
}
settlement.ApplicationNO = "CP" + SnowFlakeSingle.Instance.NextId(); //申请编号
settlement.SettlementNO = sequence.Data; //结算单号
await TenantDb.InsertNav(settlement).Include(x => x.Details).ExecuteCommandAsync();
}
else
{
if (settlement.Details.Count > 0)
await TenantDb.Insertable(settlement.Details).ExecuteCommandAsync();
await TenantDb.Updateable(settlement).IgnoreColumns(x => new
{
x.ApplicationNO,
x.SettlementNO,
x.IsLocked,
x.CreateBy,
x.CreateTime,
x.Deleted,
x.DeleteBy,
x.DeleteTime
}).ExecuteCommandAsync();
}
await OnSaveAsync(settlement);
if (settlement.Details?.Count > 0)
{
//更新费用记录的已结算金额
var fees = settlement.Details.Select(x => new FeeRecord
{
Id = x.RecordId,
SettlementAmount = x.OriginalAmount
}).ToList();
await TenantDb.Updateable(fees)
.PublicSetColumns(x => x.SettlementAmount, "+")
.UpdateColumns(x => new { x.SettlementAmount })
.ExecuteCommandAsync();
}
await TenantDb.Ado.CommitTranAsync();
return DataResult<TEntity>.Success(await PostSaveAsync(settlement));
}
catch (Exception ex)
{
await TenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(Db);
return DataResult<TEntity>.FailedWithDesc(nameof(MultiLanguageConst.Operation_Failed));
}
}
/// <summary>
/// 用于结算单的状态检查
/// </summary>
/// <param name="settlement">提交的结算单</param>
/// <param name="dbValue">数据库值新增时为null</param>
/// <returns></returns>
protected virtual DataResult EnsureSettlement(TEntity settlement, TEntity? dbValue)
{
return DataResult.Success;
}
/// <summary>
/// 在保存前调用
/// </summary>
/// <param name="settlement">结算单</param>
/// <returns></returns>
protected virtual Task<DataResult> PreSaveAsync(TEntity settlement)
{
return Task.FromResult(DataResult.Success);
}
/// <summary>
/// 在保存时调用
/// </summary>
/// <param name="settlement">已保存的结算单</param>
/// <returns></returns>
protected virtual Task OnSaveAsync(TEntity settlement)
{
return Task.CompletedTask;
}
/// <summary>
/// 在保存完成后调用
/// </summary>
/// <param name="settlement">申请单</param>
protected virtual async Task<TEntity> PostSaveAsync(TEntity settlement)
{
if (settlement.Details?.Count > 0)
{
//更新费用记录状态
var ids = settlement.Details.Where(x => x.RecordId > 0).Select(x => x.RecordId);
if (!ids.Any())
return settlement;
var fees = await TenantDb.Queryable<FeeRecord>().Where(x => ids.Contains(x.Id))
.Select(x => new FeeRecord
{
Id = x.Id,
FeeStatus = x.FeeStatus,
Amount = x.Amount,
SettlementAmount = x.SettlementAmount,
OrderAmount = x.OrderAmount,
OrderSettlementAmount = x.OrderSettlementAmount
}).ToListAsync();
List<FeeRecord> list = new(fees.Count);
foreach (var item in fees)
{
var restAmount = item.Amount - item.SettlementAmount - item.OrderAmount + item.OrderSettlementAmount;
if (restAmount == 0)
{
item.FeeStatus = FeeStatus.SettlementCompleted;
list.Add(item);
}
else if (restAmount != item.Amount)
{
item.FeeStatus = FeeStatus.PartialSettlement;
list.Add(item);
}
}
await TenantDb.Updateable(list).UpdateColumns(x => new { x.FeeStatus }).ExecuteCommandAsync();
}
return settlement;
}
#endregion
#region 删除
/// <summary>
/// 删除结算单明细
/// </summary>
/// <param name="ids">结算单明细ID</param>
/// <returns></returns>
public async Task<DataResult> DeleteDetailAsync(params long[] ids)
{
var details = await TenantDb.Queryable<ApplicationDetail>().Where(x => ids.Contains(x.Id)).Select(
x => new ApplicationDetail
{
Id = x.Id,
ApplicationId = x.ApplicationId,
RecordId = x.RecordId,
DetailId = x.DetailId,
OriginalAmount = x.OriginalAmount,
ProcessedAmount = x.ProcessedAmount,
OriginalProcessedAmount = x.OriginalProcessedAmount
}).ToListAsync();
var appIds = details.Select(x => x.ApplicationId).Distinct().ToList();
var apps = await TenantDb.Queryable<TEntity>().Where(x => appIds.Contains(x.Id)).Select(x => new TEntity
{
Id = x.Id,
Mode = x.Mode
}).ToListAsync();
foreach (var app in apps)
app.Details = details.FindAll(x => x.ApplicationId == app.Id);
var result = PreDelete(apps);
if (!result.Succeeded)
return result;
await TenantDb.Ado.BeginTranAsync();
try
{
await OnDeleteDetailAsync(apps);
await TenantDb.Deleteable(details).ExecuteCommandAsync();
await TenantDb.Ado.CommitTranAsync();
return DataResult.Success;
}
catch (Exception ex)
{
await TenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(Db);
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.Operation_Failed));
}
}
/// <summary>
/// 删除结算单
/// </summary>
/// <param name="ids">结算单ID</param>
/// <returns></returns>
public async Task<DataResult> DeleteAsync(params long[] ids)
{
var apps = await TenantDb.Queryable<TEntity>().Where(x => ids.Contains(x.Id)).Select(x => new TEntity
{
Id = x.Id,
Mode = x.Mode
}).ToListAsync();
var details = await TenantDb.Queryable<ApplicationDetail>().Where(x => ids.Contains(x.ApplicationId)).Select(
x => new ApplicationDetail
{
Id = x.Id,
ApplicationId = x.ApplicationId,
RecordId = x.RecordId,
DetailId = x.DetailId,
ApplyAmount = x.ApplyAmount,
OriginalAmount = x.OriginalAmount
}).ToListAsync();
foreach (var app in apps)
app.Details = details.FindAll(x => x.ApplicationId == app.Id); await TenantDb.Ado.BeginTranAsync();
var result = PreDelete(apps);
if (!result.Succeeded)
return result;
try
{
await OnDeleteDetailAsync(apps);
await TenantDb.DeleteNav<TEntity>(x => ids.Contains(x.Id)).Include(x => x.Details).ExecuteCommandAsync();
await TenantDb.Ado.CommitTranAsync();
return DataResult.Success;
}
catch (Exception ex)
{
await TenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(Db);
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.Operation_Failed));
}
}
/// <summary>
/// 在删除结算单或其明细之前调用,用于检查状态
/// </summary>
/// <param name="settlements">结算单</param>
/// <returns></returns>
protected virtual DataResult PreDelete(List<TEntity> settlements)
{
return DataResult.Success;
}
/// <summary>
/// 在执行删除结算单或其明细时调用
/// </summary>
/// <param name="settlements">结算单及其明细</param>
/// <returns></returns>
protected virtual async Task OnDeleteDetailAsync(List<TEntity> settlements)
{
//还原付费申请明细
var list = settlements.FindAll(x => x.Mode == SettlementMode.Payment);
if (list.Count > 0)
{
var items = list.SelectMany(x => x.Details);
var ids = items.Select(x => x.DetailId);
var details = TenantDb.Queryable<ApplicationDetail>().Where(x => ids.Contains(x.Id) && x.Category == FeeCategory.PaidApplication)
.Select(x => new ApplicationDetail
{
Id = x.Id,
ProcessedAmount = x.ProcessedAmount,
OriginalProcessedAmount = x.OriginalProcessedAmount
}).ToList();
foreach (var detail in details)
{
var item = items.FirstOrDefault(x => x.DetailId == detail.Id);
detail.ProcessedAmount -= item.ApplyAmount;
detail.OriginalProcessedAmount -= item.OriginalAmount;
}
await TenantDb.Updateable(details)
.UpdateColumns(x => new { x.ProcessedAmount, x.OriginalProcessedAmount })
.ExecuteCommandAsync();
}
}
#endregion
}
}