using DS.Module.Core;
using DS.Module.Core.Enums;
using DS.Module.Core.Extensions;
using DS.WMS.Core.Application.Entity;
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.Settlement.Interface;
using DS.WMS.Core.Sys.Interface;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
namespace DS.WMS.Core.Settlement.Method
{
///
/// 结算基础实现
///
/// 实体的类型声明
public class SettlementService : FeeServiceBase, ISettlementService
where TEntity : SettlementBase, new()
{
readonly Lazy CommonService;
///
/// 初始化
///
/// DI容器
public SettlementService(IServiceProvider serviceProvider) : base(serviceProvider)
{
CommonService = new Lazy(serviceProvider.GetRequiredService());
}
#region 保存
///
/// 提交结算单
///
///
///
public async Task> SaveAsync(SettlementRequest request)
{
var settlement = request.Settlement;
if (settlement.SettlementDate == default)
settlement.SettlementDate = DateTime.Now;
if (settlement.Mode == 0)
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.UnknownSettlementMode));
if (settlement.BillType == 0)
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.UnknownSettlementType));
TEntity? dbValue = default;
if (request.Settlement.Id > 0)
{
dbValue = await TenantDb.Queryable().Select(x => new TEntity
{
Id = x.Id,
IsLocked = x.IsLocked,
Mode = x.Mode
}).FirstAsync(x => x.Id == request.Settlement.Id);
if (dbValue != null && dbValue.IsLocked)
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.SettlementIsLocked));
}
var result = EnsureSettlement(request.Settlement, dbValue);
if (!result.Succeeded)
return DataResult.Failed(result.Message, result.MultiCode);
List? details1 = null;
//自由结算
if (settlement.Mode == SettlementMode.FreeSettlement && request.Details?.Count > 0)
{
if (settlement.Id == 0)
{
var first = request.Details[0];
settlement.CustomerId = first.CustomerId;
settlement.CustomerName = first.CustomerName;
}
details1 = request.Details.Select(x => new ApplicationDetail
{
RefId = x.ApplicationId,
DetailId = x.Id,
RecordId = x.RecordId,
CustomerName = x.CustomerName ?? settlement.CustomerName,
FeeId = x.FeeId,
FeeName = x.FeeName,
FeeType = x.FeeType,
ApplyAmount = x.RestAmount.GetValueOrDefault(),
Currency = x.Currency,
ExchangeRate = x.ExchangeRate,
OriginalAmount = x.OriginalAmount,
OriginalCurrency = x.OriginalCurrency ?? (settlement.Currency.IsNullOrEmpty() ? x.Currency : settlement.Currency),
}).ToList();
}
//按付费/发票申请结算
if (request.Documents?.Count > 0)
{
if (settlement.Id == 0)
{
var first = request.Documents[0];
settlement.CustomerId = first.CustomerId;
settlement.CustomerName = first.CustomerName;
}
var ids = request.Documents.Select(x => x.Id);
//收/付费申请结算
if (settlement.Mode == SettlementMode.Payment || settlement.Mode == SettlementMode.Charge)
{
details1 = await TenantDb.Queryable().Where(x => ids.Contains(x.ApplicationId) && x.Category == DetailCategory.PaidApplication)
.Select(x => new ApplicationDetail
{
RefId = x.ApplicationId,
DetailId = x.Id,
RecordId = x.RecordId,
Category = settlement.Mode == SettlementMode.Payment ? DetailCategory.PaidApplicationSettlement : DetailCategory.ChargeApplicationSettlement,
CustomerName = x.CustomerName ?? settlement.CustomerName,
FeeId = x.FeeId,
FeeName = x.FeeName,
FeeType = x.FeeType,
ApplyAmount = x.ApplyAmount - x.ProcessedAmount,
Currency = x.Currency,
ExchangeRate = x.ExchangeRate,
OriginalAmount = x.OriginalAmount - x.OriginalProcessedAmount,
}).ToListAsync();
}
//发票结算
else if (settlement.Mode == SettlementMode.InvoiceSettlement || settlement.Mode == SettlementMode.PaymentInvoiceSettlement)
{
details1 = await TenantDb.Queryable().Where(x => ids.Contains(x.ApplicationId) && x.Category == DetailCategory.InvoiceIssuance)
.Select(x => new ApplicationDetail
{
RefId = x.ApplicationId,
DetailId = x.Id,
RecordId = x.RecordId,
Category = DetailCategory.InvoiceSettlement,
CustomerName = x.CustomerName ?? settlement.CustomerName,
FeeId = x.FeeId,
FeeName = x.FeeName,
FeeType = x.FeeType,
ApplyAmount = x.ApplyAmount - x.ProcessedAmount,
Currency = x.Currency,
ExchangeRate = x.ExchangeRate,
OriginalAmount = x.OriginalAmount - x.OriginalProcessedAmount,
}).ToListAsync();
}
}
if (details1 != null && details1.Count > 0)
settlement.Details.AddRange(details1);
//金额禁止为0
if (settlement.Details.Exists(x => x.ApplyAmount == 0 || x.OriginalAmount == 0))
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.AmountCannotBeZero));
if (settlement.Details.Exists(x => x.OriginalCurrency.IsNullOrEmpty()))
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.OriginalCurrencyCanNotNull));
settlement.Amount = settlement.Details.Sum(x => x.ApplyAmount);
result = await PreSaveAsync(settlement);
if (!result.Succeeded)
return DataResult.Failed(result.Message, result.MultiCode);
var details = settlement.Details.FindAll(x => x.Id == 0);
await TenantDb.Ado.BeginTranAsync();
try
{
//关联导航属性插入
if (settlement.Id == 0)
{
//创建时需要生成申请单编号
var sequence = CommonService.Value.GetSequenceNext();
if (!sequence.Succeeded)
{
return DataResult.Failed(sequence.Message, MultiLanguageConst.SequenceSetNotExist);
}
settlement.ApplicationNO = "ST" + SnowFlakeSingle.Instance.NextId(); //申请编号
settlement.SettlementNO = sequence.Data; //结算单号
await TenantDb.InsertNav(settlement).Include(x => x.Details.FindAll(x => x.Id == 0)).ExecuteCommandAsync();
}
else
{
if (details.Count > 0)
await TenantDb.Insertable(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 (details.Count > 0)
{
//更新费用记录的已结算金额
var fees = 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();
PostSaveAsync(settlement);
return DataResult.Success(settlement);
}
catch (Exception ex)
{
await TenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(Db);
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.Operation_Failed));
}
}
///
/// 用于结算单的状态检查
///
/// 提交的结算单
/// 数据库值,新增时为null
///
protected virtual DataResult EnsureSettlement(TEntity settlement, TEntity? dbValue)
{
return DataResult.Success;
}
///
/// 在保存前调用
///
/// 结算单
///
protected virtual Task PreSaveAsync(TEntity settlement)
{
return Task.FromResult(DataResult.Success);
}
///
/// 在保存时调用
///
/// 已保存的结算单
///
protected virtual Task OnSaveAsync(TEntity settlement)
{
return Task.CompletedTask;
}
///
/// 在保存完成后调用
///
/// 申请单
protected virtual async Task 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;
UpdateFeeStatus(ids);
}
return settlement;
}
#endregion
#region 删除
///
/// 删除结算单明细
///
/// 结算单明细ID
///
public async Task DeleteDetailAsync(params long[] ids)
{
var details = await TenantDb.Queryable().Where(x => ids.Contains(x.Id)).Select(
x => new ApplicationDetail
{
Id = x.Id,
ApplicationId = x.ApplicationId,
RecordId = x.RecordId,
DetailId = x.DetailId,
ApplyAmount = x.ApplyAmount,
OriginalAmount = x.OriginalAmount,
ProcessedAmount = x.ProcessedAmount,
OriginalProcessedAmount = x.OriginalProcessedAmount
}).ToListAsync();
if (details.Count == 0)
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.EmptyData));
var appIds = details.Select(x => x.ApplicationId).Distinct().ToList();
var apps = await TenantDb.Queryable().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);
app.Amount = app.Details.Sum(x => x.ApplyAmount);
}
var result = PreDelete(apps);
if (!result.Succeeded)
return result;
await TenantDb.Ado.BeginTranAsync();
try
{
await OnDeleteDetailAsync(apps);
await TenantDb.Deleteable(details).ExecuteCommandAsync();
//更新结算单的结算总金额
await TenantDb.Updateable(apps)
.PublicSetColumns(it => it.Amount, "-").UpdateColumns(x => new { x.Amount })
.ExecuteCommandAsync();
await TenantDb.Ado.CommitTranAsync();
//更新费用结算状态
UpdateFeeStatus(details.Select(x => x.RecordId));
return DataResult.Success;
}
catch (Exception ex)
{
await TenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(Db);
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.Operation_Failed));
}
}
///
/// 删除结算单
///
/// 结算单ID
///
public async Task DeleteAsync(params long[] ids)
{
var apps = await TenantDb.Queryable().Where(x => ids.Contains(x.Id)).Select(x => new TEntity
{
Id = x.Id,
Mode = x.Mode
}).ToListAsync();
if (apps.Count == 0)
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.EmptyData));
var details = await TenantDb.Queryable().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(x => ids.Contains(x.Id)).Include(x => x.Details).ExecuteCommandAsync();
await TenantDb.Ado.CommitTranAsync();
//更新费用结算状态
UpdateFeeStatus(details.Select(x => x.RecordId));
return DataResult.Success;
}
catch (Exception ex)
{
await TenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(Db);
return DataResult.FailedWithDesc(nameof(MultiLanguageConst.Operation_Failed));
}
}
///
/// 在删除结算单或其明细之前调用,用于检查状态
///
/// 结算单
///
protected virtual DataResult PreDelete(List settlements)
{
return DataResult.Success;
}
///
/// 在执行删除结算单或其明细时调用
///
/// 结算单及其明细
///
protected virtual async Task OnDeleteDetailAsync(List settlements)
{
//还原费用表的已结算金额
var fees = settlements.SelectMany(x => x.Details).Select(x => new FeeRecord { Id = x.RecordId, SettlementAmount = x.OriginalAmount }).ToList();
await TenantDb.Updateable(fees)
.PublicSetColumns(it => it.SettlementAmount, "-").UpdateColumns(x => new { x.SettlementAmount })
.ExecuteCommandAsync();
}
#endregion
///
/// 设置结算单的锁定状态
///
/// 是否锁定
/// 结算ID
///
public async Task SetLockAsync(bool isLocked, params long[] ids)
{
var dtNow = DateTime.Now;
var userId = long.Parse(User.UserId);
List list = null;
if (isLocked)
{
list = ids.Select(x => new TEntity
{
Id = x,
IsLocked = isLocked,
LockTime = dtNow,
LockUserId = userId
}).ToList();
}
else
{
list = ids.Select(x => new TEntity
{
Id = x,
IsLocked = isLocked,
UnlockTime = dtNow,
UnlockUserId = userId
}).ToList();
}
return await TenantDb.Updateable(list).UpdateColumns(x => new
{
x.IsLocked,
x.LockTime,
x.UnlockTime,
x.LockUserId,
x.UnlockUserId
}).ExecuteCommandAsync() > 0 ?
DataResult.Success : DataResult.FailedWithDesc(nameof(MultiLanguageConst.Operation_Failed));
}
protected virtual Task> GetSettlementDetails(long id)
{
return Task.FromResult(new List());
}
}
}