/// <summary>
/// 费用暂估分配
/// </summary>
/// <param name="item"></param>
private void Allocation(DynamicObject sourceData)
{
#region 合同履约成本自动分配
Dictionary<long, InvoiceExp> dictionary = new Dictionary<long, InvoiceExp>();
List<StockBillComp> list = new List<StockBillComp>();
List<string> SqlList = new List<string>();
List<string> SqlListWriteStr = new List<string>();
#region 第一步,根据暂估费用应付找到所有的销售出库单
string SetAccountType = Common.CommonHelper.ObjectToString(sourceData["FSetAccountType"]);
//表头财务
DynamicObjectCollection planBlffinList = sourceData["AP_PAYABLEFIN"] as DynamicObjectCollection;
DynamicObject planBlffin = planBlffinList.FirstOrDefault();
foreach (var item in sourceData["AP_PAYABLEENTRY"] as DynamicObjectCollection)
{
//未分配
string allocationStatus = Common.CommonHelper.ObjectToString(item["FALLOCATESTATUS"]);
if (!allocationStatus.Equals("A") && SetAccountType.Equals("2")) continue;
decimal SrcHookAmount = 0; //暂估不含税金额
decimal SrcHookAPAllAmount = 0; //暂估价税合计
decimal SrcAmountLC = 0; //暂估不含税金额本位币
decimal SrcInTaxAmountLC = 0; //暂估价税合计本位币
long InterID = Convert.ToInt64(sourceData[0]); //FID
long EntryID = Convert.ToInt64(item[0]); // EntryID
string BillNo = Convert.ToString(sourceData["BillNo"]); // BillNo
int BillSeq = Convert.ToInt32(item["Seq"]); // Seq
//财务应付
if (SetAccountType.Equals("3"))
{
//未分配不用补差
if (!allocationStatus.Equals("B")) continue;
//只支持单行对单行
DynamicObjectCollection links = item["FEntityDetail_Link"] as DynamicObjectCollection;
if (links.Count != 1) continue;
//抓取上游暂估应付金额
DynamicObjectCollection queryPayResult = DBUtils.ExecuteDynamicObject(Context, string.Format("select t.FNOTAXAMOUNTFOR,t.FALLAMOUNTFOR,t.FNOTAXAMOUNT,t.FALLAMOUNT,t1.FBILLNO,t.FSEQ from T_AP_PAYABLEENTRY t left join T_AP_PAYABLE t1 on t.FID=t1.FID where FEntryID={0}", links[0]["Sid"]));
if (queryPayResult.Count > 0)
{
SrcHookAmount = Convert.ToDecimal(queryPayResult[0]["FNOTAXAMOUNTFOR"]);
SrcHookAPAllAmount = Convert.ToDecimal(queryPayResult[0]["FALLAMOUNTFOR"]);
SrcAmountLC = Convert.ToDecimal(queryPayResult[0]["FNOTAXAMOUNT"]);
SrcInTaxAmountLC = Convert.ToDecimal(queryPayResult[0]["FALLAMOUNT"]);
DynamicObjectCollection ZgchResult = DBUtils.ExecuteDynamicObject(Context, string.Format("select t.FID,t.FENTRYID,t.FSEQ,t1.FBILLNO from T_AP_PAYABLEENTRY t left join T_AP_PAYABLE t1 on t.FID=t1.FID where t1.FSETACCOUNTTYPE=2 and t1.FBILLNO like '%{0}%' and t.FSEQ={1} order by FID desc", queryPayResult[0]["FBILLNO"], queryPayResult[0]["FSEQ"]));
if (ZgchResult.Count > 0)
{
InterID = Convert.ToInt64(ZgchResult[0]["FID"]); //FID
EntryID = Convert.ToInt64(ZgchResult[0]["FENTRYID"]); // EntryID
BillNo = Convert.ToString(ZgchResult[0]["FBILLNO"]); // BillNo
BillSeq = Convert.ToInt32(ZgchResult[0]["FSEQ"]); // Seq
}
else
{
throw new KDBusinessException("", "查询不到指定的暂估应付冲回单!");
}
}
//相等不用补差额(价税合计)
if (Convert.ToDecimal(item["FALLAMOUNTFOR_D"]) == SrcHookAPAllAmount) continue;
}
//销售出库单号
DynamicObjectCollection outStockIds = item["OUTSTOCKID"] as DynamicObjectCollection;
if (outStockIds.Count <= 0) continue;
string fiterStr = string.Join(" or fid=", outStockIds.Select(x => x["OUTSTOCKID_Id"]));
fiterStr = "fid=" + fiterStr; //把最开始的or删除掉
//var result = Common.CommonHelper.GetDynamicObjectArray(Context, "AP_Payable", string.Format("FBILLNO like '%{0}%'", "AP221213100264"));
//先统计应付单
InvoiceExp invoiceExp = new InvoiceExp();
invoiceExp.SettleOrg = Convert.ToInt64(sourceData["SETTLEORGID_ID"]);
invoiceExp.BillType = Convert.ToString(sourceData["BillTypeID_Id"]);
invoiceExp.InterID = InterID;
invoiceExp.EntryID = EntryID;
invoiceExp.HookQty = Convert.ToDecimal(item["PriceQty"]);
invoiceExp.HookAmount = Convert.ToDecimal(item["FNoTaxAmountFor_D"]) - SrcHookAmount;
invoiceExp.HookAPAllAmount = Convert.ToDecimal(item["FALLAMOUNTFOR_D"]) - SrcHookAPAllAmount;
invoiceExp.InvoicePrice = Convert.ToDecimal(item["FPrice"]);
invoiceExp.ExpenseId = Convert.ToInt64(item["FCOSTID_ID"]);
invoiceExp.CurrencyId = Convert.ToInt64(sourceData["CURRENCYID_ID"]);
invoiceExp.ExchangeRate = Convert.ToDecimal(planBlffin["FExchangeRate"]);
invoiceExp.ExchangeRateType = Convert.ToInt64(planBlffin["EXCHANGETYPE_ID"]);
invoiceExp.BillDate = Convert.ToDateTime(sourceData["DATE"]);
invoiceExp.BillNo = BillNo;
invoiceExp.BillSeq = BillSeq;
invoiceExp.SupplierId = Convert.ToInt64(sourceData["SUPPLIERID_ID"]);
invoiceExp.LocalCurrencyId = Convert.ToInt64(planBlffin["MAINBOOKSTDCURRID_ID"]);
invoiceExp.AmountLC = Convert.ToDecimal(item["NOTAXAMOUNT"]) - SrcAmountLC;
invoiceExp.InTaxAmountLC = Convert.ToDecimal(item["ALLAMOUNT"]) - SrcInTaxAmountLC;
//invoiceExp.CostDepartmentId = Convert.ToInt64(item["FCOSTDEPARTMENTID_ID"]);
//invoiceExp.AllocationSource = Kingdee.K3.FIN.Core.ExpAllocSource.Manual;
//invoiceExp.AllocationCriterion = (Kingdee.K3.FIN.Core.ExpAllocCriterion)2; //自定义权重分配
dictionary.Add(invoiceExp.EntryID, invoiceExp);
//统计销售出库单
var queryResult = Common.CommonHelper.GetDynamicObjectArray(Context, "SAL_OUTSTOCK", fiterStr);
if (!queryResult.isSuccess) throw new KDBusinessException("", queryResult.errorMsg);
//统计出出库单所有明细行的权重之和(物料上加个权重字段,销售出库物料得引用这个字段,应付单也修改,增加合同履约字段,并注册了插件)
decimal weightsSum = 0;
foreach (var stockEntry in queryResult.data.Select(x => x["SAL_OUTSTOCKENTRY"] as DynamicObjectCollection))
{
foreach (var stockEntryRow in stockEntry)
{
DynamicObject Material = stockEntryRow["MaterialID"] as DynamicObject;
DynamicObjectCollection baseList = Material["MaterialBase"] as DynamicObjectCollection;
DynamicObject baseObject = baseList[0];
decimal weight = Convert.ToDecimal(baseObject["LENGTH"]) * Convert.ToDecimal(baseObject["WIDTH"]) * Convert.ToDecimal(baseObject["HEIGHT"]);
if (weight == 0) throw new KDBusinessException("", string.Format("请维护物料【{0}-{1}】中【长】【宽】【高】字段值", Material["Name"], Material["Number"]));
weightsSum += weight * Convert.ToDecimal(stockEntryRow["RealQty"]);
}
}
foreach (var stock in queryResult.data)
{
//财务信息
DynamicObjectCollection outStockFinList = stock["SAL_OUTSTOCKFIN"] as DynamicObjectCollection;
DynamicObject outStockFin = outStockFinList.FirstOrDefault();
DynamicObjectCollection stockEntry = stock["SAL_OUTSTOCKENTRY"] as DynamicObjectCollection;
foreach (var stockEntryRow in stockEntry)
{
DynamicObject Material = stockEntryRow["MaterialID"] as DynamicObject;
DynamicObjectCollection baseList = Material["MaterialBase"] as DynamicObjectCollection;
DynamicObject baseObject = baseList[0];
decimal weight = Convert.ToDecimal(baseObject["LENGTH"]) * Convert.ToDecimal(baseObject["WIDTH"]) * Convert.ToDecimal(baseObject["HEIGHT"]);
decimal qty = Convert.ToDecimal(stockEntryRow["RealQty"]);
list.Add(new StockBillComp
{
ExpenseId = invoiceExp.ExpenseId,
SettleOrg = Convert.ToInt64(outStockFin["SettleOrgID_ID"]),
BillType = Convert.ToString(stock["BillTypeID_ID"]),
InterID = Convert.ToInt64(stock[0]),
EntryID = Convert.ToInt64(stockEntryRow[0]),
HookQty = qty,
SrcExchangeRate = invoiceExp.ExchangeRate,
SrcExchangeRateType = invoiceExp.ExchangeRateType,
SrcCurrencyID = invoiceExp.CurrencyId,
SrcEntryID = invoiceExp.EntryID,
SrcHookAmount = invoiceExp.HookAmount * weight * qty / weightsSum,
SrcHookAPAllAmount = invoiceExp.HookAPAllAmount * weight * qty / weightsSum,
AmountLC = invoiceExp.AmountLC * weight * qty / weightsSum,
HookAmount = invoiceExp.InTaxAmountLC * weight * qty / weightsSum, //标准的没有赋值
InTaxAmountLC = invoiceExp.InTaxAmountLC * weight * qty / weightsSum,
BillDate = Convert.ToDateTime(stock["Date"]),
BillNo = Convert.ToString(stock["BillNo"]),
BillSeq = Convert.ToInt32(stockEntryRow["Seq"]),
BillFormId = "SAL_OUTSTOCK",
MaterialId = Convert.ToInt64(stockEntryRow["MaterialID_ID"]),
UnitId = Convert.ToInt64(stockEntryRow["BaseUnitID_ID"]),
CustomerId = Convert.ToInt64(stock["CustomerID_ID"]),
BomId = Convert.ToInt64(stockEntryRow["BomID_ID"]),
MtoNo = Convert.ToString(stockEntryRow["MTONO"]),
LotId = Convert.ToInt64(stockEntryRow["Lot_ID"]),
AuxPropId = Convert.ToInt64(stockEntryRow["AuxPropId_ID"]),
//SaleOrgId = Convert.ToInt64(stock["SaleOrgId_ID"]),
//SaleDeptId = Convert.ToInt64(stock["SaleDeptID_ID"]),
//SalesGroupId = Convert.ToInt64(stock["SalesGroupID_ID"]),
//SalesManId = Convert.ToInt64(stock["SalesManID_ID"]),
SoorDerno = Convert.ToString(stockEntryRow["SoorDerno"])
});
//构建一个updateSQL
SqlList.Add(string.Format(" Update T_SAL_OUTSTOCKENTRY set F_QWZE_ContractCosts+={0} where FENTRYID={1};", list.LastOrDefault().AmountLC, list.LastOrDefault().EntryID));
SqlListWriteStr.Add(string.Format(" Update T_SAL_OUTSTOCKENTRY set F_QWZE_ContractCosts+={0} where FENTRYID={1};", list.LastOrDefault().AmountLC * -1, list.LastOrDefault().EntryID));
}
}
}
#region 第二步,调用分配接口
if (dictionary.Count > 0 & list.Count > 0)
{
IPruchaseExpenseService service = ServiceFactory.GetService<IPruchaseExpenseService>(Context);
IOperationResult result;
try
{
result = service.AllocationContractCompCostAmount(Context, dictionary, list);
string errMsg = Common.CommonHelper.CheckOpResult(result);
if (!string.IsNullOrWhiteSpace(errMsg)) throw new KDBusinessException("", errMsg);
var successRows = result.Rows.Select(x => x.DataEntity).Select(y => y[0]);
//分配记录+SQL语句
DBUtils.Execute(Context, string.Format("/*dialect*/Update T_AP_PAYABLE set F_QWZE_RecordID='{0}',F_QWZE_ExecuteSQL='{1}' where FID={2}", string.Join(",", successRows), string.Join("", SqlListWriteStr), sourceData[0]));
//执行更新到销售出库单上
ExTranSql(Context, "/*dialect*/" + string.Join("", SqlList));
}
finally
{
ServiceFactory.CloseService(service);
}
}
#endregion
#endregion
/// <summary>
/// 取消费用暂估分配
/// </summary>
/// <param name="sourceData"></param>
private void CancelAllocation(DynamicObject sourceData)
{
string recordStr = Common.CommonHelper.ObjectToString(sourceData["F_QWZE_RecordID"]);
string SetAccountType = Common.CommonHelper.ObjectToString(sourceData["FSetAccountType"]);
string sqlStr = Common.CommonHelper.ObjectToString(sourceData["F_QWZE_ExecuteSQL"]);
#region 更新分配结果
if (!string.IsNullOrWhiteSpace(recordStr) && SetAccountType.Equals("3"))
{
List<long> ids = new List<long>();
foreach (var item in recordStr.Split(','))
{
ids.Add(Convert.ToInt64(item));
}
if (ids.Count > 0)
{
IPruchaseExpenseService service = ServiceFactory.GetService<IPruchaseExpenseService>(Context);
IOperationResult result;
try
{
result = service.UnAllocationContractCompCostAmount(Context, ids);
string errMsg = Common.CommonHelper.CheckOpResult(result);
if (!string.IsNullOrWhiteSpace(errMsg)) throw new KDBusinessException("", errMsg);
}
finally
{
ServiceFactory.CloseService(service);
}
}
}
#endregion
#region 更新销售出库单合同履约金额
if (!string.IsNullOrWhiteSpace(sqlStr))
{
ExTranSql(Context, "/*dialect*/" + sqlStr);
//将合同履约记录清除
DBUtils.Execute(Context, string.Format("/*dialect*/Update T_AP_PAYABLE set F_QWZE_RecordID='',F_QWZE_ExecuteSQL='' where FID={0}", sourceData[0]));
}
#endregion
}
private void ExTranSql(Kingdee.BOS.Context ctx, string sql)
{
using (KDTransactionScope trans = new KDTransactionScope(
System.Transactions.TransactionScopeOption.Required))
{
int i = Kingdee.BOS.App.Data.DBUtils.Execute(ctx, sql);
trans.Complete();
if (i <= 0)
{
throw new Exception("更新失败");
}
}
}
推荐阅读