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.

531 lines
24 KiB
C#

using System.Text;
using DS.Module.Core;
using DS.Module.Core.Enums;
using DS.Module.Core.Extensions;
using DS.WMS.Core.Application.Dtos;
using DS.WMS.Core.Application.Entity;
using DS.WMS.Core.Application.Interface;
using DS.WMS.Core.Fee.Dtos;
using DS.WMS.Core.Fee.Entity;
using DS.WMS.Core.Op.Entity;
using DS.WMS.Core.Sys.Entity;
using SqlSugar;
namespace DS.WMS.Core.Application.Method
{
/// <summary>
/// 发票申请服务
/// </summary>
public class InvoiceApplicationService : ApplicationService<InvoiceApplication>, IInvoiceApplicationService
{
/// <summary>
/// 初始化
/// </summary>
/// <param name="serviceProvider"></param>
public InvoiceApplicationService(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
/// <summary>
/// 获取分页列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<DataResult<List<InvoiceApplicationDto>>> GetListAsync(PageRequest request)
{
List<IConditionalModel> whereList = [];
if (!request.QueryCondition.IsNullOrEmpty())
whereList = Db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
var result = await TenantDb.Queryable<InvoiceApplication>().Includes(x => x.Details).Where(whereList)
.Select((x) => new InvoiceApplicationDto
{
Id = x.Id,
ApplicationNO = x.ApplicationNO,
Status = x.Status,
CustomerName = x.CustomerName,
InvoiceHeader = x.InvoiceHeader,
Currency = x.Currency,
ApplyAmount = x.ApplyAmount,
OriginalAmountList = x.Details.Select(y => y.OriginalCurrency + " " + y.OriginalAmount).ToList(),
InvoiceCurrency = x.InvoiceCurrency,
InvoiceAmount = x.InvoiceAmount,
CreateTime = x.CreateTime, //申请时间
CreateBy = x.CreateBy, //申请人ID
InvoiceNO = x.InvoiceNO,
InvoiceBillNO = x.InvoiceBillNO, //实际开出票号
Note = x.Note,
Reason = x.Reason,
RestAmount = 0, //未结算
InvoiceDate = x.InvoiceDate,
Category = x.Category, //申请类型
Rate = x.Rate,
PushMode = x.PushMode,
Email = x.Email,
CellPhoneNO = x.CellPhoneNO,
InvoiceRemark = x.InvoiceRemark //开票要求
}).ToQueryPageAsync(request.PageCondition);
if (result.Data.Count > 0)
{
//关联用户名称
var userIds = 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;
}
}
return result;
}
/// <summary>
/// 获取待开票的业务列表(编辑用)
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<DataResult<List<BizInvoiceApplication>>> GetBizListAsync(PageRequest request)
{
var query = CreateBizQuery();
if (!request.QueryCondition.IsNullOrEmpty())
{
var whereList = Db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
int? index = null;
foreach (var item in whereList)
{
ConditionalModel? model = item as ConditionalModel;
if (model == null)
continue;
//设置了费用范围筛选
if (string.Equals(model.FieldName, nameof(BizInvoiceApplication.FeeRange)) && int.TryParse(model.FieldValue, out int feeRangeVal))
{
FeeRange feeRange = (FeeRange)feeRangeVal;
switch (feeRange)
{
case FeeRange.Unsettled:
query = query.Where(x => x.SettlementAmount == 0);
break;
case FeeRange.Settled:
query = query.Where(x => x.SettlementAmount > 0);
break;
case FeeRange.PaidNotReceived:
break;
case FeeRange.ReceivedNotPaid:
break;
case FeeRange.NotAppliedSettled:
query = query.Where(x => x.OrderAmount == 0 && x.SettlementAmount == 0);
break;
case FeeRange.UnreconciledSettled:
query = query.Where(x => x.DebitNo == null && x.SettlementAmount == 0);
break;
case FeeRange.NotIssuedSettled:
query = query.Where(x => x.InvoiceAmount == 0 && x.SettlementAmount == 0);
break;
case FeeRange.ReconciledNotSettled:
query = query.Where(x => x.DebitNo != null && x.SettlementAmount == 0);
break;
case FeeRange.NotReceivedPaid:
break;
case FeeRange.SettledNotIssued:
query = query.Where(x => x.InvoiceAmount == 0 && x.SettlementAmount > 0);
break;
}
index = whereList.IndexOf(item);
break;
}
}
if (index.HasValue)
whereList.RemoveAt(index.Value);
query = query.Where(whereList);
}
var result = await query.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();
//关联机构名称
var orgIds = result.Data.Select(x => x.SaleDeptId).Distinct();
var orgs = await Db.Queryable<SysOrg>().Where(x => userIds.Contains(x.Id)).Select(x => new { x.Id, x.OrgName }).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;
item.SaleDeptName = orgs.Find(x => x.Id == item.SaleDeptId)?.OrgName;
}
}
return result;
}
//创建各项业务数据的查询并集
internal ISugarQueryable<BizInvoiceApplication> CreateBizQuery()
{
//海运出口
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, f) => new BizInvoiceApplication
{
Id = s.Id,
AccountDate = s.AccountDate,
BusinessType = BusinessType.OceanShippingExport,
CntrTotal = s.CntrTotal,
CreateBy = s.CreateBy,
CustomerId = f.CustomerId,//费用对象
CustomerName = f.CustomerName,
CustomerNo = s.CustomerNo,
ClientName = s.CustomerName, //委托单位
DischargePort = s.DischargePort,
ETD = s.ETD,
HBLNO = s.HBLNO,
LoadPort = s.LoadPort,
MBLNO = s.MBLNO,
OperatorId = s.OperatorId,
SaleDeptId = s.SaleDeptId,
SaleId = s.SaleId,
SaleName = s.Sale,//揽货人
Vessel = s.Vessel,//船名
Voyage = s.Voyno,//航次
BookingNO = s.BookingNo,
StlName = s.StlName,
FeeType = f.FeeType,
FeeId = f.FeeId,
Currency = f.Currency,
DebitNo = f.DebitNo,
OrderAmount = f.OrderAmount,
InvoiceAmount = f.InvoiceAmount,
SettlementAmount = f.SettlementAmount,
//未申请开票金额=(金额-开票金额-申请开票金额+申请开票金额已开票
UnBilledRMB = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed
&& f.Currency == RMB_CODE).Select(f => SqlFunc.AggregateSum(f.Amount - f.InvoiceAmount - f.OrderInvoiceAmount + f.OrderInvSettlementAmount)),
UnBilledUSD = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed
&& f.Currency == USD_CODE).Select(f => SqlFunc.AggregateSum(f.Amount - f.InvoiceAmount - f.OrderInvoiceAmount + f.OrderInvSettlementAmount)),
UnBilledOther = SqlFunc.Subqueryable<FeeRecord>().Where(f => f.BusinessId == s.Id && f.FeeStatus == FeeStatus.AuditPassed
&& f.Currency != RMB_CODE && f.Currency != USD_CODE).Select(f => SqlFunc.AggregateSum(f.Amount - f.InvoiceAmount - f.OrderInvoiceAmount + f.OrderInvSettlementAmount))
});
//海运进口
return TenantDb.UnionAll(new List<ISugarQueryable<BizInvoiceApplication>> { query1 });
}
/// <summary>
/// 根据业务编号及类型获取关联费用记录
/// </summary>
/// <param name="items">业务ID与业务类型</param>
/// <returns></returns>
public async Task<DataResult<InvoiceApplicaitonBiz>> GetFeesAsync(params BizItem[] items)
{
var bizIds = items.Select(x => x.Id).ToList();
var types = items.Select(x => x.BusinessType).ToList();
var list = await TenantDb.Queryable<FeeRecord>()
.Where(f => bizIds.Contains(f.BusinessId) && types.Contains(f.BusinessType) && f.FeeStatus == FeeStatus.AuditPassed)
.Select(f => new FeeInvoiceDto
{
RecordId = f.Id,
BusinessId = f.BusinessId,
BusinessType = f.BusinessType,
CustomerName = f.CustomerName,
FeeId = f.FeeId,
FeeName = f.FeeName,
FeeType = f.FeeType,
Amount = f.Amount,
Currency = f.Currency,
RestAmount = f.Amount - f.InvoiceAmount - f.OrderInvoiceAmount + f.OrderInvSettlementAmount,
Remark = f.Remark,
CreateBy = f.CreateBy
}).ToListAsync();
//移除开票剩余金额为0的项
list.RemoveAll(f => f.RestAmount == 0);
if (list.Count > 0)
{
//关联用户名称
var userIds = list.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 list)
{
item.CreateByName = users.Find(x => x.Id == item.CreateBy)?.UserName;
}
}
return DataResult<InvoiceApplicaitonBiz>.Success(new InvoiceApplicaitonBiz(list));
}
/// <summary>
/// 获取申请单详情
/// </summary>
/// <param name="id">申请单ID</param>
/// <returns></returns>
public async Task<DataResult<InvoiceApplicationDto>> GetAsync(long id)
{
var dto = await TenantDb.Queryable<InvoiceApplication>()
.Where((a) => a.Id == id).Select((a) => new InvoiceApplicationDto
{
Id = a.Id,
ApplicationNO = a.ApplicationNO,
Currency = a.Currency,
CustomerId = a.CustomerId,
CustomerName = a.CustomerName,
CustomerBankId = a.CustomerBankId,
Status = a.Status,
CreateTime = a.CreateTime,
CreateBy = a.CreateBy,
InvoiceDate = a.InvoiceDate,
InvoiceAmount = a.InvoiceAmount,
SaleDeptId = a.SaleDeptId,
Note = a.Note
}).FirstAsync();
if (dto != null)
{
dto.Details = await TenantDb.Queryable<ApplicationDetail>()
.LeftJoin<FeeRecord>((d, f) => d.RecordId == f.Id)
.Where(d => d.ApplicationId == id)
.Select((d, f) => new InvoiceApplicationDetailDto
{
FeeType = d.FeeType,
FeeId = d.FeeId,
FeeName = d.FeeName,
Amount = d.Amount,
OriginalAmount = d.OriginalAmount,
//未申请金额=(金额-结算金额-申请金额+申请金额已结算)
RestAmount = f.Amount - f.SettlementAmount - f.OrderAmount + f.OrderSettlementAmount,
OriginalCurrency = d.OriginalCurrency,
OriginalRate = f.ExchangeRate,
ExchangeRate = d.ExchangeRate,
AccTaxRate = f.AccTaxRate,
BusinessId = d.BusinessId,
BusinessType = d.BusinessType
}).ToListAsync();
var gList = dto.Details.GroupBy(x => x.BusinessType).ToList();
foreach (var g in gList)
{
var ids = g.Select(x => x.BusinessId).ToList();
switch (g.Key)
{
case BusinessType.OceanShippingExport:
var list1 = await TenantDb.Queryable<SeaExport>().Where(x => ids.Contains(x.Id)).Select(x => new
{
x.Id,
x.MBLNO,
x.CustomerNo,
x.CustomerName,
x.ETD,
x.CntrTotal,
x.AccountDate,
x.OperatorCode,
x.Vessel,
x.Voyno,
x.Carrier,
x.Forwarder
}).ToListAsync();
foreach (var item in g)
{
var biz = list1.Find(x => x.Id == item.BusinessId);
if (biz != null)
{
item.MBLNO = biz.MBLNO;
item.CustomerName = biz.CustomerName;
item.CustomerNo = biz.CustomerNo;
item.ETD = biz.ETD;
item.CntrTotal = biz.CntrTotal;
item.AccountDate = biz.AccountDate;
item.Operator = biz.OperatorCode;
item.Vessel = biz.Vessel;
item.Voyage = biz.Voyno;
item.Carrier = biz.Carrier;
item.Forwarder = biz.Forwarder;
}
}
break;
case BusinessType.OceanShippingImport:
break;
}
}
}
return DataResult<InvoiceApplicationDto>.Success(dto);
}
protected override async Task<List<ApplicationDetail>> GetDetailsAsync(IEnumerable<BizItem> items)
{
var ids1 = items.Select(x => x.Id);
var ids2 = items.Select(x => x.BusinessType);
var list = await TenantDb.Queryable<FeeRecord>().Where(x =>
ids1.Contains(x.BusinessId) && ids2.Contains(x.BusinessType) && x.FeeStatus == FeeStatus.AuditPassed)
.Select(x => new ApplicationDetail
{
Id = x.Id,
BusinessId = x.BusinessId,
BusinessType = x.BusinessType,
Amount = x.Amount - x.InvoiceAmount - x.OrderInvoiceAmount + x.OrderInvSettlementAmount,
ExchangeRate = x.ExchangeRate,
OriginalCurrency = x.Currency
}).ToListAsync();
list.RemoveAll(x => x.Amount == 0);
foreach (var item in list)
item.OriginalAmount = item.Amount;
return list;
}
protected override DataResult PreSave(InvoiceApplication application, InvoiceApplication dbValue)
{
if (dbValue != null && dbValue.Status != InvoiceApplicationStatus.Pending && dbValue.Status != InvoiceApplicationStatus.AuditRejected)
return DataResult.Failed("只能修改状态为:未提交/审核驳回的申请单");
//if (application.Details.Count > 0 && !string.Equals(dbValue.Currency, application.Currency, StringComparison.OrdinalIgnoreCase))
// return DataResult.Failed("提交申请单币别需与原申请单币别一致");
//if (application.Details.Count > 0)
//{
// if (!application.Currency.IsNullOrEmpty() && application.Details.Any(x => x.Currency != application.Currency))
// return DataResult.Failed($"申请单不是原币申请,所有明细币别必须为 {application.Currency}");
//}
if (application.Currency.IsNullOrEmpty())
application.Currency = RMB_CODE;
return DataResult.Success;
}
protected override DataResult CalculateAmount(InvoiceApplication application, List<FeeRecord> fees)
{
StringBuilder sb = new();
foreach (var detail in application.Details)
{
var fee = fees.Find(x => x.Id == detail.RecordId);
if (fee == null)
{
sb.Append($"未能关联明细【{detail.FeeName}】的费用信息;");
continue;
}
detail.Record = fee;
//检查税率是否一致
if (application.Rate != fee.TaxRate)
{
sb.Append($"费用【{fee.FeeName}】的税率与发票申请的税率不一致;");
continue;
}
//未申请开票金额=(金额-已开票金额-申请开票金额+申请开票金额已开票
var restAmount = fee.Amount - fee.InvoiceAmount - fee.OrderInvoiceAmount + fee.OrderInvSettlementAmount;
if (detail.OriginalAmount > 0 && detail.OriginalAmount > restAmount)
{
sb.Append($"申请单明细【{detail.FeeName}】的申请开票金额不能超出原费用的金额;");
continue;
}
if (detail.OriginalAmount < 0 && detail.OriginalAmount < restAmount)
{
sb.Append($"申请单明细【{detail.FeeName}】的申请开票金额不能超出原费用的金额;");
continue;
}
//更新费用记录的已开票金额
fee.OrderInvoiceAmount += detail.OriginalAmount;
//类别固定为发票申请
detail.Category = FeeCategory.InvoiceApplication;
}
if (sb.Length > 0)
return DataResult.Failed(sb.ToString());
return DataResult.Success;
}
protected override async Task OnSaveAsync(InvoiceApplication application, List<FeeRecord>? fees)
{
//先清空发票明细
if (application.Id > 0)
await TenantDb.Deleteable<InvoiceDetail>().Where(x => x.ApplicationId == application.Id).ExecuteCommandAsync();
//然后根据申请单明细重新生成
if (application.Details.Count > 0 && (application.InvoiceDetails == null || application.InvoiceDetails.Count == 0))
{
var feeIds = application.Details.Select(x => x.RecordId).ToList();
var list = await TenantDb.Queryable<FeeRecord>().InnerJoin<FeeCode>((f, c) => f.FeeId == c.Id)
.GroupBy((f, c) => f.Id)
.Select((f, c) => new
{
FeeId = c.Id,
c.GoodName
}).ToListAsync();
application.InvoiceDetails = list.Select(x => new InvoiceDetail
{
ApplicationId = application.Id,
Name = x.GoodName,
TaxRate = application.Rate,
TaxUnitPrice = application.Details.FindAll(y => y.FeeId == x.FeeId).Sum(x => x.Amount)
}).ToList();
}
if (application.InvoiceDetails?.Count > 0)
{
foreach (var detail in application.InvoiceDetails)
{
detail.TaxAmount = detail.TaxUnitPrice * detail.TaxRate;
detail.UnitPrice = detail.TaxUnitPrice - detail.TaxAmount;
}
application.ApplyAmount = application.InvoiceDetails.Sum(x => x.TaxUnitPrice);
application.InvoiceAmount = application.ApplyAmount;
application.AmountUppercase = new Money(application.ApplyAmount).ToString();
await TenantDb.Insertable(application.InvoiceDetails).ExecuteCommandAsync();
}
//更新已开票金额
if (fees != null && fees.Count > 0)
await TenantDb.Updateable(fees).UpdateColumns(x => new { x.OrderInvoiceAmount }).ExecuteCommandAsync();
}
protected override DataResult PreDelete(List<InvoiceApplication> applications)
{
if (applications.Any(x => x.Status != InvoiceApplicationStatus.Pending && x.Status != InvoiceApplicationStatus.AuditRejected))
return DataResult.Failed("只能删除状态为‘未提交’或‘审核驳回’的申请单", MultiLanguageConst.FeeRecordDelete);
return DataResult.Success;
}
protected override async Task OnDeleteDetailAsync(List<ApplicationDetail> details)
{
if (details.Count == 0)
return;
var appIds = details.Select(x => x.ApplicationId).Distinct().ToList();
await TenantDb.Deleteable<InvoiceDetail>(x => appIds.Contains(x.ApplicationId)).ExecuteCommandAsync();
//还原费用表的已开票金额
var fees = details.Select(x => new FeeRecord { Id = x.RecordId, OrderInvoiceAmount = x.OriginalAmount }).ToList();
await TenantDb.Updateable(fees)
.PublicSetColumns(it => it.OrderInvoiceAmount, "-")
.UpdateColumns(x => new { x.OrderInvoiceAmount })
.ExecuteCommandAsync();
}
}
}