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.

279 lines
13 KiB
C#

using DS.Module.Core;
using DS.Module.Core.Enums;
using DS.Module.Core.Extensions;
using DS.WMS.Core.Fee.Dtos;
using DS.WMS.Core.Fee.Entity;
using DS.WMS.Core.Fee.Interface;
using DS.WMS.Core.Flow.Dtos;
using DS.WMS.Core.Flow.Interface;
using DS.WMS.Core.Op.Entity;
using DS.WMS.Core.Sys.Entity;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
namespace DS.WMS.Core.Fee.Method
{
/// <summary>
/// 付费申请实现
/// </summary>
public class FeeApplicationService : FeeServiceBase, IFeeApplicationService
{
readonly IClientFlowInstanceService flowService;
/// <summary>
/// 初始化
/// </summary>
/// <param name="serviceProvider"></param>
public FeeApplicationService(IServiceProvider serviceProvider) : base(serviceProvider)
{
flowService = serviceProvider.GetRequiredService<IClientFlowInstanceService>();
}
/// <summary>
/// 获取待付费的业务列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<DataResult<List<FeeApplicationBiz>>> GetBizListAsync(PageRequest request)
{
var queryList = CreateBizQuery(TenantDb);
if (!request.QueryCondition.IsNullOrEmpty())
{
var whereList = Db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
queryList = queryList.Where(whereList);
}
var result = await queryList.ToQueryPageAsync(request.PageCondition);
if (result.Data.Count > 0)
{
//关联用户名称
var userIds = result.Data.Where(x => x.OperatorId.HasValue).Select(x => x.OperatorId.Value)
.Union(result.Data.Select(x => x.CreateBy))
.Distinct();
var users = await Db.Queryable<SysUser>().Where(x => userIds.Contains(x.Id)).Select(x => new { x.Id, x.UserName }).ToListAsync();
foreach (var item in result.Data)
{
item.CreateByName = users.Find(x => x.Id == item.CreateBy)?.UserName;
if (item.OperatorId.HasValue)
item.Operator = users.Find(x => x.Id == item.OperatorId.Value)?.UserName;
}
}
return result;
}
//创建各项业务数据的查询并集
internal static ISugarQueryable<FeeApplicationBiz> CreateBizQuery(SqlSugarScopeProvider tenantDb)
{
//海运出口
var query1 = tenantDb.Queryable<SeaExport>().InnerJoin<FeeRecord>((s, f) => s.Id == f.BusinessId && f.BusinessType == BusinessType.OceanShippingExport)
.Where((s, f) => f.FeeStatus == FeeStatus.AuditPassed)
.GroupBy((s, f) => s.Id)
.Select(s => new FeeApplicationBiz
{
Id = s.Id,
AccountDate = SqlFunc.ToDate(s.AccountDate),
BusinessType = BusinessType.OceanShippingExport,
CntrTotal = s.CntrTotal,
CreateBy = s.CreateBy,
CustomerId = s.CustomerId,
CustomerName = s.CustomerName,//委托单位
DischargePort = s.DischargePort,
ETD = s.ETD,
HBLNO = s.HBLNO,
LoadPort = s.LoadPort,
MBLNO = s.MBLNO,
OperatorId = s.OperatorId,
SaleDeptId = s.SaleDeptId,
//SaleDeptName //所属部门
SaleId = s.SaleId,
SaleName = s.Sale,//揽货人
Vessel = s.Vessel,//船名
Voyage = s.Voyno,//航次
BookingNO = s.BookingNo,
StlName = s.StlName,
UnpaidRMB = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed &&
f.FeeType == FeeType.Payable && f.Currency == "CNY").Select(f => SqlFunc.AggregateSumNoNull(f.Amount.Value)),
UnpaidUSD = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed &&
f.FeeType == FeeType.Payable && f.Currency == "USD").Select(f => SqlFunc.AggregateSumNoNull(f.Amount.Value)),
UnpaidOther = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed &&
f.FeeType == FeeType.Payable && (f.Currency != "USD" && f.Currency != "CNY")).Select(f => SqlFunc.AggregateSumNoNull(f.Amount.Value)),
UnreceivedRMB = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed &&
f.FeeType == FeeType.Receivable && f.Currency == "CNY").Select(f => SqlFunc.AggregateSumNoNull(f.Amount.Value)),
UnreceivedUSD = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed &&
f.FeeType == FeeType.Receivable && f.Currency == "USD").Select(f => SqlFunc.AggregateSumNoNull(f.Amount.Value)),
UnreceivedOther = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed &&
f.FeeType == FeeType.Receivable && (f.Currency != "USD" && f.Currency != "CNY")).Select(f => SqlFunc.AggregateSumNoNull(f.Amount.Value)),
UnpaidRMBInv = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed &&
f.FeeType == FeeType.Payable && f.Currency == "CNY").Select(f => SqlFunc.AggregateSumNoNull(f.InvoiceAmount.Value)),
UnpaidUSDInv = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed &&
f.FeeType == FeeType.Payable && f.Currency == "USD").Select(f => SqlFunc.AggregateSumNoNull(f.InvoiceAmount.Value))
});
//海运进口
return tenantDb.UnionAll(new List<ISugarQueryable<FeeApplicationBiz>> { query1 });
}
/// <summary>
/// 获取分页列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<DataResult<List<FeeApplicationDto>>> GetListAsync(PageRequest request)
{
var whereList = Db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
var data = await TenantDb.Queryable<FeeApplication>().Where(whereList).Select<FeeApplicationDto>().ToQueryPageAsync(request.PageCondition);
//关联用户名称
var userIds = data.Data.Select(x => x.CreateBy).Distinct(); //.Union(data.Data.Select(x => x.CreateBy))
var users = await Db.Queryable<SysUser>().Where(x => userIds.Contains(x.Id)).Select(x => new { x.Id, x.UserName }).ToListAsync();
foreach (var item in data.Data)
{
item.CreateByName = users.Find(x => x.Id == item.CreateBy)?.UserName;
}
return data;
}
/// <summary>
/// 提交保存申请单
/// </summary>
/// <param name="application">申请单</param>
/// <returns></returns>
public async Task<DataResult> SaveAsync(FeeApplication application)
{
if (application.Id > 0)
{
//修改需检查申请单状态
if (await TenantDb.Queryable<FeeApplication>().AnyAsync(x =>
x.Id == application.Id && (x.Status == ApplicationStatus.AuditSubmittd || x.Status == ApplicationStatus.AuditPassed)))
return DataResult.Failed("只能修改状态为:未提交/审核驳回的申请单");
}
//关联用户名称
var userIds = new long?[] { application.SettlerId, application.PaymentApplicantId };
var users = await Db.Queryable<SysUser>().Where(x => userIds.Contains(x.Id)).Select(x => new { x.Id, x.UserName }).ToListAsync();
application.SettlerName = application.SettlerId.HasValue ? users.Find(x => x.Id == application.SettlerId.Value)?.UserName : string.Empty;
application.PaymentApplicantName = application.PaymentApplicantId.HasValue ? users.Find(x => x.Id == application.PaymentApplicantId.Value)?.UserName : string.Empty;
await TenantDb.Ado.BeginTranAsync();
try
{
//关联导航属性插入
if (application.Id == 0)
{
await TenantDb.InsertNav(application).Include(x => x.Details).ExecuteCommandAsync();
}
//关联导航属性更新
else
{
await TenantDb.UpdateNav(application).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.Failed("发生错误,提交失败");
}
}
/// <summary>
/// 删除申请单
/// </summary>
/// <param name="ids">申请单ID</param>
/// <returns></returns>
public async Task<DataResult> DeleteAsync(params long[] ids)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
if (await tenantDb.Queryable<FeeApplication>().AnyAsync(x => ids.Contains(x.Id) && (x.Status != ApplicationStatus.Pending && x.Status != ApplicationStatus.AuditRejected)))
return DataResult.Failed("只能删除状态为‘待审核’或‘驳回’的申请单", MultiLanguageConst.FeeRecordDelete);
bool result = await tenantDb.DeleteNav<FeeApplication>(x => ids.Contains(x.Id)).Include(x => x.Details).ExecuteCommandAsync();
return result ? DataResult.Successed("删除成功!") : DataResult.Failed("删除失败!");
}
/// <summary>
/// 提交审批
/// </summary>
/// <param name="auditType">审批类型</param>
/// <param name="remark">审批备注</param>
/// <param name="idArray">申请单ID</param>
/// <returns></returns>
public async Task<DataResult> SubmitForApprovalAsync(AuditType auditType, string remark, params long[] idArray)
{
var list = await TenantDb.Queryable<FeeApplication>().LeftJoin<FeeApplicationDetail>((x, y) => x.Id == y.ApplicationId)
.GroupBy((x, y) => x.Id)
.Where((x, y) => idArray.Contains(x.Id))
.Select((x, y) => new
{
x.Id,
x.Status,
ItemCount = SqlFunc.AggregateCount(y.Id)
}).ToListAsync();
if (list.Exists(x => x.Status == ApplicationStatus.AuditSubmittd || x.Status == ApplicationStatus.AuditPassed))
return DataResult.Failed("提交内容包含正在审批中/已审批的申请单", MultiLanguageConst.Operation_Failed);
if (list.Exists(x => x.ItemCount == 0))
return DataResult.Failed("提交审批时必须包含费用明细,请检查", MultiLanguageConst.Operation_Failed);
var template = await FindTemplateAsync(auditType);
if (template == null)
return DataResult.Failed("未能找到审批模板");
await TenantDb.Ado.BeginTranAsync();
try
{
var list2 = list.Select(x => new FeeApplication { Id = x.Id, Status = x.Status }).ToList();
foreach (var item in list2)
{
var result = flowService.CreateFlowInstance(new CreateFlowInstanceReq
{
BusinessId = item.Id,
TemplateId = template.Id
});
if (result.Succeeded)
{
item.Status = ApplicationStatus.AuditSubmittd;
item.AuditRemark = remark;
await TenantDb.Updateable(item).ExecuteCommandAsync();
}
}
await TenantDb.Ado.CommitTranAsync();
return DataResult.Success;
}
catch (Exception ex)
{
await TenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(Db);
return DataResult.Failed("发生错误,提交失败");
}
}
/// <summary>
/// 撤销审批
/// </summary>
/// <param name="ids">申请单ID</param>
/// <returns></returns>
public async Task<DataResult> WithdrawAsync(params long[] ids)
{
throw new NotImplementedException();
}
}
}